functions.lib.php 426 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. *
  21. * This program is free software; you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation; either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  33. * or see https://www.gnu.org/
  34. */
  35. /**
  36. * \file htdocs/core/lib/functions.lib.php
  37. * \brief A set of functions for Dolibarr
  38. * This file contains all frequently used functions.
  39. */
  40. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  41. /**
  42. * Return dolibarr global constant string value
  43. * @param string $key key to return value, return '' if not set
  44. * @param string $default value to return
  45. * @return string
  46. */
  47. function getDolGlobalString($key, $default = '')
  48. {
  49. global $conf;
  50. // return $conf->global->$key ?? $default;
  51. return (string) (empty($conf->global->$key) ? $default : $conf->global->$key);
  52. }
  53. /**
  54. * Return dolibarr global constant int value
  55. * @param string $key key to return value, return 0 if not set
  56. * @param int $default value to return
  57. * @return int
  58. */
  59. function getDolGlobalInt($key, $default = 0)
  60. {
  61. global $conf;
  62. // return $conf->global->$key ?? $default;
  63. return (int) (empty($conf->global->$key) ? $default : $conf->global->$key);
  64. }
  65. /**
  66. * Return a DoliDB instance (database handler).
  67. *
  68. * @param string $type Type of database (mysql, pgsql...)
  69. * @param string $host Address of database server
  70. * @param string $user Authorized username
  71. * @param string $pass Password
  72. * @param string $name Name of database
  73. * @param int $port Port of database server
  74. * @return DoliDB A DoliDB instance
  75. */
  76. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  77. {
  78. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  79. $class = 'DoliDB'.ucfirst($type);
  80. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  81. return $dolidb;
  82. }
  83. /**
  84. * Get list of entity id to use.
  85. *
  86. * @param string $element Current element
  87. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  88. * 'product', 'productprice', 'stock', 'bom', 'mo',
  89. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  90. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  91. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  92. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  93. * 'email_template', 'event', 'donation'
  94. * 'c_paiement', 'c_payment_term', ...
  95. * @param int $shared 0=Return id of current entity only,
  96. * 1=Return id of current entity + shared entities (default)
  97. * @param object $currentobject Current object if needed
  98. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  99. */
  100. function getEntity($element, $shared = 1, $currentobject = null)
  101. {
  102. global $conf, $mc, $hookmanager, $object, $action, $db;
  103. if (! is_object($hookmanager)) {
  104. $hookmanager = new HookManager($db);
  105. }
  106. // fix different element names (France to English)
  107. switch ($element) {
  108. case 'contrat':
  109. $element = 'contract';
  110. break; // "/contrat/class/contrat.class.php"
  111. case 'order_supplier':
  112. $element = 'supplier_order';
  113. break; // "/fourn/class/fournisseur.commande.class.php"
  114. }
  115. if (is_object($mc)) {
  116. $out = $mc->getEntity($element, $shared, $currentobject);
  117. } else {
  118. $out = '';
  119. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  120. if (in_array($element, $addzero)) {
  121. $out .= '0,';
  122. }
  123. $out .= ((int) $conf->entity);
  124. }
  125. // Manipulate entities to query on the fly
  126. $parameters = array(
  127. 'element' => $element,
  128. 'shared' => $shared,
  129. 'object' => $object,
  130. 'currentobject' => $currentobject,
  131. 'out' => $out
  132. );
  133. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  134. if (is_numeric($reshook)) {
  135. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  136. $out .= ','.$hookmanager->resPrint; // add
  137. } elseif ($reshook == 1) {
  138. $out = $hookmanager->resPrint; // replace
  139. }
  140. }
  141. return $out;
  142. }
  143. /**
  144. * Set entity id to use when to create an object
  145. *
  146. * @param object $currentobject Current object
  147. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  148. */
  149. function setEntity($currentobject)
  150. {
  151. global $conf, $mc;
  152. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  153. return $mc->setEntity($currentobject);
  154. } else {
  155. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  156. }
  157. }
  158. /**
  159. * Return if string has a name dedicated to store a secret
  160. *
  161. * @param string $keyname Name of key to test
  162. * @return boolean True if key is used to store a secret
  163. */
  164. function isASecretKey($keyname)
  165. {
  166. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  167. }
  168. /**
  169. * Return information about user browser
  170. *
  171. * Returns array with the following format:
  172. * array(
  173. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  174. * 'browserversion' => Browser version. Empty if unknown
  175. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  176. * 'layout' => (tablet|phone|classic)
  177. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  178. * 'tablet' => true/false
  179. * )
  180. *
  181. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  182. * @return array Check function documentation
  183. */
  184. function getBrowserInfo($user_agent)
  185. {
  186. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  187. $name = 'unknown';
  188. $version = '';
  189. $os = 'unknown';
  190. $phone = '';
  191. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  192. $detectmobile = new Mobile_Detect(null, $user_agent);
  193. $tablet = $detectmobile->isTablet();
  194. if ($detectmobile->isMobile()) {
  195. $phone = 'unknown';
  196. // If phone/smartphone, we set phone os name.
  197. if ($detectmobile->is('AndroidOS')) {
  198. $os = $phone = 'android';
  199. } elseif ($detectmobile->is('BlackBerryOS')) {
  200. $os = $phone = 'blackberry';
  201. } elseif ($detectmobile->is('iOS')) {
  202. $os = 'ios';
  203. $phone = 'iphone';
  204. } elseif ($detectmobile->is('PalmOS')) {
  205. $os = $phone = 'palm';
  206. } elseif ($detectmobile->is('SymbianOS')) {
  207. $os = 'symbian';
  208. } elseif ($detectmobile->is('webOS')) {
  209. $os = 'webos';
  210. } elseif ($detectmobile->is('MaemoOS')) {
  211. $os = 'maemo';
  212. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  213. $os = 'windows';
  214. }
  215. }
  216. // OS
  217. if (preg_match('/linux/i', $user_agent)) {
  218. $os = 'linux';
  219. } elseif (preg_match('/macintosh/i', $user_agent)) {
  220. $os = 'macintosh';
  221. } elseif (preg_match('/windows/i', $user_agent)) {
  222. $os = 'windows';
  223. }
  224. // Name
  225. $reg = array();
  226. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  227. $name = 'firefox';
  228. $version = $reg[2];
  229. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  230. $name = 'edge';
  231. $version = $reg[2];
  232. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  233. $name = 'chrome';
  234. $version = $reg[2];
  235. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  236. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  237. $name = 'chrome';
  238. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  239. $name = 'iceweasel';
  240. } elseif (preg_match('/epiphany/i', $user_agent)) {
  241. $name = 'epiphany';
  242. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  243. $name = 'safari';
  244. $version = $reg[2];
  245. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  246. // Safari is often present in string for mobile but its not.
  247. $name = 'opera';
  248. $version = $reg[2];
  249. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  250. $name = 'ie';
  251. $version = end($reg);
  252. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  253. // MS products at end
  254. $name = 'ie';
  255. $version = end($reg);
  256. } elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  257. // MS products at end
  258. $name = 'lynxlinks';
  259. $version = $reg[4];
  260. }
  261. if ($tablet) {
  262. $layout = 'tablet';
  263. } elseif ($phone) {
  264. $layout = 'phone';
  265. } else {
  266. $layout = 'classic';
  267. }
  268. return array(
  269. 'browsername' => $name,
  270. 'browserversion' => $version,
  271. 'browseros' => $os,
  272. 'layout' => $layout,
  273. 'phone' => $phone,
  274. 'tablet' => $tablet
  275. );
  276. }
  277. /**
  278. * Function called at end of web php process
  279. *
  280. * @return void
  281. */
  282. function dol_shutdown()
  283. {
  284. global $conf, $user, $langs, $db;
  285. $disconnectdone = false;
  286. $depth = 0;
  287. if (is_object($db) && !empty($db->connected)) {
  288. $depth = $db->transaction_opened;
  289. $disconnectdone = $db->close();
  290. }
  291. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  292. }
  293. /**
  294. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  295. *
  296. * @param string $paramname Name or parameter to test
  297. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  298. */
  299. function GETPOSTISSET($paramname)
  300. {
  301. $isset = false;
  302. $relativepathstring = $_SERVER["PHP_SELF"];
  303. // Clean $relativepathstring
  304. if (constant('DOL_URL_ROOT')) {
  305. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  306. }
  307. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  308. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  309. //var_dump($relativepathstring);
  310. //var_dump($user->default_values);
  311. // Code for search criteria persistence.
  312. // Retrieve values if restore_lastsearch_values
  313. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  314. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  315. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  316. if (is_array($tmp)) {
  317. foreach ($tmp as $key => $val) {
  318. if ($key == $paramname) { // We are on the requested parameter
  319. $isset = true;
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. // If there is saved contextpage, page or limit
  326. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  327. $isset = true;
  328. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  329. $isset = true;
  330. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  331. $isset = true;
  332. }
  333. } else {
  334. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  335. }
  336. return $isset;
  337. }
  338. /**
  339. * Return value of a param into GET or POST supervariable.
  340. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  341. * Note: The property $user->default_values is loaded by main.php when loading the user.
  342. *
  343. * @param string $paramname Name of parameter to found
  344. * @param string $check Type of check
  345. * ''=no check (deprecated)
  346. * 'none'=no check (only for param that should have very rich content)
  347. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  348. * 'int'=check it's numeric (integer or float)
  349. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  350. * 'alpha'=Same than alphanohtml since v13
  351. * 'alphawithlgt'=alpha with lgt
  352. * 'alphanohtml'=check there is no html content and no " and no ../
  353. * 'aZ'=check it's a-z only
  354. * 'aZ09'=check it's simple alpha string (recommended for keys)
  355. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  356. * 'nohtml'=check there is no html content and no " and no ../
  357. * 'restricthtml'=check html content is restricted to some tags only
  358. * 'custom'= custom filter specify $filter and $options)
  359. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  360. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  361. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  362. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  363. * @return string|array Value found (string or array), or '' if check fails
  364. */
  365. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  366. {
  367. global $mysoc, $user, $conf;
  368. if (empty($paramname)) {
  369. return 'BadFirstParameterForGETPOST';
  370. }
  371. if (empty($check)) {
  372. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  373. // Enable this line to know who call the GETPOST with '' $check parameter.
  374. //var_dump(debug_backtrace()[0]);
  375. }
  376. if (empty($method)) {
  377. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  378. } elseif ($method == 1) {
  379. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  380. } elseif ($method == 2) {
  381. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  382. } elseif ($method == 3) {
  383. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  384. } else {
  385. return 'BadThirdParameterForGETPOST';
  386. }
  387. if (empty($method) || $method == 3 || $method == 4) {
  388. $relativepathstring = $_SERVER["PHP_SELF"];
  389. // Clean $relativepathstring
  390. if (constant('DOL_URL_ROOT')) {
  391. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  392. }
  393. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  394. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  395. //var_dump($relativepathstring);
  396. //var_dump($user->default_values);
  397. // Code for search criteria persistence.
  398. // Retrieve values if restore_lastsearch_values
  399. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  400. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  401. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  402. if (is_array($tmp)) {
  403. foreach ($tmp as $key => $val) {
  404. if ($key == $paramname) { // We are on the requested parameter
  405. $out = $val;
  406. break;
  407. }
  408. }
  409. }
  410. }
  411. // If there is saved contextpage, page or limit
  412. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  413. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  414. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  415. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  416. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  417. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  418. }
  419. } elseif (!isset($_GET['sortfield'])) {
  420. // Else, retrieve default values if we are not doing a sort
  421. // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
  422. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  423. // Search default value from $object->field
  424. global $object;
  425. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  426. $out = $object->fields[$paramname]['default'];
  427. }
  428. }
  429. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  430. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  431. // Now search in setup to overwrite default values
  432. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  433. if (isset($user->default_values[$relativepathstring]['createform'])) {
  434. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  435. $qualified = 0;
  436. if ($defkey != '_noquery_') {
  437. $tmpqueryarraytohave = explode('&', $defkey);
  438. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  439. $foundintru = 0;
  440. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  441. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  442. $foundintru = 1;
  443. }
  444. }
  445. if (!$foundintru) {
  446. $qualified = 1;
  447. }
  448. //var_dump($defkey.'-'.$qualified);
  449. } else {
  450. $qualified = 1;
  451. }
  452. if ($qualified) {
  453. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  454. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  455. break;
  456. }
  457. }
  458. }
  459. }
  460. }
  461. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  462. // Management of default search_filters and sort order
  463. if (!empty($user->default_values)) {
  464. // $user->default_values defined from menu 'Setup - Default values'
  465. //var_dump($user->default_values[$relativepathstring]);
  466. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  467. // Sorted on which fields ? ASC or DESC ?
  468. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  469. // Even if paramname is sortfield, data are stored into ['sortorder...']
  470. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  471. $qualified = 0;
  472. if ($defkey != '_noquery_') {
  473. $tmpqueryarraytohave = explode('&', $defkey);
  474. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  475. $foundintru = 0;
  476. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  477. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  478. $foundintru = 1;
  479. }
  480. }
  481. if (!$foundintru) {
  482. $qualified = 1;
  483. }
  484. //var_dump($defkey.'-'.$qualified);
  485. } else {
  486. $qualified = 1;
  487. }
  488. if ($qualified) {
  489. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  490. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  491. if ($out) {
  492. $out .= ', ';
  493. }
  494. if ($paramname == 'sortfield') {
  495. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  496. }
  497. if ($paramname == 'sortorder') {
  498. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  499. }
  500. }
  501. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  502. }
  503. }
  504. }
  505. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  506. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  507. $qualified = 0;
  508. if ($defkey != '_noquery_') {
  509. $tmpqueryarraytohave = explode('&', $defkey);
  510. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  511. $foundintru = 0;
  512. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  513. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  514. $foundintru = 1;
  515. }
  516. }
  517. if (!$foundintru) {
  518. $qualified = 1;
  519. }
  520. //var_dump($defkey.'-'.$qualified);
  521. } else {
  522. $qualified = 1;
  523. }
  524. if ($qualified) {
  525. // We must keep $_POST and $_GET here
  526. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  527. // We made a search from quick search menu, do we still use default filter ?
  528. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  529. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  530. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  531. }
  532. } else {
  533. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  534. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  535. }
  536. break;
  537. }
  538. }
  539. }
  540. }
  541. }
  542. }
  543. }
  544. }
  545. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  546. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  547. // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text.
  548. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  549. $reg = array();
  550. $maxloop = 20;
  551. $loopnb = 0; // Protection against infinite loop
  552. while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) { // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
  553. $loopnb++;
  554. $newout = '';
  555. if ($reg[1] == 'DAY') {
  556. $tmp = dol_getdate(dol_now(), true);
  557. $newout = $tmp['mday'];
  558. } elseif ($reg[1] == 'MONTH') {
  559. $tmp = dol_getdate(dol_now(), true);
  560. $newout = $tmp['mon'];
  561. } elseif ($reg[1] == 'YEAR') {
  562. $tmp = dol_getdate(dol_now(), true);
  563. $newout = $tmp['year'];
  564. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  565. $tmp = dol_getdate(dol_now(), true);
  566. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  567. $newout = $tmp2['day'];
  568. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  569. $tmp = dol_getdate(dol_now(), true);
  570. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  571. $newout = $tmp2['month'];
  572. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  573. $tmp = dol_getdate(dol_now(), true);
  574. $newout = ($tmp['year'] - 1);
  575. } elseif ($reg[1] == 'NEXT_DAY') {
  576. $tmp = dol_getdate(dol_now(), true);
  577. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  578. $newout = $tmp2['day'];
  579. } elseif ($reg[1] == 'NEXT_MONTH') {
  580. $tmp = dol_getdate(dol_now(), true);
  581. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  582. $newout = $tmp2['month'];
  583. } elseif ($reg[1] == 'NEXT_YEAR') {
  584. $tmp = dol_getdate(dol_now(), true);
  585. $newout = ($tmp['year'] + 1);
  586. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  587. $newout = $mysoc->country_id;
  588. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  589. $newout = $user->id;
  590. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  591. $newout = $user->fk_user;
  592. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  593. $newout = $conf->entity;
  594. } else {
  595. $newout = ''; // Key not found, we replace with empty string
  596. }
  597. //var_dump('__'.$reg[1].'__ -> '.$newout);
  598. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  599. }
  600. }
  601. // Check rule
  602. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  603. if (!is_array($out) || empty($out)) {
  604. $out = array();
  605. } else {
  606. $tmparray = explode(':', $check);
  607. if (!empty($tmparray[1])) {
  608. $tmpcheck = $tmparray[1];
  609. } else {
  610. $tmpcheck = 'alphanohtml';
  611. }
  612. foreach ($out as $outkey => $outval) {
  613. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  614. }
  615. }
  616. } else {
  617. $out = checkVal($out, $check, $filter, $options);
  618. }
  619. // Sanitizing for special parameters.
  620. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL.
  621. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  622. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  623. $out = str_replace(array(':', ';', '@'), '', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  624. do {
  625. $oldstringtoclean = $out;
  626. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  627. } while ($oldstringtoclean != $out);
  628. $out = preg_replace(array('/^[a-z]*\/\/+/i'), '', $out); // We remove schema*// to remove external URL
  629. }
  630. // Code for search criteria persistence.
  631. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  632. if (empty($method) || $method == 3 || $method == 4) {
  633. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  634. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  635. // We save search key only if $out not empty that means:
  636. // - posted value not empty, or
  637. // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not).
  638. if ($out != '') { // $out = '0' or 'abc', it is a search criteria to keep
  639. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  640. }
  641. }
  642. }
  643. return $out;
  644. }
  645. /**
  646. * Return value of a param into GET or POST supervariable.
  647. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  648. * Note: The property $user->default_values is loaded by main.php when loading the user.
  649. *
  650. * @param string $paramname Name of parameter to found
  651. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  652. * @return int Value found (int)
  653. */
  654. function GETPOSTINT($paramname, $method = 0)
  655. {
  656. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  657. }
  658. /**
  659. * Return a value after checking on a rule. A sanitization may also have been done.
  660. *
  661. * @param string $out Value to check/clear.
  662. * @param string $check Type of check/sanitizing
  663. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  664. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  665. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  666. */
  667. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  668. {
  669. global $conf;
  670. // Check is done after replacement
  671. switch ($check) {
  672. case 'none':
  673. break;
  674. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  675. if (!is_numeric($out)) {
  676. $out = '';
  677. }
  678. break;
  679. case 'intcomma':
  680. if (preg_match('/[^0-9,-]+/i', $out)) {
  681. $out = '';
  682. }
  683. break;
  684. case 'san_alpha':
  685. $out = filter_var($out, FILTER_SANITIZE_STRING);
  686. break;
  687. case 'email':
  688. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  689. break;
  690. case 'aZ':
  691. if (!is_array($out)) {
  692. $out = trim($out);
  693. if (preg_match('/[^a-z]+/i', $out)) {
  694. $out = '';
  695. }
  696. }
  697. break;
  698. case 'aZ09':
  699. if (!is_array($out)) {
  700. $out = trim($out);
  701. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  702. $out = '';
  703. }
  704. }
  705. break;
  706. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  707. if (!is_array($out)) {
  708. $out = trim($out);
  709. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  710. $out = '';
  711. }
  712. }
  713. break;
  714. case 'nohtml': // No html
  715. $out = dol_string_nohtmltag($out, 0);
  716. break;
  717. case 'alpha': // No html and no ../ and "
  718. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  719. if (!is_array($out)) {
  720. $out = trim($out);
  721. do {
  722. $oldstringtoclean = $out;
  723. // Remove html tags
  724. $out = dol_string_nohtmltag($out, 0);
  725. // Remove also other dangerous string sequences
  726. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  727. // '../' or '..\' is dangerous because it allows dir transversals
  728. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  729. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  730. } while ($oldstringtoclean != $out);
  731. // keep lines feed
  732. }
  733. break;
  734. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>"
  735. if (!is_array($out)) {
  736. $out = trim($out);
  737. do {
  738. $oldstringtoclean = $out;
  739. // Remove html tags
  740. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  741. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  742. // '../' or '..\' is dangerous because it allows dir transversals
  743. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  744. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  745. } while ($oldstringtoclean != $out);
  746. }
  747. break;
  748. case 'restricthtml': // Recommended for most html textarea
  749. case 'restricthtmlallowunvalid':
  750. do {
  751. $oldstringtoclean = $out;
  752. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  753. try {
  754. $dom = new DOMDocument;
  755. // Add a trick to solve pb with text without parent tag
  756. // like '<h1>Foo</h1><p>bar</p>' that ends up with '<h1>Foo<p>bar</p></h1>'
  757. // like 'abc' that ends up with '<p>abc</p>'
  758. $out = '<div class="tricktoremove">'.$out.'</div>';
  759. $dom->loadHTML($out, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  760. $out = trim($dom->saveHTML());
  761. // Remove the trick added to solve pb with text without parent tag
  762. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  763. $out = preg_replace('/<\/div>$/', '', $out);
  764. } catch (Exception $e) {
  765. //print $e->getMessage();
  766. return 'InvalidHTMLString';
  767. }
  768. }
  769. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  770. // encoded using text entities) so we can then exclude all numeric entities.
  771. $out = preg_replace('/&#39;/i', '&apos;', $out);
  772. // We replace chars from a/A to z/Z encoded with numeric HTML entities with the real char so we won't loose the chars at the next step (preg_replace).
  773. // No need to use a loop here, this step is not to sanitize (this is done at next step, this is to try to save chars, even if they are
  774. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  775. //$out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', 'realCharForNumericEntities', $out);
  776. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  777. return realCharForNumericEntities($m); }, $out);
  778. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  779. $out = preg_replace('/&#x?[0-9]+/i', '', $out); // For example if we have j&#x61vascript with an entities without the ; to hide the 'a' of 'javascript'.
  780. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  781. // We should also exclude non expected HTML attributes and clean content of some attributes.
  782. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  783. // Warning, the function may add a LF so we are forced to trim to compare with old $out without having always a difference and an infinit loop.
  784. $out = dol_string_onlythesehtmlattributes($out);
  785. }
  786. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  787. $out = preg_replace('/&apos;/i', "&#39;", $out);
  788. } while ($oldstringtoclean != $out);
  789. break;
  790. case 'custom':
  791. if (empty($filter)) {
  792. return 'BadFourthParameterForGETPOST';
  793. }
  794. $out = filter_var($out, $filter, $options);
  795. break;
  796. }
  797. return $out;
  798. }
  799. if (!function_exists('dol_getprefix')) {
  800. /**
  801. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  802. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  803. * or two instances in same virtual servers.
  804. *
  805. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  806. * @return string A calculated prefix
  807. */
  808. function dol_getprefix($mode = '')
  809. {
  810. // If prefix is for email (we need to have $conf alreayd loaded for this case)
  811. if ($mode == 'email') {
  812. global $conf;
  813. 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)
  814. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  815. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  816. } elseif (isset($_SERVER["SERVER_NAME"])) {
  817. return $_SERVER["SERVER_NAME"];
  818. }
  819. }
  820. // The recommended value (may be not defined for old versions)
  821. if (!empty($conf->file->instance_unique_id)) {
  822. return $conf->file->instance_unique_id;
  823. }
  824. // For backward compatibility
  825. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  826. }
  827. // If prefix is for session (no need to have $conf loaded)
  828. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  829. $tmp_instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance
  830. // The recommended value (may be not defined for old versions)
  831. if (!empty($tmp_instance_unique_id)) {
  832. return $tmp_instance_unique_id;
  833. }
  834. // For backward compatibility
  835. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  836. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  837. }
  838. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  839. }
  840. }
  841. /**
  842. * Make an include_once using default root and alternate root if it fails.
  843. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  844. * To link to a module file from a module file, use include './mymodulefile';
  845. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  846. *
  847. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  848. * @param string $classname Class name (deprecated)
  849. * @return bool True if load is a success, False if it fails
  850. */
  851. function dol_include_once($relpath, $classname = '')
  852. {
  853. 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']
  854. $fullpath = dol_buildpath($relpath);
  855. if (!file_exists($fullpath)) {
  856. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  857. return false;
  858. }
  859. if (!empty($classname) && !class_exists($classname)) {
  860. return include $fullpath;
  861. } else {
  862. return include_once $fullpath;
  863. }
  864. }
  865. /**
  866. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  867. *
  868. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  869. * @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)
  870. * @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)
  871. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  872. * 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
  873. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  874. */
  875. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  876. {
  877. global $conf;
  878. $path = preg_replace('/^\//', '', $path);
  879. if (empty($type)) { // For a filesystem path
  880. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  881. if (is_array($conf->file->dol_document_root)) {
  882. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  883. if ($key == 'main') {
  884. continue;
  885. }
  886. if (file_exists($dirroot.'/'.$path)) {
  887. $res = $dirroot.'/'.$path;
  888. return $res;
  889. }
  890. }
  891. }
  892. if ($returnemptyifnotfound) {
  893. // Not found into alternate dir
  894. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  895. return '';
  896. }
  897. }
  898. } else {
  899. // For an url path
  900. // We try to get local path of file on filesystem from url
  901. // Note that trying to know if a file on disk exist by forging path on disk from url
  902. // works only for some web server and some setup. This is bugged when
  903. // using proxy, rewriting, virtual path, etc...
  904. $res = '';
  905. if ($type == 1) {
  906. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  907. }
  908. if ($type == 2) {
  909. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  910. }
  911. if ($type == 3) {
  912. $res = DOL_URL_ROOT.'/'.$path;
  913. }
  914. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  915. if ($key == 'main') {
  916. if ($type == 3) {
  917. global $dolibarr_main_url_root;
  918. // Define $urlwithroot
  919. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  920. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  921. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  922. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  923. }
  924. continue;
  925. }
  926. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  927. if (!empty($regs[1])) {
  928. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  929. if (file_exists($dirroot.'/'.$regs[1])) {
  930. if ($type == 1) {
  931. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  932. }
  933. if ($type == 2) {
  934. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  935. }
  936. if ($type == 3) {
  937. global $dolibarr_main_url_root;
  938. // Define $urlwithroot
  939. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  940. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  941. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  942. $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
  943. }
  944. break;
  945. }
  946. }
  947. }
  948. }
  949. return $res;
  950. }
  951. /**
  952. * Create a clone of instance of object (new instance with same value for properties)
  953. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  954. * 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.
  955. *
  956. * @param object $object Object to clone
  957. * @param int $native 0=Full isolation method, 1=Native PHP method
  958. * @return object Clone object
  959. * @see https://php.net/manual/language.oop5.cloning.php
  960. */
  961. function dol_clone($object, $native = 0)
  962. {
  963. if (empty($native)) {
  964. $myclone = unserialize(serialize($object)); // serialize then unserialize is hack to be sure to have a new object for all fields
  965. } else {
  966. $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)
  967. }
  968. return $myclone;
  969. }
  970. /**
  971. * Optimize a size for some browsers (phone, smarphone, ...)
  972. *
  973. * @param int $size Size we want
  974. * @param string $type Type of optimizing:
  975. * '' = function used to define a size for truncation
  976. * 'width' = function is used to define a width
  977. * @return int New size after optimizing
  978. */
  979. function dol_size($size, $type = '')
  980. {
  981. global $conf;
  982. if (empty($conf->dol_optimize_smallscreen)) {
  983. return $size;
  984. }
  985. if ($type == 'width' && $size > 250) {
  986. return 250;
  987. } else {
  988. return 10;
  989. }
  990. }
  991. /**
  992. * Clean a string to use it as a file name.
  993. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  994. *
  995. * @param string $str String to clean
  996. * @param string $newstr String to replace bad chars with.
  997. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  998. * @return string String cleaned (a-zA-Z_)
  999. *
  1000. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1001. */
  1002. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1003. {
  1004. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1005. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1006. // Char '/' and '\' are file delimiters.
  1007. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1008. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1009. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1010. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1011. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1012. return $tmp;
  1013. }
  1014. /**
  1015. * Clean a string to use it as a path name.
  1016. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1017. *
  1018. * @param string $str String to clean
  1019. * @param string $newstr String to replace bad chars with
  1020. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1021. * @return string String cleaned (a-zA-Z_)
  1022. *
  1023. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1024. */
  1025. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1026. {
  1027. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1028. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1029. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1030. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1031. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1032. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1033. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1034. return $tmp;
  1035. }
  1036. /**
  1037. * Clean a string to use it as an URL (into a href or src attribute)
  1038. *
  1039. * @param string $stringtoclean String to clean
  1040. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1041. * @return string Escaped string.
  1042. */
  1043. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1044. {
  1045. // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char)
  1046. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1047. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1048. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1049. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1050. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1051. if ($type == 1) {
  1052. // removing : should disable links to external url like http:aaa)
  1053. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1054. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1055. }
  1056. do {
  1057. $oldstringtoclean = $stringtoclean;
  1058. // removing '&colon' should disable links to external url like http:aaa)
  1059. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1060. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1061. } while ($oldstringtoclean != $stringtoclean);
  1062. if ($type == 1) {
  1063. // removing '//' should disable links to external url like //aaa or http//)
  1064. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1065. }
  1066. return $stringtoclean;
  1067. }
  1068. /**
  1069. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1070. *
  1071. * @param string $str String to clean
  1072. * @return string Cleaned string
  1073. *
  1074. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1075. */
  1076. function dol_string_unaccent($str)
  1077. {
  1078. global $conf;
  1079. if (utf8_check($str)) {
  1080. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1081. $transliterator = \Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', \Transliterator::FORWARD);
  1082. return $transliterator->transliterate($str);
  1083. }
  1084. // See http://www.utf8-chartable.de/
  1085. $string = rawurlencode($str);
  1086. $replacements = array(
  1087. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1088. '%C3%87' => 'C',
  1089. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1090. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1091. '%C3%91' => 'N',
  1092. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1093. '%C5%A0' => 'S',
  1094. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1095. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1096. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1097. '%C3%A7' => 'c',
  1098. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1099. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1100. '%C3%B1' => 'n',
  1101. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1102. '%C5%A1' => 's',
  1103. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1104. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1105. );
  1106. $string = strtr($string, $replacements);
  1107. return rawurldecode($string);
  1108. } else {
  1109. // See http://www.ascii-code.com/
  1110. $string = strtr(
  1111. $str,
  1112. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1113. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1114. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1115. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1116. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1117. \xF9\xFA\xFB\xFC\xFD\xFF",
  1118. "AAAAAAC
  1119. EEEEIIIIDN
  1120. OOOOOUUUY
  1121. aaaaaaceeee
  1122. iiiidnooooo
  1123. uuuuyy"
  1124. );
  1125. $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"));
  1126. return $string;
  1127. }
  1128. }
  1129. /**
  1130. * Clean a string from all punctuation characters to use it as a ref or login.
  1131. * This is a more complete function than dol_sanitizeFileName.
  1132. *
  1133. * @param string $str String to clean
  1134. * @param string $newstr String to replace forbidden chars with
  1135. * @param array|string $badcharstoreplace List of forbidden characters to replace
  1136. * @param array|string $badcharstoremove List of forbidden characters to remove
  1137. * @return string Cleaned string
  1138. *
  1139. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1140. */
  1141. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1142. {
  1143. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1144. $forbidden_chars_to_remove = array();
  1145. //$forbidden_chars_to_remove=array("(",")");
  1146. if (is_array($badcharstoreplace)) {
  1147. $forbidden_chars_to_replace = $badcharstoreplace;
  1148. }
  1149. if (is_array($badcharstoremove)) {
  1150. $forbidden_chars_to_remove = $badcharstoremove;
  1151. }
  1152. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1153. }
  1154. /**
  1155. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1156. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1157. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1158. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1159. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1160. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1161. * @param string $str String to clean
  1162. * @param int $removetabcrlf Remove also CR-LF
  1163. * @return string Cleaned string
  1164. *
  1165. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1166. */
  1167. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1168. {
  1169. if ($removetabcrlf) {
  1170. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1171. } else {
  1172. 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
  1173. }
  1174. }
  1175. /**
  1176. * Returns text escaped for inclusion into javascript code
  1177. *
  1178. * @param string $stringtoescape String to escape
  1179. * @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 \
  1180. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1181. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1182. */
  1183. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1184. {
  1185. // escape quotes and backslashes, newlines, etc.
  1186. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1187. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1188. if (empty($noescapebackslashn)) {
  1189. $substitjs["\n"] = '\\n';
  1190. $substitjs['\\'] = '\\\\';
  1191. }
  1192. if (empty($mode)) {
  1193. $substitjs["'"] = "\\'";
  1194. $substitjs['"'] = "\\'";
  1195. } elseif ($mode == 1) {
  1196. $substitjs["'"] = "\\'";
  1197. } elseif ($mode == 2) {
  1198. $substitjs['"'] = '\\"';
  1199. } elseif ($mode == 3) {
  1200. $substitjs["'"] = "\\'";
  1201. $substitjs['"'] = "\\\"";
  1202. }
  1203. return strtr($stringtoescape, $substitjs);
  1204. }
  1205. /**
  1206. * Returns text escaped for inclusion into javascript code
  1207. *
  1208. * @param string $stringtoescape String to escape
  1209. * @return string Escaped string for json content.
  1210. */
  1211. function dol_escape_json($stringtoescape)
  1212. {
  1213. return str_replace('"', '\"', $stringtoescape);
  1214. }
  1215. /**
  1216. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1217. *
  1218. * @param string $stringtoescape String to escape
  1219. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1220. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1221. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes to tag.
  1222. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1223. * @return string Escaped string
  1224. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1225. */
  1226. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1227. {
  1228. if ($noescapetags == 'common') {
  1229. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1230. }
  1231. // escape quotes and backslashes, newlines, etc.
  1232. if ($escapeonlyhtmltags) {
  1233. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1234. } else {
  1235. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1236. }
  1237. if (!$keepb) {
  1238. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1239. }
  1240. if (!$keepn) {
  1241. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1242. }
  1243. if ($escapeonlyhtmltags) {
  1244. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1245. } else {
  1246. // Escape tags to keep
  1247. // TODO Does not works yet when there is attributes to tag
  1248. $tmparrayoftags = array();
  1249. if ($noescapetags) {
  1250. $tmparrayoftags = explode(',', $noescapetags);
  1251. }
  1252. if (count($tmparrayoftags)) {
  1253. foreach ($tmparrayoftags as $tagtoreplace) {
  1254. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1255. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1256. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1257. }
  1258. }
  1259. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1260. if (count($tmparrayoftags)) {
  1261. foreach ($tmparrayoftags as $tagtoreplace) {
  1262. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1263. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1264. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1265. }
  1266. }
  1267. return $result;
  1268. }
  1269. }
  1270. /**
  1271. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1272. *
  1273. * @param string $string String to encode
  1274. * @param string $encoding Character set encoding
  1275. * @return string String converted
  1276. */
  1277. function dol_strtolower($string, $encoding = "UTF-8")
  1278. {
  1279. if (function_exists('mb_strtolower')) {
  1280. return mb_strtolower($string, $encoding);
  1281. } else {
  1282. return strtolower($string);
  1283. }
  1284. }
  1285. /**
  1286. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1287. *
  1288. * @param string $string String to encode
  1289. * @param string $encoding Character set encoding
  1290. * @return string String converted
  1291. */
  1292. function dol_strtoupper($string, $encoding = "UTF-8")
  1293. {
  1294. if (function_exists('mb_strtoupper')) {
  1295. return mb_strtoupper($string, $encoding);
  1296. } else {
  1297. return strtoupper($string);
  1298. }
  1299. }
  1300. /**
  1301. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1302. *
  1303. * @param string $string String to encode
  1304. * @param string $encoding Character set encodign
  1305. * @return string String converted
  1306. */
  1307. function dol_ucfirst($string, $encoding = "UTF-8")
  1308. {
  1309. if (function_exists('mb_substr')) {
  1310. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1311. } else {
  1312. return ucfirst($string);
  1313. }
  1314. }
  1315. /**
  1316. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1317. *
  1318. * @param string $string String to encode
  1319. * @param string $encoding Character set encodign
  1320. * @return string String converted
  1321. */
  1322. function dol_ucwords($string, $encoding = "UTF-8")
  1323. {
  1324. if (function_exists('mb_convert_case')) {
  1325. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1326. } else {
  1327. return ucwords($string);
  1328. }
  1329. }
  1330. /**
  1331. * Write log message into outputs. Possible outputs can be:
  1332. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1333. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1334. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1335. * this, use logging to files instead of syslog (see setup of module).
  1336. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1337. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1338. * This function works only if syslog module is enabled.
  1339. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1340. *
  1341. * @param string $message Line to log. ''=Show nothing
  1342. * @param int $level Log level
  1343. * 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
  1344. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1345. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1346. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1347. * @param string $restricttologhandler Force output of log only to this log handler
  1348. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1349. * @return void
  1350. */
  1351. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1352. {
  1353. global $conf, $user, $debugbar;
  1354. // If syslog module enabled
  1355. if (empty($conf->syslog->enabled)) {
  1356. return;
  1357. }
  1358. // Check if we are into execution of code of a website
  1359. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1360. global $website, $websitekey;
  1361. if (is_object($website) && !empty($website->ref)) {
  1362. $suffixinfilename .= '_website_'.$website->ref;
  1363. } elseif (!empty($websitekey)) {
  1364. $suffixinfilename .= '_website_'.$websitekey;
  1365. }
  1366. }
  1367. if ($ident < 0) {
  1368. foreach ($conf->loghandlers as $loghandlerinstance) {
  1369. $loghandlerinstance->setIdent($ident);
  1370. }
  1371. }
  1372. if (!empty($message)) {
  1373. // Test log level
  1374. $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');
  1375. if (!array_key_exists($level, $logLevels)) {
  1376. throw new Exception('Incorrect log level');
  1377. }
  1378. if ($level > $conf->global->SYSLOG_LEVEL) {
  1379. return;
  1380. }
  1381. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1382. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1383. }
  1384. // If adding log inside HTML page is required
  1385. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1386. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1387. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1388. }
  1389. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1390. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1391. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1392. print "\n\n<!-- Log start\n";
  1393. print dol_escape_htmltag($message)."\n";
  1394. print "Log end -->\n";
  1395. }
  1396. $data = array(
  1397. 'message' => $message,
  1398. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1399. 'level' => $level,
  1400. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1401. 'ip' => false
  1402. );
  1403. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1404. if (!empty($remoteip)) {
  1405. $data['ip'] = $remoteip;
  1406. // This is when server run behind a reverse proxy
  1407. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1408. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1409. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1410. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1411. }
  1412. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1413. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1414. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1415. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1416. // 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).
  1417. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1418. } elseif (!empty($_SERVER['LOGNAME'])) {
  1419. // 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).
  1420. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1421. }
  1422. // Loop on each log handler and send output
  1423. foreach ($conf->loghandlers as $loghandlerinstance) {
  1424. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1425. continue;
  1426. }
  1427. $loghandlerinstance->export($data, $suffixinfilename);
  1428. }
  1429. unset($data);
  1430. }
  1431. if ($ident > 0) {
  1432. foreach ($conf->loghandlers as $loghandlerinstance) {
  1433. $loghandlerinstance->setIdent($ident);
  1434. }
  1435. }
  1436. }
  1437. /**
  1438. * Return HTML code to output a button to open a dialog popup box.
  1439. * Such buttons must be included inside a HTML form.
  1440. *
  1441. * @param string $name A name for the html component
  1442. * @param string $label Label of button
  1443. * @param string $buttonstring button string
  1444. * @param string $url Url to open
  1445. * @param string $disabled Disabled text
  1446. * @return string HTML component with button
  1447. */
  1448. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1449. {
  1450. if (strpos($url, '?') > 0) {
  1451. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1452. } else {
  1453. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1454. }
  1455. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1456. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1457. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1458. $out .= '<script type="text/javascript">
  1459. jQuery(document).ready(function () {
  1460. jQuery(".button_'.$name.'").click(function () {
  1461. console.log("Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'")
  1462. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1463. .dialog({
  1464. autoOpen: false,
  1465. modal: true,
  1466. height: (window.innerHeight - 150),
  1467. width: \'80%\',
  1468. title: "'.dol_escape_js($label).'"
  1469. });
  1470. $dialog.dialog(\'open\');
  1471. });
  1472. });
  1473. </script>';
  1474. return $out;
  1475. }
  1476. /**
  1477. * Show tab header of a card
  1478. *
  1479. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1480. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1481. * @param string $title Title
  1482. * @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)
  1483. * @param string $picto Add a picto on tab title
  1484. * @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.
  1485. * @param string $morehtmlright Add more html content on right of tabs title
  1486. * @param string $morecss More Css
  1487. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1488. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1489. * @return void
  1490. * @deprecated Use print dol_get_fiche_head() instead
  1491. */
  1492. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1493. {
  1494. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1495. }
  1496. /**
  1497. * Show tabs of a record
  1498. *
  1499. * @param array $links Array of tabs. Note that label into $links[$i][1] must be already HTML escaped.
  1500. * @param string $active Active tab name
  1501. * @param string $title Title
  1502. * @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)
  1503. * @param string $picto Add a picto on tab title
  1504. * @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.
  1505. * @param string $morehtmlright Add more html content on right of tabs title
  1506. * @param string $morecss More CSS on the link <a>
  1507. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1508. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1509. * @return string
  1510. */
  1511. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1512. {
  1513. global $conf, $langs, $hookmanager;
  1514. // Show title
  1515. $showtitle = 1;
  1516. if (!empty($conf->dol_optimize_smallscreen)) {
  1517. $showtitle = 0;
  1518. }
  1519. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1520. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1521. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1522. }
  1523. // Show right part
  1524. if ($morehtmlright) {
  1525. $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.
  1526. }
  1527. // Show title
  1528. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1529. $limittitle = 30;
  1530. $out .= '<a class="tabTitle">';
  1531. if ($picto) {
  1532. $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1533. }
  1534. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1535. $out .= '</a>';
  1536. }
  1537. // Show tabs
  1538. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1539. $maxkey = -1;
  1540. if (is_array($links) && !empty($links)) {
  1541. $keys = array_keys($links);
  1542. if (count($keys)) {
  1543. $maxkey = max($keys);
  1544. }
  1545. }
  1546. // Show tabs
  1547. // if =0 we don't use the feature
  1548. if (empty($limittoshow)) {
  1549. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1550. }
  1551. if (!empty($conf->dol_optimize_smallscreen)) {
  1552. $limittoshow = 2;
  1553. }
  1554. $displaytab = 0;
  1555. $nbintab = 0;
  1556. $popuptab = 0;
  1557. $outmore = '';
  1558. for ($i = 0; $i <= $maxkey; $i++) {
  1559. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1560. // If active tab is already present
  1561. if ($i >= $limittoshow) {
  1562. $limittoshow--;
  1563. }
  1564. }
  1565. }
  1566. for ($i = 0; $i <= $maxkey; $i++) {
  1567. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1568. $isactive = true;
  1569. } else {
  1570. $isactive = false;
  1571. }
  1572. if ($i < $limittoshow || $isactive) {
  1573. // Output entry with a visible tab
  1574. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
  1575. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1576. if (!empty($links[$i][0])) {
  1577. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1578. } else {
  1579. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1580. }
  1581. } elseif (!empty($links[$i][1])) {
  1582. //print "x $i $active ".$links[$i][2]." z";
  1583. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1584. if (!empty($links[$i][0])) {
  1585. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1586. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  1587. }
  1588. $out .= $links[$i][1];
  1589. if (!empty($links[$i][0])) {
  1590. $out .= '</a>'."\n";
  1591. }
  1592. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1593. $out .= '</div>';
  1594. }
  1595. $out .= '</div>';
  1596. } else {
  1597. // Add entry into the combo popup with the other tabs
  1598. if (!$popuptab) {
  1599. $popuptab = 1;
  1600. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1601. }
  1602. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1603. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1604. if (!empty($links[$i][0])) {
  1605. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1606. } else {
  1607. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1608. }
  1609. } elseif (!empty($links[$i][1])) {
  1610. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1611. $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.
  1612. $outmore .= '</a>'."\n";
  1613. }
  1614. $outmore .= '</div>';
  1615. $nbintab++;
  1616. }
  1617. $displaytab = $i;
  1618. }
  1619. if ($popuptab) {
  1620. $outmore .= '</div>';
  1621. }
  1622. if ($popuptab) { // If there is some tabs not shown
  1623. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1624. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1625. $widthofpopup = 200;
  1626. $tabsname = $moretabssuffix;
  1627. if (empty($tabsname)) {
  1628. $tabsname = str_replace("@", "", $picto);
  1629. }
  1630. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1631. $out .= '<div class="tab"><a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
  1632. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1633. $out .= $outmore;
  1634. $out .= '</div>';
  1635. $out .= '<div></div>';
  1636. $out .= "</div>\n";
  1637. $out .= "<script>";
  1638. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1639. var x = this.offsetLeft, y = this.offsetTop;
  1640. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1641. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1642. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1643. }
  1644. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1645. });
  1646. ";
  1647. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1648. $out .= "</script>";
  1649. }
  1650. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1651. $out .= "</div>\n";
  1652. }
  1653. if (!$notab || $notab == -1 || $notab == -2) {
  1654. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1655. }
  1656. $parameters = array('tabname' => $active, 'out' => $out);
  1657. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1658. if ($reshook > 0) {
  1659. $out = $hookmanager->resPrint;
  1660. }
  1661. return $out;
  1662. }
  1663. /**
  1664. * Show tab footer of a card
  1665. *
  1666. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1667. * @return void
  1668. * @deprecated Use print dol_get_fiche_end() instead
  1669. */
  1670. function dol_fiche_end($notab = 0)
  1671. {
  1672. print dol_get_fiche_end($notab);
  1673. }
  1674. /**
  1675. * Return tab footer of a card
  1676. *
  1677. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1678. * @return string
  1679. */
  1680. function dol_get_fiche_end($notab = 0)
  1681. {
  1682. if (!$notab || $notab == -1) {
  1683. return "\n</div>\n";
  1684. } else {
  1685. return '';
  1686. }
  1687. }
  1688. /**
  1689. * Show tab footer of a card.
  1690. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1691. *
  1692. * @param Object $object Object to show
  1693. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1694. * @param string $morehtml More html content to output just before the nav bar
  1695. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1696. * @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.
  1697. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1698. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1699. * @param string $moreparam More param to add in nav link url.
  1700. * @param int $nodbprefix Do not include DB prefix to forge table name
  1701. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1702. * @param string $morehtmlstatus More html code to show under navigation arrows
  1703. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1704. * @param string $morehtmlright More html code to show before navigation arrows
  1705. * @return void
  1706. */
  1707. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1708. {
  1709. global $conf, $form, $user, $langs, $hookmanager, $action;
  1710. $error = 0;
  1711. $maxvisiblephotos = 1;
  1712. $showimage = 1;
  1713. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1714. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1715. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1716. $showbarcode = 0;
  1717. }
  1718. $modulepart = 'unknown';
  1719. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1720. $modulepart = $object->element;
  1721. } elseif ($object->element == 'member') {
  1722. $modulepart = 'memberphoto';
  1723. } elseif ($object->element == 'user') {
  1724. $modulepart = 'userphoto';
  1725. }
  1726. if (class_exists("Imagick")) {
  1727. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1728. $modulepart = $object->element;
  1729. } elseif ($object->element == 'fichinter') {
  1730. $modulepart = 'ficheinter';
  1731. } elseif ($object->element == 'contrat') {
  1732. $modulepart = 'contract';
  1733. } elseif ($object->element == 'order_supplier') {
  1734. $modulepart = 'supplier_order';
  1735. } elseif ($object->element == 'invoice_supplier') {
  1736. $modulepart = 'supplier_invoice';
  1737. }
  1738. }
  1739. if ($object->element == 'product') {
  1740. $width = 80;
  1741. $cssclass = 'photowithmargin photoref';
  1742. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1743. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1744. if ($conf->browser->layout == 'phone') {
  1745. $maxvisiblephotos = 1;
  1746. }
  1747. if ($showimage) {
  1748. $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>';
  1749. } else {
  1750. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1751. $nophoto = '';
  1752. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1753. } else { // Show no photo link
  1754. $nophoto = '/public/theme/common/nophoto.png';
  1755. $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>';
  1756. }
  1757. }
  1758. } elseif ($object->element == 'ticket') {
  1759. $width = 80;
  1760. $cssclass = 'photoref';
  1761. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1762. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1763. if ($conf->browser->layout == 'phone') {
  1764. $maxvisiblephotos = 1;
  1765. }
  1766. if ($showimage) {
  1767. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1768. if ($object->nbphoto > 0) {
  1769. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1770. } else {
  1771. $showimage = 0;
  1772. }
  1773. }
  1774. if (!$showimage) {
  1775. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1776. $nophoto = '';
  1777. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1778. } else { // Show no photo link
  1779. $nophoto = img_picto('No photo', 'object_ticket');
  1780. $morehtmlleft .= '<!-- No photo to show -->';
  1781. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1782. $morehtmlleft .= $nophoto;
  1783. $morehtmlleft .= '</div></div>';
  1784. }
  1785. }
  1786. } else {
  1787. if ($showimage) {
  1788. if ($modulepart != 'unknown') {
  1789. $phototoshow = '';
  1790. // Check if a preview file is available
  1791. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1792. $objectref = dol_sanitizeFileName($object->ref);
  1793. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1794. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1795. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1796. $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
  1797. } else {
  1798. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1799. }
  1800. if (empty($subdir)) {
  1801. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1802. }
  1803. $filepath = $dir_output.$subdir."/";
  1804. $filepdf = $filepath.$objectref.".pdf";
  1805. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1806. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1807. $fileimage = $filepdf.'_preview.png';
  1808. $relativepathimage = $relativepath.'_preview.png';
  1809. $pdfexists = file_exists($filepdf);
  1810. // If PDF file exists
  1811. if ($pdfexists) {
  1812. // Conversion du PDF en image png si fichier png non existant
  1813. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1814. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1815. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1816. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1817. if ($ret < 0) {
  1818. $error++;
  1819. }
  1820. }
  1821. }
  1822. }
  1823. if ($pdfexists && !$error) {
  1824. $heightforphotref = 80;
  1825. if (!empty($conf->dol_optimize_smallscreen)) {
  1826. $heightforphotref = 60;
  1827. }
  1828. // If the preview file is found
  1829. if (file_exists($fileimage)) {
  1830. $phototoshow = '<div class="photoref">';
  1831. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1832. $phototoshow .= '</div>';
  1833. }
  1834. }
  1835. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1836. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  1837. }
  1838. if ($phototoshow) {
  1839. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1840. $morehtmlleft .= $phototoshow;
  1841. $morehtmlleft .= '</div>';
  1842. }
  1843. }
  1844. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1845. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1846. if ($object->element == 'action') {
  1847. $width = 80;
  1848. $cssclass = 'photorefcenter';
  1849. $nophoto = img_picto('No photo', 'title_agenda');
  1850. } else {
  1851. $width = 14;
  1852. $cssclass = 'photorefcenter';
  1853. $picto = $object->picto;
  1854. if ($object->element == 'project' && !$object->public) {
  1855. $picto = 'project'; // instead of projectpub
  1856. }
  1857. $nophoto = img_picto('No photo', 'object_'.$picto);
  1858. }
  1859. $morehtmlleft .= '<!-- No photo to show -->';
  1860. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1861. $morehtmlleft .= $nophoto;
  1862. $morehtmlleft .= '</div></div>';
  1863. $morehtmlleft .= '</div>';
  1864. }
  1865. }
  1866. }
  1867. if ($showbarcode) {
  1868. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref').'</div>';
  1869. }
  1870. if ($object->element == 'societe') {
  1871. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1872. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1873. } else {
  1874. $morehtmlstatus .= $object->getLibStatut(6);
  1875. }
  1876. } elseif ($object->element == 'product') {
  1877. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1878. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1879. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1880. } else {
  1881. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1882. }
  1883. $morehtmlstatus .= ' &nbsp; ';
  1884. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1885. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1886. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1887. } else {
  1888. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1889. }
  1890. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  1891. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1892. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1893. $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1894. }
  1895. $morehtmlstatus .= $tmptxt;
  1896. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  1897. if ($object->statut == 0) {
  1898. $morehtmlstatus .= $object->getLibStatut(5);
  1899. } else {
  1900. $morehtmlstatus .= $object->getLibStatut(4);
  1901. }
  1902. } elseif ($object->element == 'facturerec') {
  1903. if ($object->frequency == 0) {
  1904. $morehtmlstatus .= $object->getLibStatut(2);
  1905. } else {
  1906. $morehtmlstatus .= $object->getLibStatut(5);
  1907. }
  1908. } elseif ($object->element == 'project_task') {
  1909. $object->fk_statut = 1;
  1910. if ($object->progress > 0) {
  1911. $object->fk_statut = 2;
  1912. }
  1913. if ($object->progress >= 100) {
  1914. $object->fk_statut = 3;
  1915. }
  1916. $tmptxt = $object->getLibStatut(5);
  1917. $morehtmlstatus .= $tmptxt; // No status on task
  1918. } else { // Generic case
  1919. $tmptxt = $object->getLibStatut(6);
  1920. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1921. $tmptxt = $object->getLibStatut(5);
  1922. }
  1923. $morehtmlstatus .= $tmptxt;
  1924. }
  1925. // Add if object was dispatched "into accountancy"
  1926. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  1927. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  1928. if (method_exists($object, 'getVentilExportCompta')) {
  1929. $accounted = $object->getVentilExportCompta();
  1930. $langs->load("accountancy");
  1931. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1932. }
  1933. }
  1934. // Add alias for thirdparty
  1935. if (!empty($object->name_alias)) {
  1936. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1937. }
  1938. // Add label
  1939. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  1940. if (!empty($object->label)) {
  1941. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1942. }
  1943. }
  1944. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  1945. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1946. if ($moreaddress) {
  1947. $morehtmlref .= '<div class="refidno">';
  1948. $morehtmlref .= $moreaddress;
  1949. $morehtmlref .= '</div>';
  1950. }
  1951. }
  1952. 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)) {
  1953. $morehtmlref .= '<div style="clear: both;"></div>';
  1954. $morehtmlref .= '<div class="refidno">';
  1955. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1956. $morehtmlref .= '</div>';
  1957. }
  1958. $parameters=array('morehtmlref'=>$morehtmlref);
  1959. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  1960. if ($reshook < 0) {
  1961. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1962. } elseif (empty($reshook)) {
  1963. $morehtmlref .= $hookmanager->resPrint;
  1964. } elseif ($reshook > 0) {
  1965. $morehtmlref = $hookmanager->resPrint;
  1966. }
  1967. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1968. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1969. print '</div>';
  1970. print '<div class="underrefbanner clearboth"></div>';
  1971. }
  1972. /**
  1973. * Show a string with the label tag dedicated to the HTML edit field.
  1974. *
  1975. * @param string $langkey Translation key
  1976. * @param string $fieldkey Key of the html select field the text refers to
  1977. * @param int $fieldrequired 1=Field is mandatory
  1978. * @return string
  1979. * @deprecated Form::editfieldkey
  1980. */
  1981. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1982. {
  1983. global $langs;
  1984. $ret = '';
  1985. if ($fieldrequired) {
  1986. $ret .= '<span class="fieldrequired">';
  1987. }
  1988. $ret .= '<label for="'.$fieldkey.'">';
  1989. $ret .= $langs->trans($langkey);
  1990. $ret .= '</label>';
  1991. if ($fieldrequired) {
  1992. $ret .= '</span>';
  1993. }
  1994. return $ret;
  1995. }
  1996. /**
  1997. * Return string to add class property on html element with pair/impair.
  1998. *
  1999. * @param string $var 0 or 1
  2000. * @param string $moreclass More class to add
  2001. * @return string String to add class onto HTML element
  2002. */
  2003. function dol_bc($var, $moreclass = '')
  2004. {
  2005. global $bc;
  2006. $ret = ' '.$bc[$var];
  2007. if ($moreclass) {
  2008. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2009. }
  2010. return $ret;
  2011. }
  2012. /**
  2013. * Return a formated address (part address/zip/town/state) according to country rules.
  2014. * See https://en.wikipedia.org/wiki/Address
  2015. *
  2016. * @param Object $object A company or contact object
  2017. * @param int $withcountry 1=Add country into address string
  2018. * @param string $sep Separator to use to build string
  2019. * @param Translate $outputlangs Object lang that contains language for text translation.
  2020. * @param int $mode 0=Standard output, 1=Remove address
  2021. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2022. * @return string Formated string
  2023. * @see dol_print_address()
  2024. */
  2025. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2026. {
  2027. global $conf, $langs;
  2028. $ret = '';
  2029. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2030. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2031. // Address
  2032. if (empty($mode)) {
  2033. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2034. }
  2035. // Zip/Town/State
  2036. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2037. // US: title firstname name \n address lines \n town, state, zip \n country
  2038. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2039. $ret .= ($ret ? $sep : '').$town;
  2040. if (!empty($object->state)) {
  2041. $ret .= ($ret ? ", " : '').$object->state;
  2042. }
  2043. if (!empty($object->zip)) {
  2044. $ret .= ($ret ? ", " : '').$object->zip;
  2045. }
  2046. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2047. // UK: title firstname name \n address lines \n town state \n zip \n country
  2048. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2049. $ret .= ($ret ? $sep : '').$town;
  2050. if (!empty($object->state)) {
  2051. $ret .= ($ret ? ", " : '').$object->state;
  2052. }
  2053. if (!empty($object->zip)) {
  2054. $ret .= ($ret ? $sep : '').$object->zip;
  2055. }
  2056. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2057. // ES: title firstname name \n address lines \n zip town \n state \n country
  2058. $ret .= ($ret ? $sep : '').$object->zip;
  2059. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2060. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2061. if (!empty($object->state)) {
  2062. $ret .= "\n".$object->state;
  2063. }
  2064. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2065. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2066. // See https://www.sljfaq.org/afaq/addresses.html
  2067. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2068. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2069. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2070. // IT: title firstname name\n address lines \n zip town state_code \n country
  2071. $ret .= ($ret ? $sep : '').$object->zip;
  2072. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2073. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2074. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2075. } else {
  2076. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2077. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2078. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2079. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2080. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2081. $ret .= ($ret ? ", " : '').$object->state;
  2082. }
  2083. }
  2084. if (!is_object($outputlangs)) {
  2085. $outputlangs = $langs;
  2086. }
  2087. if ($withcountry) {
  2088. $langs->load("dict");
  2089. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2090. }
  2091. return $ret;
  2092. }
  2093. /**
  2094. * Format a string.
  2095. *
  2096. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2097. * @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)
  2098. * @param int $is_gmt See comment of timestamp parameter
  2099. * @return string A formatted string
  2100. */
  2101. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2102. {
  2103. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2104. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2105. } else {
  2106. return 'Error date into a not supported range';
  2107. }
  2108. }
  2109. /**
  2110. * Output date in a string format according to outputlangs (or langs if not defined).
  2111. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2112. *
  2113. * @param int $time GM Timestamps date
  2114. * @param string $format Output date format (tag of strftime function)
  2115. * "%d %b %Y",
  2116. * "%d/%m/%Y %H:%M",
  2117. * "%d/%m/%Y %H:%M:%S",
  2118. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2119. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2120. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2121. * false or 'tzserver' => output string is for local PHP server TZ usage
  2122. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2123. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  2124. * @param Translate $outputlangs Object lang that contains language for text translation.
  2125. * @param boolean $encodetooutput false=no convert into output pagecode
  2126. * @return string Formated date or '' if time is null
  2127. *
  2128. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2129. */
  2130. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2131. {
  2132. global $conf, $langs;
  2133. // If date undefined or "", we return ""
  2134. if (dol_strlen($time) == 0) {
  2135. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2136. }
  2137. if ($tzoutput === 'auto') {
  2138. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2139. }
  2140. // Clean parameters
  2141. $to_gmt = false;
  2142. $offsettz = $offsetdst = 0;
  2143. if ($tzoutput) {
  2144. $to_gmt = true; // For backward compatibility
  2145. if (is_string($tzoutput)) {
  2146. if ($tzoutput == 'tzserver') {
  2147. $to_gmt = false;
  2148. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2149. $offsettz = 0; // Timezone offset with server timezone, so 0
  2150. $offsetdst = 0; // Dst offset with server timezone, so 0
  2151. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2152. $to_gmt = true;
  2153. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2154. if (class_exists('DateTimeZone')) {
  2155. $user_date_tz = new DateTimeZone($offsettzstring);
  2156. $user_dt = new DateTime();
  2157. $user_dt->setTimezone($user_date_tz);
  2158. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2159. $offsettz = $user_dt->getOffset();
  2160. } else { // old method (The 'tzuser' was processed like the 'tzuserrel')
  2161. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2162. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2163. }
  2164. }
  2165. }
  2166. }
  2167. if (!is_object($outputlangs)) {
  2168. $outputlangs = $langs;
  2169. }
  2170. if (!$format) {
  2171. $format = 'daytextshort';
  2172. }
  2173. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2174. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2175. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2176. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2177. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2178. if ($formatwithoutreduce != $format) {
  2179. $format = $formatwithoutreduce;
  2180. $reduceformat = 1;
  2181. } // so format 'dayreduceformat' is processed like day
  2182. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2183. // TODO Add format daysmallyear and dayhoursmallyear
  2184. if ($format == 'day') {
  2185. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2186. } elseif ($format == 'hour') {
  2187. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2188. } elseif ($format == 'hourduration') {
  2189. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2190. } elseif ($format == 'daytext') {
  2191. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2192. } elseif ($format == 'daytextshort') {
  2193. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2194. } elseif ($format == 'dayhour') {
  2195. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2196. } elseif ($format == 'dayhoursec') {
  2197. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2198. } elseif ($format == 'dayhourtext') {
  2199. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2200. } elseif ($format == 'dayhourtextshort') {
  2201. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2202. } elseif ($format == 'dayhourlog') {
  2203. // Format not sensitive to language
  2204. $format = '%Y%m%d%H%M%S';
  2205. } elseif ($format == 'dayhourldap') {
  2206. $format = '%Y%m%d%H%M%SZ';
  2207. } elseif ($format == 'dayhourxcard') {
  2208. $format = '%Y%m%dT%H%M%SZ';
  2209. } elseif ($format == 'dayxcard') {
  2210. $format = '%Y%m%d';
  2211. } elseif ($format == 'dayrfc') {
  2212. $format = '%Y-%m-%d'; // DATE_RFC3339
  2213. } elseif ($format == 'dayhourrfc') {
  2214. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2215. } elseif ($format == 'standard') {
  2216. $format = '%Y-%m-%d %H:%M:%S';
  2217. }
  2218. if ($reduceformat) {
  2219. $format = str_replace('%Y', '%y', $format);
  2220. $format = str_replace('yyyy', 'yy', $format);
  2221. }
  2222. // Clean format
  2223. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2224. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2225. $format = str_replace('%b', '__b__', $format);
  2226. $format = str_replace('%B', '__B__', $format);
  2227. }
  2228. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2229. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2230. $format = str_replace('%a', '__a__', $format);
  2231. $format = str_replace('%A', '__A__', $format);
  2232. }
  2233. // Analyze date
  2234. $reg = array();
  2235. 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
  2236. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2237. return '';
  2238. } 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
  2239. // This part of code should not be used anymore.
  2240. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2241. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2242. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2243. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2244. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2245. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2246. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2247. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2248. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2249. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2250. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2251. } else {
  2252. // Date is a timestamps
  2253. if ($time < 100000000000) { // Protection against bad date values
  2254. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2255. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2256. } else {
  2257. $ret = 'Bad value '.$time.' for date';
  2258. }
  2259. }
  2260. if (preg_match('/__b__/i', $format)) {
  2261. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2262. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2263. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2264. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2265. if ($encodetooutput) {
  2266. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2267. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2268. } else {
  2269. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2270. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2271. }
  2272. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2273. $ret = str_replace('__b__', $monthtextshort, $ret);
  2274. $ret = str_replace('__B__', $monthtext, $ret);
  2275. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2276. //return $ret;
  2277. }
  2278. if (preg_match('/__a__/i', $format)) {
  2279. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2280. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2281. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2282. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2283. $ret = str_replace('__A__', $dayweek, $ret);
  2284. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2285. }
  2286. return $ret;
  2287. }
  2288. /**
  2289. * Return an array with locale date info.
  2290. * WARNING: This function use PHP server timezone by default to return locale informations.
  2291. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2292. *
  2293. * @param int $timestamp Timestamp
  2294. * @param boolean $fast Fast mode. deprecated.
  2295. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2296. * @return array Array of informations
  2297. * 'seconds' => $secs,
  2298. * 'minutes' => $min,
  2299. * 'hours' => $hour,
  2300. * 'mday' => $day,
  2301. * 'wday' => $dow, 0=sunday, 6=saturday
  2302. * 'mon' => $month,
  2303. * 'year' => $year,
  2304. * 'yday' => floor($secsInYear/$_day_power)
  2305. * '0' => original timestamp
  2306. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2307. */
  2308. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2309. {
  2310. //$datetimeobj = new DateTime('@'.$timestamp);
  2311. $datetimeobj = new DateTime();
  2312. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2313. if ($forcetimezone) {
  2314. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2315. }
  2316. $arrayinfo = array(
  2317. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2318. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2319. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2320. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2321. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2322. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2323. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2324. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2325. '0'=>$timestamp
  2326. );
  2327. return $arrayinfo;
  2328. }
  2329. /**
  2330. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2331. * Replace function mktime not available under Windows if year < 1970
  2332. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2333. *
  2334. * @param int $hour Hour (can be -1 for undefined)
  2335. * @param int $minute Minute (can be -1 for undefined)
  2336. * @param int $second Second (can be -1 for undefined)
  2337. * @param int $month Month (1 to 12)
  2338. * @param int $day Day (1 to 31)
  2339. * @param int $year Year
  2340. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2341. * False or 0 or 'tzserver' = local to server TZ
  2342. * 'auto'
  2343. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2344. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user into a GMT date.
  2345. * 'tz,TimeZone' = use specified timezone
  2346. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2347. * @return int|string Date as a timestamp, '' or false if error
  2348. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2349. */
  2350. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2351. {
  2352. global $conf;
  2353. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2354. //print 'gm:'.$gm.' gm==auto:'.($gm == 'auto').'<br>';
  2355. if ($gm === 'auto') {
  2356. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2357. }
  2358. // Clean parameters
  2359. if ($hour == -1 || empty($hour)) {
  2360. $hour = 0;
  2361. }
  2362. if ($minute == -1 || empty($minute)) {
  2363. $minute = 0;
  2364. }
  2365. if ($second == -1 || empty($second)) {
  2366. $second = 0;
  2367. }
  2368. // Check parameters
  2369. if ($check) {
  2370. if (!$month || !$day) {
  2371. return '';
  2372. }
  2373. if ($day > 31) {
  2374. return '';
  2375. }
  2376. if ($month > 12) {
  2377. return '';
  2378. }
  2379. if ($hour < 0 || $hour > 24) {
  2380. return '';
  2381. }
  2382. if ($minute < 0 || $minute > 60) {
  2383. return '';
  2384. }
  2385. if ($second < 0 || $second > 60) {
  2386. return '';
  2387. }
  2388. }
  2389. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2390. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2391. $localtz = new DateTimeZone($default_timezone);
  2392. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2393. // We use dol_tz_string first because it is more reliable.
  2394. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2395. try {
  2396. $localtz = new DateTimeZone($default_timezone);
  2397. } catch (Exception $e) {
  2398. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2399. $default_timezone = @date_default_timezone_get();
  2400. }
  2401. } elseif (strrpos($gm, "tz,") !== false) {
  2402. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2403. try {
  2404. $localtz = new DateTimeZone($timezone);
  2405. } catch (Exception $e) {
  2406. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2407. }
  2408. }
  2409. if (empty($localtz)) {
  2410. $localtz = new DateTimeZone('UTC');
  2411. }
  2412. //var_dump($localtz);
  2413. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2414. $dt = new DateTime(null, $localtz);
  2415. $dt->setDate((int) $year, (int) $month, (int) $day);
  2416. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2417. $date = $dt->getTimestamp(); // should include daylight saving time
  2418. //var_dump($date);
  2419. return $date;
  2420. }
  2421. /**
  2422. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2423. *
  2424. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2425. * 'gmt' => we return GMT timestamp,
  2426. * 'tzserver' => we add the PHP server timezone
  2427. * 'tzref' => we add the company timezone. Not implemented.
  2428. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2429. * @return int $date Timestamp
  2430. */
  2431. function dol_now($mode = 'auto')
  2432. {
  2433. $ret = 0;
  2434. if ($mode === 'auto') {
  2435. $mode = 'gmt';
  2436. }
  2437. if ($mode == 'gmt') {
  2438. $ret = time(); // Time for now at greenwich.
  2439. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2440. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2441. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2442. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2443. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2444. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2445. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2446. // $ret=dol_now('gmt')+($tzsecond*3600);
  2447. //}
  2448. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2449. // Time for now with user timezone added
  2450. //print 'time: '.time();
  2451. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2452. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2453. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2454. }
  2455. return $ret;
  2456. }
  2457. /**
  2458. * Return string with formated size
  2459. *
  2460. * @param int $size Size to print
  2461. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2462. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2463. * @return string Link
  2464. */
  2465. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2466. {
  2467. global $conf, $langs;
  2468. $level = 1024;
  2469. if (!empty($conf->dol_optimize_smallscreen)) {
  2470. $shortunit = 1;
  2471. }
  2472. // Set value text
  2473. if (empty($shortvalue) || $size < ($level * 10)) {
  2474. $ret = $size;
  2475. $textunitshort = $langs->trans("b");
  2476. $textunitlong = $langs->trans("Bytes");
  2477. } else {
  2478. $ret = round($size / $level, 0);
  2479. $textunitshort = $langs->trans("Kb");
  2480. $textunitlong = $langs->trans("KiloBytes");
  2481. }
  2482. // Use long or short text unit
  2483. if (empty($shortunit)) {
  2484. $ret .= ' '.$textunitlong;
  2485. } else {
  2486. $ret .= ' '.$textunitshort;
  2487. }
  2488. return $ret;
  2489. }
  2490. /**
  2491. * Show Url link
  2492. *
  2493. * @param string $url Url to show
  2494. * @param string $target Target for link
  2495. * @param int $max Max number of characters to show
  2496. * @param int $withpicto With picto
  2497. * @return string HTML Link
  2498. */
  2499. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2500. {
  2501. global $langs;
  2502. if (empty($url)) {
  2503. return '';
  2504. }
  2505. $link = '<a href="';
  2506. if (!preg_match('/^http/i', $url)) {
  2507. $link .= 'http://';
  2508. }
  2509. $link .= $url;
  2510. $link .= '"';
  2511. if ($target) {
  2512. $link .= ' target="'.$target.'"';
  2513. }
  2514. $link .= '>';
  2515. if (!preg_match('/^http/i', $url)) {
  2516. $link .= 'http://';
  2517. }
  2518. $link .= dol_trunc($url, $max);
  2519. $link .= '</a>';
  2520. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2521. }
  2522. /**
  2523. * Show EMail link formatted for HTML output.
  2524. *
  2525. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2526. * @param int $cid Id of contact if known
  2527. * @param int $socid Id of third party if known
  2528. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2529. * @param int $max Max number of characters to show
  2530. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2531. * @param int $withpicto Show picto
  2532. * @return string HTML Link
  2533. */
  2534. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2535. {
  2536. global $conf, $user, $langs, $hookmanager;
  2537. $newemail = dol_escape_htmltag($email);
  2538. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2539. $withpicto = 0;
  2540. }
  2541. if (empty($email)) {
  2542. return '&nbsp;';
  2543. }
  2544. if (!empty($addlink)) {
  2545. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2546. if (!preg_match('/^mailto:/i', $email)) {
  2547. $newemail .= 'mailto:';
  2548. }
  2549. $newemail .= $email;
  2550. $newemail .= '">';
  2551. $newemail .= dol_trunc($email, $max);
  2552. $newemail .= '</a>';
  2553. if ($showinvalid && !isValidEmail($email)) {
  2554. $langs->load("errors");
  2555. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2556. }
  2557. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2558. $type = 'AC_EMAIL';
  2559. $link = '';
  2560. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2561. $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>';
  2562. }
  2563. if ($link) {
  2564. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2565. }
  2566. }
  2567. } else {
  2568. if ($showinvalid && !isValidEmail($email)) {
  2569. $langs->load("errors");
  2570. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2571. }
  2572. }
  2573. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2574. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2575. //$rep .= '</div>';
  2576. if ($hookmanager) {
  2577. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2578. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2579. if ($reshook > 0) {
  2580. $rep = '';
  2581. }
  2582. $rep .= $hookmanager->resPrint;
  2583. }
  2584. return $rep;
  2585. }
  2586. /**
  2587. * Get array of social network dictionary
  2588. *
  2589. * @return array Array of Social Networks Dictionary
  2590. */
  2591. function getArrayOfSocialNetworks()
  2592. {
  2593. global $conf, $db;
  2594. $socialnetworks = array();
  2595. // Enable caching of array
  2596. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2597. $cachekey = 'socialnetworks_' . $conf->entity;
  2598. $dataretrieved = dol_getcache($cachekey);
  2599. if (!is_null($dataretrieved)) {
  2600. $socialnetworks = $dataretrieved;
  2601. } else {
  2602. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2603. $sql .= " WHERE entity=".$conf->entity;
  2604. $resql = $db->query($sql);
  2605. if ($resql) {
  2606. while ($obj = $db->fetch_object($resql)) {
  2607. $socialnetworks[$obj->code] = array(
  2608. 'rowid' => $obj->rowid,
  2609. 'label' => $obj->label,
  2610. 'url' => $obj->url,
  2611. 'icon' => $obj->icon,
  2612. 'active' => $obj->active,
  2613. );
  2614. }
  2615. }
  2616. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2617. }
  2618. return $socialnetworks;
  2619. }
  2620. /**
  2621. * Show social network link
  2622. *
  2623. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2624. * @param int $cid Id of contact if known
  2625. * @param int $socid Id of third party if known
  2626. * @param string $type 'skype','facebook',...
  2627. * @param array $dictsocialnetworks socialnetworks availables
  2628. * @return string HTML Link
  2629. */
  2630. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2631. {
  2632. global $conf, $user, $langs;
  2633. $htmllink = $value;
  2634. if (empty($value)) {
  2635. return '&nbsp;';
  2636. }
  2637. if (!empty($type)) {
  2638. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2639. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2640. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2641. if ($type == 'skype') {
  2642. $htmllink .= $value;
  2643. $htmllink .= '&nbsp;';
  2644. $htmllink .= '<a href="skype:';
  2645. $htmllink .= $value;
  2646. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2647. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2648. $htmllink .= '</a><a href="skype:';
  2649. $htmllink .= $value;
  2650. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2651. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2652. $htmllink .= '</a>';
  2653. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2654. $addlink = 'AC_SKYPE';
  2655. $link = '';
  2656. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2657. $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>';
  2658. }
  2659. $htmllink .= ($link ? ' '.$link : '');
  2660. }
  2661. } else {
  2662. if (!empty($dictsocialnetworks[$type]['url'])) {
  2663. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2664. $htmllink .= '&nbsp;<a href="'.$link.'" target="_blank" rel="noopener noreferrer">'.$value.'</a>';
  2665. } else {
  2666. $htmllink .= $value;
  2667. }
  2668. }
  2669. $htmllink .= '</div>';
  2670. } else {
  2671. $langs->load("errors");
  2672. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2673. }
  2674. return $htmllink;
  2675. }
  2676. /**
  2677. * Format phone numbers according to country
  2678. *
  2679. * @param string $phone Phone number to format
  2680. * @param string $countrycode Country code to use for formatting
  2681. * @param int $cid Id of contact if known
  2682. * @param int $socid Id of third party if known
  2683. * @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)
  2684. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2685. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2686. * @param string $titlealt Text to show on alt
  2687. * @param int $adddivfloat Add div float around phone.
  2688. * @return string Formated phone number
  2689. */
  2690. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2691. {
  2692. global $conf, $user, $langs, $mysoc, $hookmanager;
  2693. // Clean phone parameter
  2694. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2695. if (empty($phone)) {
  2696. return '';
  2697. }
  2698. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2699. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2700. }
  2701. if (empty($countrycode)) {
  2702. $countrycode = $mysoc->country_code;
  2703. }
  2704. // Short format for small screens
  2705. if ($conf->dol_optimize_smallscreen) {
  2706. $separ = '';
  2707. }
  2708. $newphone = $phone;
  2709. if (strtoupper($countrycode) == "FR") {
  2710. // France
  2711. if (dol_strlen($phone) == 10) {
  2712. $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);
  2713. } elseif (dol_strlen($phone) == 7) {
  2714. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2715. } elseif (dol_strlen($phone) == 9) {
  2716. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2717. } elseif (dol_strlen($phone) == 11) {
  2718. $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);
  2719. } elseif (dol_strlen($phone) == 12) {
  2720. $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);
  2721. }
  2722. } elseif (strtoupper($countrycode) == "CA") {
  2723. if (dol_strlen($phone) == 10) {
  2724. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2725. }
  2726. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2727. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2728. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2729. }
  2730. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2731. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2732. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2733. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2734. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2735. }
  2736. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2737. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2738. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2739. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2740. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2741. }
  2742. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2743. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2744. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2745. }
  2746. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2747. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2748. $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);
  2749. }
  2750. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2751. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2752. $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);
  2753. }
  2754. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2755. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2756. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2757. }
  2758. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2759. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2760. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2761. }
  2762. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2763. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2764. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2765. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2766. $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);
  2767. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2768. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2769. }
  2770. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2771. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2772. $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);
  2773. }
  2774. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2775. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2776. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2777. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2778. $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);
  2779. }
  2780. } elseif (strtoupper($countrycode) == "MU") {
  2781. //Maurice
  2782. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  2783. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2784. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  2785. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2786. }
  2787. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  2788. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  2789. $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);
  2790. }
  2791. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  2792. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  2793. $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);
  2794. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  2795. $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);
  2796. }
  2797. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  2798. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  2799. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2800. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  2801. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2802. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  2803. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2804. }
  2805. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  2806. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  2807. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2808. }
  2809. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  2810. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  2811. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2812. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  2813. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2814. }
  2815. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  2816. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  2817. $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);
  2818. }
  2819. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  2820. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  2821. $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);
  2822. }
  2823. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  2824. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  2825. $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);
  2826. }
  2827. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  2828. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  2829. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2830. }
  2831. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  2832. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
  2833. $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);
  2834. }
  2835. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  2836. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  2837. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2838. }
  2839. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  2840. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  2841. $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);
  2842. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  2843. $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);
  2844. }
  2845. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  2846. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  2847. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2848. }
  2849. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  2850. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2851. $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);
  2852. }
  2853. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  2854. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2855. $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);
  2856. }
  2857. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  2858. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2859. $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);
  2860. }
  2861. } elseif (strtoupper($countrycode) == "IT") {//Italie
  2862. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  2863. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2864. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  2865. $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);
  2866. }
  2867. } elseif (strtoupper($countrycode) == "AU") {
  2868. //Australie
  2869. if (dol_strlen($phone) == 12) {
  2870. //ex: +61_A_BCDE_FGHI
  2871. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2872. }
  2873. }
  2874. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2875. 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
  2876. $newphoneform = $newphone;
  2877. $newphone = '<a href="tel:'.$phone.'"';
  2878. $newphone .= '>'.$newphoneform.'</a>';
  2879. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  2880. if (empty($user->clicktodial_loaded)) {
  2881. $user->fetch_clicktodial();
  2882. }
  2883. // Define urlmask
  2884. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2885. if (!empty($conf->global->CLICKTODIAL_URL)) {
  2886. $urlmask = $conf->global->CLICKTODIAL_URL;
  2887. }
  2888. if (!empty($user->clicktodial_url)) {
  2889. $urlmask = $user->clicktodial_url;
  2890. }
  2891. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2892. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2893. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2894. // This line is for backward compatibility
  2895. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2896. // Thoose lines are for substitution
  2897. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2898. '__PHONETO__'=>urlencode($phone),
  2899. '__LOGIN__'=>$clicktodial_login,
  2900. '__PASS__'=>$clicktodial_password);
  2901. $url = make_substitutions($url, $substitarray);
  2902. $newphonesav = $newphone;
  2903. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  2904. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  2905. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  2906. $newphone .= '>'.$newphonesav.'</a>';
  2907. } else {
  2908. // Old method
  2909. $newphone = '<a href="'.$url.'"';
  2910. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  2911. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  2912. }
  2913. $newphone .= '>'.$newphonesav.'</a>';
  2914. }
  2915. }
  2916. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2917. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2918. $type = 'AC_TEL';
  2919. $link = '';
  2920. if ($addlink == 'AC_FAX') {
  2921. $type = 'AC_FAX';
  2922. }
  2923. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  2924. $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>';
  2925. }
  2926. if ($link) {
  2927. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2928. }
  2929. }
  2930. }
  2931. if (empty($titlealt)) {
  2932. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2933. }
  2934. $rep = '';
  2935. if ($hookmanager) {
  2936. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2937. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2938. $rep .= $hookmanager->resPrint;
  2939. }
  2940. if (empty($reshook)) {
  2941. $picto = '';
  2942. if ($withpicto) {
  2943. if ($withpicto == 'fax') {
  2944. $picto = 'phoning_fax';
  2945. } elseif ($withpicto == 'phone') {
  2946. $picto = 'phoning';
  2947. } elseif ($withpicto == 'mobile') {
  2948. $picto = 'phoning_mobile';
  2949. } else {
  2950. $picto = '';
  2951. }
  2952. }
  2953. if ($adddivfloat) {
  2954. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2955. } else {
  2956. $rep .= '<span style="margin-right: 10px;">';
  2957. }
  2958. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2959. if ($adddivfloat) {
  2960. $rep .= '</div>';
  2961. } else {
  2962. $rep .= '</span>';
  2963. }
  2964. }
  2965. return $rep;
  2966. }
  2967. /**
  2968. * Return an IP formated to be shown on screen
  2969. *
  2970. * @param string $ip IP
  2971. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2972. * @return string Formated IP, with country if GeoIP module is enabled
  2973. */
  2974. function dol_print_ip($ip, $mode = 0)
  2975. {
  2976. global $conf, $langs;
  2977. $ret = '';
  2978. if (empty($mode)) {
  2979. $ret .= $ip;
  2980. }
  2981. if ($mode != 2) {
  2982. $countrycode = dolGetCountryCodeFromIp($ip);
  2983. if ($countrycode) { // If success, countrycode is us, fr, ...
  2984. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  2985. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2986. } else {
  2987. $ret .= ' ('.$countrycode.')';
  2988. }
  2989. } else {
  2990. // Nothing
  2991. }
  2992. }
  2993. return $ret;
  2994. }
  2995. /**
  2996. * Return the IP of remote user.
  2997. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2998. * Then HTTP_CLIENT_IP if defined (rare)
  2999. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3000. *
  3001. * @return string Ip of remote user.
  3002. */
  3003. function getUserRemoteIP()
  3004. {
  3005. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3006. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3007. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3008. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3009. } else {
  3010. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3011. }
  3012. } else {
  3013. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3014. }
  3015. } else {
  3016. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3017. }
  3018. return $ip;
  3019. }
  3020. /**
  3021. * Return if we are using a HTTPS connexion
  3022. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3023. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3024. * Then HTTP_X_FORWARDED_SSL
  3025. *
  3026. * @return boolean True if user is using HTTPS
  3027. */
  3028. function isHTTPS()
  3029. {
  3030. $isSecure = false;
  3031. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3032. $isSecure = true;
  3033. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
  3034. $isSecure = true;
  3035. }
  3036. return $isSecure;
  3037. }
  3038. /**
  3039. * Return a country code from IP. Empty string if not found.
  3040. *
  3041. * @param string $ip IP
  3042. * @return string Country code ('us', 'fr', ...)
  3043. */
  3044. function dolGetCountryCodeFromIp($ip)
  3045. {
  3046. global $conf;
  3047. $countrycode = '';
  3048. if (!empty($conf->geoipmaxmind->enabled)) {
  3049. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3050. //$ip='24.24.24.24';
  3051. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3052. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3053. $geoip = new DolGeoIP('country', $datafile);
  3054. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3055. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3056. }
  3057. return $countrycode;
  3058. }
  3059. /**
  3060. * Return country code for current user.
  3061. * If software is used inside a local network, detection may fails (we need a public ip)
  3062. *
  3063. * @return string Country code (fr, es, it, us, ...)
  3064. */
  3065. function dol_user_country()
  3066. {
  3067. global $conf, $langs, $user;
  3068. //$ret=$user->xxx;
  3069. $ret = '';
  3070. if (!empty($conf->geoipmaxmind->enabled)) {
  3071. $ip = getUserRemoteIP();
  3072. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3073. //$ip='24.24.24.24';
  3074. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3075. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3076. $geoip = new DolGeoIP('country', $datafile);
  3077. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3078. $ret = $countrycode;
  3079. }
  3080. return $ret;
  3081. }
  3082. /**
  3083. * Format address string
  3084. *
  3085. * @param string $address Address string, already formatted with dol_format_address()
  3086. * @param int $htmlid Html ID (for example 'gmap')
  3087. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3088. * @param int $id Id of object
  3089. * @param int $noprint No output. Result is the function return
  3090. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3091. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3092. * @see dol_format_address()
  3093. */
  3094. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3095. {
  3096. global $conf, $user, $langs, $hookmanager;
  3097. $out = '';
  3098. if ($address) {
  3099. if ($hookmanager) {
  3100. $parameters = array('element' => $element, 'id' => $id);
  3101. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3102. $out .= $hookmanager->resPrint;
  3103. }
  3104. if (empty($reshook)) {
  3105. if (empty($charfornl)) {
  3106. $out .= nl2br($address);
  3107. } else {
  3108. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3109. }
  3110. // TODO Remove this block, we can add this using the hook now
  3111. $showgmap = $showomap = 0;
  3112. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3113. $showgmap = 1;
  3114. }
  3115. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3116. $showgmap = 1;
  3117. }
  3118. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3119. $showgmap = 1;
  3120. }
  3121. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3122. $showomap = 1;
  3123. }
  3124. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3125. $showomap = 1;
  3126. }
  3127. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3128. $showomap = 1;
  3129. }
  3130. if ($showgmap) {
  3131. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3132. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3133. }
  3134. if ($showomap) {
  3135. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3136. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3137. }
  3138. }
  3139. }
  3140. if ($noprint) {
  3141. return $out;
  3142. } else {
  3143. print $out;
  3144. }
  3145. }
  3146. /**
  3147. * Return true if email syntax is ok.
  3148. *
  3149. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3150. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3151. * @return boolean true if email syntax is OK, false if KO or empty string
  3152. * @see isValidMXRecord()
  3153. */
  3154. function isValidEmail($address, $acceptsupervisorkey = 0)
  3155. {
  3156. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3157. return true;
  3158. }
  3159. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3160. return true;
  3161. }
  3162. return false;
  3163. }
  3164. /**
  3165. * Return if the domain name has a valid MX record.
  3166. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3167. *
  3168. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3169. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3170. * @see isValidEmail()
  3171. */
  3172. function isValidMXRecord($domain)
  3173. {
  3174. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3175. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3176. return 0;
  3177. }
  3178. if (function_exists('getmxrr')) {
  3179. $mxhosts = array();
  3180. $weight = array();
  3181. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3182. if (count($mxhosts) > 1) {
  3183. return 1;
  3184. }
  3185. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3186. return 1;
  3187. }
  3188. return 0;
  3189. }
  3190. }
  3191. return -1;
  3192. }
  3193. /**
  3194. * Return true if phone number syntax is ok
  3195. * TODO Decide what to do with this
  3196. *
  3197. * @param string $phone phone (Ex: "0601010101")
  3198. * @return boolean true if phone syntax is OK, false if KO or empty string
  3199. */
  3200. function isValidPhone($phone)
  3201. {
  3202. return true;
  3203. }
  3204. /**
  3205. * Make a strlen call. Works even if mbstring module not enabled
  3206. *
  3207. * @param string $string String to calculate length
  3208. * @param string $stringencoding Encoding of string
  3209. * @return int Length of string
  3210. */
  3211. function dol_strlen($string, $stringencoding = 'UTF-8')
  3212. {
  3213. if (function_exists('mb_strlen')) {
  3214. return mb_strlen($string, $stringencoding);
  3215. } else {
  3216. return strlen($string);
  3217. }
  3218. }
  3219. /**
  3220. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3221. *
  3222. * @param string $string String to scan
  3223. * @param string $start Start position
  3224. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3225. * @param string $stringencoding Page code used for input string encoding
  3226. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3227. * @return string substring
  3228. */
  3229. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3230. {
  3231. global $langs;
  3232. if (empty($stringencoding)) {
  3233. $stringencoding = $langs->charset_output;
  3234. }
  3235. $ret = '';
  3236. if (empty($trunconbytes)) {
  3237. if (function_exists('mb_substr')) {
  3238. $ret = mb_substr($string, $start, $length, $stringencoding);
  3239. } else {
  3240. $ret = substr($string, $start, $length);
  3241. }
  3242. } else {
  3243. if (function_exists('mb_strcut')) {
  3244. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3245. } else {
  3246. $ret = substr($string, $start, $length);
  3247. }
  3248. }
  3249. return $ret;
  3250. }
  3251. /**
  3252. * Truncate a string to a particular length adding '…' if string larger than length.
  3253. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3254. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3255. *
  3256. * @param string $string String to truncate
  3257. * @param int $size Max string size visible (excluding …). 0 for no limit. WARNING: Final string size can have 3 more chars (if we added …, or if size was max+1 so it does not worse to replace with ...)
  3258. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3259. * @param string $stringencoding Tell what is source string encoding
  3260. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3261. * @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)
  3262. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3263. */
  3264. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3265. {
  3266. global $conf;
  3267. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3268. return $string;
  3269. }
  3270. if (empty($stringencoding)) {
  3271. $stringencoding = 'UTF-8';
  3272. }
  3273. // reduce for small screen
  3274. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3275. $size = round($size / 3);
  3276. }
  3277. // We go always here
  3278. if ($trunc == 'right') {
  3279. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3280. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3281. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3282. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3283. } else {
  3284. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3285. return $string;
  3286. }
  3287. } elseif ($trunc == 'middle') {
  3288. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3289. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3290. $size1 = round($size / 2);
  3291. $size2 = round($size / 2);
  3292. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3293. } else {
  3294. return $string;
  3295. }
  3296. } elseif ($trunc == 'left') {
  3297. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3298. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3299. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3300. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3301. } else {
  3302. return $string;
  3303. }
  3304. } elseif ($trunc == 'wrap') {
  3305. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3306. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3307. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3308. } else {
  3309. return $string;
  3310. }
  3311. } else {
  3312. return 'BadParam3CallingDolTrunc';
  3313. }
  3314. }
  3315. /**
  3316. * Show picto whatever it's its name (generic function)
  3317. *
  3318. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3319. * @param string $picto Name of image file to show ('filenew', ...)
  3320. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3321. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3322. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3323. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3324. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3325. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3326. * @param int $srconly Return only content of the src attribute of img.
  3327. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3328. * @param string $alt Force alt for bind people
  3329. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3330. * @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.
  3331. * @return string Return img tag
  3332. * @see img_object(), img_picto_common()
  3333. */
  3334. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3335. {
  3336. global $conf, $langs;
  3337. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3338. $url = DOL_URL_ROOT;
  3339. $theme = isset($conf->theme) ? $conf->theme : null;
  3340. $path = 'theme/'.$theme;
  3341. // Define fullpathpicto to use into src
  3342. if ($pictoisfullpath) {
  3343. // Clean parameters
  3344. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3345. $picto .= '.png';
  3346. }
  3347. $fullpathpicto = $picto;
  3348. $reg = array();
  3349. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3350. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3351. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3352. }
  3353. } else {
  3354. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3355. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3356. if (empty($srconly) && in_array($pictowithouttext, array(
  3357. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3358. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3359. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'bug', 'building',
  3360. 'card', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3361. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3362. 'multicurrency',
  3363. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3364. 'edit', 'ellipsis-h', 'email', 'entity', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3365. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3366. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3367. 'help', 'holiday',
  3368. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3369. 'label', 'language', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3370. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3371. 'off', 'on', 'order',
  3372. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'puce',
  3373. 'stock', 'resize', 'service', 'stats', 'trip',
  3374. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3375. 'github', 'google', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3376. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3377. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3378. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3379. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3380. 'technic', 'ticket',
  3381. 'error', 'warning',
  3382. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource', 'recurring',
  3383. 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3384. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3385. 'uncheck', 'user-cog', 'vat', 'website', 'workstation',
  3386. 'conferenceorbooth', 'eventorganization'
  3387. ))) {
  3388. $fakey = $pictowithouttext;
  3389. $facolor = '';
  3390. $fasize = '';
  3391. $fa = 'fas';
  3392. if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3393. $fa = 'far';
  3394. }
  3395. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3396. $fa = 'fab';
  3397. }
  3398. $arrayconvpictotofa = array(
  3399. 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  3400. 'bank_account'=>'university',
  3401. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3402. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3403. 'bom'=>'shapes',
  3404. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3405. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3406. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3407. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3408. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3409. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3410. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3411. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3412. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3413. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'loan'=>'money-bill-alt',
  3414. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3415. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3416. 'sign-out'=>'sign-out-alt',
  3417. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3418. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3419. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3420. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3421. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3422. 'other'=>'square',
  3423. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3424. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
  3425. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3426. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3427. 'refresh'=>'redo', 'region'=>'map-marked', 'resource'=>'laptop-house', 'recurring'=>'history',
  3428. 'service'=>'concierge-bell',
  3429. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3430. 'supplier'=>'building', 'technic'=>'cogs',
  3431. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3432. 'title_agenda'=>'calendar-alt',
  3433. 'uncheck'=>'times', 'uparrow'=>'share', 'vat'=>'money-check-alt', 'vcard'=>'address-card',
  3434. 'jabber'=>'comment-o',
  3435. 'website'=>'globe-americas', 'workstation'=>'pallet',
  3436. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3437. );
  3438. if ($pictowithouttext == 'off') {
  3439. $fakey = 'fa-square';
  3440. $fasize = '1.3em';
  3441. } elseif ($pictowithouttext == 'on') {
  3442. $fakey = 'fa-check-square';
  3443. $fasize = '1.3em';
  3444. } elseif ($pictowithouttext == 'listlight') {
  3445. $fakey = 'fa-download';
  3446. $marginleftonlyshort = 1;
  3447. } elseif ($pictowithouttext == 'printer') {
  3448. $fakey = 'fa-print';
  3449. $fasize = '1.2em';
  3450. } elseif ($pictowithouttext == 'note') {
  3451. $fakey = 'fa-sticky-note';
  3452. $marginleftonlyshort = 1;
  3453. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3454. $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');
  3455. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3456. if (preg_match('/selected/', $pictowithouttext)) {
  3457. $facolor = '#888';
  3458. }
  3459. $marginleftonlyshort = 1;
  3460. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3461. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3462. } else {
  3463. $fakey = 'fa-'.$pictowithouttext;
  3464. }
  3465. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3466. $morecss .= ' em092';
  3467. }
  3468. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3469. $morecss .= ' em088';
  3470. }
  3471. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3472. $morecss .= ' em080';
  3473. }
  3474. // Define $marginleftonlyshort
  3475. $arrayconvpictotomarginleftonly = array(
  3476. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3477. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3478. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3479. );
  3480. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3481. $marginleftonlyshort = 0;
  3482. }
  3483. // Add CSS
  3484. $arrayconvpictotomorcess = array(
  3485. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3486. 'bank_account'=>'bg-infobox-bank_account',
  3487. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3488. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3489. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3490. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3491. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3492. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3493. 'incoterm'=>'infobox-supplier_proposal',
  3494. 'multicurrency'=>'infobox-bank_account',
  3495. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3496. 'order'=>'infobox-commande',
  3497. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3498. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_red'=>'font-status8',
  3499. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3500. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3501. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  3502. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3503. 'resource'=>'infobox-action',
  3504. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3505. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3506. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3507. 'vat'=>'infobox-bank_account',
  3508. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3509. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3510. );
  3511. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3512. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3513. }
  3514. // Define $color
  3515. $arrayconvpictotocolor = array(
  3516. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3517. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3518. 'dynamicprice'=>'#a69944',
  3519. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3520. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3521. 'lot'=>'#a69944',
  3522. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3523. 'other'=>'#ddd',
  3524. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3525. //'shipment'=>'#a69944',
  3526. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3527. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3528. 'website'=>'#304', 'workstation'=>'#a69944'
  3529. );
  3530. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3531. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3532. }
  3533. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3534. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3535. $morestyle = '';
  3536. $reg = array();
  3537. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3538. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3539. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3540. }
  3541. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3542. $morestyle = $reg[1];
  3543. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3544. }
  3545. $moreatt = trim($moreatt);
  3546. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3547. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3548. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3549. $enabledisablehtml .= $titlealt;
  3550. }*/
  3551. $enabledisablehtml .= '</span>';
  3552. return $enabledisablehtml;
  3553. }
  3554. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3555. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3556. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3557. $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
  3558. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3559. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3560. }
  3561. // If we ask an image into $url/$mymodule/img (instead of default path)
  3562. $regs = array();
  3563. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3564. $picto = $regs[1];
  3565. $path = $regs[2]; // $path is $mymodule
  3566. }
  3567. // Clean parameters
  3568. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3569. $picto .= '.png';
  3570. }
  3571. // If alt path are defined, define url where img file is, according to physical path
  3572. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3573. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3574. if ($type == 'main') {
  3575. continue;
  3576. }
  3577. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3578. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3579. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3580. break;
  3581. }
  3582. }
  3583. // $url is '' or '/custom', $path is current theme or
  3584. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3585. }
  3586. if ($srconly) {
  3587. return $fullpathpicto;
  3588. }
  3589. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3590. return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dol_escape_htmltag($alt).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
  3591. }
  3592. /**
  3593. * Show a picto called object_picto (generic function)
  3594. *
  3595. * @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.
  3596. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3597. * For external modules use imagename@mymodule to search into directory "img" of module.
  3598. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3599. * @param int $pictoisfullpath If 1, image path is a full path
  3600. * @param int $srconly Return only content of the src attribute of img.
  3601. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3602. * @return string Return img tag
  3603. * @see img_picto(), img_picto_common()
  3604. */
  3605. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3606. {
  3607. if (strpos($picto, '^') === 0) {
  3608. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3609. } else {
  3610. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3611. }
  3612. }
  3613. /**
  3614. * Show weather picto
  3615. *
  3616. * @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.
  3617. * @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).
  3618. * @param string $moreatt Add more attribute on img tag
  3619. * @param int $pictoisfullpath If 1, image path is a full path
  3620. * @param string $morecss More CSS
  3621. * @return string Return img tag
  3622. * @see img_object(), img_picto()
  3623. */
  3624. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3625. {
  3626. global $conf;
  3627. if (is_numeric($picto)) {
  3628. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3629. //$picto = $leveltopicto[$picto];
  3630. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3631. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3632. $picto .= '.png';
  3633. }
  3634. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3635. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3636. }
  3637. /**
  3638. * Show picto (generic function)
  3639. *
  3640. * @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.
  3641. * @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.
  3642. * @param string $moreatt Add more attribute on img tag
  3643. * @param int $pictoisfullpath If 1, image path is a full path
  3644. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3645. * @return string Return img tag
  3646. * @see img_object(), img_picto()
  3647. */
  3648. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  3649. {
  3650. global $conf;
  3651. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3652. $picto .= '.png';
  3653. }
  3654. if ($pictoisfullpath) {
  3655. $path = $picto;
  3656. } else {
  3657. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3658. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3659. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3660. if (file_exists($themepath)) {
  3661. $path = $themepath;
  3662. }
  3663. }
  3664. }
  3665. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  3666. }
  3667. /**
  3668. * Show logo action
  3669. *
  3670. * @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.
  3671. * @param string $numaction Action id or code to show
  3672. * @param string $picto Name of image file to show ('filenew', ...)
  3673. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3674. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3675. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3676. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3677. * @return string Return an img tag
  3678. */
  3679. function img_action($titlealt, $numaction, $picto = '')
  3680. {
  3681. global $langs;
  3682. if (empty($titlealt) || $titlealt == 'default') {
  3683. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3684. $numaction = -1;
  3685. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3686. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3687. $numaction = 0;
  3688. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3689. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3690. $numaction = 1;
  3691. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3692. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3693. $numaction = 2;
  3694. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3695. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3696. $numaction = 3;
  3697. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3698. } else {
  3699. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3700. $numaction = 0;
  3701. }
  3702. }
  3703. if (!is_numeric($numaction)) {
  3704. $numaction = 0;
  3705. }
  3706. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3707. }
  3708. /**
  3709. * Show pdf logo
  3710. *
  3711. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3712. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3713. * @return string Retourne tag img
  3714. */
  3715. function img_pdf($titlealt = 'default', $size = 3)
  3716. {
  3717. global $langs;
  3718. if ($titlealt == 'default') {
  3719. $titlealt = $langs->trans('Show');
  3720. }
  3721. return img_picto($titlealt, 'pdf'.$size.'.png');
  3722. }
  3723. /**
  3724. * Show logo +
  3725. *
  3726. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3727. * @param string $other Add more attributes on img
  3728. * @return string Return tag img
  3729. */
  3730. function img_edit_add($titlealt = 'default', $other = '')
  3731. {
  3732. global $langs;
  3733. if ($titlealt == 'default') {
  3734. $titlealt = $langs->trans('Add');
  3735. }
  3736. return img_picto($titlealt, 'edit_add.png', $other);
  3737. }
  3738. /**
  3739. * Show logo -
  3740. *
  3741. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3742. * @param string $other Add more attributes on img
  3743. * @return string Return tag img
  3744. */
  3745. function img_edit_remove($titlealt = 'default', $other = '')
  3746. {
  3747. global $langs;
  3748. if ($titlealt == 'default') {
  3749. $titlealt = $langs->trans('Remove');
  3750. }
  3751. return img_picto($titlealt, 'edit_remove.png', $other);
  3752. }
  3753. /**
  3754. * Show logo editer/modifier fiche
  3755. *
  3756. * @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.
  3757. * @param integer $float If you have to put the style "float: right"
  3758. * @param string $other Add more attributes on img
  3759. * @return string Return tag img
  3760. */
  3761. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3762. {
  3763. global $langs;
  3764. if ($titlealt == 'default') {
  3765. $titlealt = $langs->trans('Modify');
  3766. }
  3767. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3768. }
  3769. /**
  3770. * Show logo view card
  3771. *
  3772. * @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.
  3773. * @param integer $float If you have to put the style "float: right"
  3774. * @param string $other Add more attributes on img
  3775. * @return string Return tag img
  3776. */
  3777. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  3778. {
  3779. global $langs;
  3780. if ($titlealt == 'default') {
  3781. $titlealt = $langs->trans('View');
  3782. }
  3783. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3784. return img_picto($titlealt, 'view.png', $moreatt);
  3785. }
  3786. /**
  3787. * Show delete logo
  3788. *
  3789. * @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.
  3790. * @param string $other Add more attributes on img
  3791. * @param string $morecss More CSS
  3792. * @return string Retourne tag img
  3793. */
  3794. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3795. {
  3796. global $langs;
  3797. if ($titlealt == 'default') {
  3798. $titlealt = $langs->trans('Delete');
  3799. }
  3800. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3801. }
  3802. /**
  3803. * Show printer logo
  3804. *
  3805. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3806. * @param string $other Add more attributes on img
  3807. * @return string Retourne tag img
  3808. */
  3809. function img_printer($titlealt = "default", $other = '')
  3810. {
  3811. global $langs;
  3812. if ($titlealt == "default") {
  3813. $titlealt = $langs->trans("Print");
  3814. }
  3815. return img_picto($titlealt, 'printer.png', $other);
  3816. }
  3817. /**
  3818. * Show split logo
  3819. *
  3820. * @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.
  3821. * @param string $other Add more attributes on img
  3822. * @return string Retourne tag img
  3823. */
  3824. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3825. {
  3826. global $langs;
  3827. if ($titlealt == 'default') {
  3828. $titlealt = $langs->trans('Split');
  3829. }
  3830. return img_picto($titlealt, 'split.png', $other);
  3831. }
  3832. /**
  3833. * Show help logo with cursor "?"
  3834. *
  3835. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3836. * @param int|string $usealttitle Text to use as alt title
  3837. * @return string Return tag img
  3838. */
  3839. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3840. {
  3841. global $langs;
  3842. if ($usealttitle) {
  3843. if (is_string($usealttitle)) {
  3844. $usealttitle = dol_escape_htmltag($usealttitle);
  3845. } else {
  3846. $usealttitle = $langs->trans('Info');
  3847. }
  3848. }
  3849. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3850. }
  3851. /**
  3852. * Show info logo
  3853. *
  3854. * @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.
  3855. * @return string Return img tag
  3856. */
  3857. function img_info($titlealt = 'default')
  3858. {
  3859. global $langs;
  3860. if ($titlealt == 'default') {
  3861. $titlealt = $langs->trans('Informations');
  3862. }
  3863. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3864. }
  3865. /**
  3866. * Show warning logo
  3867. *
  3868. * @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.
  3869. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3870. * @param string $morecss Add more CSS
  3871. * @return string Return img tag
  3872. */
  3873. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3874. {
  3875. global $langs;
  3876. if ($titlealt == 'default') {
  3877. $titlealt = $langs->trans('Warning');
  3878. }
  3879. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3880. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3881. }
  3882. /**
  3883. * Show error logo
  3884. *
  3885. * @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.
  3886. * @return string Return img tag
  3887. */
  3888. function img_error($titlealt = 'default')
  3889. {
  3890. global $langs;
  3891. if ($titlealt == 'default') {
  3892. $titlealt = $langs->trans('Error');
  3893. }
  3894. return img_picto($titlealt, 'error.png');
  3895. }
  3896. /**
  3897. * Show next logo
  3898. *
  3899. * @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.
  3900. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3901. * @return string Return img tag
  3902. */
  3903. function img_next($titlealt = 'default', $moreatt = '')
  3904. {
  3905. global $langs;
  3906. if ($titlealt == 'default') {
  3907. $titlealt = $langs->trans('Next');
  3908. }
  3909. //return img_picto($titlealt, 'next.png', $moreatt);
  3910. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3911. }
  3912. /**
  3913. * Show previous logo
  3914. *
  3915. * @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.
  3916. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3917. * @return string Return img tag
  3918. */
  3919. function img_previous($titlealt = 'default', $moreatt = '')
  3920. {
  3921. global $langs;
  3922. if ($titlealt == 'default') {
  3923. $titlealt = $langs->trans('Previous');
  3924. }
  3925. //return img_picto($titlealt, 'previous.png', $moreatt);
  3926. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3927. }
  3928. /**
  3929. * Show down arrow logo
  3930. *
  3931. * @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.
  3932. * @param int $selected Selected
  3933. * @param string $moreclass Add more CSS classes
  3934. * @return string Return img tag
  3935. */
  3936. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3937. {
  3938. global $langs;
  3939. if ($titlealt == 'default') {
  3940. $titlealt = $langs->trans('Down');
  3941. }
  3942. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3943. }
  3944. /**
  3945. * Show top arrow logo
  3946. *
  3947. * @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.
  3948. * @param int $selected Selected
  3949. * @param string $moreclass Add more CSS classes
  3950. * @return string Return img tag
  3951. */
  3952. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3953. {
  3954. global $langs;
  3955. if ($titlealt == 'default') {
  3956. $titlealt = $langs->trans('Up');
  3957. }
  3958. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3959. }
  3960. /**
  3961. * Show left arrow logo
  3962. *
  3963. * @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.
  3964. * @param int $selected Selected
  3965. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3966. * @return string Return img tag
  3967. */
  3968. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3969. {
  3970. global $langs;
  3971. if ($titlealt == 'default') {
  3972. $titlealt = $langs->trans('Left');
  3973. }
  3974. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3975. }
  3976. /**
  3977. * Show right arrow logo
  3978. *
  3979. * @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.
  3980. * @param int $selected Selected
  3981. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3982. * @return string Return img tag
  3983. */
  3984. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3985. {
  3986. global $langs;
  3987. if ($titlealt == 'default') {
  3988. $titlealt = $langs->trans('Right');
  3989. }
  3990. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3991. }
  3992. /**
  3993. * Show tick logo if allowed
  3994. *
  3995. * @param string $allow Allow
  3996. * @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.
  3997. * @return string Return img tag
  3998. */
  3999. function img_allow($allow, $titlealt = 'default')
  4000. {
  4001. global $langs;
  4002. if ($titlealt == 'default') {
  4003. $titlealt = $langs->trans('Active');
  4004. }
  4005. if ($allow == 1) {
  4006. return img_picto($titlealt, 'tick.png');
  4007. }
  4008. return '-';
  4009. }
  4010. /**
  4011. * Return image of a credit card according to its brand name
  4012. *
  4013. * @param string $brand Brand name of credit card
  4014. * @param string $morecss More CSS
  4015. * @return string Return img tag
  4016. */
  4017. function img_credit_card($brand, $morecss = null)
  4018. {
  4019. if (is_null($morecss)) {
  4020. $morecss = 'fa-2x';
  4021. }
  4022. if ($brand == 'visa' || $brand == 'Visa') {
  4023. $brand = 'cc-visa';
  4024. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4025. $brand = 'cc-mastercard';
  4026. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4027. $brand = 'cc-amex';
  4028. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4029. $brand = 'cc-discover';
  4030. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4031. $brand = 'cc-jcb';
  4032. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4033. $brand = 'cc-diners-club';
  4034. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4035. $brand = 'credit-card';
  4036. }
  4037. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4038. }
  4039. /**
  4040. * Show MIME img of a file
  4041. *
  4042. * @param string $file Filename
  4043. * @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.
  4044. * @param string $morecss More css
  4045. * @return string Return img tag
  4046. */
  4047. function img_mime($file, $titlealt = '', $morecss = '')
  4048. {
  4049. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4050. $mimetype = dol_mimetype($file, '', 1);
  4051. $mimeimg = dol_mimetype($file, '', 2);
  4052. $mimefa = dol_mimetype($file, '', 4);
  4053. if (empty($titlealt)) {
  4054. $titlealt = 'Mime type: '.$mimetype;
  4055. }
  4056. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4057. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4058. }
  4059. /**
  4060. * Show search logo
  4061. *
  4062. * @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.
  4063. * @param string $other Add more attributes on img
  4064. * @return string Retourne tag img
  4065. */
  4066. function img_search($titlealt = 'default', $other = '')
  4067. {
  4068. global $conf, $langs;
  4069. if ($titlealt == 'default') {
  4070. $titlealt = $langs->trans('Search');
  4071. }
  4072. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4073. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4074. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4075. return $input;
  4076. }
  4077. /**
  4078. * Show search logo
  4079. *
  4080. * @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.
  4081. * @param string $other Add more attributes on img
  4082. * @return string Retourne tag img
  4083. */
  4084. function img_searchclear($titlealt = 'default', $other = '')
  4085. {
  4086. global $conf, $langs;
  4087. if ($titlealt == 'default') {
  4088. $titlealt = $langs->trans('Search');
  4089. }
  4090. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4091. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4092. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4093. return $input;
  4094. }
  4095. /**
  4096. * Show information for admin users or standard users
  4097. *
  4098. * @param string $text Text info
  4099. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4100. * @param int $nodiv No div
  4101. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4102. * @param string $morecss More CSS ('', 'warning', 'error')
  4103. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4104. * @return string String with info text
  4105. */
  4106. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  4107. {
  4108. global $conf, $langs;
  4109. if ($infoonimgalt) {
  4110. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  4111. } else {
  4112. if (empty($conf->use_javascript_ajax)) {
  4113. $textfordropdown = '';
  4114. }
  4115. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4116. $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>');
  4117. if ($textfordropdown) {
  4118. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4119. $tmpresult .= '<script type="text/javascript">
  4120. jQuery(document).ready(function() {
  4121. jQuery(".'.$class.'text").click(function() {
  4122. console.log("toggle text");
  4123. jQuery(".'.$class.'").toggle();
  4124. });
  4125. });
  4126. </script>';
  4127. $result = $tmpresult.$result;
  4128. }
  4129. }
  4130. return $result;
  4131. }
  4132. /**
  4133. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4134. * This function must be called when a blocking technical error is encountered.
  4135. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4136. *
  4137. * @param DoliDB|string $db Database handler
  4138. * @param string|string[] $error String or array of errors strings to show
  4139. * @param array $errors Array of errors
  4140. * @return void
  4141. * @see dol_htmloutput_errors()
  4142. */
  4143. function dol_print_error($db = '', $error = '', $errors = null)
  4144. {
  4145. global $conf, $langs, $argv;
  4146. global $dolibarr_main_prod;
  4147. $out = '';
  4148. $syslog = '';
  4149. // If error occurs before the $lang object was loaded
  4150. if (!$langs) {
  4151. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4152. $langs = new Translate('', $conf);
  4153. $langs->load("main");
  4154. }
  4155. // Load translation files required by the error messages
  4156. $langs->loadLangs(array('main', 'errors'));
  4157. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4158. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4159. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4160. $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";
  4161. }
  4162. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4163. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4164. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4165. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4166. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4167. }
  4168. if (function_exists("phpversion")) {
  4169. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4170. }
  4171. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4172. if (function_exists("php_uname")) {
  4173. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4174. }
  4175. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4176. $out .= "<br>\n";
  4177. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4178. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4179. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4180. $out .= "<br>\n";
  4181. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4182. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4183. } else // Mode CLI
  4184. {
  4185. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4186. $syslog .= "pid=".dol_getmypid();
  4187. }
  4188. if (!empty($conf->modules)) {
  4189. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4190. }
  4191. if (is_object($db)) {
  4192. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4193. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4194. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4195. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4196. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4197. $out .= "<br>\n";
  4198. } else // Mode CLI
  4199. {
  4200. // No dol_escape_htmltag for output, we are in CLI mode
  4201. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4202. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4203. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4204. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4205. }
  4206. $syslog .= ", sql=".$db->lastquery();
  4207. $syslog .= ", db_error=".$db->lasterror();
  4208. }
  4209. if ($error || $errors) {
  4210. $langs->load("errors");
  4211. // Merge all into $errors array
  4212. if (is_array($error) && is_array($errors)) {
  4213. $errors = array_merge($error, $errors);
  4214. } elseif (is_array($error)) {
  4215. $errors = $error;
  4216. } elseif (is_array($errors)) {
  4217. $errors = array_merge(array($error), $errors);
  4218. } else {
  4219. $errors = array_merge(array($error));
  4220. }
  4221. foreach ($errors as $msg) {
  4222. if (empty($msg)) {
  4223. continue;
  4224. }
  4225. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4226. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4227. } else // Mode CLI
  4228. {
  4229. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4230. }
  4231. $syslog .= ", msg=".$msg;
  4232. }
  4233. }
  4234. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4235. xdebug_print_function_stack();
  4236. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4237. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4238. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4239. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4240. $out .= "<br>\n";
  4241. }
  4242. // Return a http error code if possible
  4243. if (!headers_sent()) {
  4244. http_response_code(500);
  4245. }
  4246. if (empty($dolibarr_main_prod)) {
  4247. print $out;
  4248. } else {
  4249. if (empty($langs->defaultlang)) {
  4250. $langs->setDefaultLang();
  4251. }
  4252. $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.
  4253. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4254. print 'This website or feature is currently temporarly not available or failed after a technical error.<br><br>This may be due to a maintenance operation. Current status of operation ('.dol_print_date(dol_now(), 'dayhourrfc').') are on next line...<br><br>'."\n";
  4255. print $langs->trans("DolibarrHasDetectedError").'. ';
  4256. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4257. define("MAIN_CORE_ERROR", 1);
  4258. }
  4259. dol_syslog("Error ".$syslog, LOG_ERR);
  4260. }
  4261. /**
  4262. * Show a public email and error code to contact if technical error
  4263. *
  4264. * @param string $prefixcode Prefix of public error code
  4265. * @param string $errormessage Complete error message
  4266. * @param array $errormessages Array of error messages
  4267. * @param string $morecss More css
  4268. * @param string $email Email
  4269. * @return void
  4270. */
  4271. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4272. {
  4273. global $langs, $conf;
  4274. if (empty($email)) {
  4275. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4276. }
  4277. $langs->load("errors");
  4278. $now = dol_now();
  4279. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4280. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4281. if ($errormessage) {
  4282. print '<br><br>'.$errormessage;
  4283. }
  4284. if (is_array($errormessages) && count($errormessages)) {
  4285. foreach ($errormessages as $mesgtoshow) {
  4286. print '<br><br>'.$mesgtoshow;
  4287. }
  4288. }
  4289. print '</div></div>';
  4290. }
  4291. /**
  4292. * Show title line of an array
  4293. *
  4294. * @param string $name Label of field
  4295. * @param string $file Url used when we click on sort picto
  4296. * @param string $field Field to use for new sorting
  4297. * @param string $begin ("" by defaut)
  4298. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4299. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  4300. * @param string $sortfield Current field used to sort
  4301. * @param string $sortorder Current sort order
  4302. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4303. * @param string $tooltip Tooltip
  4304. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4305. * @return void
  4306. */
  4307. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4308. {
  4309. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4310. }
  4311. /**
  4312. * Get title line of an array
  4313. *
  4314. * @param string $name Translation key of field to show or complete HTML string to show
  4315. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4316. * @param string $file Url used when we click on sort picto
  4317. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4318. * @param string $begin ("" by defaut)
  4319. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4320. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  4321. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4322. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4323. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4324. * @param string $disablesortlink 1=Disable sort link
  4325. * @param string $tooltip Tooltip
  4326. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4327. * @return string
  4328. */
  4329. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4330. {
  4331. global $conf, $langs, $form;
  4332. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4333. if ($moreattrib == 'class="right"') {
  4334. $prefix .= 'right '; // For backward compatibility
  4335. }
  4336. $sortorder = strtoupper($sortorder);
  4337. $out = '';
  4338. $sortimg = '';
  4339. $tag = 'th';
  4340. if ($thead == 2) {
  4341. $tag = 'div';
  4342. }
  4343. $tmpsortfield = explode(',', $sortfield);
  4344. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4345. $tmpfield = explode(',', $field);
  4346. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4347. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4348. $prefix = 'wrapcolumntitle '.$prefix;
  4349. }
  4350. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4351. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4352. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4353. $liste_titre = 'liste_titre';
  4354. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4355. $liste_titre = 'liste_titre_sel';
  4356. }
  4357. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4358. //$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)).'"' : '');
  4359. $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4360. $out .= '>';
  4361. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4362. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4363. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4364. $options = preg_replace('/&+/i', '&', $options);
  4365. if (!preg_match('/^&/', $options)) {
  4366. $options = '&'.$options;
  4367. }
  4368. $sortordertouseinlink = '';
  4369. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4370. if (preg_match('/^DESC/i', $sortorder)) {
  4371. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4372. } else // We reverse the var $sortordertouseinlink
  4373. {
  4374. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4375. }
  4376. } else // We are on field that is the first current sorting criteria
  4377. {
  4378. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4379. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4380. } else {
  4381. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4382. }
  4383. }
  4384. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4385. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4386. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4387. $out .= '>';
  4388. }
  4389. if ($tooltip) {
  4390. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4391. $tmptooltip = explode(':', $tooltip);
  4392. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4393. } else {
  4394. $out .= $langs->trans($name);
  4395. }
  4396. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4397. $out .= '</a>';
  4398. }
  4399. if (empty($thead) && $field) { // If this is a sort field
  4400. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4401. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4402. $options = preg_replace('/&+/i', '&', $options);
  4403. if (!preg_match('/^&/', $options)) {
  4404. $options = '&'.$options;
  4405. }
  4406. if (!$sortorder || $field1 != $sortfield1) {
  4407. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4408. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4409. } else {
  4410. if (preg_match('/^DESC/', $sortorder)) {
  4411. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4412. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4413. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  4414. }
  4415. if (preg_match('/^ASC/', $sortorder)) {
  4416. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4417. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4418. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  4419. }
  4420. }
  4421. }
  4422. $out .= $sortimg;
  4423. $out .= '</'.$tag.'>';
  4424. return $out;
  4425. }
  4426. /**
  4427. * Show a title.
  4428. *
  4429. * @param string $title Title to show
  4430. * @return void
  4431. * @deprecated Use load_fiche_titre instead
  4432. * @see load_fiche_titre()
  4433. */
  4434. function print_titre($title)
  4435. {
  4436. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4437. print '<div class="titre">'.$title.'</div>';
  4438. }
  4439. /**
  4440. * Show a title with picto
  4441. *
  4442. * @param string $title Title to show
  4443. * @param string $mesg Added message to show on right
  4444. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4445. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4446. * @param int $id To force an id on html objects
  4447. * @return void
  4448. * @deprecated Use print load_fiche_titre instead
  4449. */
  4450. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4451. {
  4452. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4453. }
  4454. /**
  4455. * Load a title with picto
  4456. *
  4457. * @param string $titre Title to show
  4458. * @param string $morehtmlright Added message to show on right
  4459. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4460. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4461. * @param string $id To force an id on html objects
  4462. * @param string $morecssontable More css on table
  4463. * @param string $morehtmlcenter Added message to show on center
  4464. * @return string
  4465. * @see print_barre_liste()
  4466. */
  4467. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4468. {
  4469. global $conf;
  4470. $return = '';
  4471. if ($picto == 'setup') {
  4472. $picto = 'generic';
  4473. }
  4474. $return .= "\n";
  4475. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4476. $return .= '<tr class="titre">';
  4477. if ($picto) {
  4478. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4479. }
  4480. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4481. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4482. $return .= '</td>';
  4483. if (dol_strlen($morehtmlcenter)) {
  4484. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4485. }
  4486. if (dol_strlen($morehtmlright)) {
  4487. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4488. }
  4489. $return .= '</tr></table>'."\n";
  4490. return $return;
  4491. }
  4492. /**
  4493. * Print a title with navigation controls for pagination
  4494. *
  4495. * @param string $titre Title to show (required)
  4496. * @param int $page Numero of page to show in navigation links (required)
  4497. * @param string $file Url of page (required)
  4498. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4499. * @param string $sortfield Field to sort on ('' by default)
  4500. * @param string $sortorder Order to sort ('' by default)
  4501. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4502. * @param int $num Number of records found by select with limit+1
  4503. * @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.
  4504. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4505. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4506. * @param string $morehtmlright More html to show (after arrows)
  4507. * @param string $morecss More css to the table
  4508. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4509. * @param int $hideselectlimit Force to hide select limit
  4510. * @param int $hidenavigation Force to hide all navigation tools
  4511. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4512. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4513. * @return void
  4514. */
  4515. 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 = '')
  4516. {
  4517. global $conf, $langs;
  4518. $savlimit = $limit;
  4519. $savtotalnboflines = $totalnboflines;
  4520. $totalnboflines = abs((int) $totalnboflines);
  4521. if ($picto == 'setup') {
  4522. $picto = 'title_setup.png';
  4523. }
  4524. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4525. $picto = 'title.gif';
  4526. }
  4527. if ($limit < 0) {
  4528. $limit = $conf->liste_limit;
  4529. }
  4530. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4531. $nextpage = 1;
  4532. } else {
  4533. $nextpage = 0;
  4534. }
  4535. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4536. print "\n";
  4537. print "<!-- Begin title -->\n";
  4538. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4539. // Left
  4540. if ($picto && $titre) {
  4541. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4542. }
  4543. print '<td class="nobordernopadding valignmiddle col-title">';
  4544. print '<div class="titre inline-block">'.$titre;
  4545. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4546. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4547. }
  4548. print '</div></td>';
  4549. // Center
  4550. if ($morehtmlcenter) {
  4551. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4552. }
  4553. // Right
  4554. print '<td class="nobordernopadding valignmiddle right">';
  4555. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4556. if ($sortfield) {
  4557. $options .= "&sortfield=".urlencode($sortfield);
  4558. }
  4559. if ($sortorder) {
  4560. $options .= "&sortorder=".urlencode($sortorder);
  4561. }
  4562. // Show navigation bar
  4563. $pagelist = '';
  4564. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4565. if ($totalnboflines) { // If we know total nb of lines
  4566. // Define nb of extra page links before and after selected page + ... + first or last
  4567. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4568. if ($limit > 0) {
  4569. $nbpages = ceil($totalnboflines / $limit);
  4570. } else {
  4571. $nbpages = 1;
  4572. }
  4573. $cpt = ($page - $maxnbofpage);
  4574. if ($cpt < 0) {
  4575. $cpt = 0;
  4576. }
  4577. if ($cpt >= 1) {
  4578. if (empty($pagenavastextinput)) {
  4579. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4580. if ($cpt > 2) {
  4581. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4582. } elseif ($cpt == 2) {
  4583. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4584. }
  4585. }
  4586. }
  4587. do {
  4588. if ($pagenavastextinput) {
  4589. if ($cpt == $page) {
  4590. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4591. $pagelist .= '/';
  4592. }
  4593. } else {
  4594. if ($cpt == $page) {
  4595. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4596. } else {
  4597. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4598. }
  4599. }
  4600. $cpt++;
  4601. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4602. if (empty($pagenavastextinput)) {
  4603. if ($cpt < $nbpages) {
  4604. if ($cpt < $nbpages - 2) {
  4605. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4606. } elseif ($cpt == $nbpages - 2) {
  4607. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4608. }
  4609. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4610. }
  4611. } else {
  4612. //var_dump($page.' '.$cpt.' '.$nbpages);
  4613. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4614. }
  4615. } else {
  4616. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4617. }
  4618. }
  4619. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4620. 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
  4621. }
  4622. // js to autoselect page field on focus
  4623. if ($pagenavastextinput) {
  4624. print ajax_autoselect('.pageplusone');
  4625. }
  4626. print '</td>';
  4627. print '</tr></table>'."\n";
  4628. print "<!-- End title -->\n\n";
  4629. }
  4630. /**
  4631. * Function to show navigation arrows into lists
  4632. *
  4633. * @param int $page Number of page
  4634. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4635. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4636. * @param integer $nextpage Do we show a next page button
  4637. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4638. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4639. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4640. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4641. * @param int $hideselectlimit Force to hide select limit
  4642. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4643. * @return void
  4644. */
  4645. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4646. {
  4647. global $conf, $langs;
  4648. print '<div class="pagination"><ul>';
  4649. if ($beforearrows) {
  4650. print '<li class="paginationbeforearrows">';
  4651. print $beforearrows;
  4652. print '</li>';
  4653. }
  4654. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4655. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000,25000:25000';
  4656. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4657. //$pagesizechoices.=',2:2';
  4658. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4659. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4660. }
  4661. print '<li class="pagination">';
  4662. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4663. $tmpchoice = explode(',', $pagesizechoices);
  4664. $tmpkey = $limit.':'.$limit;
  4665. if (!in_array($tmpkey, $tmpchoice)) {
  4666. $tmpchoice[] = $tmpkey;
  4667. }
  4668. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4669. if (!in_array($tmpkey, $tmpchoice)) {
  4670. $tmpchoice[] = $tmpkey;
  4671. }
  4672. asort($tmpchoice, SORT_NUMERIC);
  4673. foreach ($tmpchoice as $val) {
  4674. $selected = '';
  4675. $tmp = explode(':', $val);
  4676. $key = $tmp[0];
  4677. $val = $tmp[1];
  4678. if ($key != '' && $val != '') {
  4679. if ((int) $key == (int) $limit) {
  4680. $selected = ' selected="selected"';
  4681. }
  4682. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4683. }
  4684. }
  4685. print '</select>';
  4686. if ($conf->use_javascript_ajax) {
  4687. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4688. <script>
  4689. jQuery(document).ready(function () {
  4690. jQuery(".selectlimit").change(function() {
  4691. console.log("Change limit. Send submit");
  4692. $(this).parents(\'form:first\').submit();
  4693. });
  4694. });
  4695. </script>
  4696. ';
  4697. }
  4698. print '</li>';
  4699. }
  4700. if ($page > 0) {
  4701. 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>';
  4702. }
  4703. if ($betweenarrows) {
  4704. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4705. print $betweenarrows;
  4706. print '<!--</div>-->';
  4707. }
  4708. if ($nextpage > 0) {
  4709. 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>';
  4710. }
  4711. if ($afterarrows) {
  4712. print '<li class="paginationafterarrows">';
  4713. print $afterarrows;
  4714. print '</li>';
  4715. }
  4716. print '</ul></div>'."\n";
  4717. }
  4718. /**
  4719. * Return a string with VAT rate label formated for view output
  4720. * Used into pdf and HTML pages
  4721. *
  4722. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4723. * @param boolean $addpercent Add a percent % sign in output
  4724. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4725. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4726. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4727. */
  4728. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4729. {
  4730. $morelabel = '';
  4731. if (preg_match('/%/', $rate)) {
  4732. $rate = str_replace('%', '', $rate);
  4733. $addpercent = true;
  4734. }
  4735. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  4736. $morelabel = ' ('.$reg[1].')';
  4737. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4738. }
  4739. if (preg_match('/\*/', $rate)) {
  4740. $rate = str_replace('*', '', $rate);
  4741. $info_bits |= 1;
  4742. }
  4743. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4744. if (!preg_match('/\//', $rate)) {
  4745. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4746. } else {
  4747. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4748. $ret = $rate.($addpercent ? '%' : '');
  4749. }
  4750. if (($info_bits & 1) && $usestarfornpr >= 0) {
  4751. $ret .= ' *';
  4752. }
  4753. $ret .= $morelabel;
  4754. return $ret;
  4755. }
  4756. /**
  4757. * Function to format a value into an amount for visual output
  4758. * Function used into PDF and HTML pages
  4759. *
  4760. * @param float $amount Amount to format
  4761. * @param integer $form Type of format, HTML or not (not by default)
  4762. * @param Translate|string $outlangs Object langs for output
  4763. * @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.
  4764. * @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)
  4765. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4766. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4767. * @return string String with formated amount
  4768. *
  4769. * @see price2num() Revert function of price
  4770. */
  4771. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4772. {
  4773. global $langs, $conf;
  4774. // Clean parameters
  4775. if (empty($amount)) {
  4776. $amount = 0; // To have a numeric value if amount not defined or = ''
  4777. }
  4778. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4779. if ($rounding < 0) {
  4780. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4781. }
  4782. $nbdecimal = $rounding;
  4783. // Output separators by default (french)
  4784. $dec = ',';
  4785. $thousand = ' ';
  4786. // If $outlangs not forced, we use use language
  4787. if (!is_object($outlangs)) {
  4788. $outlangs = $langs;
  4789. }
  4790. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4791. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4792. }
  4793. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4794. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4795. }
  4796. if ($thousand == 'None') {
  4797. $thousand = '';
  4798. } elseif ($thousand == 'Space') {
  4799. $thousand = ' ';
  4800. }
  4801. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4802. //print "amount=".$amount."-";
  4803. $amount = str_replace(',', '.', $amount); // should be useless
  4804. //print $amount."-";
  4805. $datas = explode('.', $amount);
  4806. $decpart = isset($datas[1]) ? $datas[1] : '';
  4807. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4808. //print "decpart=".$decpart."<br>";
  4809. $end = '';
  4810. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4811. if (dol_strlen($decpart) > $nbdecimal) {
  4812. $nbdecimal = dol_strlen($decpart);
  4813. }
  4814. // Si on depasse max
  4815. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  4816. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4817. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  4818. // Si un affichage est tronque, on montre des ...
  4819. $end = '...';
  4820. }
  4821. }
  4822. // If force rounding
  4823. if ($forcerounding >= 0) {
  4824. $nbdecimal = $forcerounding;
  4825. }
  4826. // Format number
  4827. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4828. if ($form) {
  4829. $output = preg_replace('/\s/', '&nbsp;', $output);
  4830. $output = preg_replace('/\'/', '&#039;', $output);
  4831. }
  4832. // Add symbol of currency if requested
  4833. $cursymbolbefore = $cursymbolafter = '';
  4834. if ($currency_code) {
  4835. if ($currency_code == 'auto') {
  4836. $currency_code = $conf->currency;
  4837. }
  4838. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4839. $listoflanguagesbefore = array('nl_NL');
  4840. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  4841. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4842. } else {
  4843. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4844. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4845. }
  4846. }
  4847. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4848. return $output;
  4849. }
  4850. /**
  4851. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4852. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4853. * should be roundtext2num().
  4854. *
  4855. * @param string|float $amount Amount to convert/clean or round
  4856. * @param string|int $rounding ''=No rounding
  4857. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4858. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4859. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4860. * 'CU'=Round to Max unit price of foreign currency accuracy
  4861. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  4862. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  4863. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4864. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  4865. * @return string Amount with universal numeric format (Example: '99.99999').
  4866. * If conversion fails to return a numeric, it returns:
  4867. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  4868. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  4869. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  4870. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  4871. *
  4872. * @see price() Opposite function of price2num
  4873. */
  4874. function price2num($amount, $rounding = '', $option = 0)
  4875. {
  4876. global $langs, $conf;
  4877. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4878. // Numbers must be '1234.56'
  4879. // Decimal delimiter for PHP and database SQL requests must be '.'
  4880. $dec = ',';
  4881. $thousand = ' ';
  4882. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4883. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4884. }
  4885. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4886. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4887. }
  4888. if ($thousand == 'None') {
  4889. $thousand = '';
  4890. } elseif ($thousand == 'Space') {
  4891. $thousand = ' ';
  4892. }
  4893. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4894. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4895. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4896. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4897. if (!is_numeric($amount)) {
  4898. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  4899. }
  4900. if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come from input data, so 1.123 is 1123
  4901. $amount = str_replace($thousand, '', $amount);
  4902. }
  4903. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4904. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4905. // So if number was already a good number, it is converted into local Dolibarr setup.
  4906. if (is_numeric($amount)) {
  4907. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4908. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4909. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4910. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4911. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4912. }
  4913. //print "QQ".$amount."<br>\n";
  4914. // Now make replace (the main goal of function)
  4915. if ($thousand != ',' && $thousand != '.') {
  4916. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4917. }
  4918. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4919. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4920. $amount = str_replace($dec, '.', $amount);
  4921. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  4922. }
  4923. //print ' XX'.$amount.' '.$rounding;
  4924. // Now, $amount is a real PHP float number. We make a rounding if required.
  4925. if ($rounding) {
  4926. $nbofdectoround = '';
  4927. if ($rounding == 'MU') {
  4928. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4929. } elseif ($rounding == 'MT') {
  4930. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4931. } elseif ($rounding == 'MS') {
  4932. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  4933. } elseif ($rounding == 'CU') {
  4934. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  4935. } elseif ($rounding == 'CT') {
  4936. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  4937. } elseif (is_numeric($rounding)) {
  4938. $nbofdectoround = (int) $rounding;
  4939. }
  4940. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  4941. if (dol_strlen($nbofdectoround)) {
  4942. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  4943. } else {
  4944. return 'ErrorBadParameterProvidedToFunction';
  4945. }
  4946. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4947. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4948. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4949. if (is_numeric($amount)) {
  4950. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4951. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4952. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4953. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4954. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4955. }
  4956. //print "TT".$amount.'<br>';
  4957. // Always make replace because each math function (like round) replace
  4958. // with local values and we want a number that has a SQL string format x.y
  4959. if ($thousand != ',' && $thousand != '.') {
  4960. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4961. }
  4962. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4963. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4964. $amount = str_replace($dec, '.', $amount);
  4965. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  4966. }
  4967. return $amount;
  4968. }
  4969. /**
  4970. * Output a dimension with best unit
  4971. *
  4972. * @param float $dimension Dimension
  4973. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4974. * @param string $type 'weight', 'volume', ...
  4975. * @param Translate $outputlangs Translate language object
  4976. * @param int $round -1 = non rounding, x = number of decimal
  4977. * @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)
  4978. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  4979. * @return string String to show dimensions
  4980. */
  4981. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  4982. {
  4983. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4984. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  4985. $dimension = $dimension * 1000000;
  4986. $unit = $unit - 6;
  4987. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  4988. $dimension = $dimension * 1000;
  4989. $unit = $unit - 3;
  4990. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  4991. $dimension = $dimension / 1000000;
  4992. $unit = $unit + 6;
  4993. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  4994. $dimension = $dimension / 1000;
  4995. $unit = $unit + 3;
  4996. }
  4997. // Special case when we want output unit into pound or ounce
  4998. /* TODO
  4999. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5000. {
  5001. $dimension = // convert dimension from standard unit into ounce or pound
  5002. $unit = $forceunitoutput;
  5003. }
  5004. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5005. {
  5006. $dimension = // convert dimension from standard unit into ounce or pound
  5007. $unit = $forceunitoutput;
  5008. }*/
  5009. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5010. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5011. return $ret;
  5012. }
  5013. /**
  5014. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5015. * Note: This function applies same rules than get_default_tva
  5016. *
  5017. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5018. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5019. * @param Societe $thirdparty_buyer Object of buying third party
  5020. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5021. * @param int $vatnpr If vat rate is NPR or not
  5022. * @return mixed 0 if not found, localtax rate if found
  5023. * @see get_default_tva()
  5024. */
  5025. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5026. {
  5027. global $db, $conf, $mysoc;
  5028. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5029. $thirdparty_seller = $mysoc;
  5030. }
  5031. 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);
  5032. $vatratecleaned = $vatrate;
  5033. $reg = array();
  5034. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5035. $vatratecleaned = trim($reg[1]);
  5036. $vatratecode = $reg[2];
  5037. }
  5038. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5039. {
  5040. return 0;
  5041. }*/
  5042. // Some test to guess with no need to make database access
  5043. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5044. if ($local == 1) {
  5045. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5046. return 0;
  5047. }
  5048. if ($thirdparty_seller->id == $mysoc->id) {
  5049. if (!$thirdparty_buyer->localtax1_assuj) {
  5050. return 0;
  5051. }
  5052. } else {
  5053. if (!$thirdparty_seller->localtax1_assuj) {
  5054. return 0;
  5055. }
  5056. }
  5057. }
  5058. if ($local == 2) {
  5059. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5060. if (!$mysoc->localtax2_assuj) {
  5061. return 0; // If main vat is 0, IRPF may be different than 0.
  5062. }
  5063. if ($thirdparty_seller->id == $mysoc->id) {
  5064. if (!$thirdparty_buyer->localtax2_assuj) {
  5065. return 0;
  5066. }
  5067. } else {
  5068. if (!$thirdparty_seller->localtax2_assuj) {
  5069. return 0;
  5070. }
  5071. }
  5072. }
  5073. } else {
  5074. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5075. return 0;
  5076. }
  5077. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5078. return 0;
  5079. }
  5080. }
  5081. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5082. if (in_array($mysoc->country_code, array('ES'))) {
  5083. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5084. }
  5085. // Search local taxes
  5086. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5087. if ($local == 1) {
  5088. if ($thirdparty_seller != $mysoc) {
  5089. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5090. return $thirdparty_seller->localtax1_value;
  5091. }
  5092. } else { // i am the seller
  5093. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5094. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5095. }
  5096. }
  5097. }
  5098. if ($local == 2) {
  5099. if ($thirdparty_seller != $mysoc) {
  5100. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5101. // TODO We should also return value defined on thirdparty only if defined
  5102. return $thirdparty_seller->localtax2_value;
  5103. }
  5104. } else { // i am the seller
  5105. if (in_array($mysoc->country_code, array('ES'))) {
  5106. return $thirdparty_buyer->localtax2_value;
  5107. } else {
  5108. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5109. }
  5110. }
  5111. }
  5112. }
  5113. // By default, search value of local tax on line of common tax
  5114. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5115. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5116. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5117. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5118. if (!empty($vatratecode)) {
  5119. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5120. } else {
  5121. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5122. }
  5123. $resql = $db->query($sql);
  5124. if ($resql) {
  5125. $obj = $db->fetch_object($resql);
  5126. if ($obj) {
  5127. if ($local == 1) {
  5128. return $obj->localtax1;
  5129. } elseif ($local == 2) {
  5130. return $obj->localtax2;
  5131. }
  5132. }
  5133. }
  5134. return 0;
  5135. }
  5136. /**
  5137. * Return true if LocalTax (1 or 2) is unique.
  5138. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5139. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5140. *
  5141. * @param int $local Local tax to test (1 or 2)
  5142. * @return boolean True if LocalTax have multiple values, False if not
  5143. */
  5144. function isOnlyOneLocalTax($local)
  5145. {
  5146. $tax = get_localtax_by_third($local);
  5147. $valors = explode(":", $tax);
  5148. if (count($valors) > 1) {
  5149. return false;
  5150. } else {
  5151. return true;
  5152. }
  5153. }
  5154. /**
  5155. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5156. *
  5157. * @param int $local LocalTax to get
  5158. * @return number Values of localtax
  5159. */
  5160. function get_localtax_by_third($local)
  5161. {
  5162. global $db, $mysoc;
  5163. $sql = "SELECT t.localtax1, t.localtax2 ";
  5164. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5165. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5166. $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";
  5167. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5168. $sql .= " )";
  5169. $resql = $db->query($sql);
  5170. if ($resql) {
  5171. $obj = $db->fetch_object($resql);
  5172. if ($local == 1) {
  5173. return $obj->localtax1;
  5174. } elseif ($local == 2) {
  5175. return $obj->localtax2;
  5176. }
  5177. }
  5178. return 0;
  5179. }
  5180. /**
  5181. * Get tax (VAT) main information from Id.
  5182. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5183. *
  5184. * @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.
  5185. * @param Societe $buyer Company object
  5186. * @param Societe $seller Company object
  5187. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5188. * @return array array('rowid'=> , 'code'=> ...)
  5189. * @see getLocalTaxesFromRate()
  5190. */
  5191. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5192. {
  5193. global $db, $mysoc;
  5194. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5195. // Search local taxes
  5196. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5197. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5198. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5199. if ($firstparamisid) {
  5200. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5201. } else {
  5202. $vatratecleaned = $vatrate;
  5203. $vatratecode = '';
  5204. $reg = array();
  5205. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5206. $vatratecleaned = $reg[1];
  5207. $vatratecode = $reg[2];
  5208. }
  5209. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5210. /*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 ??
  5211. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5212. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5213. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5214. if ($vatratecode) {
  5215. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5216. }
  5217. }
  5218. $resql = $db->query($sql);
  5219. if ($resql) {
  5220. $obj = $db->fetch_object($resql);
  5221. if ($obj) {
  5222. return array(
  5223. 'rowid'=>$obj->rowid,
  5224. 'code'=>$obj->code,
  5225. 'rate'=>$obj->rate,
  5226. 'localtax1'=>$obj->localtax1,
  5227. 'localtax1_type'=>$obj->localtax1_type,
  5228. 'localtax2'=>$obj->localtax2,
  5229. 'localtax2_type'=>$obj->localtax2_type,
  5230. 'npr'=>$obj->npr,
  5231. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5232. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5233. );
  5234. } else {
  5235. return array();
  5236. }
  5237. } else {
  5238. dol_print_error($db);
  5239. }
  5240. return array();
  5241. }
  5242. /**
  5243. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5244. * This does not take into account the seller setup if subject to vat or not, only country.
  5245. *
  5246. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5247. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5248. * provide the selected value to the function calcul_price_total.
  5249. *
  5250. * @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.
  5251. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5252. * @param Societe $buyer Company object
  5253. * @param Societe $seller Company object
  5254. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5255. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5256. * @see getTaxesFromId()
  5257. */
  5258. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5259. {
  5260. global $db, $mysoc;
  5261. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5262. // Search local taxes
  5263. $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";
  5264. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5265. if ($firstparamisid) {
  5266. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5267. } else {
  5268. $vatratecleaned = $vatrate;
  5269. $vatratecode = '';
  5270. $reg = array();
  5271. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5272. $vatratecleaned = $reg[1];
  5273. $vatratecode = $reg[2];
  5274. }
  5275. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5276. if ($mysoc->country_code == 'ES') {
  5277. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5278. } else {
  5279. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5280. }
  5281. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5282. if ($vatratecode) {
  5283. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5284. }
  5285. }
  5286. $resql = $db->query($sql);
  5287. if ($resql) {
  5288. $obj = $db->fetch_object($resql);
  5289. if ($obj) {
  5290. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5291. if ($local == 1) {
  5292. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5293. } elseif ($local == 2) {
  5294. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5295. } else {
  5296. 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);
  5297. }
  5298. }
  5299. }
  5300. return array();
  5301. }
  5302. /**
  5303. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5304. * Function called by get_default_tva().
  5305. *
  5306. * @param int $idprod Id of product or 0 if not a predefined product
  5307. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5308. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5309. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5310. * @see get_product_localtax_for_country()
  5311. */
  5312. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5313. {
  5314. global $db, $conf, $mysoc;
  5315. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5316. $ret = 0;
  5317. $found = 0;
  5318. if ($idprod > 0) {
  5319. // Load product
  5320. $product = new Product($db);
  5321. $result = $product->fetch($idprod);
  5322. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5323. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5324. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5325. $ret = $product->vatrate_supplier;
  5326. if ($product->default_vat_code) {
  5327. $ret .= ' ('.$product->default_vat_code.')';
  5328. }
  5329. } else {
  5330. $ret = $product->tva_tx; // Default vat of product we defined
  5331. if ($product->default_vat_code) {
  5332. $ret .= ' ('.$product->default_vat_code.')';
  5333. }
  5334. }
  5335. $found = 1;
  5336. } else {
  5337. // TODO Read default product vat according to product and another countrycode.
  5338. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5339. }
  5340. }
  5341. if (!$found) {
  5342. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5343. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5344. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5345. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5346. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5347. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5348. $sql .= $db->plimit(1);
  5349. $resql = $db->query($sql);
  5350. if ($resql) {
  5351. $obj = $db->fetch_object($resql);
  5352. if ($obj) {
  5353. $ret = $obj->vat_rate;
  5354. if ($obj->default_vat_code) {
  5355. $ret .= ' ('.$obj->default_vat_code.')';
  5356. }
  5357. }
  5358. $db->free($resql);
  5359. } else {
  5360. dol_print_error($db);
  5361. }
  5362. } else {
  5363. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5364. }
  5365. }
  5366. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5367. return $ret;
  5368. }
  5369. /**
  5370. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5371. *
  5372. * @param int $idprod Id of product
  5373. * @param int $local 1 for localtax1, 2 for localtax 2
  5374. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5375. * @return int <0 if KO, Vat rate if OK
  5376. * @see get_product_vat_for_country()
  5377. */
  5378. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5379. {
  5380. global $db, $mysoc;
  5381. if (!class_exists('Product')) {
  5382. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5383. }
  5384. $ret = 0;
  5385. $found = 0;
  5386. if ($idprod > 0) {
  5387. // Load product
  5388. $product = new Product($db);
  5389. $result = $product->fetch($idprod);
  5390. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5391. /* Not defined yet, so we don't use this
  5392. if ($local==1) $ret=$product->localtax1_tx;
  5393. elseif ($local==2) $ret=$product->localtax2_tx;
  5394. $found=1;
  5395. */
  5396. } else {
  5397. // TODO Read default product vat according to product and another countrycode.
  5398. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5399. }
  5400. }
  5401. if (!$found) {
  5402. // If vat of product for the country not found or not defined, we return higher vat of country.
  5403. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5404. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5405. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5406. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5407. $sql .= $db->plimit(1);
  5408. $resql = $db->query($sql);
  5409. if ($resql) {
  5410. $obj = $db->fetch_object($resql);
  5411. if ($obj) {
  5412. if ($local == 1) {
  5413. $ret = $obj->localtax1;
  5414. } elseif ($local == 2) {
  5415. $ret = $obj->localtax2;
  5416. }
  5417. }
  5418. } else {
  5419. dol_print_error($db);
  5420. }
  5421. }
  5422. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5423. return $ret;
  5424. }
  5425. /**
  5426. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5427. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5428. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5429. * VATRULE 3: Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  5430. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5431. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5432. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5433. *
  5434. * @param Societe $thirdparty_seller Objet societe vendeuse
  5435. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5436. * @param int $idprod Id product
  5437. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5438. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5439. * @see get_default_npr(), get_default_localtax()
  5440. */
  5441. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5442. {
  5443. global $conf;
  5444. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5445. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5446. $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;
  5447. $seller_country_code = $thirdparty_seller->country_code;
  5448. $seller_in_cee = isInEEC($thirdparty_seller);
  5449. $buyer_country_code = $thirdparty_buyer->country_code;
  5450. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5451. 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 : ''));
  5452. // 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)
  5453. // we use the buyer VAT.
  5454. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5455. if ($seller_in_cee && $buyer_in_cee) {
  5456. $isacompany = $thirdparty_buyer->isACompany();
  5457. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5458. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5459. if (!isValidVATID($thirdparty_buyer)) {
  5460. $isacompany = 0;
  5461. }
  5462. }
  5463. if (!$isacompany) {
  5464. //print 'VATRULE 0';
  5465. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5466. }
  5467. }
  5468. }
  5469. // If seller does not use VAT
  5470. if (!$seller_use_vat) {
  5471. //print 'VATRULE 1';
  5472. return 0;
  5473. }
  5474. // 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.
  5475. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5476. if (($seller_country_code == $buyer_country_code)
  5477. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5478. //print 'VATRULE 2';
  5479. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5480. }
  5481. // 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.
  5482. // 'VATRULE 3' - Not supported
  5483. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5484. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5485. if (($seller_in_cee && $buyer_in_cee)) {
  5486. $isacompany = $thirdparty_buyer->isACompany();
  5487. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5488. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5489. if (!isValidVATID($thirdparty_buyer)) {
  5490. $isacompany = 0;
  5491. }
  5492. }
  5493. if (!$isacompany) {
  5494. //print 'VATRULE 4';
  5495. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5496. } else {
  5497. //print 'VATRULE 5';
  5498. return 0;
  5499. }
  5500. }
  5501. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5502. // I don't see any use case that need this rule.
  5503. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5504. $isacompany = $thirdparty_buyer->isACompany();
  5505. if (!$isacompany) {
  5506. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5507. //print 'VATRULE extra';
  5508. }
  5509. }
  5510. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5511. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5512. //print 'VATRULE 6';
  5513. return 0;
  5514. }
  5515. /**
  5516. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5517. *
  5518. * @param Societe $thirdparty_seller Thirdparty seller
  5519. * @param Societe $thirdparty_buyer Thirdparty buyer
  5520. * @param int $idprod Id product
  5521. * @param int $idprodfournprice Id supplier price for product
  5522. * @return float 0 or 1
  5523. * @see get_default_tva(), get_default_localtax()
  5524. */
  5525. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5526. {
  5527. global $db;
  5528. if ($idprodfournprice > 0) {
  5529. if (!class_exists('ProductFournisseur')) {
  5530. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5531. }
  5532. $prodprice = new ProductFournisseur($db);
  5533. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5534. return $prodprice->fourn_tva_npr;
  5535. } elseif ($idprod > 0) {
  5536. if (!class_exists('Product')) {
  5537. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5538. }
  5539. $prod = new Product($db);
  5540. $prod->fetch($idprod);
  5541. return $prod->tva_npr;
  5542. }
  5543. return 0;
  5544. }
  5545. /**
  5546. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5547. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5548. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5549. * Sinon TVA proposee par defaut=0. Fin de regle.
  5550. *
  5551. * @param Societe $thirdparty_seller Thirdparty seller
  5552. * @param Societe $thirdparty_buyer Thirdparty buyer
  5553. * @param int $local Localtax to process (1 or 2)
  5554. * @param int $idprod Id product
  5555. * @return integer localtax, -1 si ne peut etre determine
  5556. * @see get_default_tva(), get_default_npr()
  5557. */
  5558. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5559. {
  5560. global $mysoc;
  5561. if (!is_object($thirdparty_seller)) {
  5562. return -1;
  5563. }
  5564. if (!is_object($thirdparty_buyer)) {
  5565. return -1;
  5566. }
  5567. if ($local == 1) { // Localtax 1
  5568. if ($mysoc->country_code == 'ES') {
  5569. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5570. return 0;
  5571. }
  5572. } else {
  5573. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5574. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5575. return 0;
  5576. }
  5577. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5578. return 0;
  5579. }
  5580. }
  5581. } elseif ($local == 2) { //I Localtax 2
  5582. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5583. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5584. return 0;
  5585. }
  5586. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5587. return 0;
  5588. }
  5589. }
  5590. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5591. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5592. }
  5593. return 0;
  5594. }
  5595. /**
  5596. * Return yes or no in current language
  5597. *
  5598. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5599. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5600. * @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.
  5601. * @return string HTML string
  5602. */
  5603. function yn($yesno, $case = 1, $color = 0)
  5604. {
  5605. global $langs;
  5606. $result = 'unknown';
  5607. $classname = '';
  5608. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5609. $result = $langs->trans('yes');
  5610. if ($case == 1 || $case == 3) {
  5611. $result = $langs->trans("Yes");
  5612. }
  5613. if ($case == 2) {
  5614. $result = '<input type="checkbox" value="1" checked disabled>';
  5615. }
  5616. if ($case == 3) {
  5617. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5618. }
  5619. $classname = 'ok';
  5620. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5621. $result = $langs->trans("no");
  5622. if ($case == 1 || $case == 3) {
  5623. $result = $langs->trans("No");
  5624. }
  5625. if ($case == 2) {
  5626. $result = '<input type="checkbox" value="0" disabled>';
  5627. }
  5628. if ($case == 3) {
  5629. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5630. }
  5631. if ($color == 2) {
  5632. $classname = 'ok';
  5633. } else {
  5634. $classname = 'error';
  5635. }
  5636. }
  5637. if ($color) {
  5638. return '<span class="'.$classname.'">'.$result.'</span>';
  5639. }
  5640. return $result;
  5641. }
  5642. /**
  5643. * Return a path to have a the directory according to object where files are stored.
  5644. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5645. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5646. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5647. * Example out with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  5648. *
  5649. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5650. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5651. * @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)
  5652. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5653. * @param Object $object Object to use to get ref to forge the path.
  5654. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5655. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5656. */
  5657. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5658. {
  5659. global $conf;
  5660. if (empty($modulepart) && !empty($object->module)) {
  5661. $modulepart = $object->module;
  5662. }
  5663. $path = '';
  5664. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5665. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5666. $arrayforoldpath[] = 'product';
  5667. }
  5668. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5669. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5670. if (empty($alpha)) {
  5671. $num = preg_replace('/([^0-9])/i', '', $num);
  5672. } else {
  5673. $num = preg_replace('/^.*\-/i', '', $num);
  5674. }
  5675. $num = substr("000".$num, -$level);
  5676. if ($level == 1) {
  5677. $path = substr($num, 0, 1);
  5678. }
  5679. if ($level == 2) {
  5680. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5681. }
  5682. if ($level == 3) {
  5683. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5684. }
  5685. } else {
  5686. // We will enhance here a common way of forging path for document storage.
  5687. // In a future, we may distribute directories on several levels depending on setup and object.
  5688. // Here, $object->id, $object->ref and $modulepart are required.
  5689. //var_dump($modulepart);
  5690. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5691. }
  5692. if (empty($withoutslash) && !empty($path)) {
  5693. $path .= '/';
  5694. }
  5695. return $path;
  5696. }
  5697. /**
  5698. * Creation of a directory (this can create recursive subdir)
  5699. *
  5700. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5701. * @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)
  5702. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5703. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5704. */
  5705. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5706. {
  5707. global $conf;
  5708. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5709. $dir_osencoded = dol_osencode($dir);
  5710. if (@is_dir($dir_osencoded)) {
  5711. return 0;
  5712. }
  5713. $nberr = 0;
  5714. $nbcreated = 0;
  5715. $ccdir = '';
  5716. if (!empty($dataroot)) {
  5717. // Remove data root from loop
  5718. $dir = str_replace($dataroot.'/', '', $dir);
  5719. $ccdir = $dataroot.'/';
  5720. }
  5721. $cdir = explode("/", $dir);
  5722. $num = count($cdir);
  5723. for ($i = 0; $i < $num; $i++) {
  5724. if ($i > 0) {
  5725. $ccdir .= '/'.$cdir[$i];
  5726. } else {
  5727. $ccdir .= $cdir[$i];
  5728. }
  5729. if (preg_match("/^.:$/", $ccdir, $regs)) {
  5730. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5731. }
  5732. // Attention, le is_dir() peut echouer bien que le rep existe.
  5733. // (ex selon config de open_basedir)
  5734. if ($ccdir) {
  5735. $ccdir_osencoded = dol_osencode($ccdir);
  5736. if (!@is_dir($ccdir_osencoded)) {
  5737. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5738. umask(0);
  5739. $dirmaskdec = octdec($newmask);
  5740. if (empty($newmask)) {
  5741. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5742. }
  5743. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5744. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  5745. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5746. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5747. $nberr++;
  5748. } else {
  5749. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5750. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5751. $nbcreated++;
  5752. }
  5753. } else {
  5754. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5755. }
  5756. }
  5757. }
  5758. return ($nberr ? -$nberr : $nbcreated);
  5759. }
  5760. /**
  5761. * Return picto saying a field is required
  5762. *
  5763. * @return string Chaine avec picto obligatoire
  5764. */
  5765. function picto_required()
  5766. {
  5767. return '<span class="fieldrequired">*</span>';
  5768. }
  5769. /**
  5770. * Clean a string from all HTML tags and entities.
  5771. * This function differs from strip_tags because:
  5772. * - <br> are replaced with \n if removelinefeed=0 or 1
  5773. * - if entities are found, they are decoded BEFORE the strip
  5774. * - you can decide to convert line feed into a space
  5775. *
  5776. * @param string $stringtoclean String to clean
  5777. * @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..."
  5778. * @param string $pagecodeto Encoding of input/output string
  5779. * @param integer $strip_tags 0=Use internal strip, 1=Use strip_tags() php function (bugged when text contains a < char that is not for a html tag or when tags is not closed like '<img onload=aaa')
  5780. * @param integer $removedoublespaces Replace double space into one space
  5781. * @return string String cleaned
  5782. *
  5783. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5784. */
  5785. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5786. {
  5787. if ($removelinefeed == 2) {
  5788. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5789. }
  5790. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5791. // We remove entities BEFORE stripping (in case of an open separator char that is entity encoded and not the closing other, the strip will fails)
  5792. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5793. $temp = str_replace('< ', '__ltspace__', $temp);
  5794. if ($strip_tags) {
  5795. $temp = strip_tags($temp);
  5796. } else {
  5797. $temp = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  5798. $pattern = "/<[^<>]+>/";
  5799. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5800. $temp = preg_replace($pattern, "", $temp); // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5801. $temp = preg_replace($pattern, "", $temp); // pass 2 - $temp after pass 2: 0000-021
  5802. // Remove '<' into remainging, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
  5803. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  5804. }
  5805. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5806. // Remove also carriage returns
  5807. if ($removelinefeed == 1) {
  5808. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5809. }
  5810. // And double quotes
  5811. if ($removedoublespaces) {
  5812. while (strpos($temp, " ")) {
  5813. $temp = str_replace(" ", " ", $temp);
  5814. }
  5815. }
  5816. $temp = str_replace('__ltspace__', '< ', $temp);
  5817. return trim($temp);
  5818. }
  5819. /**
  5820. * Clean a string to keep only desirable HTML tags.
  5821. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  5822. *
  5823. * @param string $stringtoclean String to clean
  5824. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5825. * @param int $removeclassattribute 1=Remove the class attribute from tags
  5826. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  5827. * @param int $allowiframe Allow iframe tags.
  5828. * @return string String cleaned
  5829. *
  5830. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5831. */
  5832. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  5833. {
  5834. $allowed_tags = array(
  5835. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5836. "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"
  5837. );
  5838. if ($allowiframe) {
  5839. $allowed_tags[] = "iframe";
  5840. }
  5841. $allowed_tags_string = join("><", $allowed_tags);
  5842. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5843. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  5844. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5845. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  5846. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5847. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  5848. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  5849. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </> changing string obfuscated with </> that pass injection detection into harmfull string
  5850. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5851. $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $temp); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless
  5852. }
  5853. if ($removeclassattribute) { // Clean for remaining html tags
  5854. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5855. }
  5856. // Remove 'javascript:' that we should not find into a text with
  5857. // Warning: This is not reliable to fight against obfuscated javascript, there is a lot of other solution to include js into a common html tag (only filtered by a GETPOST(.., powerfullfilter)).
  5858. if ($cleanalsojavascript) {
  5859. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5860. }
  5861. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  5862. return $temp;
  5863. }
  5864. /**
  5865. * Clean a string from some undesirable HTML tags.
  5866. * Note: Complementary to dol_string_onlythesehtmltags().
  5867. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  5868. *
  5869. * @param string $stringtoclean String to clean
  5870. * @param array $allowed_attributes Array of tags not allowed
  5871. * @return string String cleaned
  5872. *
  5873. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  5874. */
  5875. function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = array("allow", "allowfullscreen", "alt", "class", "contenteditable", "data-html", "frameborder", "height", "href", "id", "name", "src", "style", "target", "title", "width"))
  5876. {
  5877. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  5878. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  5879. $dom = new DOMDocument(null, 'UTF-8');
  5880. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  5881. if (is_object($dom)) {
  5882. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  5883. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  5884. //var_dump($attrs->item($ii));
  5885. if (! empty($attrs->item($ii)->name)) {
  5886. // Delete attribute if not into allowed_attributes
  5887. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  5888. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  5889. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  5890. $valuetoclean = $attrs->item($ii)->value;
  5891. do {
  5892. $oldvaluetoclean = $valuetoclean;
  5893. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  5894. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  5895. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  5896. $valuetoclean = preg_replace('/display\s*://m', '', $valuetoclean);
  5897. $valuetoclean = preg_replace('/z-index\s*://m', '', $valuetoclean);
  5898. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*://m', '', $valuetoclean);
  5899. }
  5900. } while ($oldvaluetoclean != $valuetoclean);
  5901. $attrs->item($ii)->value = $valuetoclean;
  5902. }
  5903. }
  5904. }
  5905. }
  5906. }
  5907. $return = $dom->saveHTML();
  5908. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  5909. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  5910. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  5911. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  5912. return trim($return);
  5913. } else {
  5914. return $stringtoclean;
  5915. }
  5916. }
  5917. /**
  5918. * Clean a string from some undesirable HTML tags.
  5919. * Note. Not as secured as dol_string_onlythesehtmltags().
  5920. *
  5921. * @param string $stringtoclean String to clean
  5922. * @param array $disallowed_tags Array of tags not allowed
  5923. * @param string $cleanalsosomestyles Clean also some tags
  5924. * @return string String cleaned
  5925. *
  5926. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  5927. */
  5928. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5929. {
  5930. $temp = $stringtoclean;
  5931. foreach ($disallowed_tags as $tagtoremove) {
  5932. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5933. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5934. }
  5935. if ($cleanalsosomestyles) {
  5936. $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
  5937. }
  5938. return $temp;
  5939. }
  5940. /**
  5941. * Return first line of text. Cut will depends if content is HTML or not.
  5942. *
  5943. * @param string $text Input text
  5944. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5945. * @param string $charset Charset of $text string (UTF-8 by default)
  5946. * @return string Output text
  5947. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5948. */
  5949. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5950. {
  5951. if ($nboflines == 1) {
  5952. if (dol_textishtml($text)) {
  5953. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5954. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5955. } else {
  5956. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5957. }
  5958. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5959. } else {
  5960. $ishtml = 0;
  5961. if (dol_textishtml($text)) {
  5962. $text = preg_replace('/\n/', '', $text);
  5963. $ishtml = 1;
  5964. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5965. } else {
  5966. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5967. }
  5968. $text = strtr($text, $repTable);
  5969. if ($charset == 'UTF-8') {
  5970. $pattern = '/(<br[^>]*>)/Uu';
  5971. } else {
  5972. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5973. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5974. }
  5975. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5976. $firstline = '';
  5977. $i = 0;
  5978. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5979. while (($i < $nba) && ($i < ($nboflines * 2))) {
  5980. if ($i % 2 == 0) {
  5981. $firstline .= $a[$i];
  5982. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  5983. $firstline .= ($ishtml ? "<br>\n" : "\n");
  5984. }
  5985. $i++;
  5986. }
  5987. unset($a);
  5988. return $firstline.(($i < $nba) ? '...' : '');
  5989. }
  5990. }
  5991. /**
  5992. * Replace CRLF in string with a HTML BR tag.
  5993. * 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.
  5994. *
  5995. * @param string $stringtoencode String to encode
  5996. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5997. * @param bool $forxml false=Use <br>, true=Use <br />
  5998. * @return string String encoded
  5999. * @see dol_nboflines(), dolGetFirstLineOfText()
  6000. */
  6001. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6002. {
  6003. if (!$nl2brmode) {
  6004. return nl2br($stringtoencode, $forxml);
  6005. } else {
  6006. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6007. return $ret;
  6008. }
  6009. }
  6010. /**
  6011. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6012. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6013. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6014. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6015. * For PDF usage, you can show text by 2 ways:
  6016. * - writeHTMLCell -> param must be encoded into HTML.
  6017. * - MultiCell -> param must not be encoded into HTML.
  6018. * Because writeHTMLCell convert also \n into <br>, if function
  6019. * is used to build PDF, nl2brmode must be 1.
  6020. *
  6021. * @param string $stringtoencode String to encode
  6022. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6023. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6024. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6025. * @return string String encoded
  6026. */
  6027. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6028. {
  6029. $newstring = $stringtoencode;
  6030. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6031. $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.
  6032. if ($removelasteolbr) {
  6033. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6034. }
  6035. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6036. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6037. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6038. } else {
  6039. if ($removelasteolbr) {
  6040. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6041. }
  6042. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6043. }
  6044. // Other substitutions that htmlentities does not do
  6045. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6046. return $newstring;
  6047. }
  6048. /**
  6049. * This function is called to decode a HTML string (it decodes entities and br tags)
  6050. *
  6051. * @param string $stringtodecode String to decode
  6052. * @param string $pagecodeto Page code for result
  6053. * @return string String decoded
  6054. */
  6055. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6056. {
  6057. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6058. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6059. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6060. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6061. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6062. return $ret;
  6063. }
  6064. /**
  6065. * This function remove all ending \n and br at end
  6066. *
  6067. * @param string $stringtodecode String to decode
  6068. * @return string String decoded
  6069. */
  6070. function dol_htmlcleanlastbr($stringtodecode)
  6071. {
  6072. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6073. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6074. return $ret;
  6075. }
  6076. /**
  6077. * Replace html_entity_decode functions to manage errors
  6078. *
  6079. * @param string $a Operand a
  6080. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6081. * @param string $c Operand c
  6082. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6083. * @return string String decoded
  6084. */
  6085. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6086. {
  6087. $newstring = $a;
  6088. if ($keepsomeentities) {
  6089. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6090. }
  6091. $newstring = html_entity_decode($newstring, $b, $c);
  6092. if ($keepsomeentities) {
  6093. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6094. }
  6095. return $newstring;
  6096. }
  6097. /**
  6098. * Replace htmlentities functions.
  6099. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6100. *
  6101. * @param string $string The input string to encode
  6102. * @param int $flags Flags (see PHP doc above)
  6103. * @param string $encoding Encoding page code
  6104. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6105. * @return string $ret Encoded string
  6106. */
  6107. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6108. {
  6109. return htmlentities($string, $flags, $encoding, $double_encode);
  6110. }
  6111. /**
  6112. * Check if a string is a correct iso string
  6113. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6114. * Example, if string contains euro symbol that has ascii code 128
  6115. *
  6116. * @param string $s String to check
  6117. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6118. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6119. */
  6120. function dol_string_is_good_iso($s, $clean = 0)
  6121. {
  6122. $len = dol_strlen($s);
  6123. $out = '';
  6124. $ok = 1;
  6125. for ($scursor = 0; $scursor < $len; $scursor++) {
  6126. $ordchar = ord($s[$scursor]);
  6127. //print $scursor.'-'.$ordchar.'<br>';
  6128. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6129. $ok = 0;
  6130. break;
  6131. } elseif ($ordchar > 126 && $ordchar < 160) {
  6132. $ok = 0;
  6133. break;
  6134. } elseif ($clean) {
  6135. $out .= $s[$scursor];
  6136. }
  6137. }
  6138. if ($clean) {
  6139. return $out;
  6140. }
  6141. return $ok;
  6142. }
  6143. /**
  6144. * Return nb of lines of a clear text
  6145. *
  6146. * @param string $s String to check
  6147. * @param int $maxchar Not yet used
  6148. * @return int Number of lines
  6149. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6150. */
  6151. function dol_nboflines($s, $maxchar = 0)
  6152. {
  6153. if ($s == '') {
  6154. return 0;
  6155. }
  6156. $arraystring = explode("\n", $s);
  6157. $nb = count($arraystring);
  6158. return $nb;
  6159. }
  6160. /**
  6161. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6162. *
  6163. * @param string $text Text
  6164. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6165. * @param string $charset Give the charset used to encode the $text variable in memory.
  6166. * @return int Number of lines
  6167. * @see dol_nboflines(), dolGetFirstLineOfText()
  6168. */
  6169. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6170. {
  6171. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6172. if (dol_textishtml($text)) {
  6173. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6174. }
  6175. $text = strtr($text, $repTable);
  6176. if ($charset == 'UTF-8') {
  6177. $pattern = '/(<br[^>]*>)/Uu';
  6178. } else {
  6179. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6180. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6181. }
  6182. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6183. $nblines = (int) floor((count($a) + 1) / 2);
  6184. // count possible auto line breaks
  6185. if ($maxlinesize) {
  6186. foreach ($a as $line) {
  6187. if (dol_strlen($line) > $maxlinesize) {
  6188. //$line_dec = html_entity_decode(strip_tags($line));
  6189. $line_dec = html_entity_decode($line);
  6190. if (dol_strlen($line_dec) > $maxlinesize) {
  6191. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6192. $nblines += substr_count($line_dec, '\n');
  6193. }
  6194. }
  6195. }
  6196. }
  6197. unset($a);
  6198. return $nblines;
  6199. }
  6200. /**
  6201. * Return if a text is a html content
  6202. *
  6203. * @param string $msg Content to check
  6204. * @param int $option 0=Full detection, 1=Fast check
  6205. * @return boolean true/false
  6206. * @see dol_concatdesc()
  6207. */
  6208. function dol_textishtml($msg, $option = 0)
  6209. {
  6210. if ($option == 1) {
  6211. if (preg_match('/<html/i', $msg)) {
  6212. return true;
  6213. } elseif (preg_match('/<body/i', $msg)) {
  6214. return true;
  6215. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6216. return true;
  6217. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6218. return true;
  6219. } elseif (preg_match('/<br/i', $msg)) {
  6220. return true;
  6221. }
  6222. return false;
  6223. } else {
  6224. if (preg_match('/<html/i', $msg)) {
  6225. return true;
  6226. } elseif (preg_match('/<body/i', $msg)) {
  6227. return true;
  6228. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6229. return true;
  6230. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6231. return true;
  6232. } elseif (preg_match('/<br\/>/i', $msg)) {
  6233. return true;
  6234. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6235. return true;
  6236. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6237. return true;
  6238. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6239. return true; // must accept <img src="http://example.com/aaa.png" />
  6240. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6241. return true; // must accept <a href="http://example.com/aaa.png" />
  6242. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6243. return true;
  6244. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6245. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6246. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6247. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6248. }
  6249. return false;
  6250. }
  6251. }
  6252. /**
  6253. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6254. * text1 html + text2 html => text1 + '<br>' + text2
  6255. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6256. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6257. * text1 txt + text2 txt => text1 + '\n' + text2
  6258. *
  6259. * @param string $text1 Text 1
  6260. * @param string $text2 Text 2
  6261. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6262. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6263. * @return string Text 1 + new line + Text2
  6264. * @see dol_textishtml()
  6265. */
  6266. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6267. {
  6268. if (!empty($invert)) {
  6269. $tmp = $text1;
  6270. $text1 = $text2;
  6271. $text2 = $tmp;
  6272. }
  6273. $ret = '';
  6274. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6275. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6276. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6277. return $ret;
  6278. }
  6279. /**
  6280. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6281. *
  6282. * @param Translate $outputlangs Output language
  6283. * @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)
  6284. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6285. * @param Object $object Object for keys on object
  6286. * @return array Array of substitutions
  6287. * @see setSubstitFromObject()
  6288. */
  6289. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6290. {
  6291. global $db, $conf, $mysoc, $user, $extrafields;
  6292. $substitutionarray = array();
  6293. if (empty($exclude) || !in_array('user', $exclude)) {
  6294. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6295. // this will include signature content first and then replace var found into content of signature
  6296. $signature = $user->signature;
  6297. $substitutionarray = array_merge($substitutionarray, array(
  6298. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6299. ));
  6300. if (is_object($user)) {
  6301. $substitutionarray = array_merge($substitutionarray, array(
  6302. '__USER_ID__' => (string) $user->id,
  6303. '__USER_LOGIN__' => (string) $user->login,
  6304. '__USER_EMAIL__' => (string) $user->email,
  6305. '__USER_LASTNAME__' => (string) $user->lastname,
  6306. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6307. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6308. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6309. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6310. ));
  6311. }
  6312. }
  6313. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6314. $substitutionarray = array_merge($substitutionarray, array(
  6315. '__MYCOMPANY_NAME__' => $mysoc->name,
  6316. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6317. '__MYCOMPANY_PHONE__' => $mysoc->phone,
  6318. '__MYCOMPANY_FAX__' => $mysoc->fax,
  6319. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6320. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6321. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6322. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6323. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6324. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6325. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6326. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6327. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6328. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6329. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6330. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6331. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6332. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6333. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6334. ));
  6335. }
  6336. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6337. if ($onlykey) {
  6338. $substitutionarray['__ID__'] = '__ID__';
  6339. $substitutionarray['__REF__'] = '__REF__';
  6340. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6341. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6342. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6343. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6344. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6345. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6346. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6347. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6348. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6349. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6350. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6351. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6352. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6353. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6354. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6355. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6356. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6357. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6358. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6359. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6360. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6361. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6362. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6363. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6364. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6365. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6366. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6367. }
  6368. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6369. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6370. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6371. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6372. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6373. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6374. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6375. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6376. }
  6377. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature')) {
  6378. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6379. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6380. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6381. }
  6382. if (!empty($conf->projet->enabled)) { // Most objects
  6383. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6384. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6385. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6386. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6387. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6388. }
  6389. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6390. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6391. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6392. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6393. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6394. }
  6395. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6396. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6397. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6398. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6399. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6400. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6401. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  6402. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6403. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6404. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6405. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6406. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6407. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6408. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6409. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6410. }
  6411. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6412. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6413. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6414. }
  6415. } else {
  6416. $substitutionarray['__ID__'] = $object->id;
  6417. $substitutionarray['__REF__'] = $object->ref;
  6418. $substitutionarray['__NEWREF__'] = $object->newref;
  6419. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6420. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6421. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6422. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6423. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6424. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6425. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6426. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6427. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6428. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6429. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6430. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6431. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6432. // For backward compatibility
  6433. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6434. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6435. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6436. $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 : '')) : '');
  6437. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6438. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6439. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6440. if (method_exists($object, 'getCivilityLabel')) {
  6441. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6442. }
  6443. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6444. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6445. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6446. if (method_exists($object, 'getFullName')) {
  6447. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6448. }
  6449. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6450. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6451. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6452. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6453. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6454. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6455. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6456. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6457. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6458. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6459. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  6460. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  6461. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  6462. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6463. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6464. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  6465. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  6466. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6467. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6468. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6469. }
  6470. if (is_object($object) && $object->element == 'societe') {
  6471. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6472. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6473. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6474. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6475. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6476. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6477. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  6478. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  6479. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6480. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6481. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6482. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6483. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6484. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6485. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6486. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6487. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6488. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6489. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6490. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6491. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6492. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6493. } elseif (is_object($object->thirdparty)) {
  6494. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6495. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6496. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6497. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6498. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6499. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6500. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  6501. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  6502. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6503. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6504. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6505. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6506. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6507. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6508. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6509. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6510. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6511. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6512. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6513. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6514. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6515. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6516. }
  6517. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6518. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6519. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  6520. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  6521. }
  6522. if (is_object($object->project)) {
  6523. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6524. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6525. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6526. }
  6527. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6528. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6529. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6530. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6531. }
  6532. if (is_object($object) && $object->element == 'shipping') {
  6533. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6534. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6535. }
  6536. if (is_object($object) && $object->element == 'reception') {
  6537. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6538. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6539. }
  6540. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6541. $dateplannedstart = '';
  6542. $datenextexpiration = '';
  6543. foreach ($object->lines as $line) {
  6544. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6545. $dateplannedstart = $line->date_ouverture_prevue;
  6546. }
  6547. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6548. $datenextexpiration = $line->date_fin_prevue;
  6549. }
  6550. }
  6551. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6552. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6553. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6554. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6555. }
  6556. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6557. if ($object->table_element && $object->id > 0) {
  6558. if (!is_object($extrafields)) {
  6559. $extrafields = new ExtraFields($db);
  6560. }
  6561. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6562. if ($object->fetch_optionals() > 0) {
  6563. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6564. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6565. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6566. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6567. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6568. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6569. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6570. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6571. $datetime = $object->array_options['options_'.$key];
  6572. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6573. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6574. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6575. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6576. }
  6577. }
  6578. }
  6579. }
  6580. }
  6581. // Complete substitution array with the url to make online payment
  6582. $paymenturl = '';
  6583. if (empty($substitutionarray['__REF__'])) {
  6584. $paymenturl = '';
  6585. } else {
  6586. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6587. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6588. $outputlangs->loadLangs(array('paypal', 'other'));
  6589. $typeforonlinepayment = 'free';
  6590. if (is_object($object) && $object->element == 'commande') {
  6591. $typeforonlinepayment = 'order';
  6592. }
  6593. if (is_object($object) && $object->element == 'facture') {
  6594. $typeforonlinepayment = 'invoice';
  6595. }
  6596. if (is_object($object) && $object->element == 'member') {
  6597. $typeforonlinepayment = 'member';
  6598. }
  6599. if (is_object($object) && $object->element == 'contrat') {
  6600. $typeforonlinepayment = 'contract';
  6601. }
  6602. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6603. $paymenturl = $url;
  6604. }
  6605. if ($object->id > 0) {
  6606. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6607. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6608. if (is_object($object) && $object->element == 'propal') {
  6609. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  6610. }
  6611. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6612. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6613. } else {
  6614. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6615. }
  6616. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6617. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6618. } else {
  6619. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6620. }
  6621. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6622. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6623. } else {
  6624. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6625. }
  6626. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6627. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6628. } else {
  6629. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6630. }
  6631. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6632. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6633. } else {
  6634. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6635. }
  6636. if (is_object($object) && $object->element == 'propal') {
  6637. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6638. }
  6639. if (is_object($object) && $object->element == 'commande') {
  6640. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6641. }
  6642. if (is_object($object) && $object->element == 'facture') {
  6643. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6644. }
  6645. if (is_object($object) && $object->element == 'contrat') {
  6646. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6647. }
  6648. if (is_object($object) && $object->element == 'supplier_proposal') {
  6649. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6650. }
  6651. if (is_object($object) && $object->element == 'shipping') {
  6652. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  6653. }
  6654. }
  6655. if (is_object($object) && $object->element == 'action') {
  6656. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6657. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  6658. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  6659. }
  6660. }
  6661. }
  6662. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  6663. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  6664. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  6665. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  6666. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  6667. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  6668. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  6669. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  6670. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6671. $substitutionarray['__AMOUNT_VAT_TEXT__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, '', true) : dol_convertToWord($object->total_tva, $outputlangs, '', true)) : '';
  6672. $substitutionarray['__AMOUNT_VAT_TEXTCURRENCY__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, $conf->currency, true) : dol_convertToWord($object->total_tva, $outputlangs, $conf->currency, true)) : '';
  6673. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6674. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  6675. }
  6676. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6677. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  6678. }
  6679. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6680. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6681. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? (isset($object->total_vat) ? price($object->total_vat, 0, $outputlangs, 0, -1, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, -1, -1, $conf->currency) : null)) : '';
  6682. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6683. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6684. }
  6685. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6686. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6687. }
  6688. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  6689. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  6690. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  6691. // TODO Add other keys for foreign multicurrency
  6692. // For backward compatibility
  6693. if ($onlykey != 2) {
  6694. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  6695. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  6696. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6697. }
  6698. }
  6699. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  6700. if (empty($exclude) || !in_array('date', $exclude)) {
  6701. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6702. $tmp = dol_getdate(dol_now(), true);
  6703. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6704. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  6705. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6706. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  6707. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  6708. $substitutionarray = array_merge($substitutionarray, array(
  6709. '__DAY__' => (string) $tmp['mday'],
  6710. '__DAY_TEXT__' => $daytext, // Monday
  6711. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  6712. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  6713. '__MONTH__' => (string) $tmp['mon'],
  6714. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  6715. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  6716. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  6717. '__YEAR__' => (string) $tmp['year'],
  6718. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  6719. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  6720. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  6721. '__NEXT_DAY__' => (string) $tmp4['day'],
  6722. '__NEXT_MONTH__' => (string) $tmp5['month'],
  6723. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  6724. ));
  6725. }
  6726. if (!empty($conf->multicompany->enabled)) {
  6727. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  6728. }
  6729. if (empty($exclude) || !in_array('system', $exclude)) {
  6730. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  6731. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  6732. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  6733. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  6734. }
  6735. return $substitutionarray;
  6736. }
  6737. /**
  6738. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  6739. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  6740. * Example of usage:
  6741. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  6742. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  6743. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  6744. *
  6745. * @param string $text Source string in which we must do substitution
  6746. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  6747. * @param Translate $outputlangs Output language
  6748. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  6749. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  6750. * @return string Output string after substitutions
  6751. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  6752. */
  6753. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  6754. {
  6755. global $conf, $langs;
  6756. if (!is_array($substitutionarray)) {
  6757. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  6758. }
  6759. if (empty($outputlangs)) {
  6760. $outputlangs = $langs;
  6761. }
  6762. // Is initial text HTML or simple text ?
  6763. $msgishtml = 0;
  6764. if (dol_textishtml($text, 1)) {
  6765. $msgishtml = 1;
  6766. }
  6767. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  6768. if (is_object($outputlangs)) {
  6769. $reg = array();
  6770. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  6771. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  6772. $tmp = explode('|', $reg[1]);
  6773. if (!empty($tmp[1])) {
  6774. $outputlangs->load($tmp[1]);
  6775. }
  6776. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  6777. if (empty($converttextinhtmlifnecessary)) {
  6778. // convert $newval into HTML is necessary
  6779. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6780. } else {
  6781. if (! $msgishtml) {
  6782. $valueishtml = dol_textishtml($value, 1);
  6783. if ($valueishtml) {
  6784. $text = dol_htmlentitiesbr($text);
  6785. $msgishtml = 1;
  6786. }
  6787. } else {
  6788. $value = dol_nl2br("$value");
  6789. }
  6790. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  6791. }
  6792. }
  6793. }
  6794. // Make substitution for constant keys.
  6795. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  6796. $reg = array();
  6797. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  6798. $keyfound = $reg[1];
  6799. if (isASecretKey($keyfound)) {
  6800. $value = '*****forbidden*****';
  6801. } else {
  6802. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  6803. }
  6804. if (empty($converttextinhtmlifnecessary)) {
  6805. // convert $newval into HTML is necessary
  6806. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6807. } else {
  6808. if (! $msgishtml) {
  6809. $valueishtml = dol_textishtml($value, 1);
  6810. if ($valueishtml) {
  6811. $text = dol_htmlentitiesbr($text);
  6812. $msgishtml = 1;
  6813. }
  6814. } else {
  6815. $value = dol_nl2br("$value");
  6816. }
  6817. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  6818. }
  6819. }
  6820. // Make substitition for array $substitutionarray
  6821. foreach ($substitutionarray as $key => $value) {
  6822. if (!isset($value)) {
  6823. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  6824. }
  6825. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  6826. $value = ''; // Protection
  6827. }
  6828. if (empty($converttextinhtmlifnecessary)) {
  6829. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6830. } else {
  6831. if (! $msgishtml) {
  6832. $valueishtml = dol_textishtml($value, 1);
  6833. if ($valueishtml) {
  6834. $text = dol_htmlentitiesbr($text);
  6835. $msgishtml = 1;
  6836. }
  6837. } else {
  6838. $value = dol_nl2br("$value");
  6839. }
  6840. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6841. }
  6842. }
  6843. return $text;
  6844. }
  6845. /**
  6846. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6847. * In this case, method completesubstitutionarray provided by module is called.
  6848. *
  6849. * @param array $substitutionarray Array substitution old value => new value value
  6850. * @param Translate $outputlangs Output language
  6851. * @param Object $object Source object
  6852. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6853. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6854. * @return void
  6855. * @see make_substitutions()
  6856. */
  6857. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6858. {
  6859. global $conf, $user;
  6860. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6861. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  6862. // Check if there is external substitution to do, requested by plugins
  6863. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  6864. foreach ($dirsubstitutions as $reldir) {
  6865. $dir = dol_buildpath($reldir, 0);
  6866. // Check if directory exists
  6867. if (!dol_is_dir($dir)) {
  6868. continue;
  6869. }
  6870. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  6871. foreach ($substitfiles as $substitfile) {
  6872. $reg = array();
  6873. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  6874. $module = $reg[1];
  6875. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  6876. // Include the user's functions file
  6877. require_once $dir.$substitfile['name'];
  6878. // Call the user's function, and only if it is defined
  6879. $function_name = $module."_".$callfunc;
  6880. if (function_exists($function_name)) {
  6881. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  6882. }
  6883. }
  6884. }
  6885. }
  6886. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  6887. // to list all tags in odt template
  6888. $tags = '';
  6889. foreach ($substitutionarray as $key => $value) {
  6890. $tags .= '{'.$key.'} => '.$value."\n";
  6891. }
  6892. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  6893. }
  6894. }
  6895. /**
  6896. * Format output for start and end date
  6897. *
  6898. * @param int $date_start Start date
  6899. * @param int $date_end End date
  6900. * @param string $format Output format
  6901. * @param Translate $outputlangs Output language
  6902. * @return void
  6903. */
  6904. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  6905. {
  6906. print get_date_range($date_start, $date_end, $format, $outputlangs);
  6907. }
  6908. /**
  6909. * Format output for start and end date
  6910. *
  6911. * @param int $date_start Start date
  6912. * @param int $date_end End date
  6913. * @param string $format Output format
  6914. * @param Translate $outputlangs Output language
  6915. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  6916. * @return string String
  6917. */
  6918. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  6919. {
  6920. global $langs;
  6921. $out = '';
  6922. if (!is_object($outputlangs)) {
  6923. $outputlangs = $langs;
  6924. }
  6925. if ($date_start && $date_end) {
  6926. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6927. }
  6928. if ($date_start && !$date_end) {
  6929. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6930. }
  6931. if (!$date_start && $date_end) {
  6932. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6933. }
  6934. return $out;
  6935. }
  6936. /**
  6937. * Return firstname and lastname in correct order
  6938. *
  6939. * @param string $firstname Firstname
  6940. * @param string $lastname Lastname
  6941. * @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
  6942. * @return string Firstname + lastname or Lastname + firstname
  6943. */
  6944. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  6945. {
  6946. global $conf;
  6947. $ret = '';
  6948. // If order not defined, we use the setup
  6949. if ($nameorder < 0) {
  6950. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  6951. }
  6952. if ($nameorder == 1) {
  6953. $ret .= $firstname;
  6954. if ($firstname && $lastname) {
  6955. $ret .= ' ';
  6956. }
  6957. $ret .= $lastname;
  6958. } elseif ($nameorder == 2 || $nameorder == 3) {
  6959. $ret .= $firstname;
  6960. if (empty($ret) && $nameorder == 3) {
  6961. $ret .= $lastname;
  6962. }
  6963. } else { // 0, 4 or 5
  6964. $ret .= $lastname;
  6965. if (empty($ret) && $nameorder == 5) {
  6966. $ret .= $firstname;
  6967. }
  6968. if ($nameorder == 0) {
  6969. if ($firstname && $lastname) {
  6970. $ret .= ' ';
  6971. }
  6972. $ret .= $firstname;
  6973. }
  6974. }
  6975. return $ret;
  6976. }
  6977. /**
  6978. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  6979. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6980. * Note: Prefer to use setEventMessages instead.
  6981. *
  6982. * @param string|string[] $mesgs Message string or array
  6983. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6984. * @return void
  6985. * @see dol_htmloutput_events()
  6986. */
  6987. function setEventMessage($mesgs, $style = 'mesgs')
  6988. {
  6989. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  6990. if (!is_array($mesgs)) {
  6991. // If mesgs is a string
  6992. if ($mesgs) {
  6993. $_SESSION['dol_events'][$style][] = $mesgs;
  6994. }
  6995. } else {
  6996. // If mesgs is an array
  6997. foreach ($mesgs as $mesg) {
  6998. if ($mesg) {
  6999. $_SESSION['dol_events'][$style][] = $mesg;
  7000. }
  7001. }
  7002. }
  7003. }
  7004. /**
  7005. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7006. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7007. *
  7008. * @param string $mesg Message string
  7009. * @param array $mesgs Message array
  7010. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7011. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7012. * @return void
  7013. * @see dol_htmloutput_events()
  7014. */
  7015. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  7016. {
  7017. if (empty($mesg) && empty($mesgs)) {
  7018. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  7019. } else {
  7020. if ($messagekey) {
  7021. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7022. // TODO
  7023. $mesg .= '';
  7024. }
  7025. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7026. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7027. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7028. }
  7029. if (empty($mesgs)) {
  7030. setEventMessage($mesg, $style);
  7031. } else {
  7032. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7033. setEventMessage($mesg, $style); // Add message string if not already into array
  7034. }
  7035. setEventMessage($mesgs, $style);
  7036. }
  7037. }
  7038. }
  7039. }
  7040. /**
  7041. * Print formated messages to output (Used to show messages on html output).
  7042. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7043. * no need to call it explicitely.
  7044. *
  7045. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7046. * @return void
  7047. * @see dol_htmloutput_mesg()
  7048. */
  7049. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7050. {
  7051. // Show mesgs
  7052. if (isset($_SESSION['dol_events']['mesgs'])) {
  7053. if (empty($disabledoutputofmessages)) {
  7054. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7055. }
  7056. unset($_SESSION['dol_events']['mesgs']);
  7057. }
  7058. // Show errors
  7059. if (isset($_SESSION['dol_events']['errors'])) {
  7060. if (empty($disabledoutputofmessages)) {
  7061. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7062. }
  7063. unset($_SESSION['dol_events']['errors']);
  7064. }
  7065. // Show warnings
  7066. if (isset($_SESSION['dol_events']['warnings'])) {
  7067. if (empty($disabledoutputofmessages)) {
  7068. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7069. }
  7070. unset($_SESSION['dol_events']['warnings']);
  7071. }
  7072. }
  7073. /**
  7074. * Get formated messages to output (Used to show messages on html output).
  7075. * This include also the translation of the message key.
  7076. *
  7077. * @param string $mesgstring Message string or message key
  7078. * @param string[] $mesgarray Array of message strings or message keys
  7079. * @param string $style Style of message output ('ok' or 'error')
  7080. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7081. * @return string Return html output
  7082. *
  7083. * @see dol_print_error()
  7084. * @see dol_htmloutput_errors()
  7085. * @see setEventMessages()
  7086. */
  7087. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7088. {
  7089. global $conf, $langs;
  7090. $ret = 0;
  7091. $return = '';
  7092. $out = '';
  7093. $divstart = $divend = '';
  7094. // If inline message with no format, we add it.
  7095. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7096. $divstart = '<div class="'.$style.' clearboth">';
  7097. $divend = '</div>';
  7098. }
  7099. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7100. $langs->load("errors");
  7101. $out .= $divstart;
  7102. if (is_array($mesgarray) && count($mesgarray)) {
  7103. foreach ($mesgarray as $message) {
  7104. $ret++;
  7105. $out .= $langs->trans($message);
  7106. if ($ret < count($mesgarray)) {
  7107. $out .= "<br>\n";
  7108. }
  7109. }
  7110. }
  7111. if ($mesgstring) {
  7112. $langs->load("errors");
  7113. $ret++;
  7114. $out .= $langs->trans($mesgstring);
  7115. }
  7116. $out .= $divend;
  7117. }
  7118. if ($out) {
  7119. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7120. $return = '<script>
  7121. $(document).ready(function() {
  7122. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7123. if (block) {
  7124. $.dolEventValid("","'.dol_escape_js($out).'");
  7125. } else {
  7126. /* jnotify(message, preset of message type, keepmessage) */
  7127. $.jnotify("'.dol_escape_js($out).'",
  7128. "'.($style == "ok" ? 3000 : $style).'",
  7129. '.($style == "ok" ? "false" : "true").',
  7130. { remove: function (){} } );
  7131. }
  7132. });
  7133. </script>';
  7134. } else {
  7135. $return = $out;
  7136. }
  7137. }
  7138. return $return;
  7139. }
  7140. /**
  7141. * Get formated error messages to output (Used to show messages on html output).
  7142. *
  7143. * @param string $mesgstring Error message
  7144. * @param array $mesgarray Error messages array
  7145. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7146. * @return string Return html output
  7147. *
  7148. * @see dol_print_error()
  7149. * @see dol_htmloutput_mesg()
  7150. */
  7151. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7152. {
  7153. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7154. }
  7155. /**
  7156. * Print formated messages to output (Used to show messages on html output).
  7157. *
  7158. * @param string $mesgstring Message string or message key
  7159. * @param string[] $mesgarray Array of message strings or message keys
  7160. * @param string $style Which style to use ('ok', 'warning', 'error')
  7161. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7162. * @return void
  7163. *
  7164. * @see dol_print_error()
  7165. * @see dol_htmloutput_errors()
  7166. * @see setEventMessages()
  7167. */
  7168. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7169. {
  7170. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7171. return;
  7172. }
  7173. $iserror = 0;
  7174. $iswarning = 0;
  7175. if (is_array($mesgarray)) {
  7176. foreach ($mesgarray as $val) {
  7177. if ($val && preg_match('/class="error"/i', $val)) {
  7178. $iserror++;
  7179. break;
  7180. }
  7181. if ($val && preg_match('/class="warning"/i', $val)) {
  7182. $iswarning++;
  7183. break;
  7184. }
  7185. }
  7186. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7187. $iserror++;
  7188. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7189. $iswarning++;
  7190. }
  7191. if ($style == 'error') {
  7192. $iserror++;
  7193. }
  7194. if ($style == 'warning') {
  7195. $iswarning++;
  7196. }
  7197. if ($iserror || $iswarning) {
  7198. // Remove div from texts
  7199. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7200. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7201. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7202. // Remove div from texts array
  7203. if (is_array($mesgarray)) {
  7204. $newmesgarray = array();
  7205. foreach ($mesgarray as $val) {
  7206. if (is_string($val)) {
  7207. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7208. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7209. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7210. $newmesgarray[] = $tmpmesgstring;
  7211. } else {
  7212. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7213. }
  7214. }
  7215. $mesgarray = $newmesgarray;
  7216. }
  7217. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7218. } else {
  7219. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7220. }
  7221. }
  7222. /**
  7223. * Print formated error messages to output (Used to show messages on html output).
  7224. *
  7225. * @param string $mesgstring Error message
  7226. * @param array $mesgarray Error messages array
  7227. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7228. * @return void
  7229. *
  7230. * @see dol_print_error()
  7231. * @see dol_htmloutput_mesg()
  7232. */
  7233. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7234. {
  7235. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7236. }
  7237. /**
  7238. * Advanced sort array by second index function, which produces ascending (default)
  7239. * or descending output and uses optionally natural case insensitive sorting (which
  7240. * can be optionally case sensitive as well).
  7241. *
  7242. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7243. * @param string $index Key in array to use for sorting criteria
  7244. * @param int $order Sort order ('asc' or 'desc')
  7245. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7246. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7247. * @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.
  7248. * @return array Sorted array
  7249. */
  7250. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7251. {
  7252. // Clean parameters
  7253. $order = strtolower($order);
  7254. if (is_array($array)) {
  7255. $sizearray = count($array);
  7256. if ($sizearray > 0) {
  7257. $temp = array();
  7258. foreach (array_keys($array) as $key) {
  7259. if (is_object($array[$key])) {
  7260. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7261. } else {
  7262. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7263. }
  7264. }
  7265. if (!$natsort) {
  7266. if ($order == 'asc') {
  7267. asort($temp);
  7268. } else {
  7269. arsort($temp);
  7270. }
  7271. } else {
  7272. if ($case_sensitive) {
  7273. natsort($temp);
  7274. } else {
  7275. natcasesort($temp); // natecasesort is not sensible to case
  7276. }
  7277. if ($order != 'asc') {
  7278. $temp = array_reverse($temp, true);
  7279. }
  7280. }
  7281. $sorted = array();
  7282. foreach (array_keys($temp) as $key) {
  7283. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7284. }
  7285. return $sorted;
  7286. }
  7287. }
  7288. return $array;
  7289. }
  7290. /**
  7291. * Check if a string is in UTF8
  7292. *
  7293. * @param string $str String to check
  7294. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7295. */
  7296. function utf8_check($str)
  7297. {
  7298. $str = (string) $str; // Sometimes string is an int.
  7299. // We must use here a binary strlen function (so not dol_strlen)
  7300. $strLength = dol_strlen($str);
  7301. for ($i = 0; $i < $strLength; $i++) {
  7302. if (ord($str[$i]) < 0x80) {
  7303. continue; // 0bbbbbbb
  7304. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7305. $n = 1; // 110bbbbb
  7306. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7307. $n = 2; // 1110bbbb
  7308. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7309. $n = 3; // 11110bbb
  7310. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7311. $n = 4; // 111110bb
  7312. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7313. $n = 5; // 1111110b
  7314. } else {
  7315. return false; // Does not match any model
  7316. }
  7317. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7318. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7319. return false;
  7320. }
  7321. }
  7322. }
  7323. return true;
  7324. }
  7325. /**
  7326. * Check if a string is in ASCII
  7327. *
  7328. * @param string $str String to check
  7329. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7330. */
  7331. function ascii_check($str)
  7332. {
  7333. if (function_exists('mb_check_encoding')) {
  7334. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7335. if (!mb_check_encoding($str, 'ASCII')) {
  7336. return false;
  7337. }
  7338. } else {
  7339. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7340. return false; // Contains a byte > 7f
  7341. }
  7342. }
  7343. return true;
  7344. }
  7345. /**
  7346. * Return a string encoded into OS filesystem encoding. This function is used to define
  7347. * value to pass to filesystem PHP functions.
  7348. *
  7349. * @param string $str String to encode (UTF-8)
  7350. * @return string Encoded string (UTF-8, ISO-8859-1)
  7351. */
  7352. function dol_osencode($str)
  7353. {
  7354. global $conf;
  7355. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7356. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7357. $tmp = 'iso-8859-1'; // By default for windows
  7358. }
  7359. if (empty($tmp)) {
  7360. $tmp = 'utf-8'; // By default for other
  7361. }
  7362. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7363. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7364. }
  7365. if ($tmp == 'iso-8859-1') {
  7366. return utf8_decode($str);
  7367. }
  7368. return $str;
  7369. }
  7370. /**
  7371. * Return an id or code from a code or id.
  7372. * Store also Code-Id into a cache to speed up next request on same key.
  7373. *
  7374. * @param DoliDB $db Database handler
  7375. * @param string $key Code or Id to get Id or Code
  7376. * @param string $tablename Table name without prefix
  7377. * @param string $fieldkey Field to search the key into
  7378. * @param string $fieldid Field to get
  7379. * @param int $entityfilter Filter by entity
  7380. * @return int <0 if KO, Id of code if OK
  7381. * @see $langs->getLabelFromKey
  7382. */
  7383. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  7384. {
  7385. global $cache_codes;
  7386. // If key empty
  7387. if ($key == '') {
  7388. return '';
  7389. }
  7390. // Check in cache
  7391. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7392. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7393. }
  7394. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7395. $sql = "SELECT ".$fieldid." as valuetoget";
  7396. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7397. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7398. if (!empty($entityfilter)) {
  7399. $sql .= " AND entity IN (".getEntity($tablename).")";
  7400. }
  7401. $resql = $db->query($sql);
  7402. if ($resql) {
  7403. $obj = $db->fetch_object($resql);
  7404. if ($obj) {
  7405. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7406. } else {
  7407. $cache_codes[$tablename][$key][$fieldid] = '';
  7408. }
  7409. $db->free($resql);
  7410. return $cache_codes[$tablename][$key][$fieldid];
  7411. } else {
  7412. return -1;
  7413. }
  7414. }
  7415. /**
  7416. * Verify if condition in string is ok or not
  7417. *
  7418. * @param string $strToEvaluate String with condition to check
  7419. * @return boolean True or False. Note: It returns True if $strToEvaluate is ''
  7420. */
  7421. function verifCond($strToEvaluate)
  7422. {
  7423. global $user, $conf, $langs;
  7424. global $leftmenu;
  7425. global $rights; // To export to dol_eval function
  7426. //print $strToEvaluate."<br>\n";
  7427. $rights = true;
  7428. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  7429. $str = 'if(!('.$strToEvaluate.')) { $rights = false; }';
  7430. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  7431. }
  7432. return $rights;
  7433. }
  7434. /**
  7435. * Replace eval function to add more security.
  7436. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7437. *
  7438. * @param string $s String to evaluate
  7439. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7440. * @param int $hideerrors 1=Hide errors
  7441. * @return mixed Nothing or return result of eval
  7442. */
  7443. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  7444. {
  7445. // Only global variables can be changed by eval function and returned to caller
  7446. global $db, $langs, $user, $conf, $website, $websitepage;
  7447. global $action, $mainmenu, $leftmenu;
  7448. global $rights;
  7449. global $object;
  7450. global $mysoc;
  7451. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7452. global $soc; // For backward compatibility
  7453. // Replace dangerous char (used for RCE), we allow only PHP variable testing.
  7454. if (strpos($s, '`') !== false) {
  7455. return 'Bad string syntax to evaluate: '.$s;
  7456. }
  7457. // We block use of php exec or php file functions
  7458. $forbiddenphpstrings = array('$$');
  7459. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7460. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI");
  7461. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask"));
  7462. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  7463. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  7464. do {
  7465. $oldstringtoclean = $s;
  7466. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7467. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  7468. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7469. } while ($oldstringtoclean != $s);
  7470. if (strpos($s, '__forbiddenstring__') !== false) {
  7471. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7472. return 'Bad string syntax to evaluate: '.$s;
  7473. }
  7474. //print $s."<br>\n";
  7475. if ($returnvalue) {
  7476. if ($hideerrors) {
  7477. return @eval('return '.$s.';');
  7478. } else {
  7479. return eval('return '.$s.';');
  7480. }
  7481. } else {
  7482. if ($hideerrors) {
  7483. @eval($s);
  7484. } else {
  7485. eval($s);
  7486. }
  7487. }
  7488. }
  7489. /**
  7490. * Return if var element is ok
  7491. *
  7492. * @param string $element Variable to check
  7493. * @return boolean Return true of variable is not empty
  7494. */
  7495. function dol_validElement($element)
  7496. {
  7497. return (trim($element) != '');
  7498. }
  7499. /**
  7500. * Return img flag of country for a language code or country code.
  7501. *
  7502. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7503. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7504. * @param int $notitlealt No title alt
  7505. * @return string HTML img string with flag.
  7506. */
  7507. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  7508. {
  7509. if (empty($codelang)) {
  7510. return '';
  7511. }
  7512. if ($codelang == 'auto') {
  7513. return '<span class="fa fa-language"></span>';
  7514. }
  7515. $langtocountryflag = array(
  7516. 'ar_AR' => '',
  7517. 'ca_ES' => 'catalonia',
  7518. 'da_DA' => 'dk',
  7519. 'fr_CA' => 'mq',
  7520. 'sv_SV' => 'se',
  7521. 'sw_SW' => 'unknown',
  7522. 'AQ' => 'unknown',
  7523. 'CW' => 'unknown',
  7524. 'IM' => 'unknown',
  7525. 'JE' => 'unknown',
  7526. 'MF' => 'unknown',
  7527. 'BL' => 'unknown',
  7528. 'SX' => 'unknown'
  7529. );
  7530. if (isset($langtocountryflag[$codelang])) {
  7531. $flagImage = $langtocountryflag[$codelang];
  7532. } else {
  7533. $tmparray = explode('_', $codelang);
  7534. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7535. }
  7536. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  7537. }
  7538. /**
  7539. * Return default language from country code.
  7540. * Return null if not found.
  7541. *
  7542. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  7543. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  7544. */
  7545. function getLanguageCodeFromCountryCode($countrycode)
  7546. {
  7547. global $mysoc;
  7548. if (empty($countrycode)) {
  7549. return null;
  7550. }
  7551. if (strtoupper($countrycode) == 'MQ') {
  7552. return 'fr_CA';
  7553. }
  7554. if (strtoupper($countrycode) == 'SE') {
  7555. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7556. }
  7557. if (strtoupper($countrycode) == 'CH') {
  7558. if ($mysoc->country_code == 'FR') {
  7559. return 'fr_CH';
  7560. }
  7561. if ($mysoc->country_code == 'DE') {
  7562. return 'de_CH';
  7563. }
  7564. if ($mysoc->country_code == 'IT') {
  7565. return 'it_CH';
  7566. }
  7567. }
  7568. // Locale list taken from:
  7569. // http://stackoverflow.com/questions/3191664/
  7570. // list-of-all-locales-and-their-short-codes
  7571. $locales = array(
  7572. 'af-ZA',
  7573. 'am-ET',
  7574. 'ar-AE',
  7575. 'ar-BH',
  7576. 'ar-DZ',
  7577. 'ar-EG',
  7578. 'ar-IQ',
  7579. 'ar-JO',
  7580. 'ar-KW',
  7581. 'ar-LB',
  7582. 'ar-LY',
  7583. 'ar-MA',
  7584. 'ar-OM',
  7585. 'ar-QA',
  7586. 'ar-SA',
  7587. 'ar-SY',
  7588. 'ar-TN',
  7589. 'ar-YE',
  7590. //'as-IN', // Moved after en-IN
  7591. 'ba-RU',
  7592. 'be-BY',
  7593. 'bg-BG',
  7594. 'bn-BD',
  7595. //'bn-IN', // Moved after en-IN
  7596. 'bo-CN',
  7597. 'br-FR',
  7598. 'ca-ES',
  7599. 'co-FR',
  7600. 'cs-CZ',
  7601. 'cy-GB',
  7602. 'da-DK',
  7603. 'de-AT',
  7604. 'de-CH',
  7605. 'de-DE',
  7606. 'de-LI',
  7607. 'de-LU',
  7608. 'dv-MV',
  7609. 'el-GR',
  7610. 'en-AU',
  7611. 'en-BZ',
  7612. 'en-CA',
  7613. 'en-GB',
  7614. 'en-IE',
  7615. 'en-IN',
  7616. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  7617. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  7618. 'en-JM',
  7619. 'en-MY',
  7620. 'en-NZ',
  7621. 'en-PH',
  7622. 'en-SG',
  7623. 'en-TT',
  7624. 'en-US',
  7625. 'en-ZA',
  7626. 'en-ZW',
  7627. 'es-AR',
  7628. 'es-BO',
  7629. 'es-CL',
  7630. 'es-CO',
  7631. 'es-CR',
  7632. 'es-DO',
  7633. 'es-EC',
  7634. 'es-ES',
  7635. 'es-GT',
  7636. 'es-HN',
  7637. 'es-MX',
  7638. 'es-NI',
  7639. 'es-PA',
  7640. 'es-PE',
  7641. 'es-PR',
  7642. 'es-PY',
  7643. 'es-SV',
  7644. 'es-US',
  7645. 'es-UY',
  7646. 'es-VE',
  7647. 'et-EE',
  7648. 'eu-ES',
  7649. 'fa-IR',
  7650. 'fi-FI',
  7651. 'fo-FO',
  7652. 'fr-BE',
  7653. 'fr-CA',
  7654. 'fr-CH',
  7655. 'fr-FR',
  7656. 'fr-LU',
  7657. 'fr-MC',
  7658. 'fy-NL',
  7659. 'ga-IE',
  7660. 'gd-GB',
  7661. 'gl-ES',
  7662. 'gu-IN',
  7663. 'he-IL',
  7664. 'hi-IN',
  7665. 'hr-BA',
  7666. 'hr-HR',
  7667. 'hu-HU',
  7668. 'hy-AM',
  7669. 'id-ID',
  7670. 'ig-NG',
  7671. 'ii-CN',
  7672. 'is-IS',
  7673. 'it-CH',
  7674. 'it-IT',
  7675. 'ja-JP',
  7676. 'ka-GE',
  7677. 'kk-KZ',
  7678. 'kl-GL',
  7679. 'km-KH',
  7680. 'kn-IN',
  7681. 'ko-KR',
  7682. 'ky-KG',
  7683. 'lb-LU',
  7684. 'lo-LA',
  7685. 'lt-LT',
  7686. 'lv-LV',
  7687. 'mi-NZ',
  7688. 'mk-MK',
  7689. 'ml-IN',
  7690. 'mn-MN',
  7691. 'mr-IN',
  7692. 'ms-BN',
  7693. 'ms-MY',
  7694. 'mt-MT',
  7695. 'nb-NO',
  7696. 'ne-NP',
  7697. 'nl-BE',
  7698. 'nl-NL',
  7699. 'nn-NO',
  7700. 'oc-FR',
  7701. 'or-IN',
  7702. 'pa-IN',
  7703. 'pl-PL',
  7704. 'ps-AF',
  7705. 'pt-BR',
  7706. 'pt-PT',
  7707. 'rm-CH',
  7708. 'ro-MD',
  7709. 'ro-RO',
  7710. 'ru-RU',
  7711. 'rw-RW',
  7712. 'sa-IN',
  7713. 'se-FI',
  7714. 'se-NO',
  7715. 'se-SE',
  7716. 'si-LK',
  7717. 'sk-SK',
  7718. 'sl-SI',
  7719. 'sq-AL',
  7720. 'sv-FI',
  7721. 'sv-SE',
  7722. 'sw-KE',
  7723. 'ta-IN',
  7724. 'te-IN',
  7725. 'th-TH',
  7726. 'tk-TM',
  7727. 'tn-ZA',
  7728. 'tr-TR',
  7729. 'tt-RU',
  7730. 'ug-CN',
  7731. 'uk-UA',
  7732. 'ur-PK',
  7733. 'vi-VN',
  7734. 'wo-SN',
  7735. 'xh-ZA',
  7736. 'yo-NG',
  7737. 'zh-CN',
  7738. 'zh-HK',
  7739. 'zh-MO',
  7740. 'zh-SG',
  7741. 'zh-TW',
  7742. 'zu-ZA',
  7743. );
  7744. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  7745. if (in_array($buildprimarykeytotest, $locales)) {
  7746. return strtolower($countrycode).'_'.strtoupper($countrycode);
  7747. }
  7748. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  7749. foreach ($locales as $locale) {
  7750. $locale_language = locale_get_primary_language($locale);
  7751. $locale_region = locale_get_region($locale);
  7752. if (strtoupper($countrycode) == $locale_region) {
  7753. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  7754. return strtolower($locale_language).'_'.strtoupper($locale_region);
  7755. }
  7756. }
  7757. } else {
  7758. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  7759. }
  7760. return null;
  7761. }
  7762. /**
  7763. * Complete or removed entries into a head array (used to build tabs).
  7764. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  7765. * Or by change using hook completeTabsHead
  7766. *
  7767. * @param Conf $conf Object conf
  7768. * @param Translate $langs Object langs
  7769. * @param object|null $object Object object
  7770. * @param array $head Object head
  7771. * @param int $h New position to fill
  7772. * @param string $type Value for object where objectvalue can be
  7773. * 'thirdparty' to add a tab in third party view
  7774. * 'intervention' to add a tab in intervention view
  7775. * 'supplier_order' to add a tab in supplier order view
  7776. * 'supplier_invoice' to add a tab in supplier invoice view
  7777. * 'invoice' to add a tab in customer invoice view
  7778. * 'order' to add a tab in customer order view
  7779. * 'contract' to add a tabl in contract view
  7780. * 'product' to add a tab in product view
  7781. * 'propal' to add a tab in propal view
  7782. * 'user' to add a tab in user view
  7783. * 'group' to add a tab in group view
  7784. * 'member' to add a tab in fundation member view
  7785. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  7786. * 'ecm' to add a tab for another ecm view
  7787. * 'stock' to add a tab for warehouse view
  7788. * @param string $mode 'add' to complete head, 'remove' to remove entries
  7789. * @return void
  7790. */
  7791. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  7792. {
  7793. global $hookmanager;
  7794. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  7795. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  7796. $values = explode(':', $value);
  7797. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  7798. if (count($values) == 6) { // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  7799. if ($values[0] != $type) {
  7800. continue;
  7801. }
  7802. if (verifCond($values[4])) {
  7803. if ($values[3]) {
  7804. $langs->load($values[3]);
  7805. }
  7806. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7807. $substitutionarray = array();
  7808. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7809. $label = make_substitutions($reg[1], $substitutionarray);
  7810. } else {
  7811. $label = $langs->trans($values[2]);
  7812. }
  7813. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  7814. $head[$h][1] = $label;
  7815. $head[$h][2] = str_replace('+', '', $values[1]);
  7816. $h++;
  7817. }
  7818. } elseif (count($values) == 5) { // deprecated
  7819. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  7820. if ($values[0] != $type) {
  7821. continue;
  7822. }
  7823. if ($values[3]) {
  7824. $langs->load($values[3]);
  7825. }
  7826. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7827. $substitutionarray = array();
  7828. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7829. $label = make_substitutions($reg[1], $substitutionarray);
  7830. } else {
  7831. $label = $langs->trans($values[2]);
  7832. }
  7833. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  7834. $head[$h][1] = $label;
  7835. $head[$h][2] = str_replace('+', '', $values[1]);
  7836. $h++;
  7837. }
  7838. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  7839. if ($values[0] != $type) {
  7840. continue;
  7841. }
  7842. $tabname = str_replace('-', '', $values[1]);
  7843. foreach ($head as $key => $val) {
  7844. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  7845. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  7846. if ($head[$key][2] == $tabname && $condition) {
  7847. unset($head[$key]);
  7848. break;
  7849. }
  7850. }
  7851. }
  7852. }
  7853. }
  7854. // No need to make a return $head. Var is modified as a reference
  7855. if (!empty($hookmanager)) {
  7856. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  7857. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  7858. if ($reshook > 0) { // Hook ask to replace completely the array
  7859. $head = $hookmanager->resArray;
  7860. } else { // Hook
  7861. $head = array_merge($head, $hookmanager->resArray);
  7862. }
  7863. $h = count($head);
  7864. }
  7865. }
  7866. /**
  7867. * Print common footer :
  7868. * conf->global->MAIN_HTML_FOOTER
  7869. * js for switch of menu hider
  7870. * js for conf->global->MAIN_GOOGLE_AN_ID
  7871. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  7872. * js for conf->logbuffer
  7873. *
  7874. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  7875. * @return void
  7876. */
  7877. function printCommonFooter($zone = 'private')
  7878. {
  7879. global $conf, $hookmanager, $user, $debugbar;
  7880. global $action;
  7881. global $micro_start_time;
  7882. if ($zone == 'private') {
  7883. print "\n".'<!-- Common footer for private page -->'."\n";
  7884. } else {
  7885. print "\n".'<!-- Common footer for public page -->'."\n";
  7886. }
  7887. // A div to store page_y POST parameter so we can read it using javascript
  7888. print "\n<!-- A div to store page_y POST parameter -->\n";
  7889. print '<div id="page_y" style="display: none;">'.(empty($_POST['page_y']) ? '' : $_POST['page_y']).'</div>'."\n";
  7890. $parameters = array();
  7891. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  7892. if (empty($reshook)) {
  7893. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  7894. print $conf->global->MAIN_HTML_FOOTER."\n";
  7895. }
  7896. print "\n";
  7897. if (!empty($conf->use_javascript_ajax)) {
  7898. print '<script>'."\n";
  7899. print 'jQuery(document).ready(function() {'."\n";
  7900. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  7901. print "\n";
  7902. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  7903. print 'jQuery("li.menuhider").click(function(event) {';
  7904. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  7905. print ' console.log("We click on .menuhider");'."\n";
  7906. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  7907. print '});'."\n";
  7908. }
  7909. // Management of focus and mandatory for fields
  7910. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  7911. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  7912. $relativepathstring = $_SERVER["PHP_SELF"];
  7913. // Clean $relativepathstring
  7914. if (constant('DOL_URL_ROOT')) {
  7915. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  7916. }
  7917. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  7918. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  7919. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  7920. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  7921. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  7922. $qualified = 0;
  7923. if ($defkey != '_noquery_') {
  7924. $tmpqueryarraytohave = explode('&', $defkey);
  7925. $foundintru = 0;
  7926. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7927. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7928. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7929. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7930. $foundintru = 1;
  7931. }
  7932. }
  7933. if (!$foundintru) {
  7934. $qualified = 1;
  7935. }
  7936. //var_dump($defkey.'-'.$qualified);
  7937. } else {
  7938. $qualified = 1;
  7939. }
  7940. if ($qualified) {
  7941. foreach ($defval as $paramkey => $paramval) {
  7942. // Set focus on field
  7943. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  7944. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  7945. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  7946. }
  7947. }
  7948. }
  7949. }
  7950. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  7951. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  7952. $qualified = 0;
  7953. if ($defkey != '_noquery_') {
  7954. $tmpqueryarraytohave = explode('&', $defkey);
  7955. $foundintru = 0;
  7956. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7957. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7958. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7959. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7960. $foundintru = 1;
  7961. }
  7962. }
  7963. if (!$foundintru) {
  7964. $qualified = 1;
  7965. }
  7966. //var_dump($defkey.'-'.$qualified);
  7967. } else {
  7968. $qualified = 1;
  7969. }
  7970. if ($qualified) {
  7971. foreach ($defval as $paramkey => $paramval) {
  7972. // Add property 'required' on input
  7973. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7974. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7975. print '// required on a select works only if key is "", so we add the required attributes but also we reset the key -1 or 0 to an empty string'."\n";
  7976. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7977. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  7978. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  7979. }
  7980. }
  7981. }
  7982. }
  7983. }
  7984. print '});'."\n";
  7985. // End of tuning
  7986. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  7987. print "\n";
  7988. print "/* JS CODE TO ENABLE to add memory info */\n";
  7989. print 'window.console && console.log("';
  7990. if (!empty($conf->global->MEMCACHED_SERVER)) {
  7991. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  7992. }
  7993. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  7994. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  7995. $micro_end_time = microtime(true);
  7996. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  7997. }
  7998. if (function_exists("memory_get_usage")) {
  7999. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  8000. }
  8001. if (function_exists("memory_get_peak_usage")) {
  8002. print ' - Real mem peak: '.memory_get_peak_usage(true);
  8003. }
  8004. if (function_exists("zend_loader_file_encoded")) {
  8005. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8006. }
  8007. print '");'."\n";
  8008. }
  8009. print "\n".'</script>'."\n";
  8010. // Google Analytics
  8011. // TODO Add a hook here
  8012. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8013. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8014. foreach ($tmptagarray as $tmptag) {
  8015. print "\n";
  8016. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8017. print "
  8018. <!-- Global site tag (gtag.js) - Google Analytics -->
  8019. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  8020. <script>
  8021. window.dataLayer = window.dataLayer || [];
  8022. function gtag(){dataLayer.push(arguments);}
  8023. gtag('js', new Date());
  8024. gtag('config', '".trim($tmptag)."');
  8025. </script>";
  8026. print "\n";
  8027. }
  8028. }
  8029. }
  8030. // Add Xdebug coverage of code
  8031. if (defined('XDEBUGCOVERAGE')) {
  8032. print_r(xdebug_get_code_coverage());
  8033. }
  8034. // Add DebugBar data
  8035. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8036. $debugbar['time']->stopMeasure('pageaftermaster');
  8037. print '<!-- Output debugbar data -->'."\n";
  8038. $renderer = $debugbar->getRenderer();
  8039. print $debugbar->getRenderer()->render();
  8040. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8041. print "\n";
  8042. print "<!-- Start of log output\n";
  8043. //print '<div class="hidden">'."\n";
  8044. foreach ($conf->logbuffer as $logline) {
  8045. print $logline."<br>\n";
  8046. }
  8047. //print '</div>'."\n";
  8048. print "End of log output -->\n";
  8049. }
  8050. }
  8051. }
  8052. /**
  8053. * Split a string with 2 keys into key array.
  8054. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8055. *
  8056. * @param string $string String to explode
  8057. * @param string $delimiter Delimiter between each couple of data
  8058. * @param string $kv Delimiter between key and value
  8059. * @return array Array of data exploded
  8060. */
  8061. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8062. {
  8063. if ($a = explode($delimiter, $string)) {
  8064. $ka = array();
  8065. foreach ($a as $s) { // each part
  8066. if ($s) {
  8067. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8068. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8069. } else { // key delimiter not found
  8070. $ka[] = trim($s);
  8071. }
  8072. }
  8073. }
  8074. return $ka;
  8075. }
  8076. return array();
  8077. }
  8078. /**
  8079. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  8080. *
  8081. * @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.
  8082. * @return void
  8083. */
  8084. function dol_set_focus($selector)
  8085. {
  8086. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8087. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8088. }
  8089. /**
  8090. * Return getmypid() or random PID when function is disabled
  8091. * Some web hosts disable this php function for security reasons
  8092. * and sometimes we can't redeclare function
  8093. *
  8094. * @return int
  8095. */
  8096. function dol_getmypid()
  8097. {
  8098. if (!function_exists('getmypid')) {
  8099. return mt_rand(1, 32768);
  8100. } else {
  8101. return getmypid();
  8102. }
  8103. }
  8104. /**
  8105. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8106. *
  8107. * @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")
  8108. * @param string $value The value to look for.
  8109. * If param $mode is 0, can contains several keywords separated with a space or |
  8110. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8111. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8112. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8113. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8114. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8115. * @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')
  8116. * 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'
  8117. * @param integer $nofirstand 1=Do not output the first 'AND'
  8118. * @return string $res The statement to append to the SQL query
  8119. */
  8120. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8121. {
  8122. global $db, $langs;
  8123. $value = trim($value);
  8124. if ($mode == 0) {
  8125. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8126. }
  8127. if ($mode == 1) {
  8128. $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
  8129. }
  8130. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8131. $crits = explode(' ', $value);
  8132. $res = '';
  8133. if (!is_array($fields)) {
  8134. $fields = array($fields);
  8135. }
  8136. $j = 0;
  8137. foreach ($crits as $crit) {
  8138. $crit = trim($crit);
  8139. $i = 0;
  8140. $i2 = 0;
  8141. $newres = '';
  8142. foreach ($fields as $field) {
  8143. if ($mode == 1) {
  8144. $operator = '=';
  8145. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8146. $reg = array();
  8147. preg_match('/([<>=]+)/', $crit, $reg);
  8148. if ($reg[1]) {
  8149. $operator = $reg[1];
  8150. }
  8151. if ($newcrit != '') {
  8152. $numnewcrit = price2num($newcrit);
  8153. if (is_numeric($numnewcrit)) {
  8154. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  8155. } else {
  8156. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8157. }
  8158. $i2++; // a criteria was added to string
  8159. }
  8160. } elseif ($mode == 2 || $mode == -2) {
  8161. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8162. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8163. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8164. if ($mode == -2) {
  8165. $newres .= ' OR '.$field.' IS NULL';
  8166. }
  8167. $i2++; // a criteria was added to string
  8168. } elseif ($mode == 3 || $mode == -3) {
  8169. $tmparray = explode(',', $crit);
  8170. if (count($tmparray)) {
  8171. $listofcodes = '';
  8172. foreach ($tmparray as $val) {
  8173. $val = trim($val);
  8174. if ($val) {
  8175. $listofcodes .= ($listofcodes ? ',' : '');
  8176. $listofcodes .= "'".$db->escape($val)."'";
  8177. }
  8178. }
  8179. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8180. $i2++; // a criteria was added to string
  8181. }
  8182. if ($mode == -3) {
  8183. $newres .= ' OR '.$field.' IS NULL';
  8184. }
  8185. } elseif ($mode == 4) {
  8186. $tmparray = explode(',', $crit);
  8187. if (count($tmparray)) {
  8188. $listofcodes = '';
  8189. foreach ($tmparray as $val) {
  8190. $val = trim($val);
  8191. if ($val) {
  8192. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8193. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8194. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8195. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8196. $newres .= ')';
  8197. $i2++;
  8198. }
  8199. }
  8200. }
  8201. } else // $mode=0
  8202. {
  8203. $tmpcrits = explode('|', $crit);
  8204. $i3 = 0;
  8205. foreach ($tmpcrits as $tmpcrit) {
  8206. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8207. continue;
  8208. }
  8209. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8210. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8211. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? ((float) trim($tmpcrit)) : '0');
  8212. } else {
  8213. $newres .= $field." LIKE '";
  8214. $tmpcrit = trim($tmpcrit);
  8215. $tmpcrit2 = $tmpcrit;
  8216. $tmpbefore = '%';
  8217. $tmpafter = '%';
  8218. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8219. $tmpbefore = '';
  8220. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8221. }
  8222. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8223. $tmpafter = '';
  8224. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8225. }
  8226. $newres .= $tmpbefore;
  8227. $newres .= $db->escape($tmpcrit2);
  8228. $newres .= $tmpafter;
  8229. $newres .= "'";
  8230. if ($tmpcrit2 == '') {
  8231. $newres .= " OR ".$field." IS NULL";
  8232. }
  8233. }
  8234. $i3++;
  8235. }
  8236. $i2++; // a criteria was added to string
  8237. }
  8238. $i++;
  8239. }
  8240. if ($newres) {
  8241. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8242. }
  8243. $j++;
  8244. }
  8245. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8246. //print 'xx'.$res.'yy';
  8247. return $res;
  8248. }
  8249. /**
  8250. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8251. *
  8252. * @param Object $object Object
  8253. * @return string Url string
  8254. */
  8255. function showDirectDownloadLink($object)
  8256. {
  8257. global $conf, $langs;
  8258. $out = '';
  8259. $url = $object->getLastMainDocLink($object->element);
  8260. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8261. if ($url) {
  8262. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8263. $out .= ajax_autoselect("directdownloadlink", 0);
  8264. } else {
  8265. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8266. }
  8267. return $out;
  8268. }
  8269. /**
  8270. * Return the filename of file to get the thumbs
  8271. *
  8272. * @param string $file Original filename (full or relative path)
  8273. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8274. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8275. * @return string New file name (full or relative path, including the thumbs/)
  8276. */
  8277. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8278. {
  8279. $dirName = dirname($file);
  8280. if ($dirName == '.') {
  8281. $dirName = '';
  8282. }
  8283. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8284. $fileName = basename($fileName);
  8285. if (empty($extImgTarget)) {
  8286. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8287. }
  8288. if (empty($extImgTarget)) {
  8289. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8290. }
  8291. if (empty($extImgTarget)) {
  8292. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8293. }
  8294. if (empty($extImgTarget)) {
  8295. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8296. }
  8297. if (empty($extImgTarget)) {
  8298. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8299. }
  8300. if (empty($extImgTarget)) {
  8301. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8302. }
  8303. if (!$extImgTarget) {
  8304. return $file;
  8305. }
  8306. $subdir = '';
  8307. if ($extName) {
  8308. $subdir = 'thumbs/';
  8309. }
  8310. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8311. }
  8312. /**
  8313. * Return URL we can use for advanced preview links
  8314. *
  8315. * @param string $modulepart propal, facture, facture_fourn, ...
  8316. * @param string $relativepath Relative path of docs.
  8317. * @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)
  8318. * @param string $param More param on http links
  8319. * @return string|array Output string with href link or array with all components of link
  8320. */
  8321. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8322. {
  8323. global $conf, $langs;
  8324. if (empty($conf->use_javascript_ajax)) {
  8325. return '';
  8326. }
  8327. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8328. if ($alldata == 1) {
  8329. if ($isAllowedForPreview) {
  8330. 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));
  8331. } else {
  8332. return array();
  8333. }
  8334. }
  8335. // old behavior, return a string
  8336. if ($isAllowedForPreview) {
  8337. 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')).'\')';
  8338. } else {
  8339. return '';
  8340. }
  8341. }
  8342. /**
  8343. * Make content of an input box selected when we click into input field.
  8344. *
  8345. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8346. * @param string $addlink Add a 'link to' after
  8347. * @param string $textonlink Text to show on link or 'image'
  8348. * @return string
  8349. */
  8350. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  8351. {
  8352. global $langs;
  8353. $out = '<script>
  8354. jQuery(document).ready(function () {
  8355. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8356. });
  8357. </script>';
  8358. if ($addlink) {
  8359. if ($textonlink === 'image') {
  8360. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  8361. } else {
  8362. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  8363. }
  8364. }
  8365. return $out;
  8366. }
  8367. /**
  8368. * Return if a file is qualified for preview
  8369. *
  8370. * @param string $file Filename we looking for information
  8371. * @return int 1 If allowed, 0 otherwise
  8372. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8373. */
  8374. function dolIsAllowedForPreview($file)
  8375. {
  8376. global $conf;
  8377. // Check .noexe extension in filename
  8378. if (preg_match('/\.noexe$/i', $file)) {
  8379. return 0;
  8380. }
  8381. // Check mime types
  8382. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8383. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8384. $mime_preview[] = 'svg+xml';
  8385. }
  8386. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8387. //$mime_preview[]='archive';
  8388. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8389. if ($num_mime !== false) {
  8390. return 1;
  8391. }
  8392. // By default, not allowed for preview
  8393. return 0;
  8394. }
  8395. /**
  8396. * Return mime type of a file
  8397. *
  8398. * @param string $file Filename we looking for MIME type
  8399. * @param string $default Default mime type if extension not found in known list
  8400. * @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
  8401. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8402. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8403. */
  8404. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8405. {
  8406. $mime = $default;
  8407. $imgmime = 'other.png';
  8408. $famime = 'file-o';
  8409. $srclang = '';
  8410. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8411. // Plain text files
  8412. if (preg_match('/\.txt$/i', $tmpfile)) {
  8413. $mime = 'text/plain';
  8414. $imgmime = 'text.png';
  8415. $famime = 'file-text-o';
  8416. }
  8417. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8418. $mime = 'text/richtext';
  8419. $imgmime = 'text.png';
  8420. $famime = 'file-text-o';
  8421. }
  8422. if (preg_match('/\.csv$/i', $tmpfile)) {
  8423. $mime = 'text/csv';
  8424. $imgmime = 'text.png';
  8425. $famime = 'file-text-o';
  8426. }
  8427. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8428. $mime = 'text/tab-separated-values';
  8429. $imgmime = 'text.png';
  8430. $famime = 'file-text-o';
  8431. }
  8432. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8433. $mime = 'text/plain';
  8434. $imgmime = 'text.png';
  8435. $famime = 'file-text-o';
  8436. }
  8437. if (preg_match('/\.ini$/i', $tmpfile)) {
  8438. $mime = 'text/plain';
  8439. $imgmime = 'text.png';
  8440. $srclang = 'ini';
  8441. $famime = 'file-text-o';
  8442. }
  8443. if (preg_match('/\.md$/i', $tmpfile)) {
  8444. $mime = 'text/plain';
  8445. $imgmime = 'text.png';
  8446. $srclang = 'md';
  8447. $famime = 'file-text-o';
  8448. }
  8449. if (preg_match('/\.css$/i', $tmpfile)) {
  8450. $mime = 'text/css';
  8451. $imgmime = 'css.png';
  8452. $srclang = 'css';
  8453. $famime = 'file-text-o';
  8454. }
  8455. if (preg_match('/\.lang$/i', $tmpfile)) {
  8456. $mime = 'text/plain';
  8457. $imgmime = 'text.png';
  8458. $srclang = 'lang';
  8459. $famime = 'file-text-o';
  8460. }
  8461. // Certificate files
  8462. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8463. $mime = 'text/plain';
  8464. $imgmime = 'text.png';
  8465. $famime = 'file-text-o';
  8466. }
  8467. // XML based (HTML/XML/XAML)
  8468. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8469. $mime = 'text/html';
  8470. $imgmime = 'html.png';
  8471. $srclang = 'html';
  8472. $famime = 'file-text-o';
  8473. }
  8474. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8475. $mime = 'text/xml';
  8476. $imgmime = 'other.png';
  8477. $srclang = 'xml';
  8478. $famime = 'file-text-o';
  8479. }
  8480. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8481. $mime = 'text/xml';
  8482. $imgmime = 'other.png';
  8483. $srclang = 'xaml';
  8484. $famime = 'file-text-o';
  8485. }
  8486. // Languages
  8487. if (preg_match('/\.bas$/i', $tmpfile)) {
  8488. $mime = 'text/plain';
  8489. $imgmime = 'text.png';
  8490. $srclang = 'bas';
  8491. $famime = 'file-code-o';
  8492. }
  8493. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8494. $mime = 'text/plain';
  8495. $imgmime = 'text.png';
  8496. $srclang = 'c';
  8497. $famime = 'file-code-o';
  8498. }
  8499. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8500. $mime = 'text/plain';
  8501. $imgmime = 'text.png';
  8502. $srclang = 'cpp';
  8503. $famime = 'file-code-o';
  8504. }
  8505. if (preg_match('/\.cs$/i', $tmpfile)) {
  8506. $mime = 'text/plain';
  8507. $imgmime = 'text.png';
  8508. $srclang = 'cs';
  8509. $famime = 'file-code-o';
  8510. }
  8511. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8512. $mime = 'text/plain';
  8513. $imgmime = 'text.png';
  8514. $srclang = 'h';
  8515. $famime = 'file-code-o';
  8516. }
  8517. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8518. $mime = 'text/plain';
  8519. $imgmime = 'text.png';
  8520. $srclang = 'java';
  8521. $famime = 'file-code-o';
  8522. }
  8523. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8524. $mime = 'text/plain';
  8525. $imgmime = 'php.png';
  8526. $srclang = 'php';
  8527. $famime = 'file-code-o';
  8528. }
  8529. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8530. $mime = 'text/plain';
  8531. $imgmime = 'php.png';
  8532. $srclang = 'php';
  8533. $famime = 'file-code-o';
  8534. }
  8535. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8536. $mime = 'text/plain';
  8537. $imgmime = 'pl.png';
  8538. $srclang = 'perl';
  8539. $famime = 'file-code-o';
  8540. }
  8541. if (preg_match('/\.sql$/i', $tmpfile)) {
  8542. $mime = 'text/plain';
  8543. $imgmime = 'text.png';
  8544. $srclang = 'sql';
  8545. $famime = 'file-code-o';
  8546. }
  8547. if (preg_match('/\.js$/i', $tmpfile)) {
  8548. $mime = 'text/x-javascript';
  8549. $imgmime = 'jscript.png';
  8550. $srclang = 'js';
  8551. $famime = 'file-code-o';
  8552. }
  8553. // Open office
  8554. if (preg_match('/\.odp$/i', $tmpfile)) {
  8555. $mime = 'application/vnd.oasis.opendocument.presentation';
  8556. $imgmime = 'ooffice.png';
  8557. $famime = 'file-powerpoint-o';
  8558. }
  8559. if (preg_match('/\.ods$/i', $tmpfile)) {
  8560. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8561. $imgmime = 'ooffice.png';
  8562. $famime = 'file-excel-o';
  8563. }
  8564. if (preg_match('/\.odt$/i', $tmpfile)) {
  8565. $mime = 'application/vnd.oasis.opendocument.text';
  8566. $imgmime = 'ooffice.png';
  8567. $famime = 'file-word-o';
  8568. }
  8569. // MS Office
  8570. if (preg_match('/\.mdb$/i', $tmpfile)) {
  8571. $mime = 'application/msaccess';
  8572. $imgmime = 'mdb.png';
  8573. $famime = 'file-o';
  8574. }
  8575. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  8576. $mime = 'application/msword';
  8577. $imgmime = 'doc.png';
  8578. $famime = 'file-word-o';
  8579. }
  8580. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  8581. $mime = 'application/msword';
  8582. $imgmime = 'doc.png';
  8583. $famime = 'file-word-o';
  8584. }
  8585. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  8586. $mime = 'application/vnd.ms-excel';
  8587. $imgmime = 'xls.png';
  8588. $famime = 'file-excel-o';
  8589. }
  8590. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  8591. $mime = 'application/vnd.ms-excel';
  8592. $imgmime = 'xls.png';
  8593. $famime = 'file-excel-o';
  8594. }
  8595. if (preg_match('/\.xls$/i', $tmpfile)) {
  8596. $mime = 'application/vnd.ms-excel';
  8597. $imgmime = 'xls.png';
  8598. $famime = 'file-excel-o';
  8599. }
  8600. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  8601. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  8602. $imgmime = 'xls.png';
  8603. $famime = 'file-excel-o';
  8604. }
  8605. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  8606. $mime = 'application/vnd.ms-powerpoint';
  8607. $imgmime = 'ppt.png';
  8608. $famime = 'file-powerpoint-o';
  8609. }
  8610. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  8611. $mime = 'application/x-mspowerpoint';
  8612. $imgmime = 'ppt.png';
  8613. $famime = 'file-powerpoint-o';
  8614. }
  8615. // Other
  8616. if (preg_match('/\.pdf$/i', $tmpfile)) {
  8617. $mime = 'application/pdf';
  8618. $imgmime = 'pdf.png';
  8619. $famime = 'file-pdf-o';
  8620. }
  8621. // Scripts
  8622. if (preg_match('/\.bat$/i', $tmpfile)) {
  8623. $mime = 'text/x-bat';
  8624. $imgmime = 'script.png';
  8625. $srclang = 'dos';
  8626. $famime = 'file-code-o';
  8627. }
  8628. if (preg_match('/\.sh$/i', $tmpfile)) {
  8629. $mime = 'text/x-sh';
  8630. $imgmime = 'script.png';
  8631. $srclang = 'bash';
  8632. $famime = 'file-code-o';
  8633. }
  8634. if (preg_match('/\.ksh$/i', $tmpfile)) {
  8635. $mime = 'text/x-ksh';
  8636. $imgmime = 'script.png';
  8637. $srclang = 'bash';
  8638. $famime = 'file-code-o';
  8639. }
  8640. if (preg_match('/\.bash$/i', $tmpfile)) {
  8641. $mime = 'text/x-bash';
  8642. $imgmime = 'script.png';
  8643. $srclang = 'bash';
  8644. $famime = 'file-code-o';
  8645. }
  8646. // Images
  8647. if (preg_match('/\.ico$/i', $tmpfile)) {
  8648. $mime = 'image/x-icon';
  8649. $imgmime = 'image.png';
  8650. $famime = 'file-image-o';
  8651. }
  8652. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  8653. $mime = 'image/jpeg';
  8654. $imgmime = 'image.png';
  8655. $famime = 'file-image-o';
  8656. }
  8657. if (preg_match('/\.png$/i', $tmpfile)) {
  8658. $mime = 'image/png';
  8659. $imgmime = 'image.png';
  8660. $famime = 'file-image-o';
  8661. }
  8662. if (preg_match('/\.gif$/i', $tmpfile)) {
  8663. $mime = 'image/gif';
  8664. $imgmime = 'image.png';
  8665. $famime = 'file-image-o';
  8666. }
  8667. if (preg_match('/\.bmp$/i', $tmpfile)) {
  8668. $mime = 'image/bmp';
  8669. $imgmime = 'image.png';
  8670. $famime = 'file-image-o';
  8671. }
  8672. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  8673. $mime = 'image/tiff';
  8674. $imgmime = 'image.png';
  8675. $famime = 'file-image-o';
  8676. }
  8677. if (preg_match('/\.svg$/i', $tmpfile)) {
  8678. $mime = 'image/svg+xml';
  8679. $imgmime = 'image.png';
  8680. $famime = 'file-image-o';
  8681. }
  8682. if (preg_match('/\.webp$/i', $tmpfile)) {
  8683. $mime = 'image/webp';
  8684. $imgmime = 'image.png';
  8685. $famime = 'file-image-o';
  8686. }
  8687. // Calendar
  8688. if (preg_match('/\.vcs$/i', $tmpfile)) {
  8689. $mime = 'text/calendar';
  8690. $imgmime = 'other.png';
  8691. $famime = 'file-text-o';
  8692. }
  8693. if (preg_match('/\.ics$/i', $tmpfile)) {
  8694. $mime = 'text/calendar';
  8695. $imgmime = 'other.png';
  8696. $famime = 'file-text-o';
  8697. }
  8698. // Other
  8699. if (preg_match('/\.torrent$/i', $tmpfile)) {
  8700. $mime = 'application/x-bittorrent';
  8701. $imgmime = 'other.png';
  8702. $famime = 'file-o';
  8703. }
  8704. // Audio
  8705. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  8706. $mime = 'audio';
  8707. $imgmime = 'audio.png';
  8708. $famime = 'file-audio-o';
  8709. }
  8710. // Video
  8711. if (preg_match('/\.mp4$/i', $tmpfile)) {
  8712. $mime = 'video/mp4';
  8713. $imgmime = 'video.png';
  8714. $famime = 'file-video-o';
  8715. }
  8716. if (preg_match('/\.ogv$/i', $tmpfile)) {
  8717. $mime = 'video/ogg';
  8718. $imgmime = 'video.png';
  8719. $famime = 'file-video-o';
  8720. }
  8721. if (preg_match('/\.webm$/i', $tmpfile)) {
  8722. $mime = 'video/webm';
  8723. $imgmime = 'video.png';
  8724. $famime = 'file-video-o';
  8725. }
  8726. if (preg_match('/\.avi$/i', $tmpfile)) {
  8727. $mime = 'video/x-msvideo';
  8728. $imgmime = 'video.png';
  8729. $famime = 'file-video-o';
  8730. }
  8731. if (preg_match('/\.divx$/i', $tmpfile)) {
  8732. $mime = 'video/divx';
  8733. $imgmime = 'video.png';
  8734. $famime = 'file-video-o';
  8735. }
  8736. if (preg_match('/\.xvid$/i', $tmpfile)) {
  8737. $mime = 'video/xvid';
  8738. $imgmime = 'video.png';
  8739. $famime = 'file-video-o';
  8740. }
  8741. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  8742. $mime = 'video';
  8743. $imgmime = 'video.png';
  8744. $famime = 'file-video-o';
  8745. }
  8746. // Archive
  8747. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  8748. $mime = 'archive';
  8749. $imgmime = 'archive.png';
  8750. $famime = 'file-archive-o';
  8751. } // application/xxx where zzz is zip, ...
  8752. // Exe
  8753. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  8754. $mime = 'application/octet-stream';
  8755. $imgmime = 'other.png';
  8756. $famime = 'file-o';
  8757. }
  8758. // Lib
  8759. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  8760. $mime = 'library';
  8761. $imgmime = 'library.png';
  8762. $famime = 'file-o';
  8763. }
  8764. // Err
  8765. if (preg_match('/\.err$/i', $tmpfile)) {
  8766. $mime = 'error';
  8767. $imgmime = 'error.png';
  8768. $famime = 'file-text-o';
  8769. }
  8770. // Return string
  8771. if ($mode == 1) {
  8772. $tmp = explode('/', $mime);
  8773. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  8774. }
  8775. if ($mode == 2) {
  8776. return $imgmime;
  8777. }
  8778. if ($mode == 3) {
  8779. return $srclang;
  8780. }
  8781. if ($mode == 4) {
  8782. return $famime;
  8783. }
  8784. return $mime;
  8785. }
  8786. /**
  8787. * Return the value of a filed into a dictionary for the record $id.
  8788. * This also set all the values into a cache for a next search.
  8789. *
  8790. * @param string $tablename Name of dictionary
  8791. * @param string $field The name of field where to find the value to return
  8792. * @param int $id Id of line record
  8793. * @param bool $checkentity Add filter on entity
  8794. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  8795. * @return string The value of field $field. This also set $dictvalues cache.
  8796. */
  8797. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  8798. {
  8799. global $conf, $db;
  8800. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  8801. if (is_null($dictvalues)) {
  8802. $dictvalues = array();
  8803. $sql = "SELECT * FROM ".$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  8804. if ($checkentity) {
  8805. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  8806. }
  8807. $resql = $db->query($sql);
  8808. if ($resql) {
  8809. while ($obj = $db->fetch_object($resql)) {
  8810. $dictvalues[$obj->{$rowidfield}] = $obj;
  8811. }
  8812. } else {
  8813. dol_print_error($db);
  8814. }
  8815. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  8816. }
  8817. if (!empty($dictvalues[$id])) {
  8818. // Found
  8819. return $dictvalues[$id]->{$field};
  8820. } else {
  8821. // Not found
  8822. return '';
  8823. }
  8824. }
  8825. /**
  8826. * Return true if the color is light
  8827. *
  8828. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  8829. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  8830. */
  8831. function colorIsLight($stringcolor)
  8832. {
  8833. $stringcolor = str_replace('#', '', $stringcolor);
  8834. $res = -1;
  8835. if (!empty($stringcolor)) {
  8836. $res = 0;
  8837. $tmp = explode(',', $stringcolor);
  8838. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  8839. $r = $tmp[0];
  8840. $g = $tmp[1];
  8841. $b = $tmp[2];
  8842. } else {
  8843. $hexr = $stringcolor[0].$stringcolor[1];
  8844. $hexg = $stringcolor[2].$stringcolor[3];
  8845. $hexb = $stringcolor[4].$stringcolor[5];
  8846. $r = hexdec($hexr);
  8847. $g = hexdec($hexg);
  8848. $b = hexdec($hexb);
  8849. }
  8850. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  8851. if ($bright > 0.6) {
  8852. $res = 1;
  8853. }
  8854. }
  8855. return $res;
  8856. }
  8857. /**
  8858. * Function to test if an entry is enabled or not
  8859. *
  8860. * @param string $type_user 0=We test for internal user, 1=We test for external user
  8861. * @param array $menuentry Array for feature entry to test
  8862. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  8863. * @return int 0=Hide, 1=Show, 2=Show gray
  8864. */
  8865. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  8866. {
  8867. global $conf;
  8868. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  8869. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  8870. if (empty($menuentry['enabled'])) {
  8871. return 0; // Entry disabled by condition
  8872. }
  8873. if ($type_user && $menuentry['module']) {
  8874. $tmploops = explode('|', $menuentry['module']);
  8875. $found = 0;
  8876. foreach ($tmploops as $tmploop) {
  8877. if (in_array($tmploop, $listofmodulesforexternal)) {
  8878. $found++;
  8879. break;
  8880. }
  8881. }
  8882. if (!$found) {
  8883. return 0; // Entry is for menus all excluded to external users
  8884. }
  8885. }
  8886. if (!$menuentry['perms'] && $type_user) {
  8887. return 0; // No permissions and user is external
  8888. }
  8889. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  8890. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  8891. }
  8892. if (!$menuentry['perms']) {
  8893. return 2; // No permissions and user is external
  8894. }
  8895. return 1;
  8896. }
  8897. /**
  8898. * Round to next multiple.
  8899. *
  8900. * @param double $n Number to round up
  8901. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  8902. * @return integer Value rounded.
  8903. */
  8904. function roundUpToNextMultiple($n, $x = 5)
  8905. {
  8906. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  8907. }
  8908. /**
  8909. * Function dolGetBadge
  8910. *
  8911. * @param string $label label of badge no html : use in alt attribute for accessibility
  8912. * @param string $html optional : label of badge with html
  8913. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  8914. * @param string $mode default '' , 'pill', 'dot'
  8915. * @param string $url the url for link
  8916. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  8917. * @return string Html badge
  8918. */
  8919. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  8920. {
  8921. $attr = array(
  8922. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  8923. );
  8924. if (empty($html)) {
  8925. $html = $label;
  8926. }
  8927. if (!empty($url)) {
  8928. $attr['href'] = $url;
  8929. }
  8930. if ($mode === 'dot') {
  8931. $attr['class'] .= ' classfortooltip';
  8932. $attr['title'] = $html;
  8933. $attr['aria-label'] = $label;
  8934. $html = '';
  8935. }
  8936. // Override attr
  8937. if (!empty($params['attr']) && is_array($params['attr'])) {
  8938. foreach ($params['attr'] as $key => $value) {
  8939. if ($key == 'class') {
  8940. $attr['class'] .= ' '.$value;
  8941. } elseif ($key == 'classOverride') {
  8942. $attr['class'] = $value;
  8943. } else {
  8944. $attr[$key] = $value;
  8945. }
  8946. }
  8947. }
  8948. // TODO: add hook
  8949. // escape all attribute
  8950. $attr = array_map('dol_escape_htmltag', $attr);
  8951. $TCompiledAttr = array();
  8952. foreach ($attr as $key => $value) {
  8953. $TCompiledAttr[] = $key.'="'.$value.'"';
  8954. }
  8955. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  8956. $tag = !empty($url) ? 'a' : 'span';
  8957. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  8958. }
  8959. /**
  8960. * Output the badge of a status.
  8961. *
  8962. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  8963. * @param string $statusLabelShort Short label of badge no html
  8964. * @param string $html Optional : label of badge with html
  8965. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  8966. * @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
  8967. * @param string $url The url for link
  8968. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  8969. * @return string Html status string
  8970. */
  8971. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  8972. {
  8973. global $conf;
  8974. $return = '';
  8975. $dolGetBadgeParams = array();
  8976. if (!empty($params['badgeParams'])) {
  8977. $dolGetBadgeParams = $params['badgeParams'];
  8978. }
  8979. // TODO : add a hook
  8980. if ($displayMode == 0) {
  8981. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  8982. } elseif ($displayMode == 1) {
  8983. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  8984. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  8985. // Use status with images (for backward compatibility)
  8986. $return = '';
  8987. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  8988. $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>' : '');
  8989. // For small screen, we always use the short label instead of long label.
  8990. if (!empty($conf->dol_optimize_smallscreen)) {
  8991. if ($displayMode == 0) {
  8992. $displayMode = 1;
  8993. } elseif ($displayMode == 4) {
  8994. $displayMode = 2;
  8995. } elseif ($displayMode == 6) {
  8996. $displayMode = 5;
  8997. }
  8998. }
  8999. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  9000. $statusImg = array(
  9001. 'status0' => 'statut0',
  9002. 'status1' => 'statut1',
  9003. 'status2' => 'statut2',
  9004. 'status3' => 'statut3',
  9005. 'status4' => 'statut4',
  9006. 'status5' => 'statut5',
  9007. 'status6' => 'statut6',
  9008. 'status7' => 'statut7',
  9009. 'status8' => 'statut8',
  9010. 'status9' => 'statut9'
  9011. );
  9012. if (!empty($statusImg[$statusType])) {
  9013. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  9014. } else {
  9015. $htmlImg = img_picto($statusLabel, $statusType);
  9016. }
  9017. if ($displayMode === 2) {
  9018. $return = $htmlImg.' '.$htmlLabelShort;
  9019. } elseif ($displayMode === 3) {
  9020. $return = $htmlImg;
  9021. } elseif ($displayMode === 4) {
  9022. $return = $htmlImg.' '.$htmlLabel;
  9023. } elseif ($displayMode === 5) {
  9024. $return = $htmlLabelShort.' '.$htmlImg;
  9025. } else { // $displayMode >= 6
  9026. $return = $htmlLabel.' '.$htmlImg;
  9027. }
  9028. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9029. // Use new badge
  9030. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9031. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9032. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9033. if ($displayMode == 3) {
  9034. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9035. } elseif ($displayMode === 5) {
  9036. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9037. } else {
  9038. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9039. }
  9040. }
  9041. return $return;
  9042. }
  9043. /**
  9044. * Function dolGetButtonAction
  9045. *
  9046. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  9047. * @param string $html optional : content with html
  9048. * @param string $actionType default, delete, danger
  9049. * @param string $url the url for link
  9050. * @param string $id attribute id of button
  9051. * @param int $userRight user action right
  9052. * // phpcs:disable
  9053. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  9054. * 'attr' => [ // to add or override button attributes
  9055. * 'xxxxx' => '', // your xxxxx attribute you want
  9056. * 'class' => '', // to add more css class to the button class attribute
  9057. * 'classOverride' => '' // to replace class attribute of the button
  9058. * ],
  9059. * 'confirm' => [
  9060. * 'url' => 'http://', // Overide Url to go when user click on action btn, if empty default url is $url.?confirm=yes, for no js compatibility use $url for fallback confirm.
  9061. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  9062. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  9063. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  9064. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  9065. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  9066. * ],
  9067. * ]
  9068. * // phpcs:enable
  9069. * @return string html button
  9070. */
  9071. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  9072. {
  9073. global $hookmanager, $action, $object, $langs;
  9074. $class = 'butAction';
  9075. if ($actionType == 'danger' || $actionType == 'delete') {
  9076. $class = 'butActionDelete';
  9077. if (strpos($url, 'token=') === false) $url .= '&token='.newToken();
  9078. }
  9079. $attr = array(
  9080. 'class' => $class,
  9081. 'href' => empty($url) ? '' : $url,
  9082. 'title' => $label
  9083. );
  9084. if (empty($html)) {
  9085. $html = $label;
  9086. } else {
  9087. $attr['aria-label'] = $label;
  9088. }
  9089. if (empty($userRight)) {
  9090. $attr['class'] = 'butActionRefused';
  9091. $attr['href'] = '';
  9092. }
  9093. if (!empty($id)) {
  9094. $attr['id'] = $id;
  9095. }
  9096. // Override attr
  9097. if (!empty($params['attr']) && is_array($params['attr'])) {
  9098. foreach ($params['attr'] as $key => $value) {
  9099. if ($key == 'class') {
  9100. $attr['class'] .= ' '.$value;
  9101. } elseif ($key == 'classOverride') {
  9102. $attr['class'] = $value;
  9103. } else {
  9104. $attr[$key] = $value;
  9105. }
  9106. }
  9107. }
  9108. // Js Confirm button
  9109. if ($userRight && !empty($params['confirm'])) {
  9110. if (!is_array($params['confirm'])) {
  9111. $params['confirm'] = array(
  9112. 'url' => $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes'
  9113. );
  9114. }
  9115. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9116. $attr['data-confirm-url'] = $params['confirm']['url'];
  9117. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9118. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9119. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9120. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9121. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9122. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9123. $attr['class'].= ' butActionConfirm';
  9124. }
  9125. if (isset($attr['href']) && empty($attr['href'])) {
  9126. unset($attr['href']);
  9127. }
  9128. // escape all attribute
  9129. $attr = array_map('dol_escape_htmltag', $attr);
  9130. $TCompiledAttr = array();
  9131. foreach ($attr as $key => $value) {
  9132. $TCompiledAttr[] = $key.'="'.$value.'"';
  9133. }
  9134. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9135. $tag = !empty($attr['href']) ? 'a' : 'span';
  9136. $parameters = array(
  9137. 'TCompiledAttr' => $TCompiledAttr,
  9138. 'compiledAttributes' => $compiledAttributes,
  9139. 'attr' => $attr,
  9140. 'tag' => $tag,
  9141. 'label' => $label,
  9142. 'html' => $html,
  9143. 'actionType' => $actionType,
  9144. 'url' => $url,
  9145. 'id' => $id,
  9146. 'userRight' => $userRight,
  9147. 'params' => $params
  9148. );
  9149. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9150. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9151. if (empty($reshook)) {
  9152. return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
  9153. } else {
  9154. return $hookmanager->resPrint;
  9155. }
  9156. }
  9157. /**
  9158. * Add space between dolGetButtonTitle
  9159. *
  9160. * @param string $moreClass more css class label
  9161. * @return string html of title separator
  9162. */
  9163. function dolGetButtonTitleSeparator($moreClass = "")
  9164. {
  9165. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9166. }
  9167. /**
  9168. * get field error icon
  9169. *
  9170. * @param string $fieldValidationErrorMsg message to add in tooltip
  9171. * @return string html output
  9172. */
  9173. function getFieldErrorIcon($fieldValidationErrorMsg)
  9174. {
  9175. $out = '';
  9176. if (!empty($fieldValidationErrorMsg)) {
  9177. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9178. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9179. $out.= '</span>';
  9180. }
  9181. return $out;
  9182. }
  9183. /**
  9184. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9185. *
  9186. * @param string $label label of button
  9187. * @param string $helpText optional : content for help tooltip
  9188. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9189. * @param string $url the url for link
  9190. * @param string $id attribute id of button
  9191. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  9192. * @param array $params various params for future : recommended rather than adding more function arguments
  9193. * @return string html button
  9194. */
  9195. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9196. {
  9197. global $langs, $conf, $user;
  9198. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9199. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9200. return '';
  9201. }
  9202. $class = 'btnTitle';
  9203. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots'))) {
  9204. $class .= ' btnTitlePlus';
  9205. }
  9206. $useclassfortooltip = 1;
  9207. if (!empty($params['morecss'])) {
  9208. $class .= ' '.$params['morecss'];
  9209. }
  9210. $attr = array(
  9211. 'class' => $class,
  9212. 'href' => empty($url) ? '' : $url
  9213. );
  9214. if (!empty($helpText)) {
  9215. $attr['title'] = dol_escape_htmltag($helpText);
  9216. } elseif (empty($attr['title']) && $label) {
  9217. $attr['title'] = $label;
  9218. $useclassfortooltip = 0;
  9219. }
  9220. if ($status == 2) {
  9221. $attr['class'] .= ' btnTitleSelected';
  9222. } elseif ($status <= 0) {
  9223. $attr['class'] .= ' refused';
  9224. $attr['href'] = '';
  9225. if ($status == -1) { // disable
  9226. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9227. } elseif ($status == 0) { // Not enough permissions
  9228. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9229. }
  9230. }
  9231. if (!empty($attr['title']) && $useclassfortooltip) {
  9232. $attr['class'] .= ' classfortooltip';
  9233. }
  9234. if (!empty($id)) {
  9235. $attr['id'] = $id;
  9236. }
  9237. // Override attr
  9238. if (!empty($params['attr']) && is_array($params['attr'])) {
  9239. foreach ($params['attr'] as $key => $value) {
  9240. if ($key == 'class') {
  9241. $attr['class'] .= ' '.$value;
  9242. } elseif ($key == 'classOverride') {
  9243. $attr['class'] = $value;
  9244. } else {
  9245. $attr[$key] = $value;
  9246. }
  9247. }
  9248. }
  9249. if (isset($attr['href']) && empty($attr['href'])) {
  9250. unset($attr['href']);
  9251. }
  9252. // TODO : add a hook
  9253. // escape all attribute
  9254. $attr = array_map('dol_escape_htmltag', $attr);
  9255. $TCompiledAttr = array();
  9256. foreach ($attr as $key => $value) {
  9257. $TCompiledAttr[] = $key.'="'.$value.'"';
  9258. }
  9259. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9260. $tag = (empty($attr['href']) ? 'span' : 'a');
  9261. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9262. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9263. if (!empty($params['forcenohideoftext'])) {
  9264. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9265. }
  9266. $button .= '</'.$tag.'>';
  9267. return $button;
  9268. }
  9269. /**
  9270. * Get an array with properties of an element.
  9271. * Called by fetchObjectByElement.
  9272. *
  9273. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9274. * @return array (module, classpath, element, subelement, classfile, classname)
  9275. */
  9276. function getElementProperties($element_type)
  9277. {
  9278. $regs = array();
  9279. $classfile = $classname = $classpath = '';
  9280. // Parse element/subelement (ex: project_task)
  9281. $module = $element_type;
  9282. $element = $element_type;
  9283. $subelement = $element_type;
  9284. // If we ask an resource form external module (instead of default path)
  9285. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9286. $element = $subelement = $regs[1];
  9287. $module = $regs[2];
  9288. }
  9289. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9290. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9291. $module = $element = $regs[1];
  9292. $subelement = $regs[2];
  9293. }
  9294. // For compat
  9295. if ($element_type == "action") {
  9296. $classpath = 'comm/action/class';
  9297. $subelement = 'Actioncomm';
  9298. $module = 'agenda';
  9299. }
  9300. // To work with non standard path
  9301. if ($element_type == 'facture' || $element_type == 'invoice') {
  9302. $classpath = 'compta/facture/class';
  9303. $module = 'facture';
  9304. $subelement = 'facture';
  9305. }
  9306. if ($element_type == 'commande' || $element_type == 'order') {
  9307. $classpath = 'commande/class';
  9308. $module = 'commande';
  9309. $subelement = 'commande';
  9310. }
  9311. if ($element_type == 'propal') {
  9312. $classpath = 'comm/propal/class';
  9313. }
  9314. if ($element_type == 'supplier_proposal') {
  9315. $classpath = 'supplier_proposal/class';
  9316. }
  9317. if ($element_type == 'shipping') {
  9318. $classpath = 'expedition/class';
  9319. $subelement = 'expedition';
  9320. $module = 'expedition_bon';
  9321. }
  9322. if ($element_type == 'delivery') {
  9323. $classpath = 'delivery/class';
  9324. $subelement = 'delivery';
  9325. $module = 'delivery_note';
  9326. }
  9327. if ($element_type == 'contract') {
  9328. $classpath = 'contrat/class';
  9329. $module = 'contrat';
  9330. $subelement = 'contrat';
  9331. }
  9332. if ($element_type == 'member') {
  9333. $classpath = 'adherents/class';
  9334. $module = 'adherent';
  9335. $subelement = 'adherent';
  9336. }
  9337. if ($element_type == 'cabinetmed_cons') {
  9338. $classpath = 'cabinetmed/class';
  9339. $module = 'cabinetmed';
  9340. $subelement = 'cabinetmedcons';
  9341. }
  9342. if ($element_type == 'fichinter') {
  9343. $classpath = 'fichinter/class';
  9344. $module = 'ficheinter';
  9345. $subelement = 'fichinter';
  9346. }
  9347. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9348. $classpath = 'resource/class';
  9349. $module = 'resource';
  9350. $subelement = 'dolresource';
  9351. }
  9352. if ($element_type == 'propaldet') {
  9353. $classpath = 'comm/propal/class';
  9354. $module = 'propal';
  9355. $subelement = 'propaleligne';
  9356. }
  9357. if ($element_type == 'order_supplier') {
  9358. $classpath = 'fourn/class';
  9359. $module = 'fournisseur';
  9360. $subelement = 'commandefournisseur';
  9361. $classfile = 'fournisseur.commande';
  9362. }
  9363. if ($element_type == 'invoice_supplier') {
  9364. $classpath = 'fourn/class';
  9365. $module = 'fournisseur';
  9366. $subelement = 'facturefournisseur';
  9367. $classfile = 'fournisseur.facture';
  9368. }
  9369. if ($element_type == "service") {
  9370. $classpath = 'product/class';
  9371. $subelement = 'product';
  9372. }
  9373. if (empty($classfile)) {
  9374. $classfile = strtolower($subelement);
  9375. }
  9376. if (empty($classname)) {
  9377. $classname = ucfirst($subelement);
  9378. }
  9379. if (empty($classpath)) {
  9380. $classpath = $module.'/class';
  9381. }
  9382. $element_properties = array(
  9383. 'module' => $module,
  9384. 'classpath' => $classpath,
  9385. 'element' => $element,
  9386. 'subelement' => $subelement,
  9387. 'classfile' => $classfile,
  9388. 'classname' => $classname
  9389. );
  9390. return $element_properties;
  9391. }
  9392. /**
  9393. * Fetch an object from its id and element_type
  9394. * Inclusion of classes is automatic
  9395. *
  9396. * @param int $element_id Element id
  9397. * @param string $element_type Element type
  9398. * @param string $element_ref Element ref (Use this or element_id but not both)
  9399. * @return int|object object || 0 || -1 if error
  9400. */
  9401. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9402. {
  9403. global $conf, $db;
  9404. $element_prop = getElementProperties($element_type);
  9405. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9406. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9407. $objecttmp = new $element_prop['classname']($db);
  9408. $ret = $objecttmp->fetch($element_id, $element_ref);
  9409. if ($ret >= 0) {
  9410. return $objecttmp;
  9411. }
  9412. }
  9413. return 0;
  9414. }
  9415. /**
  9416. * Return if a file can contains executable content
  9417. *
  9418. * @param string $filename File name to test
  9419. * @return boolean True if yes, False if no
  9420. */
  9421. function isAFileWithExecutableContent($filename)
  9422. {
  9423. 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)) {
  9424. return true;
  9425. }
  9426. return false;
  9427. }
  9428. /**
  9429. * Return the value of token currently saved into session with name 'newtoken'.
  9430. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9431. *
  9432. * @return string
  9433. */
  9434. function newToken()
  9435. {
  9436. return $_SESSION['newtoken'];
  9437. }
  9438. /**
  9439. * Return the value of token currently saved into session with name 'token'.
  9440. *
  9441. * @return string
  9442. */
  9443. function currentToken()
  9444. {
  9445. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  9446. }
  9447. /**
  9448. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9449. *
  9450. * @param string $header The first left header of the table (automatic translated)
  9451. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9452. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9453. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9454. * @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"
  9455. * @return void
  9456. *
  9457. * @see finishSimpleTable()
  9458. */
  9459. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9460. {
  9461. global $langs;
  9462. print '<div class="div-table-responsive-no-min">';
  9463. print '<table class="noborder centpercent">';
  9464. print '<tr class="liste_titre">';
  9465. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9466. print $langs->trans($header);
  9467. // extra space between the first header and the number
  9468. if ($number > -1) {
  9469. print ' ';
  9470. }
  9471. if (!empty($link)) {
  9472. if (!empty($arguments)) {
  9473. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9474. } else {
  9475. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9476. }
  9477. }
  9478. if ($number > -1) {
  9479. print '<span class="badge">'.$number.'</span>';
  9480. }
  9481. if (!empty($link)) {
  9482. print '</a>';
  9483. }
  9484. print '</th>';
  9485. if ($number < 0 && !empty($link)) {
  9486. print '<th class="right">';
  9487. if (!empty($arguments)) {
  9488. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9489. } else {
  9490. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9491. }
  9492. print $langs->trans("FullList");
  9493. print '</a>';
  9494. print '</th>';
  9495. }
  9496. print '</tr>';
  9497. }
  9498. /**
  9499. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9500. *
  9501. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9502. * @return void
  9503. *
  9504. * @see startSimpleTable()
  9505. */
  9506. function finishSimpleTable($addLineBreak = false)
  9507. {
  9508. print '</table>';
  9509. print '</div>';
  9510. if ($addLineBreak) {
  9511. print '<br>';
  9512. }
  9513. }
  9514. /**
  9515. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9516. *
  9517. * @param integer $tableColumnCount The complete count columns of the table
  9518. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9519. * @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)
  9520. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9521. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9522. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9523. * @return void
  9524. */
  9525. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9526. {
  9527. global $langs;
  9528. if ($num === 0) {
  9529. print '<tr class="oddeven">';
  9530. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9531. print '</tr>';
  9532. return;
  9533. }
  9534. if ($nbofloop === 0) {
  9535. // don't show a summary line
  9536. return;
  9537. }
  9538. if ($num === 0) {
  9539. $colspan = $tableColumnCount;
  9540. } elseif ($num > $nbofloop) {
  9541. $colspan = $tableColumnCount;
  9542. } else {
  9543. $colspan = $tableColumnCount - 1;
  9544. }
  9545. if ($extraRightColumn) {
  9546. $colspan--;
  9547. }
  9548. print '<tr class="liste_total">';
  9549. if ($nbofloop > 0 && $num > $nbofloop) {
  9550. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9551. } else {
  9552. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  9553. print '<td class="right" width="100">'.price($total).'</td>';
  9554. }
  9555. if ($extraRightColumn) {
  9556. print '<td></td>';
  9557. }
  9558. print '</tr>';
  9559. }
  9560. /**
  9561. * Return a file on output using a low memory. It can return very large files with no need of memory.
  9562. * WARNING: This close output buffers.
  9563. *
  9564. * @param string $fullpath_original_file_osencoded Full path of file to return.
  9565. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  9566. * @return void
  9567. */
  9568. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  9569. {
  9570. global $conf;
  9571. if ($method == -1) {
  9572. $method = 0;
  9573. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  9574. $method = 1;
  9575. }
  9576. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  9577. $method = 2;
  9578. }
  9579. }
  9580. // Be sure we don't have output buffering enabled to have readfile working correctly
  9581. while (ob_get_level()) {
  9582. ob_end_flush();
  9583. }
  9584. // Solution 0
  9585. if ($method == 0) {
  9586. readfile($fullpath_original_file_osencoded);
  9587. } elseif ($method == 1) {
  9588. // Solution 1
  9589. $handle = fopen($fullpath_original_file_osencoded, "rb");
  9590. while (!feof($handle)) {
  9591. print fread($handle, 8192);
  9592. }
  9593. fclose($handle);
  9594. } elseif ($method == 2) {
  9595. // Solution 2
  9596. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  9597. $handle2 = fopen("php://output", "wb");
  9598. stream_copy_to_stream($handle1, $handle2);
  9599. fclose($handle1);
  9600. fclose($handle2);
  9601. }
  9602. }
  9603. /**
  9604. * Create a button to copy $valuetocopy in the clipboard.
  9605. * Code that handle the click is inside lib_foot.jsp.php.
  9606. *
  9607. * @param string $valuetocopy The value to print
  9608. * @param int $showonlyonhover Show the copy-paste button only on hover
  9609. * @param string $texttoshow Replace the value to show with this text
  9610. * @return string The string to print for the button
  9611. */
  9612. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  9613. {
  9614. /*
  9615. global $conf;
  9616. if (!empty($conf->dol_no_mouse_hover)) {
  9617. $showonlyonhover = 0;
  9618. }*/
  9619. $tag = 'span'; // Using div does not work when using the js copy code.
  9620. if ($texttoshow) {
  9621. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint">'.dol_escape_htmltag($texttoshow, 1, 1).'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  9622. } else {
  9623. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  9624. }
  9625. return $result;
  9626. }
  9627. /**
  9628. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  9629. *
  9630. * @param string $stringtodecode String to decode (json or serialize coded)
  9631. * @return mixed The decoded object.
  9632. */
  9633. function jsonOrUnserialize($stringtodecode)
  9634. {
  9635. $result = json_decode($stringtodecode);
  9636. if ($result === null) {
  9637. $result = unserialize($stringtodecode);
  9638. }
  9639. return $result;
  9640. }
  9641. /**
  9642. * Return if a $sqlfilters parameter is valid and will pass the preg_replace_callback() to replace Generic filter string with SQL filter string
  9643. * Example of usage:
  9644. * if ($sqlfilters) {
  9645. * $errormessage = '';
  9646. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9647. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9648. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9649. * }
  9650. * }
  9651. *
  9652. * @param string $sqlfilters sqlfilter string
  9653. * @param string $error Error message
  9654. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  9655. */
  9656. function dolCheckFilters($sqlfilters, &$error = '')
  9657. {
  9658. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  9659. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  9660. $tmp = $sqlfilters;
  9661. $i = 0; $nb = strlen($tmp);
  9662. $counter = 0;
  9663. while ($i < $nb) {
  9664. if ($tmp[$i] == '(') {
  9665. $counter++;
  9666. }
  9667. if ($tmp[$i] == ')') {
  9668. $counter--;
  9669. }
  9670. if ($counter < 0) {
  9671. $error = "Bad sqlfilters=".$sqlfilters;
  9672. dol_syslog($error, LOG_WARNING);
  9673. return false;
  9674. }
  9675. $i++;
  9676. }
  9677. return true;
  9678. }
  9679. /**
  9680. * Function to forge a SQL criteria from a Generic filter string.
  9681. * Example of usage:
  9682. * if ($sqlfilters) {
  9683. * $errormessage = '';
  9684. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9685. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9686. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9687. * }
  9688. * }
  9689. *
  9690. * @param array $matches Array of found string by regex search.
  9691. * Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL"
  9692. * @return string Forged criteria. Example: "t.field like 'abc%'"
  9693. */
  9694. function dolForgeCriteriaCallback($matches)
  9695. {
  9696. global $db;
  9697. //dol_syslog("Convert matches ".$matches[1]);
  9698. if (empty($matches[1])) {
  9699. return '';
  9700. }
  9701. $tmp = explode(':', $matches[1], 3);
  9702. if (count($tmp) < 3) {
  9703. return '';
  9704. }
  9705. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  9706. $operator = strtoupper(preg_replace('/[^a-z<>=]/i', '', trim($tmp[1])));
  9707. $tmpescaped = trim($tmp[2]);
  9708. $regbis = array();
  9709. if ($operator == 'IN') {
  9710. $tmpescaped = "(".$db->sanitize($tmpescaped, 1).")";
  9711. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  9712. $tmpescaped = "'".$db->escape($regbis[1])."'";
  9713. } else {
  9714. $tmpescaped = $db->sanitize($db->escape($tmpescaped));
  9715. }
  9716. return $db->escape($operand).' '.$db->escape($operator)." ".$tmpescaped;
  9717. }