functions.lib.php 447 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2022 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
  21. *
  22. * This program is free software; you can redistribute it and/or modify
  23. * it under the terms of the GNU General Public License as published by
  24. * the Free Software Foundation; either version 3 of the License, or
  25. * (at your option) any later version.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU General Public License
  33. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  34. * or see https://www.gnu.org/
  35. */
  36. /**
  37. * \file htdocs/core/lib/functions.lib.php
  38. * \brief A set of functions for Dolibarr
  39. * This file contains all frequently used functions.
  40. */
  41. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  42. /**
  43. * Return dolibarr global constant string value
  44. * @param string $key key to return value, return '' if not set
  45. * @param string $default value to return
  46. * @return string
  47. */
  48. function getDolGlobalString($key, $default = '')
  49. {
  50. global $conf;
  51. // return $conf->global->$key ?? $default;
  52. return (string) (empty($conf->global->$key) ? $default : $conf->global->$key);
  53. }
  54. /**
  55. * Return dolibarr global constant int value
  56. * @param string $key key to return value, return 0 if not set
  57. * @param int $default value to return
  58. * @return int
  59. */
  60. function getDolGlobalInt($key, $default = 0)
  61. {
  62. global $conf;
  63. // return $conf->global->$key ?? $default;
  64. return (int) (empty($conf->global->$key) ? $default : $conf->global->$key);
  65. }
  66. /**
  67. * Is Dolibarr module enabled
  68. * @param string $module module name to check
  69. * @return int
  70. */
  71. function isModEnabled($module)
  72. {
  73. global $conf;
  74. return !empty($conf->$module->enabled);
  75. }
  76. /**
  77. * Return a DoliDB instance (database handler).
  78. *
  79. * @param string $type Type of database (mysql, pgsql...)
  80. * @param string $host Address of database server
  81. * @param string $user Authorized username
  82. * @param string $pass Password
  83. * @param string $name Name of database
  84. * @param int $port Port of database server
  85. * @return DoliDB A DoliDB instance
  86. */
  87. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  88. {
  89. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  90. $class = 'DoliDB'.ucfirst($type);
  91. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  92. return $dolidb;
  93. }
  94. /**
  95. * Get list of entity id to use.
  96. *
  97. * @param string $element Current element
  98. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  99. * 'product', 'productprice', 'stock', 'bom', 'mo',
  100. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  101. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  102. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  103. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  104. * 'email_template', 'event', 'donation'
  105. * 'c_paiement', 'c_payment_term', ...
  106. * @param int $shared 0=Return id of current entity only,
  107. * 1=Return id of current entity + shared entities (default)
  108. * @param object $currentobject Current object if needed
  109. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  110. */
  111. function getEntity($element, $shared = 1, $currentobject = null)
  112. {
  113. global $conf, $mc, $hookmanager, $object, $action, $db;
  114. if (! is_object($hookmanager)) {
  115. $hookmanager = new HookManager($db);
  116. }
  117. // fix different element names (France to English)
  118. switch ($element) {
  119. case 'contrat':
  120. $element = 'contract';
  121. break; // "/contrat/class/contrat.class.php"
  122. case 'order_supplier':
  123. $element = 'supplier_order';
  124. break; // "/fourn/class/fournisseur.commande.class.php"
  125. }
  126. if (is_object($mc)) {
  127. $out = $mc->getEntity($element, $shared, $currentobject);
  128. } else {
  129. $out = '';
  130. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  131. if (in_array($element, $addzero)) {
  132. $out .= '0,';
  133. }
  134. $out .= ((int) $conf->entity);
  135. }
  136. // Manipulate entities to query on the fly
  137. $parameters = array(
  138. 'element' => $element,
  139. 'shared' => $shared,
  140. 'object' => $object,
  141. 'currentobject' => $currentobject,
  142. 'out' => $out
  143. );
  144. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  145. if (is_numeric($reshook)) {
  146. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  147. $out .= ','.$hookmanager->resPrint; // add
  148. } elseif ($reshook == 1) {
  149. $out = $hookmanager->resPrint; // replace
  150. }
  151. }
  152. return $out;
  153. }
  154. /**
  155. * Set entity id to use when to create an object
  156. *
  157. * @param object $currentobject Current object
  158. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  159. */
  160. function setEntity($currentobject)
  161. {
  162. global $conf, $mc;
  163. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  164. return $mc->setEntity($currentobject);
  165. } else {
  166. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  167. }
  168. }
  169. /**
  170. * Return if string has a name dedicated to store a secret
  171. *
  172. * @param string $keyname Name of key to test
  173. * @return boolean True if key is used to store a secret
  174. */
  175. function isASecretKey($keyname)
  176. {
  177. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  178. }
  179. /**
  180. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  181. *
  182. * @param int|string $n Numeric value
  183. * @return string Column in Excel format
  184. */
  185. function num2Alpha($n)
  186. {
  187. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
  188. $r = chr($n % 26 + 0x41) . $r;
  189. return $r;
  190. }
  191. /**
  192. * Return information about user browser
  193. *
  194. * Returns array with the following format:
  195. * array(
  196. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  197. * 'browserversion' => Browser version. Empty if unknown
  198. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  199. * 'layout' => (tablet|phone|classic)
  200. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  201. * 'tablet' => true/false
  202. * )
  203. *
  204. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  205. * @return array Check function documentation
  206. */
  207. function getBrowserInfo($user_agent)
  208. {
  209. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  210. $name = 'unknown';
  211. $version = '';
  212. $os = 'unknown';
  213. $phone = '';
  214. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  215. $detectmobile = new Mobile_Detect(null, $user_agent);
  216. $tablet = $detectmobile->isTablet();
  217. if ($detectmobile->isMobile()) {
  218. $phone = 'unknown';
  219. // If phone/smartphone, we set phone os name.
  220. if ($detectmobile->is('AndroidOS')) {
  221. $os = $phone = 'android';
  222. } elseif ($detectmobile->is('BlackBerryOS')) {
  223. $os = $phone = 'blackberry';
  224. } elseif ($detectmobile->is('iOS')) {
  225. $os = 'ios';
  226. $phone = 'iphone';
  227. } elseif ($detectmobile->is('PalmOS')) {
  228. $os = $phone = 'palm';
  229. } elseif ($detectmobile->is('SymbianOS')) {
  230. $os = 'symbian';
  231. } elseif ($detectmobile->is('webOS')) {
  232. $os = 'webos';
  233. } elseif ($detectmobile->is('MaemoOS')) {
  234. $os = 'maemo';
  235. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  236. $os = 'windows';
  237. }
  238. }
  239. // OS
  240. if (preg_match('/linux/i', $user_agent)) {
  241. $os = 'linux';
  242. } elseif (preg_match('/macintosh/i', $user_agent)) {
  243. $os = 'macintosh';
  244. } elseif (preg_match('/windows/i', $user_agent)) {
  245. $os = 'windows';
  246. }
  247. // Name
  248. $reg = array();
  249. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  250. $name = 'firefox';
  251. $version = $reg[2];
  252. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  253. $name = 'edge';
  254. $version = $reg[2];
  255. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  256. $name = 'chrome';
  257. $version = $reg[2];
  258. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  259. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  260. $name = 'chrome';
  261. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  262. $name = 'iceweasel';
  263. } elseif (preg_match('/epiphany/i', $user_agent)) {
  264. $name = 'epiphany';
  265. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  266. $name = 'safari';
  267. $version = $reg[2];
  268. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  269. // Safari is often present in string for mobile but its not.
  270. $name = 'opera';
  271. $version = $reg[2];
  272. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  273. $name = 'ie';
  274. $version = end($reg);
  275. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  276. // MS products at end
  277. $name = 'ie';
  278. $version = end($reg);
  279. } elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  280. // MS products at end
  281. $name = 'lynxlinks';
  282. $version = $reg[4];
  283. }
  284. if ($tablet) {
  285. $layout = 'tablet';
  286. } elseif ($phone) {
  287. $layout = 'phone';
  288. } else {
  289. $layout = 'classic';
  290. }
  291. return array(
  292. 'browsername' => $name,
  293. 'browserversion' => $version,
  294. 'browseros' => $os,
  295. 'layout' => $layout,
  296. 'phone' => $phone,
  297. 'tablet' => $tablet
  298. );
  299. }
  300. /**
  301. * Function called at end of web php process
  302. *
  303. * @return void
  304. */
  305. function dol_shutdown()
  306. {
  307. global $conf, $user, $langs, $db;
  308. $disconnectdone = false;
  309. $depth = 0;
  310. if (is_object($db) && !empty($db->connected)) {
  311. $depth = $db->transaction_opened;
  312. $disconnectdone = $db->close();
  313. }
  314. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  315. }
  316. /**
  317. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  318. *
  319. * @param string $paramname Name or parameter to test
  320. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  321. */
  322. function GETPOSTISSET($paramname)
  323. {
  324. $isset = false;
  325. $relativepathstring = $_SERVER["PHP_SELF"];
  326. // Clean $relativepathstring
  327. if (constant('DOL_URL_ROOT')) {
  328. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  329. }
  330. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  331. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  332. //var_dump($relativepathstring);
  333. //var_dump($user->default_values);
  334. // Code for search criteria persistence.
  335. // Retrieve values if restore_lastsearch_values
  336. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  337. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  338. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  339. if (is_array($tmp)) {
  340. foreach ($tmp as $key => $val) {
  341. if ($key == $paramname) { // We are on the requested parameter
  342. $isset = true;
  343. break;
  344. }
  345. }
  346. }
  347. }
  348. // If there is saved contextpage, limit, page or mode
  349. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  350. $isset = true;
  351. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  352. $isset = true;
  353. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  354. $isset = true;
  355. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  356. $isset = true;
  357. }
  358. } else {
  359. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  360. }
  361. return $isset;
  362. }
  363. /**
  364. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  365. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  366. *
  367. * @param string $paramname Name or parameter to test
  368. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  369. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  370. */
  371. function GETPOSTISARRAY($paramname, $method = 0)
  372. {
  373. // for $method test need return the same $val as GETPOST
  374. if (empty($method)) {
  375. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  376. } elseif ($method == 1) {
  377. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  378. } elseif ($method == 2) {
  379. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  380. } elseif ($method == 3) {
  381. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  382. } else {
  383. $val = 'BadFirstParameterForGETPOST';
  384. }
  385. return is_array($val);
  386. }
  387. /**
  388. * Return value of a param into GET or POST supervariable.
  389. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  390. * Note: The property $user->default_values is loaded by main.php when loading the user.
  391. *
  392. * @param string $paramname Name of parameter to found
  393. * @param string $check Type of check
  394. * ''=no check (deprecated)
  395. * 'none'=no check (only for param that should have very rich content like passwords)
  396. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  397. * 'int'=check it's numeric (integer or float)
  398. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  399. * 'alpha'=Same than alphanohtml since v13
  400. * 'alphawithlgt'=alpha with lgt
  401. * 'alphanohtml'=check there is no html content and no " and no ../
  402. * 'aZ'=check it's a-z only
  403. * 'aZ09'=check it's simple alpha string (recommended for keys)
  404. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  405. * 'nohtml'=check there is no html content and no " and no ../
  406. * 'restricthtml'=check html content is restricted to some tags only
  407. * 'custom'= custom filter specify $filter and $options)
  408. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  409. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  410. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  411. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  412. * @return string|array Value found (string or array), or '' if check fails
  413. */
  414. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  415. {
  416. global $mysoc, $user, $conf;
  417. if (empty($paramname)) {
  418. return 'BadFirstParameterForGETPOST';
  419. }
  420. if (empty($check)) {
  421. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  422. // Enable this line to know who call the GETPOST with '' $check parameter.
  423. //var_dump(debug_backtrace()[0]);
  424. }
  425. if (empty($method)) {
  426. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  427. } elseif ($method == 1) {
  428. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  429. } elseif ($method == 2) {
  430. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  431. } elseif ($method == 3) {
  432. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  433. } else {
  434. return 'BadThirdParameterForGETPOST';
  435. }
  436. if (empty($method) || $method == 3 || $method == 4) {
  437. $relativepathstring = $_SERVER["PHP_SELF"];
  438. // Clean $relativepathstring
  439. if (constant('DOL_URL_ROOT')) {
  440. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  441. }
  442. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  443. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  444. //var_dump($relativepathstring);
  445. //var_dump($user->default_values);
  446. // Code for search criteria persistence.
  447. // Retrieve values if restore_lastsearch_values
  448. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  449. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  450. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  451. if (is_array($tmp)) {
  452. foreach ($tmp as $key => $val) {
  453. if ($key == $paramname) { // We are on the requested parameter
  454. $out = $val;
  455. break;
  456. }
  457. }
  458. }
  459. }
  460. // If there is saved contextpage, page or limit
  461. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  462. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  463. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  464. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  465. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  466. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  467. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  468. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  469. }
  470. } elseif (!isset($_GET['sortfield'])) {
  471. // Else, retrieve default values if we are not doing a sort
  472. // 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
  473. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  474. // Search default value from $object->field
  475. global $object;
  476. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  477. $out = $object->fields[$paramname]['default'];
  478. }
  479. }
  480. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  481. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  482. // Now search in setup to overwrite default values
  483. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  484. if (isset($user->default_values[$relativepathstring]['createform'])) {
  485. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  486. $qualified = 0;
  487. if ($defkey != '_noquery_') {
  488. $tmpqueryarraytohave = explode('&', $defkey);
  489. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  490. $foundintru = 0;
  491. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  492. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  493. $foundintru = 1;
  494. }
  495. }
  496. if (!$foundintru) {
  497. $qualified = 1;
  498. }
  499. //var_dump($defkey.'-'.$qualified);
  500. } else {
  501. $qualified = 1;
  502. }
  503. if ($qualified) {
  504. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  505. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  506. break;
  507. }
  508. }
  509. }
  510. }
  511. }
  512. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  513. // Management of default search_filters and sort order
  514. if (!empty($user->default_values)) {
  515. // $user->default_values defined from menu 'Setup - Default values'
  516. //var_dump($user->default_values[$relativepathstring]);
  517. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  518. // Sorted on which fields ? ASC or DESC ?
  519. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  520. // Even if paramname is sortfield, data are stored into ['sortorder...']
  521. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  522. $qualified = 0;
  523. if ($defkey != '_noquery_') {
  524. $tmpqueryarraytohave = explode('&', $defkey);
  525. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  526. $foundintru = 0;
  527. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  528. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  529. $foundintru = 1;
  530. }
  531. }
  532. if (!$foundintru) {
  533. $qualified = 1;
  534. }
  535. //var_dump($defkey.'-'.$qualified);
  536. } else {
  537. $qualified = 1;
  538. }
  539. if ($qualified) {
  540. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  541. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  542. if ($out) {
  543. $out .= ', ';
  544. }
  545. if ($paramname == 'sortfield') {
  546. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  547. }
  548. if ($paramname == 'sortorder') {
  549. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  550. }
  551. }
  552. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  553. }
  554. }
  555. }
  556. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  557. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  558. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  559. continue;
  560. }
  561. $qualified = 0;
  562. if ($defkey != '_noquery_') {
  563. $tmpqueryarraytohave = explode('&', $defkey);
  564. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  565. $foundintru = 0;
  566. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  567. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  568. $foundintru = 1;
  569. }
  570. }
  571. if (!$foundintru) {
  572. $qualified = 1;
  573. }
  574. //var_dump($defkey.'-'.$qualified);
  575. } else {
  576. $qualified = 1;
  577. }
  578. if ($qualified) {
  579. // We must keep $_POST and $_GET here
  580. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  581. // We made a search from quick search menu, do we still use default filter ?
  582. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  583. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  584. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  585. }
  586. } else {
  587. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  588. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  589. }
  590. break;
  591. }
  592. }
  593. }
  594. }
  595. }
  596. }
  597. }
  598. }
  599. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  600. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  601. // 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.
  602. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  603. $reg = array();
  604. $maxloop = 20;
  605. $loopnb = 0; // Protection against infinite loop
  606. 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.
  607. $loopnb++;
  608. $newout = '';
  609. if ($reg[1] == 'DAY') {
  610. $tmp = dol_getdate(dol_now(), true);
  611. $newout = $tmp['mday'];
  612. } elseif ($reg[1] == 'MONTH') {
  613. $tmp = dol_getdate(dol_now(), true);
  614. $newout = $tmp['mon'];
  615. } elseif ($reg[1] == 'YEAR') {
  616. $tmp = dol_getdate(dol_now(), true);
  617. $newout = $tmp['year'];
  618. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  619. $tmp = dol_getdate(dol_now(), true);
  620. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  621. $newout = $tmp2['day'];
  622. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  623. $tmp = dol_getdate(dol_now(), true);
  624. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  625. $newout = $tmp2['month'];
  626. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  627. $tmp = dol_getdate(dol_now(), true);
  628. $newout = ($tmp['year'] - 1);
  629. } elseif ($reg[1] == 'NEXT_DAY') {
  630. $tmp = dol_getdate(dol_now(), true);
  631. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  632. $newout = $tmp2['day'];
  633. } elseif ($reg[1] == 'NEXT_MONTH') {
  634. $tmp = dol_getdate(dol_now(), true);
  635. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  636. $newout = $tmp2['month'];
  637. } elseif ($reg[1] == 'NEXT_YEAR') {
  638. $tmp = dol_getdate(dol_now(), true);
  639. $newout = ($tmp['year'] + 1);
  640. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  641. $newout = $mysoc->country_id;
  642. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  643. $newout = $user->id;
  644. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  645. $newout = $user->fk_user;
  646. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  647. $newout = $conf->entity;
  648. } else {
  649. $newout = ''; // Key not found, we replace with empty string
  650. }
  651. //var_dump('__'.$reg[1].'__ -> '.$newout);
  652. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  653. }
  654. }
  655. // Check rule
  656. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  657. if (!is_array($out) || empty($out)) {
  658. $out = array();
  659. } else {
  660. $tmparray = explode(':', $check);
  661. if (!empty($tmparray[1])) {
  662. $tmpcheck = $tmparray[1];
  663. } else {
  664. $tmpcheck = 'alphanohtml';
  665. }
  666. foreach ($out as $outkey => $outval) {
  667. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  668. }
  669. }
  670. } else {
  671. $out = sanitizeVal($out, $check, $filter, $options);
  672. }
  673. // Sanitizing for special parameters.
  674. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  675. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  676. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  677. $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
  678. do {
  679. $oldstringtoclean = $out;
  680. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  681. $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
  682. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  683. } while ($oldstringtoclean != $out);
  684. }
  685. // Code for search criteria persistence.
  686. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  687. if (empty($method) || $method == 3 || $method == 4) {
  688. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  689. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  690. // We save search key only if $out not empty that means:
  691. // - posted value not empty, or
  692. // - 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).
  693. if ($out != '') { // $out = '0' or 'abc', it is a search criteria to keep
  694. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  695. }
  696. }
  697. }
  698. return $out;
  699. }
  700. /**
  701. * Return value of a param into GET or POST supervariable.
  702. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  703. * Note: The property $user->default_values is loaded by main.php when loading the user.
  704. *
  705. * @param string $paramname Name of parameter to found
  706. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  707. * @return int Value found (int)
  708. */
  709. function GETPOSTINT($paramname, $method = 0)
  710. {
  711. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  712. }
  713. /**
  714. * Return a sanitized or empty value after checking value against a rule.
  715. *
  716. * @deprecated
  717. * @param string|array $out Value to check/clear.
  718. * @param string $check Type of check/sanitizing
  719. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  720. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  721. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  722. */
  723. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  724. {
  725. return sanitizeVal($out, $check, $filter, $options);
  726. }
  727. /**
  728. * Return a sanitized or empty value after checking value against a rule.
  729. *
  730. * @param string|array $out Value to check/clear.
  731. * @param string $check Type of check/sanitizing
  732. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  733. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  734. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  735. */
  736. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  737. {
  738. global $conf;
  739. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  740. // Check is done after replacement
  741. switch ($check) {
  742. case 'none':
  743. break;
  744. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  745. if (!is_numeric($out)) {
  746. $out = '';
  747. }
  748. break;
  749. case 'intcomma':
  750. if (preg_match('/[^0-9,-]+/i', $out)) {
  751. $out = '';
  752. }
  753. break;
  754. case 'san_alpha':
  755. $out = filter_var($out, FILTER_SANITIZE_STRING);
  756. break;
  757. case 'email':
  758. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  759. break;
  760. case 'aZ':
  761. if (!is_array($out)) {
  762. $out = trim($out);
  763. if (preg_match('/[^a-z]+/i', $out)) {
  764. $out = '';
  765. }
  766. }
  767. break;
  768. case 'aZ09':
  769. if (!is_array($out)) {
  770. $out = trim($out);
  771. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  772. $out = '';
  773. }
  774. }
  775. break;
  776. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  777. if (!is_array($out)) {
  778. $out = trim($out);
  779. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  780. $out = '';
  781. }
  782. }
  783. break;
  784. case 'nohtml': // No html
  785. $out = dol_string_nohtmltag($out, 0);
  786. break;
  787. case 'alpha': // No html and no ../ and "
  788. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  789. if (!is_array($out)) {
  790. $out = trim($out);
  791. do {
  792. $oldstringtoclean = $out;
  793. // Remove html tags
  794. $out = dol_string_nohtmltag($out, 0);
  795. // Remove also other dangerous string sequences
  796. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  797. // '../' or '..\' is dangerous because it allows dir transversals
  798. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  799. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  800. } while ($oldstringtoclean != $out);
  801. // keep lines feed
  802. }
  803. break;
  804. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
  805. if (!is_array($out)) {
  806. $out = trim($out);
  807. do {
  808. $oldstringtoclean = $out;
  809. // Remove html tags
  810. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  811. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  812. // '../' or '..\' is dangerous because it allows dir transversals
  813. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  814. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  815. } while ($oldstringtoclean != $out);
  816. }
  817. break;
  818. case 'restricthtml': // Recommended for most html textarea
  819. case 'restricthtmlallowunvalid':
  820. do {
  821. $oldstringtoclean = $out;
  822. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  823. try {
  824. $dom = new DOMDocument;
  825. // Add a trick to solve pb with text without parent tag
  826. // like '<h1>Foo</h1><p>bar</p>' that ends up with '<h1>Foo<p>bar</p></h1>'
  827. // like 'abc' that ends up with '<p>abc</p>'
  828. $out = '<div class="tricktoremove">'.$out.'</div>';
  829. $dom->loadHTML($out, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  830. $out = trim($dom->saveHTML());
  831. // Remove the trick added to solve pb with text without parent tag
  832. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  833. $out = preg_replace('/<\/div>$/', '', $out);
  834. } catch (Exception $e) {
  835. //print $e->getMessage();
  836. return 'InvalidHTMLString';
  837. }
  838. }
  839. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  840. // encoded using text entities) so we can then exclude all numeric entities.
  841. $out = preg_replace('/&#39;/i', '&apos;', $out);
  842. // 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).
  843. // 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
  844. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  845. //$out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', 'realCharForNumericEntities', $out);
  846. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  847. return realCharForNumericEntities($m); }, $out);
  848. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  849. $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'.
  850. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  851. // We should also exclude non expected HTML attributes and clean content of some attributes.
  852. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  853. // 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.
  854. $out = dol_string_onlythesehtmlattributes($out);
  855. }
  856. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  857. $out = preg_replace('/&apos;/i', "&#39;", $out);
  858. } while ($oldstringtoclean != $out);
  859. break;
  860. case 'custom':
  861. if (empty($filter)) {
  862. return 'BadFourthParameterForGETPOST';
  863. }
  864. $out = filter_var($out, $filter, $options);
  865. break;
  866. }
  867. return $out;
  868. }
  869. if (!function_exists('dol_getprefix')) {
  870. /**
  871. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  872. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  873. * or two instances in same virtual servers.
  874. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  875. *
  876. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  877. * @return string A calculated prefix
  878. */
  879. function dol_getprefix($mode = '')
  880. {
  881. // If prefix is for email (we need to have $conf already loaded for this case)
  882. if ($mode == 'email') {
  883. global $conf;
  884. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  885. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  886. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  887. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  888. return $_SERVER["SERVER_NAME"];
  889. }
  890. }
  891. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  892. if (!empty($conf->file->instance_unique_id)) {
  893. return sha1('dolibarr'.$conf->file->instance_unique_id);
  894. }
  895. // For backward compatibility when instance_unique_id is not set
  896. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  897. }
  898. // If prefix is for session (no need to have $conf loaded)
  899. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  900. $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
  901. // The recommended value (may be not defined for old versions)
  902. if (!empty($tmp_instance_unique_id)) {
  903. return sha1('dolibarr'.$tmp_instance_unique_id);
  904. }
  905. // For backward compatibility when instance_unique_id is not set
  906. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  907. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  908. } else {
  909. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  910. }
  911. }
  912. }
  913. /**
  914. * Make an include_once using default root and alternate root if it fails.
  915. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  916. * To link to a module file from a module file, use include './mymodulefile';
  917. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  918. *
  919. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  920. * @param string $classname Class name (deprecated)
  921. * @return bool True if load is a success, False if it fails
  922. */
  923. function dol_include_once($relpath, $classname = '')
  924. {
  925. 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']
  926. $fullpath = dol_buildpath($relpath);
  927. if (!file_exists($fullpath)) {
  928. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  929. return false;
  930. }
  931. if (!empty($classname) && !class_exists($classname)) {
  932. return include $fullpath;
  933. } else {
  934. return include_once $fullpath;
  935. }
  936. }
  937. /**
  938. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  939. *
  940. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  941. * @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)
  942. * @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)
  943. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  944. * 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
  945. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  946. */
  947. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  948. {
  949. global $conf;
  950. $path = preg_replace('/^\//', '', $path);
  951. if (empty($type)) { // For a filesystem path
  952. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  953. if (is_array($conf->file->dol_document_root)) {
  954. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  955. if ($key == 'main') {
  956. continue;
  957. }
  958. if (file_exists($dirroot.'/'.$path)) {
  959. $res = $dirroot.'/'.$path;
  960. return $res;
  961. }
  962. }
  963. }
  964. if ($returnemptyifnotfound) {
  965. // Not found into alternate dir
  966. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  967. return '';
  968. }
  969. }
  970. } else {
  971. // For an url path
  972. // We try to get local path of file on filesystem from url
  973. // Note that trying to know if a file on disk exist by forging path on disk from url
  974. // works only for some web server and some setup. This is bugged when
  975. // using proxy, rewriting, virtual path, etc...
  976. $res = '';
  977. if ($type == 1) {
  978. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  979. }
  980. if ($type == 2) {
  981. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  982. }
  983. if ($type == 3) {
  984. $res = DOL_URL_ROOT.'/'.$path;
  985. }
  986. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  987. if ($key == 'main') {
  988. if ($type == 3) {
  989. global $dolibarr_main_url_root;
  990. // Define $urlwithroot
  991. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  992. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  993. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  994. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  995. }
  996. continue;
  997. }
  998. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  999. if (!empty($regs[1])) {
  1000. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1001. if (file_exists($dirroot.'/'.$regs[1])) {
  1002. if ($type == 1) {
  1003. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1004. }
  1005. if ($type == 2) {
  1006. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1007. }
  1008. if ($type == 3) {
  1009. global $dolibarr_main_url_root;
  1010. // Define $urlwithroot
  1011. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1012. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1013. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1014. $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
  1015. }
  1016. break;
  1017. }
  1018. }
  1019. }
  1020. }
  1021. return $res;
  1022. }
  1023. /**
  1024. * Create a clone of instance of object (new instance with same value for properties)
  1025. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  1026. * 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.
  1027. *
  1028. * @param object $object Object to clone
  1029. * @param int $native 0=Full isolation method, 1=Native PHP method
  1030. * @return object Clone object
  1031. * @see https://php.net/manual/language.oop5.cloning.php
  1032. */
  1033. function dol_clone($object, $native = 0)
  1034. {
  1035. if (empty($native)) {
  1036. $myclone = unserialize(serialize($object)); // serialize then unserialize is hack to be sure to have a new object for all fields
  1037. } else {
  1038. $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)
  1039. }
  1040. return $myclone;
  1041. }
  1042. /**
  1043. * Optimize a size for some browsers (phone, smarphone, ...)
  1044. *
  1045. * @param int $size Size we want
  1046. * @param string $type Type of optimizing:
  1047. * '' = function used to define a size for truncation
  1048. * 'width' = function is used to define a width
  1049. * @return int New size after optimizing
  1050. */
  1051. function dol_size($size, $type = '')
  1052. {
  1053. global $conf;
  1054. if (empty($conf->dol_optimize_smallscreen)) {
  1055. return $size;
  1056. }
  1057. if ($type == 'width' && $size > 250) {
  1058. return 250;
  1059. } else {
  1060. return 10;
  1061. }
  1062. }
  1063. /**
  1064. * Clean a string to use it as a file name.
  1065. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1066. *
  1067. * @param string $str String to clean
  1068. * @param string $newstr String to replace bad chars with.
  1069. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1070. * @return string String cleaned (a-zA-Z_)
  1071. *
  1072. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1073. */
  1074. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1075. {
  1076. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1077. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1078. // Char '/' and '\' are file delimiters.
  1079. // 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
  1080. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1081. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1082. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1083. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1084. $tmp = str_replace('..', '', $tmp);
  1085. return $tmp;
  1086. }
  1087. /**
  1088. * Clean a string to use it as a path name.
  1089. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1090. *
  1091. * @param string $str String to clean
  1092. * @param string $newstr String to replace bad chars with
  1093. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1094. * @return string String cleaned (a-zA-Z_)
  1095. *
  1096. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1097. */
  1098. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1099. {
  1100. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1101. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1102. // 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
  1103. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1104. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1105. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1106. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1107. $tmp = str_replace('..', '', $tmp);
  1108. return $tmp;
  1109. }
  1110. /**
  1111. * Clean a string to use it as an URL (into a href or src attribute)
  1112. *
  1113. * @param string $stringtoclean String to clean
  1114. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1115. * @return string Escaped string.
  1116. */
  1117. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1118. {
  1119. // 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)
  1120. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1121. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1122. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1123. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1124. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1125. if ($type == 1) {
  1126. // removing : should disable links to external url like http:aaa)
  1127. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1128. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1129. }
  1130. do {
  1131. $oldstringtoclean = $stringtoclean;
  1132. // removing '&colon' should disable links to external url like http:aaa)
  1133. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1134. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1135. } while ($oldstringtoclean != $stringtoclean);
  1136. if ($type == 1) {
  1137. // removing '//' should disable links to external url like //aaa or http//)
  1138. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1139. }
  1140. return $stringtoclean;
  1141. }
  1142. /**
  1143. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1144. *
  1145. * @param string $str String to clean
  1146. * @return string Cleaned string
  1147. *
  1148. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1149. */
  1150. function dol_string_unaccent($str)
  1151. {
  1152. global $conf;
  1153. if (utf8_check($str)) {
  1154. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1155. $transliterator = \Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', \Transliterator::FORWARD);
  1156. return $transliterator->transliterate($str);
  1157. }
  1158. // See http://www.utf8-chartable.de/
  1159. $string = rawurlencode($str);
  1160. $replacements = array(
  1161. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1162. '%C3%87' => 'C',
  1163. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1164. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1165. '%C3%91' => 'N',
  1166. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1167. '%C5%A0' => 'S',
  1168. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1169. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1170. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1171. '%C3%A7' => 'c',
  1172. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1173. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1174. '%C3%B1' => 'n',
  1175. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1176. '%C5%A1' => 's',
  1177. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1178. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1179. );
  1180. $string = strtr($string, $replacements);
  1181. return rawurldecode($string);
  1182. } else {
  1183. // See http://www.ascii-code.com/
  1184. $string = strtr(
  1185. $str,
  1186. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1187. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1188. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1189. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1190. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1191. \xF9\xFA\xFB\xFC\xFD\xFF",
  1192. "AAAAAAC
  1193. EEEEIIIIDN
  1194. OOOOOUUUY
  1195. aaaaaaceeee
  1196. iiiidnooooo
  1197. uuuuyy"
  1198. );
  1199. $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"));
  1200. return $string;
  1201. }
  1202. }
  1203. /**
  1204. * Clean a string from all punctuation characters to use it as a ref or login.
  1205. * This is a more complete function than dol_sanitizeFileName.
  1206. *
  1207. * @param string $str String to clean
  1208. * @param string $newstr String to replace forbidden chars with
  1209. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1210. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1211. * @return string Cleaned string
  1212. *
  1213. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1214. */
  1215. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1216. {
  1217. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1218. $forbidden_chars_to_remove = array();
  1219. //$forbidden_chars_to_remove=array("(",")");
  1220. if (is_array($badcharstoreplace)) {
  1221. $forbidden_chars_to_replace = $badcharstoreplace;
  1222. }
  1223. if (is_array($badcharstoremove)) {
  1224. $forbidden_chars_to_remove = $badcharstoremove;
  1225. }
  1226. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1227. }
  1228. /**
  1229. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1230. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1231. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1232. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1233. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1234. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1235. * @param string $str String to clean
  1236. * @param int $removetabcrlf Remove also CR-LF
  1237. * @return string Cleaned string
  1238. *
  1239. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1240. */
  1241. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1242. {
  1243. if ($removetabcrlf) {
  1244. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1245. } else {
  1246. 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
  1247. }
  1248. }
  1249. /**
  1250. * Returns text escaped for inclusion into javascript code
  1251. *
  1252. * @param string $stringtoescape String to escape
  1253. * @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 \
  1254. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1255. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1256. */
  1257. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1258. {
  1259. // escape quotes and backslashes, newlines, etc.
  1260. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1261. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1262. if (empty($noescapebackslashn)) {
  1263. $substitjs["\n"] = '\\n';
  1264. $substitjs['\\'] = '\\\\';
  1265. }
  1266. if (empty($mode)) {
  1267. $substitjs["'"] = "\\'";
  1268. $substitjs['"'] = "\\'";
  1269. } elseif ($mode == 1) {
  1270. $substitjs["'"] = "\\'";
  1271. } elseif ($mode == 2) {
  1272. $substitjs['"'] = '\\"';
  1273. } elseif ($mode == 3) {
  1274. $substitjs["'"] = "\\'";
  1275. $substitjs['"'] = "\\\"";
  1276. }
  1277. return strtr($stringtoescape, $substitjs);
  1278. }
  1279. /**
  1280. * Returns text escaped for inclusion into javascript code
  1281. *
  1282. * @param string $stringtoescape String to escape
  1283. * @return string Escaped string for json content.
  1284. */
  1285. function dol_escape_json($stringtoescape)
  1286. {
  1287. return str_replace('"', '\"', $stringtoescape);
  1288. }
  1289. /**
  1290. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1291. *
  1292. * @param string $stringtoescape String to escape
  1293. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1294. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1295. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes to tag.
  1296. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1297. * @return string Escaped string
  1298. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1299. */
  1300. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1301. {
  1302. if ($noescapetags == 'common') {
  1303. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1304. }
  1305. // escape quotes and backslashes, newlines, etc.
  1306. if ($escapeonlyhtmltags) {
  1307. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1308. } else {
  1309. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1310. }
  1311. if (!$keepb) {
  1312. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1313. }
  1314. if (!$keepn) {
  1315. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1316. }
  1317. if ($escapeonlyhtmltags) {
  1318. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1319. } else {
  1320. // Escape tags to keep
  1321. // TODO Does not works yet when there is attributes to tag
  1322. $tmparrayoftags = array();
  1323. if ($noescapetags) {
  1324. $tmparrayoftags = explode(',', $noescapetags);
  1325. }
  1326. if (count($tmparrayoftags)) {
  1327. foreach ($tmparrayoftags as $tagtoreplace) {
  1328. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1329. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1330. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1331. }
  1332. }
  1333. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1334. if (count($tmparrayoftags)) {
  1335. foreach ($tmparrayoftags as $tagtoreplace) {
  1336. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1337. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1338. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1339. }
  1340. }
  1341. return $result;
  1342. }
  1343. }
  1344. /**
  1345. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1346. *
  1347. * @param string $string String to encode
  1348. * @param string $encoding Character set encoding
  1349. * @return string String converted
  1350. */
  1351. function dol_strtolower($string, $encoding = "UTF-8")
  1352. {
  1353. if (function_exists('mb_strtolower')) {
  1354. return mb_strtolower($string, $encoding);
  1355. } else {
  1356. return strtolower($string);
  1357. }
  1358. }
  1359. /**
  1360. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1361. *
  1362. * @param string $string String to encode
  1363. * @param string $encoding Character set encoding
  1364. * @return string String converted
  1365. */
  1366. function dol_strtoupper($string, $encoding = "UTF-8")
  1367. {
  1368. if (function_exists('mb_strtoupper')) {
  1369. return mb_strtoupper($string, $encoding);
  1370. } else {
  1371. return strtoupper($string);
  1372. }
  1373. }
  1374. /**
  1375. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1376. *
  1377. * @param string $string String to encode
  1378. * @param string $encoding Character set encodign
  1379. * @return string String converted
  1380. */
  1381. function dol_ucfirst($string, $encoding = "UTF-8")
  1382. {
  1383. if (function_exists('mb_substr')) {
  1384. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1385. } else {
  1386. return ucfirst($string);
  1387. }
  1388. }
  1389. /**
  1390. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1391. *
  1392. * @param string $string String to encode
  1393. * @param string $encoding Character set encodign
  1394. * @return string String converted
  1395. */
  1396. function dol_ucwords($string, $encoding = "UTF-8")
  1397. {
  1398. if (function_exists('mb_convert_case')) {
  1399. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1400. } else {
  1401. return ucwords($string);
  1402. }
  1403. }
  1404. /**
  1405. * Write log message into outputs. Possible outputs can be:
  1406. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1407. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1408. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1409. * this, use logging to files instead of syslog (see setup of module).
  1410. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1411. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1412. * This function works only if syslog module is enabled.
  1413. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1414. *
  1415. * @param string $message Line to log. ''=Show nothing
  1416. * @param int $level Log level
  1417. * 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
  1418. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1419. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1420. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1421. * @param string $restricttologhandler Force output of log only to this log handler
  1422. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1423. * @return void
  1424. */
  1425. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1426. {
  1427. global $conf, $user, $debugbar;
  1428. // If syslog module enabled
  1429. if (empty($conf->syslog->enabled)) {
  1430. return;
  1431. }
  1432. // Check if we are into execution of code of a website
  1433. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1434. global $website, $websitekey;
  1435. if (is_object($website) && !empty($website->ref)) {
  1436. $suffixinfilename .= '_website_'.$website->ref;
  1437. } elseif (!empty($websitekey)) {
  1438. $suffixinfilename .= '_website_'.$websitekey;
  1439. }
  1440. }
  1441. if ($ident < 0) {
  1442. foreach ($conf->loghandlers as $loghandlerinstance) {
  1443. $loghandlerinstance->setIdent($ident);
  1444. }
  1445. }
  1446. if (!empty($message)) {
  1447. // Test log level
  1448. $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');
  1449. if (!array_key_exists($level, $logLevels)) {
  1450. throw new Exception('Incorrect log level');
  1451. }
  1452. if ($level > $conf->global->SYSLOG_LEVEL) {
  1453. return;
  1454. }
  1455. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1456. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1457. }
  1458. // If adding log inside HTML page is required
  1459. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1460. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1461. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1462. }
  1463. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1464. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1465. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1466. print "\n\n<!-- Log start\n";
  1467. print dol_escape_htmltag($message)."\n";
  1468. print "Log end -->\n";
  1469. }
  1470. $data = array(
  1471. 'message' => $message,
  1472. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1473. 'level' => $level,
  1474. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1475. 'ip' => false
  1476. );
  1477. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1478. if (!empty($remoteip)) {
  1479. $data['ip'] = $remoteip;
  1480. // This is when server run behind a reverse proxy
  1481. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1482. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1483. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1484. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1485. }
  1486. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1487. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1488. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1489. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1490. // 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).
  1491. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1492. } elseif (!empty($_SERVER['LOGNAME'])) {
  1493. // 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).
  1494. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1495. }
  1496. // Loop on each log handler and send output
  1497. foreach ($conf->loghandlers as $loghandlerinstance) {
  1498. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1499. continue;
  1500. }
  1501. $loghandlerinstance->export($data, $suffixinfilename);
  1502. }
  1503. unset($data);
  1504. }
  1505. if ($ident > 0) {
  1506. foreach ($conf->loghandlers as $loghandlerinstance) {
  1507. $loghandlerinstance->setIdent($ident);
  1508. }
  1509. }
  1510. }
  1511. /**
  1512. * Return HTML code to output a button to open a dialog popup box.
  1513. * Such buttons must be included inside a HTML form.
  1514. *
  1515. * @param string $name A name for the html component
  1516. * @param string $label Label shown in Popup title top bar
  1517. * @param string $buttonstring button string
  1518. * @param string $url Url to open
  1519. * @param string $disabled Disabled text
  1520. * @param string $morecss More CSS
  1521. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1522. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1523. * @return string HTML component with button
  1524. */
  1525. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'button bordertransp', $backtopagejsfields = '')
  1526. {
  1527. if (strpos($url, '?') > 0) {
  1528. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1529. } else {
  1530. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1531. }
  1532. $out = '';
  1533. $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
  1534. if ($backtopagejsfields) {
  1535. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1536. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1537. $backtopagejsfields = $name.":".$backtopagejsfields;
  1538. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1539. } else {
  1540. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1541. }
  1542. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1543. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1544. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1545. }
  1546. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1547. $out .= '<!-- a link for button to open url into a dialog popup backtopagejsfields = '.$backtopagejsfields.' -->'."\n";
  1548. $out .= '<a class="cursorpointer button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1549. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1550. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1551. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1552. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1553. $out .= '<script type="text/javascript">
  1554. jQuery(document).ready(function () {
  1555. jQuery(".button_'.$name.'").click(function () {
  1556. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1557. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1558. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1559. $tmpdialog.dialog({
  1560. autoOpen: false,
  1561. modal: true,
  1562. height: (window.innerHeight - 150),
  1563. width: \'80%\',
  1564. title: \''.dol_escape_js($label).'\',
  1565. open: function (event, ui) {
  1566. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1567. },
  1568. close: function (event, ui) {
  1569. returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1570. returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1571. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1572. if (returnedid != "" && returnedid != "div for returned id") {
  1573. jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
  1574. }
  1575. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1576. jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
  1577. }
  1578. }
  1579. });
  1580. $tmpdialog.dialog(\'open\');
  1581. });
  1582. });
  1583. </script>';
  1584. return $out;
  1585. }
  1586. /**
  1587. * Show tab header of a card
  1588. *
  1589. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1590. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1591. * @param string $title Title
  1592. * @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)
  1593. * @param string $picto Add a picto on tab title
  1594. * @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.
  1595. * @param string $morehtmlright Add more html content on right of tabs title
  1596. * @param string $morecss More Css
  1597. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1598. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1599. * @return void
  1600. * @deprecated Use print dol_get_fiche_head() instead
  1601. */
  1602. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1603. {
  1604. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1605. }
  1606. /**
  1607. * Show tabs of a record
  1608. *
  1609. * @param array $links Array of tabs. Note that label into $links[$i][1] must be already HTML escaped.
  1610. * @param string $active Active tab name
  1611. * @param string $title Title
  1612. * @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)
  1613. * @param string $picto Add a picto on tab title
  1614. * @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.
  1615. * @param string $morehtmlright Add more html content on right of tabs title
  1616. * @param string $morecss More CSS on the link <a>
  1617. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1618. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1619. * @return string
  1620. */
  1621. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1622. {
  1623. global $conf, $langs, $hookmanager;
  1624. // Show title
  1625. $showtitle = 1;
  1626. if (!empty($conf->dol_optimize_smallscreen)) {
  1627. $showtitle = 0;
  1628. }
  1629. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1630. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1631. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1632. }
  1633. // Show right part
  1634. if ($morehtmlright) {
  1635. $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.
  1636. }
  1637. // Show title
  1638. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1639. $limittitle = 30;
  1640. $out .= '<a class="tabTitle">';
  1641. if ($picto) {
  1642. $noprefix = $pictoisfullpath;
  1643. if (strpos($picto, 'fontawesome_') !== false) {
  1644. $noprefix = 1;
  1645. }
  1646. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1647. }
  1648. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1649. $out .= '</a>';
  1650. }
  1651. // Show tabs
  1652. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1653. $maxkey = -1;
  1654. if (is_array($links) && !empty($links)) {
  1655. $keys = array_keys($links);
  1656. if (count($keys)) {
  1657. $maxkey = max($keys);
  1658. }
  1659. }
  1660. // Show tabs
  1661. // if =0 we don't use the feature
  1662. if (empty($limittoshow)) {
  1663. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1664. }
  1665. if (!empty($conf->dol_optimize_smallscreen)) {
  1666. $limittoshow = 2;
  1667. }
  1668. $displaytab = 0;
  1669. $nbintab = 0;
  1670. $popuptab = 0;
  1671. $outmore = '';
  1672. for ($i = 0; $i <= $maxkey; $i++) {
  1673. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1674. // If active tab is already present
  1675. if ($i >= $limittoshow) {
  1676. $limittoshow--;
  1677. }
  1678. }
  1679. }
  1680. for ($i = 0; $i <= $maxkey; $i++) {
  1681. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1682. $isactive = true;
  1683. } else {
  1684. $isactive = false;
  1685. }
  1686. if ($i < $limittoshow || $isactive) {
  1687. // Output entry with a visible tab
  1688. $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])).' -->';
  1689. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1690. if (!empty($links[$i][0])) {
  1691. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1692. } else {
  1693. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1694. }
  1695. } elseif (!empty($links[$i][1])) {
  1696. //print "x $i $active ".$links[$i][2]." z";
  1697. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1698. if (!empty($links[$i][0])) {
  1699. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1700. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  1701. }
  1702. $out .= $links[$i][1];
  1703. if (!empty($links[$i][0])) {
  1704. $out .= '</a>'."\n";
  1705. }
  1706. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1707. $out .= '</div>';
  1708. }
  1709. $out .= '</div>';
  1710. } else {
  1711. // Add entry into the combo popup with the other tabs
  1712. if (!$popuptab) {
  1713. $popuptab = 1;
  1714. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1715. }
  1716. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1717. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1718. if (!empty($links[$i][0])) {
  1719. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1720. } else {
  1721. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1722. }
  1723. } elseif (!empty($links[$i][1])) {
  1724. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1725. $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.
  1726. $outmore .= '</a>'."\n";
  1727. }
  1728. $outmore .= '</div>';
  1729. $nbintab++;
  1730. }
  1731. $displaytab = $i;
  1732. }
  1733. if ($popuptab) {
  1734. $outmore .= '</div>';
  1735. }
  1736. if ($popuptab) { // If there is some tabs not shown
  1737. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1738. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1739. $widthofpopup = 200;
  1740. $tabsname = $moretabssuffix;
  1741. if (empty($tabsname)) {
  1742. $tabsname = str_replace("@", "", $picto);
  1743. }
  1744. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  1745. $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".
  1746. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1747. $out .= $outmore;
  1748. $out .= '</div>';
  1749. $out .= '<div></div>';
  1750. $out .= "</div>\n";
  1751. $out .= "<script>";
  1752. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1753. var x = this.offsetLeft, y = this.offsetTop;
  1754. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1755. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1756. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1757. }
  1758. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1759. });
  1760. ";
  1761. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1762. $out .= "</script>";
  1763. }
  1764. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1765. $out .= "</div>\n";
  1766. }
  1767. if (!$notab || $notab == -1 || $notab == -2) {
  1768. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1769. }
  1770. $parameters = array('tabname' => $active, 'out' => $out);
  1771. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1772. if ($reshook > 0) {
  1773. $out = $hookmanager->resPrint;
  1774. }
  1775. return $out;
  1776. }
  1777. /**
  1778. * Show tab footer of a card
  1779. *
  1780. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1781. * @return void
  1782. * @deprecated Use print dol_get_fiche_end() instead
  1783. */
  1784. function dol_fiche_end($notab = 0)
  1785. {
  1786. print dol_get_fiche_end($notab);
  1787. }
  1788. /**
  1789. * Return tab footer of a card
  1790. *
  1791. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1792. * @return string
  1793. */
  1794. function dol_get_fiche_end($notab = 0)
  1795. {
  1796. if (!$notab || $notab == -1) {
  1797. return "\n</div>\n";
  1798. } else {
  1799. return '';
  1800. }
  1801. }
  1802. /**
  1803. * Show tab footer of a card.
  1804. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1805. *
  1806. * @param Object $object Object to show
  1807. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1808. * @param string $morehtml More html content to output just before the nav bar
  1809. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1810. * @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.
  1811. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1812. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1813. * @param string $moreparam More param to add in nav link url.
  1814. * @param int $nodbprefix Do not include DB prefix to forge table name
  1815. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1816. * @param string $morehtmlstatus More html code to show under navigation arrows
  1817. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1818. * @param string $morehtmlright More html code to show before navigation arrows
  1819. * @return void
  1820. */
  1821. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1822. {
  1823. global $conf, $form, $user, $langs, $hookmanager, $action;
  1824. $error = 0;
  1825. $maxvisiblephotos = 1;
  1826. $showimage = 1;
  1827. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1828. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1829. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1830. $showbarcode = 0;
  1831. }
  1832. $modulepart = 'unknown';
  1833. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1834. $modulepart = $object->element;
  1835. } elseif ($object->element == 'member') {
  1836. $modulepart = 'memberphoto';
  1837. } elseif ($object->element == 'user') {
  1838. $modulepart = 'userphoto';
  1839. }
  1840. if (class_exists("Imagick")) {
  1841. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1842. $modulepart = $object->element;
  1843. } elseif ($object->element == 'fichinter') {
  1844. $modulepart = 'ficheinter';
  1845. } elseif ($object->element == 'contrat') {
  1846. $modulepart = 'contract';
  1847. } elseif ($object->element == 'order_supplier') {
  1848. $modulepart = 'supplier_order';
  1849. } elseif ($object->element == 'invoice_supplier') {
  1850. $modulepart = 'supplier_invoice';
  1851. }
  1852. }
  1853. if ($object->element == 'product') {
  1854. $width = 80;
  1855. $cssclass = 'photowithmargin photoref';
  1856. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1857. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1858. if ($conf->browser->layout == 'phone') {
  1859. $maxvisiblephotos = 1;
  1860. }
  1861. if ($showimage) {
  1862. $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>';
  1863. } else {
  1864. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1865. $nophoto = '';
  1866. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1867. } else { // Show no photo link
  1868. $nophoto = '/public/theme/common/nophoto.png';
  1869. $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>';
  1870. }
  1871. }
  1872. } elseif ($object->element == 'ticket') {
  1873. $width = 80;
  1874. $cssclass = 'photoref';
  1875. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1876. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1877. if ($conf->browser->layout == 'phone') {
  1878. $maxvisiblephotos = 1;
  1879. }
  1880. if ($showimage) {
  1881. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1882. if ($object->nbphoto > 0) {
  1883. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1884. } else {
  1885. $showimage = 0;
  1886. }
  1887. }
  1888. if (!$showimage) {
  1889. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1890. $nophoto = '';
  1891. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1892. } else { // Show no photo link
  1893. $nophoto = img_picto('No photo', 'object_ticket');
  1894. $morehtmlleft .= '<!-- No photo to show -->';
  1895. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1896. $morehtmlleft .= $nophoto;
  1897. $morehtmlleft .= '</div></div>';
  1898. }
  1899. }
  1900. } else {
  1901. if ($showimage) {
  1902. if ($modulepart != 'unknown') {
  1903. $phototoshow = '';
  1904. // Check if a preview file is available
  1905. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1906. $objectref = dol_sanitizeFileName($object->ref);
  1907. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1908. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1909. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1910. $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
  1911. } else {
  1912. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1913. }
  1914. if (empty($subdir)) {
  1915. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1916. }
  1917. $filepath = $dir_output.$subdir."/";
  1918. $filepdf = $filepath.$objectref.".pdf";
  1919. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1920. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1921. $fileimage = $filepdf.'_preview.png';
  1922. $relativepathimage = $relativepath.'_preview.png';
  1923. $pdfexists = file_exists($filepdf);
  1924. // If PDF file exists
  1925. if ($pdfexists) {
  1926. // Conversion du PDF en image png si fichier png non existant
  1927. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1928. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1929. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1930. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1931. if ($ret < 0) {
  1932. $error++;
  1933. }
  1934. }
  1935. }
  1936. }
  1937. if ($pdfexists && !$error) {
  1938. $heightforphotref = 80;
  1939. if (!empty($conf->dol_optimize_smallscreen)) {
  1940. $heightforphotref = 60;
  1941. }
  1942. // If the preview file is found
  1943. if (file_exists($fileimage)) {
  1944. $phototoshow = '<div class="photoref">';
  1945. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1946. $phototoshow .= '</div>';
  1947. }
  1948. }
  1949. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1950. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  1951. }
  1952. if ($phototoshow) {
  1953. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1954. $morehtmlleft .= $phototoshow;
  1955. $morehtmlleft .= '</div>';
  1956. }
  1957. }
  1958. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1959. if ($object->element == 'action') {
  1960. $width = 80;
  1961. $cssclass = 'photorefcenter';
  1962. $nophoto = img_picto('No photo', 'title_agenda');
  1963. } else {
  1964. $width = 14;
  1965. $cssclass = 'photorefcenter';
  1966. $picto = $object->picto;
  1967. $prefix = 'object_';
  1968. if ($object->element == 'project' && !$object->public) {
  1969. $picto = 'project'; // instead of projectpub
  1970. }
  1971. if (strpos($picto, 'fontawesome_') !== false) {
  1972. $prefix = '';
  1973. }
  1974. $nophoto = img_picto('No photo', $prefix.$picto);
  1975. }
  1976. $morehtmlleft .= '<!-- No photo to show -->';
  1977. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1978. $morehtmlleft .= $nophoto;
  1979. $morehtmlleft .= '</div></div>';
  1980. }
  1981. }
  1982. }
  1983. if ($showbarcode) {
  1984. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref').'</div>';
  1985. }
  1986. if ($object->element == 'societe') {
  1987. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1988. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1989. } else {
  1990. $morehtmlstatus .= $object->getLibStatut(6);
  1991. }
  1992. } elseif ($object->element == 'product') {
  1993. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1994. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1995. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1996. } else {
  1997. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1998. }
  1999. $morehtmlstatus .= ' &nbsp; ';
  2000. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2001. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2002. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2003. } else {
  2004. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2005. }
  2006. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  2007. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2008. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2009. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2010. }
  2011. $morehtmlstatus .= $tmptxt;
  2012. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2013. if ($object->statut == 0) {
  2014. $morehtmlstatus .= $object->getLibStatut(5);
  2015. } else {
  2016. $morehtmlstatus .= $object->getLibStatut(4);
  2017. }
  2018. } elseif ($object->element == 'facturerec') {
  2019. if ($object->frequency == 0) {
  2020. $morehtmlstatus .= $object->getLibStatut(2);
  2021. } else {
  2022. $morehtmlstatus .= $object->getLibStatut(5);
  2023. }
  2024. } elseif ($object->element == 'project_task') {
  2025. $object->fk_statut = 1;
  2026. if ($object->progress > 0) {
  2027. $object->fk_statut = 2;
  2028. }
  2029. if ($object->progress >= 100) {
  2030. $object->fk_statut = 3;
  2031. }
  2032. $tmptxt = $object->getLibStatut(5);
  2033. $morehtmlstatus .= $tmptxt; // No status on task
  2034. } else { // Generic case
  2035. $tmptxt = $object->getLibStatut(6);
  2036. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2037. $tmptxt = $object->getLibStatut(5);
  2038. }
  2039. $morehtmlstatus .= $tmptxt;
  2040. }
  2041. // Add if object was dispatched "into accountancy"
  2042. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2043. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2044. if (method_exists($object, 'getVentilExportCompta')) {
  2045. $accounted = $object->getVentilExportCompta();
  2046. $langs->load("accountancy");
  2047. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2048. }
  2049. }
  2050. // Add alias for thirdparty
  2051. if (!empty($object->name_alias)) {
  2052. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  2053. }
  2054. // Add label
  2055. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2056. if (!empty($object->label)) {
  2057. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  2058. }
  2059. }
  2060. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2061. $moreaddress = $object->getBannerAddress('refaddress', $object);
  2062. if ($moreaddress) {
  2063. $morehtmlref .= '<div class="refidno">';
  2064. $morehtmlref .= $moreaddress;
  2065. $morehtmlref .= '</div>';
  2066. }
  2067. }
  2068. 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)) {
  2069. $morehtmlref .= '<div style="clear: both;"></div>';
  2070. $morehtmlref .= '<div class="refidno">';
  2071. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  2072. $morehtmlref .= '</div>';
  2073. }
  2074. $parameters=array('morehtmlref'=>$morehtmlref);
  2075. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2076. if ($reshook < 0) {
  2077. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2078. } elseif (empty($reshook)) {
  2079. $morehtmlref .= $hookmanager->resPrint;
  2080. } elseif ($reshook > 0) {
  2081. $morehtmlref = $hookmanager->resPrint;
  2082. }
  2083. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2084. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2085. print '</div>';
  2086. print '<div class="underrefbanner clearboth"></div>';
  2087. }
  2088. /**
  2089. * Show a string with the label tag dedicated to the HTML edit field.
  2090. *
  2091. * @param string $langkey Translation key
  2092. * @param string $fieldkey Key of the html select field the text refers to
  2093. * @param int $fieldrequired 1=Field is mandatory
  2094. * @return string
  2095. * @deprecated Form::editfieldkey
  2096. */
  2097. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2098. {
  2099. global $langs;
  2100. $ret = '';
  2101. if ($fieldrequired) {
  2102. $ret .= '<span class="fieldrequired">';
  2103. }
  2104. $ret .= '<label for="'.$fieldkey.'">';
  2105. $ret .= $langs->trans($langkey);
  2106. $ret .= '</label>';
  2107. if ($fieldrequired) {
  2108. $ret .= '</span>';
  2109. }
  2110. return $ret;
  2111. }
  2112. /**
  2113. * Return string to add class property on html element with pair/impair.
  2114. *
  2115. * @param string $var 0 or 1
  2116. * @param string $moreclass More class to add
  2117. * @return string String to add class onto HTML element
  2118. */
  2119. function dol_bc($var, $moreclass = '')
  2120. {
  2121. global $bc;
  2122. $ret = ' '.$bc[$var];
  2123. if ($moreclass) {
  2124. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2125. }
  2126. return $ret;
  2127. }
  2128. /**
  2129. * Return a formated address (part address/zip/town/state) according to country rules.
  2130. * See https://en.wikipedia.org/wiki/Address
  2131. *
  2132. * @param Object $object A company or contact object
  2133. * @param int $withcountry 1=Add country into address string
  2134. * @param string $sep Separator to use to build string
  2135. * @param Translate $outputlangs Object lang that contains language for text translation.
  2136. * @param int $mode 0=Standard output, 1=Remove address
  2137. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2138. * @return string Formated string
  2139. * @see dol_print_address()
  2140. */
  2141. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2142. {
  2143. global $conf, $langs, $hookmanager;
  2144. $ret = '';
  2145. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2146. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2147. // Address
  2148. if (empty($mode)) {
  2149. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2150. }
  2151. // Zip/Town/State
  2152. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2153. // US: title firstname name \n address lines \n town, state, zip \n country
  2154. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2155. $ret .= (($ret && $town) ? $sep : '').$town;
  2156. if (!empty($object->state)) {
  2157. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2158. }
  2159. if (!empty($object->zip)) {
  2160. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2161. }
  2162. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2163. // UK: title firstname name \n address lines \n town state \n zip \n country
  2164. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2165. $ret .= ($ret ? $sep : '').$town;
  2166. if (!empty($object->state)) {
  2167. $ret .= ($ret ? ", " : '').$object->state;
  2168. }
  2169. if (!empty($object->zip)) {
  2170. $ret .= ($ret ? $sep : '').$object->zip;
  2171. }
  2172. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2173. // ES: title firstname name \n address lines \n zip town \n state \n country
  2174. $ret .= ($ret ? $sep : '').$object->zip;
  2175. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2176. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2177. if (!empty($object->state)) {
  2178. $ret .= "\n".$object->state;
  2179. }
  2180. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2181. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2182. // See https://www.sljfaq.org/afaq/addresses.html
  2183. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2184. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2185. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2186. // IT: title firstname name\n address lines \n zip town state_code \n country
  2187. $ret .= ($ret ? $sep : '').$object->zip;
  2188. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2189. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2190. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2191. } else {
  2192. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2193. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2194. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2195. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2196. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2197. $ret .= ($ret ? ", " : '').$object->state;
  2198. }
  2199. }
  2200. if (!is_object($outputlangs)) {
  2201. $outputlangs = $langs;
  2202. }
  2203. if ($withcountry) {
  2204. $langs->load("dict");
  2205. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2206. }
  2207. if ($hookmanager) {
  2208. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2209. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2210. if ($reshook > 0) {
  2211. $ret = '';
  2212. }
  2213. $ret .= $hookmanager->resPrint;
  2214. }
  2215. return $ret;
  2216. }
  2217. /**
  2218. * Format a string.
  2219. *
  2220. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2221. * @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)
  2222. * @param int $is_gmt See comment of timestamp parameter
  2223. * @return string A formatted string
  2224. */
  2225. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2226. {
  2227. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2228. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2229. } else {
  2230. return 'Error date into a not supported range';
  2231. }
  2232. }
  2233. /**
  2234. * Output date in a string format according to outputlangs (or langs if not defined).
  2235. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2236. *
  2237. * @param int $time GM Timestamps date
  2238. * @param string $format Output date format (tag of strftime function)
  2239. * "%d %b %Y",
  2240. * "%d/%m/%Y %H:%M",
  2241. * "%d/%m/%Y %H:%M:%S",
  2242. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2243. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2244. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2245. * false or 'tzserver' => output string is for local PHP server TZ usage
  2246. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2247. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2248. * @param Translate $outputlangs Object lang that contains language for text translation.
  2249. * @param boolean $encodetooutput false=no convert into output pagecode
  2250. * @return string Formated date or '' if time is null
  2251. *
  2252. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2253. */
  2254. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2255. {
  2256. global $conf, $langs;
  2257. // If date undefined or "", we return ""
  2258. if (dol_strlen($time) == 0) {
  2259. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2260. }
  2261. if ($tzoutput === 'auto') {
  2262. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2263. }
  2264. // Clean parameters
  2265. $to_gmt = false;
  2266. $offsettz = $offsetdst = 0;
  2267. if ($tzoutput) {
  2268. $to_gmt = true; // For backward compatibility
  2269. if (is_string($tzoutput)) {
  2270. if ($tzoutput == 'tzserver') {
  2271. $to_gmt = false;
  2272. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2273. $offsettz = 0; // Timezone offset with server timezone, so 0
  2274. $offsetdst = 0; // Dst offset with server timezone, so 0
  2275. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2276. $to_gmt = true;
  2277. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2278. if (class_exists('DateTimeZone')) {
  2279. $user_date_tz = new DateTimeZone($offsettzstring);
  2280. $user_dt = new DateTime();
  2281. $user_dt->setTimezone($user_date_tz);
  2282. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2283. $offsettz = $user_dt->getOffset();
  2284. } else { // old method (The 'tzuser' was processed like the 'tzuserrel')
  2285. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2286. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2287. }
  2288. }
  2289. }
  2290. }
  2291. if (!is_object($outputlangs)) {
  2292. $outputlangs = $langs;
  2293. }
  2294. if (!$format) {
  2295. $format = 'daytextshort';
  2296. }
  2297. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2298. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2299. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2300. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2301. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2302. if ($formatwithoutreduce != $format) {
  2303. $format = $formatwithoutreduce;
  2304. $reduceformat = 1;
  2305. } // so format 'dayreduceformat' is processed like day
  2306. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2307. // TODO Add format daysmallyear and dayhoursmallyear
  2308. if ($format == 'day') {
  2309. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2310. } elseif ($format == 'hour') {
  2311. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2312. } elseif ($format == 'hourduration') {
  2313. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2314. } elseif ($format == 'daytext') {
  2315. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2316. } elseif ($format == 'daytextshort') {
  2317. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2318. } elseif ($format == 'dayhour') {
  2319. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2320. } elseif ($format == 'dayhoursec') {
  2321. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2322. } elseif ($format == 'dayhourtext') {
  2323. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2324. } elseif ($format == 'dayhourtextshort') {
  2325. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2326. } elseif ($format == 'dayhourlog') {
  2327. // Format not sensitive to language
  2328. $format = '%Y%m%d%H%M%S';
  2329. } elseif ($format == 'dayhourlogsmall') {
  2330. // Format not sensitive to language
  2331. $format = '%Y%m%d%H%M';
  2332. } elseif ($format == 'dayhourldap') {
  2333. $format = '%Y%m%d%H%M%SZ';
  2334. } elseif ($format == 'dayhourxcard') {
  2335. $format = '%Y%m%dT%H%M%SZ';
  2336. } elseif ($format == 'dayxcard') {
  2337. $format = '%Y%m%d';
  2338. } elseif ($format == 'dayrfc') {
  2339. $format = '%Y-%m-%d'; // DATE_RFC3339
  2340. } elseif ($format == 'dayhourrfc') {
  2341. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2342. } elseif ($format == 'standard') {
  2343. $format = '%Y-%m-%d %H:%M:%S';
  2344. }
  2345. if ($reduceformat) {
  2346. $format = str_replace('%Y', '%y', $format);
  2347. $format = str_replace('yyyy', 'yy', $format);
  2348. }
  2349. // Clean format
  2350. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2351. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2352. $format = str_replace('%b', '__b__', $format);
  2353. $format = str_replace('%B', '__B__', $format);
  2354. }
  2355. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2356. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2357. $format = str_replace('%a', '__a__', $format);
  2358. $format = str_replace('%A', '__A__', $format);
  2359. }
  2360. // Analyze date
  2361. $reg = array();
  2362. 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
  2363. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2364. return '';
  2365. } 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
  2366. // This part of code should not be used anymore.
  2367. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2368. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2369. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2370. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2371. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2372. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2373. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2374. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2375. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2376. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2377. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2378. } else {
  2379. // Date is a timestamps
  2380. if ($time < 100000000000) { // Protection against bad date values
  2381. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2382. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2383. } else {
  2384. $ret = 'Bad value '.$time.' for date';
  2385. }
  2386. }
  2387. if (preg_match('/__b__/i', $format)) {
  2388. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2389. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2390. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2391. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2392. if ($encodetooutput) {
  2393. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2394. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2395. } else {
  2396. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2397. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2398. }
  2399. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2400. $ret = str_replace('__b__', $monthtextshort, $ret);
  2401. $ret = str_replace('__B__', $monthtext, $ret);
  2402. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2403. //return $ret;
  2404. }
  2405. if (preg_match('/__a__/i', $format)) {
  2406. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2407. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2408. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2409. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2410. $ret = str_replace('__A__', $dayweek, $ret);
  2411. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2412. }
  2413. return $ret;
  2414. }
  2415. /**
  2416. * Return an array with locale date info.
  2417. * WARNING: This function use PHP server timezone by default to return locale informations.
  2418. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2419. *
  2420. * @param int $timestamp Timestamp
  2421. * @param boolean $fast Fast mode. deprecated.
  2422. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2423. * @return array Array of informations
  2424. * 'seconds' => $secs,
  2425. * 'minutes' => $min,
  2426. * 'hours' => $hour,
  2427. * 'mday' => $day,
  2428. * 'wday' => $dow, 0=sunday, 6=saturday
  2429. * 'mon' => $month,
  2430. * 'year' => $year,
  2431. * 'yday' => floor($secsInYear/$_day_power)
  2432. * '0' => original timestamp
  2433. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2434. */
  2435. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2436. {
  2437. //$datetimeobj = new DateTime('@'.$timestamp);
  2438. $datetimeobj = new DateTime();
  2439. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2440. if ($forcetimezone) {
  2441. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2442. }
  2443. $arrayinfo = array(
  2444. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2445. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2446. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2447. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2448. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2449. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2450. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2451. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2452. '0'=>$timestamp
  2453. );
  2454. return $arrayinfo;
  2455. }
  2456. /**
  2457. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2458. * Replace function mktime not available under Windows if year < 1970
  2459. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2460. *
  2461. * @param int $hour Hour (can be -1 for undefined)
  2462. * @param int $minute Minute (can be -1 for undefined)
  2463. * @param int $second Second (can be -1 for undefined)
  2464. * @param int $month Month (1 to 12)
  2465. * @param int $day Day (1 to 31)
  2466. * @param int $year Year
  2467. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2468. * False or 0 or 'tzserver' = local to server TZ
  2469. * 'auto'
  2470. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2471. * '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.
  2472. * 'tz,TimeZone' = use specified timezone
  2473. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2474. * @return int|string Date as a timestamp, '' or false if error
  2475. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2476. */
  2477. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2478. {
  2479. global $conf;
  2480. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2481. if ($gm === 'auto') {
  2482. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2483. }
  2484. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2485. // Clean parameters
  2486. if ($hour == -1 || empty($hour)) {
  2487. $hour = 0;
  2488. }
  2489. if ($minute == -1 || empty($minute)) {
  2490. $minute = 0;
  2491. }
  2492. if ($second == -1 || empty($second)) {
  2493. $second = 0;
  2494. }
  2495. // Check parameters
  2496. if ($check) {
  2497. if (!$month || !$day) {
  2498. return '';
  2499. }
  2500. if ($day > 31) {
  2501. return '';
  2502. }
  2503. if ($month > 12) {
  2504. return '';
  2505. }
  2506. if ($hour < 0 || $hour > 24) {
  2507. return '';
  2508. }
  2509. if ($minute < 0 || $minute > 60) {
  2510. return '';
  2511. }
  2512. if ($second < 0 || $second > 60) {
  2513. return '';
  2514. }
  2515. }
  2516. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2517. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2518. $localtz = new DateTimeZone($default_timezone);
  2519. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2520. // We use dol_tz_string first because it is more reliable.
  2521. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2522. try {
  2523. $localtz = new DateTimeZone($default_timezone);
  2524. } catch (Exception $e) {
  2525. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2526. $default_timezone = @date_default_timezone_get();
  2527. }
  2528. } elseif (strrpos($gm, "tz,") !== false) {
  2529. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2530. try {
  2531. $localtz = new DateTimeZone($timezone);
  2532. } catch (Exception $e) {
  2533. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2534. }
  2535. }
  2536. if (empty($localtz)) {
  2537. $localtz = new DateTimeZone('UTC');
  2538. }
  2539. //var_dump($localtz);
  2540. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2541. $dt = new DateTime('now', $localtz);
  2542. $dt->setDate((int) $year, (int) $month, (int) $day);
  2543. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2544. $date = $dt->getTimestamp(); // should include daylight saving time
  2545. //var_dump($date);
  2546. return $date;
  2547. }
  2548. /**
  2549. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2550. *
  2551. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2552. * 'gmt' => we return GMT timestamp,
  2553. * 'tzserver' => we add the PHP server timezone
  2554. * 'tzref' => we add the company timezone. Not implemented.
  2555. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2556. * @return int $date Timestamp
  2557. */
  2558. function dol_now($mode = 'auto')
  2559. {
  2560. $ret = 0;
  2561. if ($mode === 'auto') {
  2562. $mode = 'gmt';
  2563. }
  2564. if ($mode == 'gmt') {
  2565. $ret = time(); // Time for now at greenwich.
  2566. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2567. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2568. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2569. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2570. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2571. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2572. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2573. // $ret=dol_now('gmt')+($tzsecond*3600);
  2574. //}
  2575. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2576. // Time for now with user timezone added
  2577. //print 'time: '.time();
  2578. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2579. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2580. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2581. }
  2582. return $ret;
  2583. }
  2584. /**
  2585. * Return string with formated size
  2586. *
  2587. * @param int $size Size to print
  2588. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2589. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2590. * @return string Link
  2591. */
  2592. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2593. {
  2594. global $conf, $langs;
  2595. $level = 1024;
  2596. if (!empty($conf->dol_optimize_smallscreen)) {
  2597. $shortunit = 1;
  2598. }
  2599. // Set value text
  2600. if (empty($shortvalue) || $size < ($level * 10)) {
  2601. $ret = $size;
  2602. $textunitshort = $langs->trans("b");
  2603. $textunitlong = $langs->trans("Bytes");
  2604. } else {
  2605. $ret = round($size / $level, 0);
  2606. $textunitshort = $langs->trans("Kb");
  2607. $textunitlong = $langs->trans("KiloBytes");
  2608. }
  2609. // Use long or short text unit
  2610. if (empty($shortunit)) {
  2611. $ret .= ' '.$textunitlong;
  2612. } else {
  2613. $ret .= ' '.$textunitshort;
  2614. }
  2615. return $ret;
  2616. }
  2617. /**
  2618. * Show Url link
  2619. *
  2620. * @param string $url Url to show
  2621. * @param string $target Target for link
  2622. * @param int $max Max number of characters to show
  2623. * @param int $withpicto With picto
  2624. * @return string HTML Link
  2625. */
  2626. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2627. {
  2628. global $langs;
  2629. if (empty($url)) {
  2630. return '';
  2631. }
  2632. $link = '<a href="';
  2633. if (!preg_match('/^http/i', $url)) {
  2634. $link .= 'http://';
  2635. }
  2636. $link .= $url;
  2637. $link .= '"';
  2638. if ($target) {
  2639. $link .= ' target="'.$target.'"';
  2640. }
  2641. $link .= '>';
  2642. if (!preg_match('/^http/i', $url)) {
  2643. $link .= 'http://';
  2644. }
  2645. $link .= dol_trunc($url, $max);
  2646. $link .= '</a>';
  2647. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2648. }
  2649. /**
  2650. * Show EMail link formatted for HTML output.
  2651. *
  2652. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2653. * @param int $cid Id of contact if known
  2654. * @param int $socid Id of third party if known
  2655. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2656. * @param int $max Max number of characters to show
  2657. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2658. * @param int|string $withpicto Show picto
  2659. * @return string HTML Link
  2660. */
  2661. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2662. {
  2663. global $conf, $user, $langs, $hookmanager;
  2664. $newemail = dol_escape_htmltag($email);
  2665. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2666. $withpicto = 0;
  2667. }
  2668. if (empty($email)) {
  2669. return '&nbsp;';
  2670. }
  2671. if (!empty($addlink)) {
  2672. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2673. if (!preg_match('/^mailto:/i', $email)) {
  2674. $newemail .= 'mailto:';
  2675. }
  2676. $newemail .= $email;
  2677. $newemail .= '">';
  2678. $newemail .= dol_trunc($email, $max);
  2679. $newemail .= '</a>';
  2680. if ($showinvalid && !isValidEmail($email)) {
  2681. $langs->load("errors");
  2682. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2683. }
  2684. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2685. $type = 'AC_EMAIL';
  2686. $link = '';
  2687. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2688. $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>';
  2689. }
  2690. if ($link) {
  2691. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2692. }
  2693. }
  2694. } else {
  2695. if ($showinvalid && !isValidEmail($email)) {
  2696. $langs->load("errors");
  2697. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2698. }
  2699. }
  2700. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2701. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  2702. //$rep .= '</div>';
  2703. if ($hookmanager) {
  2704. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2705. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2706. if ($reshook > 0) {
  2707. $rep = '';
  2708. }
  2709. $rep .= $hookmanager->resPrint;
  2710. }
  2711. return $rep;
  2712. }
  2713. /**
  2714. * Get array of social network dictionary
  2715. *
  2716. * @return array Array of Social Networks Dictionary
  2717. */
  2718. function getArrayOfSocialNetworks()
  2719. {
  2720. global $conf, $db;
  2721. $socialnetworks = array();
  2722. // Enable caching of array
  2723. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2724. $cachekey = 'socialnetworks_' . $conf->entity;
  2725. $dataretrieved = dol_getcache($cachekey);
  2726. if (!is_null($dataretrieved)) {
  2727. $socialnetworks = $dataretrieved;
  2728. } else {
  2729. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2730. $sql .= " WHERE entity=".$conf->entity;
  2731. $resql = $db->query($sql);
  2732. if ($resql) {
  2733. while ($obj = $db->fetch_object($resql)) {
  2734. $socialnetworks[$obj->code] = array(
  2735. 'rowid' => $obj->rowid,
  2736. 'label' => $obj->label,
  2737. 'url' => $obj->url,
  2738. 'icon' => $obj->icon,
  2739. 'active' => $obj->active,
  2740. );
  2741. }
  2742. }
  2743. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2744. }
  2745. return $socialnetworks;
  2746. }
  2747. /**
  2748. * Show social network link
  2749. *
  2750. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2751. * @param int $cid Id of contact if known
  2752. * @param int $socid Id of third party if known
  2753. * @param string $type 'skype','facebook',...
  2754. * @param array $dictsocialnetworks socialnetworks availables
  2755. * @return string HTML Link
  2756. */
  2757. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2758. {
  2759. global $conf, $user, $langs;
  2760. $htmllink = $value;
  2761. if (empty($value)) {
  2762. return '&nbsp;';
  2763. }
  2764. if (!empty($type)) {
  2765. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2766. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2767. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2768. if ($type == 'skype') {
  2769. $htmllink .= dol_escape_htmltag($value);
  2770. $htmllink .= '&nbsp;';
  2771. $htmllink .= '<a href="skype:';
  2772. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2773. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  2774. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2775. $htmllink .= '</a><a href="skype:';
  2776. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2777. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  2778. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2779. $htmllink .= '</a>';
  2780. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2781. $addlink = 'AC_SKYPE';
  2782. $link = '';
  2783. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2784. $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>';
  2785. }
  2786. $htmllink .= ($link ? ' '.$link : '');
  2787. }
  2788. } else {
  2789. if (!empty($dictsocialnetworks[$type]['url'])) {
  2790. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  2791. if ($tmpvirginurl) {
  2792. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  2793. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  2794. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  2795. if ($tmpvirginurl3) {
  2796. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  2797. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  2798. }
  2799. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  2800. if ($tmpvirginurl2) {
  2801. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  2802. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  2803. }
  2804. }
  2805. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2806. if (preg_match('/^https?:\/\//i', $link)) {
  2807. $htmllink .= '&nbsp;<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  2808. } else {
  2809. $htmllink .= '&nbsp;<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  2810. }
  2811. } else {
  2812. $htmllink .= dol_escape_htmltag($value);
  2813. }
  2814. }
  2815. $htmllink .= '</div>';
  2816. } else {
  2817. $langs->load("errors");
  2818. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2819. }
  2820. return $htmllink;
  2821. }
  2822. /**
  2823. * Format profIDs according to country
  2824. *
  2825. * @param string $profID Value of profID to format
  2826. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  2827. * @param string $countrycode Country code to use for formatting
  2828. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  2829. * @param string $separ Separation between numbers for a better visibility example : xxx xxx xxx xxxxx
  2830. * @return string Formated profID
  2831. */
  2832. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
  2833. {
  2834. global $mysoc;
  2835. if (empty($profID) || empty($profIDtype)) {
  2836. return '';
  2837. }
  2838. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2839. $newProfID = $profID;
  2840. $id = substr($profIDtype, -1);
  2841. $ret = '';
  2842. if (strtoupper($countrycode) == 'FR') {
  2843. // France
  2844. if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
  2845. if ($id == 2 && dol_strlen($newProfID) == 14) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3).$separ.substr($newProfID, 9, 5);
  2846. if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) $newProfID = substr($newProfID, 0, 4).$separ.substr($newProfID, 4, 3).$separ.substr($newProfID, 7, 3).$separ.substr($newProfID, 10, 3);
  2847. }
  2848. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  2849. else $ret = $newProfID;
  2850. return $ret;
  2851. }
  2852. /**
  2853. * Format phone numbers according to country
  2854. *
  2855. * @param string $phone Phone number to format
  2856. * @param string $countrycode Country code to use for formatting
  2857. * @param int $cid Id of contact if known
  2858. * @param int $socid Id of third party if known
  2859. * @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)
  2860. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2861. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2862. * @param string $titlealt Text to show on alt
  2863. * @param int $adddivfloat Add div float around phone.
  2864. * @return string Formated phone number
  2865. */
  2866. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2867. {
  2868. global $conf, $user, $langs, $mysoc, $hookmanager;
  2869. // Clean phone parameter
  2870. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2871. if (empty($phone)) {
  2872. return '';
  2873. }
  2874. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2875. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2876. }
  2877. if (empty($countrycode) && is_object($mysoc)) {
  2878. $countrycode = $mysoc->country_code;
  2879. }
  2880. // Short format for small screens
  2881. if ($conf->dol_optimize_smallscreen) {
  2882. $separ = '';
  2883. }
  2884. $newphone = $phone;
  2885. if (strtoupper($countrycode) == "FR") {
  2886. // France
  2887. if (dol_strlen($phone) == 10) {
  2888. $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);
  2889. } elseif (dol_strlen($phone) == 7) {
  2890. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2891. } elseif (dol_strlen($phone) == 9) {
  2892. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2893. } elseif (dol_strlen($phone) == 11) {
  2894. $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);
  2895. } elseif (dol_strlen($phone) == 12) {
  2896. $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);
  2897. }
  2898. } elseif (strtoupper($countrycode) == "CA") {
  2899. if (dol_strlen($phone) == 10) {
  2900. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2901. }
  2902. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2903. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2904. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2905. }
  2906. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2907. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2908. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2909. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2910. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2911. }
  2912. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2913. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2914. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2915. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2916. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2917. }
  2918. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2919. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2920. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2921. }
  2922. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2923. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2924. $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);
  2925. }
  2926. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2927. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2928. $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);
  2929. }
  2930. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2931. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2932. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2933. }
  2934. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2935. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2936. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2937. }
  2938. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2939. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2940. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2941. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2942. $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);
  2943. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2944. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2945. }
  2946. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2947. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2948. $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);
  2949. }
  2950. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2951. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2952. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2953. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2954. $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);
  2955. }
  2956. } elseif (strtoupper($countrycode) == "MU") {
  2957. //Maurice
  2958. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  2959. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2960. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  2961. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2962. }
  2963. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  2964. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  2965. $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);
  2966. }
  2967. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  2968. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  2969. $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);
  2970. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  2971. $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);
  2972. }
  2973. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  2974. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  2975. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2976. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  2977. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2978. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  2979. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2980. }
  2981. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  2982. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  2983. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2984. }
  2985. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  2986. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  2987. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2988. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  2989. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2990. }
  2991. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  2992. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  2993. $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);
  2994. }
  2995. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  2996. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  2997. $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);
  2998. }
  2999. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3000. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3001. $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);
  3002. }
  3003. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3004. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3005. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3006. }
  3007. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3008. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
  3009. $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);
  3010. }
  3011. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3012. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3013. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3014. }
  3015. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3016. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3017. $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);
  3018. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3019. $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);
  3020. }
  3021. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3022. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3023. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3024. }
  3025. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3026. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3027. $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);
  3028. }
  3029. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3030. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3031. $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);
  3032. }
  3033. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3034. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3035. $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);
  3036. }
  3037. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3038. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3039. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3040. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3041. $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);
  3042. }
  3043. } elseif (strtoupper($countrycode) == "AU") {
  3044. //Australie
  3045. if (dol_strlen($phone) == 12) {
  3046. //ex: +61_A_BCDE_FGHI
  3047. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3048. }
  3049. }
  3050. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3051. 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
  3052. $newphoneform = $newphone;
  3053. $newphone = '<a href="tel:'.$phone.'"';
  3054. $newphone .= '>'.$newphoneform.'</a>';
  3055. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3056. if (empty($user->clicktodial_loaded)) {
  3057. $user->fetch_clicktodial();
  3058. }
  3059. // Define urlmask
  3060. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  3061. if (!empty($conf->global->CLICKTODIAL_URL)) {
  3062. $urlmask = $conf->global->CLICKTODIAL_URL;
  3063. }
  3064. if (!empty($user->clicktodial_url)) {
  3065. $urlmask = $user->clicktodial_url;
  3066. }
  3067. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  3068. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  3069. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  3070. // This line is for backward compatibility
  3071. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3072. // Thoose lines are for substitution
  3073. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3074. '__PHONETO__'=>urlencode($phone),
  3075. '__LOGIN__'=>$clicktodial_login,
  3076. '__PASS__'=>$clicktodial_password);
  3077. $url = make_substitutions($url, $substitarray);
  3078. $newphonesav = $newphone;
  3079. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  3080. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3081. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3082. $newphone .= '>'.$newphonesav.'</a>';
  3083. } else {
  3084. // Old method
  3085. $newphone = '<a href="'.$url.'"';
  3086. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  3087. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  3088. }
  3089. $newphone .= '>'.$newphonesav.'</a>';
  3090. }
  3091. }
  3092. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  3093. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  3094. $type = 'AC_TEL';
  3095. $link = '';
  3096. if ($addlink == 'AC_FAX') {
  3097. $type = 'AC_FAX';
  3098. }
  3099. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  3100. $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>';
  3101. }
  3102. if ($link) {
  3103. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  3104. }
  3105. }
  3106. }
  3107. if (empty($titlealt)) {
  3108. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3109. }
  3110. $rep = '';
  3111. if ($hookmanager) {
  3112. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3113. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3114. $rep .= $hookmanager->resPrint;
  3115. }
  3116. if (empty($reshook)) {
  3117. $picto = '';
  3118. if ($withpicto) {
  3119. if ($withpicto == 'fax') {
  3120. $picto = 'phoning_fax';
  3121. } elseif ($withpicto == 'phone') {
  3122. $picto = 'phoning';
  3123. } elseif ($withpicto == 'mobile') {
  3124. $picto = 'phoning_mobile';
  3125. } else {
  3126. $picto = '';
  3127. }
  3128. }
  3129. if ($adddivfloat) {
  3130. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3131. } else {
  3132. $rep .= '<span style="margin-right: 10px;">';
  3133. }
  3134. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  3135. if ($adddivfloat) {
  3136. $rep .= '</div>';
  3137. } else {
  3138. $rep .= '</span>';
  3139. }
  3140. }
  3141. return $rep;
  3142. }
  3143. /**
  3144. * Return an IP formated to be shown on screen
  3145. *
  3146. * @param string $ip IP
  3147. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3148. * @return string Formated IP, with country if GeoIP module is enabled
  3149. */
  3150. function dol_print_ip($ip, $mode = 0)
  3151. {
  3152. global $conf, $langs;
  3153. $ret = '';
  3154. if (empty($mode)) {
  3155. $ret .= $ip;
  3156. }
  3157. if ($mode != 2) {
  3158. $countrycode = dolGetCountryCodeFromIp($ip);
  3159. if ($countrycode) { // If success, countrycode is us, fr, ...
  3160. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3161. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3162. } else {
  3163. $ret .= ' ('.$countrycode.')';
  3164. }
  3165. } else {
  3166. // Nothing
  3167. }
  3168. }
  3169. return $ret;
  3170. }
  3171. /**
  3172. * Return the IP of remote user.
  3173. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3174. * Then HTTP_CLIENT_IP if defined (rare)
  3175. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3176. *
  3177. * @return string Ip of remote user.
  3178. */
  3179. function getUserRemoteIP()
  3180. {
  3181. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3182. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3183. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3184. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3185. } else {
  3186. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3187. }
  3188. } else {
  3189. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3190. }
  3191. } else {
  3192. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3193. }
  3194. return $ip;
  3195. }
  3196. /**
  3197. * Return if we are using a HTTPS connexion
  3198. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3199. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3200. * Then HTTP_X_FORWARDED_SSL
  3201. *
  3202. * @return boolean True if user is using HTTPS
  3203. */
  3204. function isHTTPS()
  3205. {
  3206. $isSecure = false;
  3207. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3208. $isSecure = true;
  3209. } 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') {
  3210. $isSecure = true;
  3211. }
  3212. return $isSecure;
  3213. }
  3214. /**
  3215. * Return a country code from IP. Empty string if not found.
  3216. *
  3217. * @param string $ip IP
  3218. * @return string Country code ('us', 'fr', ...)
  3219. */
  3220. function dolGetCountryCodeFromIp($ip)
  3221. {
  3222. global $conf;
  3223. $countrycode = '';
  3224. if (!empty($conf->geoipmaxmind->enabled)) {
  3225. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3226. //$ip='24.24.24.24';
  3227. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3228. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3229. $geoip = new DolGeoIP('country', $datafile);
  3230. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3231. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3232. }
  3233. return $countrycode;
  3234. }
  3235. /**
  3236. * Return country code for current user.
  3237. * If software is used inside a local network, detection may fails (we need a public ip)
  3238. *
  3239. * @return string Country code (fr, es, it, us, ...)
  3240. */
  3241. function dol_user_country()
  3242. {
  3243. global $conf, $langs, $user;
  3244. //$ret=$user->xxx;
  3245. $ret = '';
  3246. if (!empty($conf->geoipmaxmind->enabled)) {
  3247. $ip = getUserRemoteIP();
  3248. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3249. //$ip='24.24.24.24';
  3250. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3251. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3252. $geoip = new DolGeoIP('country', $datafile);
  3253. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3254. $ret = $countrycode;
  3255. }
  3256. return $ret;
  3257. }
  3258. /**
  3259. * Format address string
  3260. *
  3261. * @param string $address Address string, already formatted with dol_format_address()
  3262. * @param int $htmlid Html ID (for example 'gmap')
  3263. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3264. * @param int $id Id of object
  3265. * @param int $noprint No output. Result is the function return
  3266. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3267. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3268. * @see dol_format_address()
  3269. */
  3270. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3271. {
  3272. global $conf, $user, $langs, $hookmanager;
  3273. $out = '';
  3274. if ($address) {
  3275. if ($hookmanager) {
  3276. $parameters = array('element' => $element, 'id' => $id);
  3277. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3278. $out .= $hookmanager->resPrint;
  3279. }
  3280. if (empty($reshook)) {
  3281. if (empty($charfornl)) {
  3282. $out .= nl2br($address);
  3283. } else {
  3284. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3285. }
  3286. // TODO Remove this block, we can add this using the hook now
  3287. $showgmap = $showomap = 0;
  3288. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3289. $showgmap = 1;
  3290. }
  3291. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3292. $showgmap = 1;
  3293. }
  3294. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3295. $showgmap = 1;
  3296. }
  3297. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3298. $showomap = 1;
  3299. }
  3300. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3301. $showomap = 1;
  3302. }
  3303. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3304. $showomap = 1;
  3305. }
  3306. if ($showgmap) {
  3307. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3308. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3309. }
  3310. if ($showomap) {
  3311. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3312. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3313. }
  3314. }
  3315. }
  3316. if ($noprint) {
  3317. return $out;
  3318. } else {
  3319. print $out;
  3320. }
  3321. }
  3322. /**
  3323. * Return true if email syntax is ok.
  3324. *
  3325. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3326. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3327. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3328. * @return boolean true if email syntax is OK, false if KO or empty string
  3329. * @see isValidMXRecord()
  3330. */
  3331. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3332. {
  3333. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3334. return true;
  3335. }
  3336. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3337. return true;
  3338. }
  3339. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3340. return true;
  3341. }
  3342. return false;
  3343. }
  3344. /**
  3345. * Return if the domain name has a valid MX record.
  3346. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3347. *
  3348. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3349. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3350. * @see isValidEmail()
  3351. */
  3352. function isValidMXRecord($domain)
  3353. {
  3354. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3355. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3356. return 0;
  3357. }
  3358. if (function_exists('getmxrr')) {
  3359. $mxhosts = array();
  3360. $weight = array();
  3361. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3362. if (count($mxhosts) > 1) {
  3363. return 1;
  3364. }
  3365. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3366. return 1;
  3367. }
  3368. return 0;
  3369. }
  3370. }
  3371. return -1;
  3372. }
  3373. /**
  3374. * Return true if phone number syntax is ok
  3375. * TODO Decide what to do with this
  3376. *
  3377. * @param string $phone phone (Ex: "0601010101")
  3378. * @return boolean true if phone syntax is OK, false if KO or empty string
  3379. */
  3380. function isValidPhone($phone)
  3381. {
  3382. return true;
  3383. }
  3384. /**
  3385. * Make a strlen call. Works even if mbstring module not enabled
  3386. *
  3387. * @param string $string String to calculate length
  3388. * @param string $stringencoding Encoding of string
  3389. * @return int Length of string
  3390. */
  3391. function dol_strlen($string, $stringencoding = 'UTF-8')
  3392. {
  3393. if (function_exists('mb_strlen')) {
  3394. return mb_strlen($string, $stringencoding);
  3395. } else {
  3396. return strlen($string);
  3397. }
  3398. }
  3399. /**
  3400. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3401. *
  3402. * @param string $string String to scan
  3403. * @param string $start Start position
  3404. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3405. * @param string $stringencoding Page code used for input string encoding
  3406. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3407. * @return string substring
  3408. */
  3409. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3410. {
  3411. global $langs;
  3412. if (empty($stringencoding)) {
  3413. $stringencoding = $langs->charset_output;
  3414. }
  3415. $ret = '';
  3416. if (empty($trunconbytes)) {
  3417. if (function_exists('mb_substr')) {
  3418. $ret = mb_substr($string, $start, $length, $stringencoding);
  3419. } else {
  3420. $ret = substr($string, $start, $length);
  3421. }
  3422. } else {
  3423. if (function_exists('mb_strcut')) {
  3424. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3425. } else {
  3426. $ret = substr($string, $start, $length);
  3427. }
  3428. }
  3429. return $ret;
  3430. }
  3431. /**
  3432. * Truncate a string to a particular length adding '…' if string larger than length.
  3433. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3434. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3435. *
  3436. * @param string $string String to truncate
  3437. * @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 ...)
  3438. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3439. * @param string $stringencoding Tell what is source string encoding
  3440. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3441. * @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)
  3442. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3443. */
  3444. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3445. {
  3446. global $conf;
  3447. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3448. return $string;
  3449. }
  3450. if (empty($stringencoding)) {
  3451. $stringencoding = 'UTF-8';
  3452. }
  3453. // reduce for small screen
  3454. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3455. $size = round($size / 3);
  3456. }
  3457. // We go always here
  3458. if ($trunc == 'right') {
  3459. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3460. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3461. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3462. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3463. } else {
  3464. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3465. return $string;
  3466. }
  3467. } elseif ($trunc == 'middle') {
  3468. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3469. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3470. $size1 = round($size / 2);
  3471. $size2 = round($size / 2);
  3472. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3473. } else {
  3474. return $string;
  3475. }
  3476. } elseif ($trunc == 'left') {
  3477. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3478. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3479. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3480. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3481. } else {
  3482. return $string;
  3483. }
  3484. } elseif ($trunc == 'wrap') {
  3485. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3486. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3487. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3488. } else {
  3489. return $string;
  3490. }
  3491. } else {
  3492. return 'BadParam3CallingDolTrunc';
  3493. }
  3494. }
  3495. /**
  3496. * Show picto whatever it's its name (generic function)
  3497. *
  3498. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3499. * @param string $picto Name of image file to show ('filenew', ...)
  3500. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3501. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3502. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3503. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3504. * Example: fontawesome_envelope-open-text_fas_red_1em if you want to use fontaweseome icons: fontawesome_<icon-name>_<style>_<color>_<size> (only icon-name is mandatory)
  3505. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3506. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3507. * @param int $srconly Return only content of the src attribute of img.
  3508. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3509. * @param string $alt Force alt for bind people
  3510. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3511. * @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.
  3512. * @return string Return img tag
  3513. * @see img_object(), img_picto_common()
  3514. */
  3515. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3516. {
  3517. global $conf, $langs;
  3518. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3519. $url = DOL_URL_ROOT;
  3520. $theme = isset($conf->theme) ? $conf->theme : null;
  3521. $path = 'theme/'.$theme;
  3522. // Define fullpathpicto to use into src
  3523. if ($pictoisfullpath) {
  3524. // Clean parameters
  3525. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3526. $picto .= '.png';
  3527. }
  3528. $fullpathpicto = $picto;
  3529. $reg = array();
  3530. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3531. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3532. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3533. }
  3534. } else {
  3535. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3536. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3537. if (strpos($pictowithouttext, 'fontawesome_') !== false || preg_match('/^fa-/', $pictowithouttext)) {
  3538. // This is a font awesome image 'fonwtawesome_xxx' or 'fa-xxx'
  3539. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  3540. $pictowithouttextarray = explode('_', $pictowithouttext);
  3541. $marginleftonlyshort = 0;
  3542. if (!empty($pictowithouttextarray[1])) {
  3543. $fakey = 'fa-'.$pictowithouttextarray[1];
  3544. $fa = empty($pictowithouttextarray[2]) ? 'fa' : $pictowithouttextarray[2];
  3545. $facolor = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  3546. $fasize = empty($pictowithouttextarray[4]) ? '' : $pictowithouttextarray[4];
  3547. } else {
  3548. $fakey = 'fa-'.$pictowithouttext;
  3549. $fa = 'fa';
  3550. $facolor = '';
  3551. $fasize = '';
  3552. }
  3553. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3554. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3555. $morestyle = '';
  3556. $reg = array();
  3557. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3558. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3559. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3560. }
  3561. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3562. $morestyle = $reg[1];
  3563. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3564. }
  3565. $moreatt = trim($moreatt);
  3566. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3567. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3568. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3569. $enabledisablehtml .= $titlealt;
  3570. }*/
  3571. $enabledisablehtml .= '</span>';
  3572. return $enabledisablehtml;
  3573. }
  3574. if (empty($srconly) && in_array($pictowithouttext, array(
  3575. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3576. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3577. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  3578. 'card', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3579. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3580. 'currency', 'multicurrency',
  3581. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3582. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3583. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3584. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3585. 'help', 'holiday',
  3586. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3587. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3588. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3589. 'off', 'on', 'order',
  3590. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'puce',
  3591. 'stock', 'resize', 'service', 'stats', 'trip',
  3592. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3593. 'github', 'google', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3594. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3595. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3596. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3597. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3598. 'technic', 'ticket',
  3599. 'error', 'warning',
  3600. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource', 'recurring',
  3601. 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3602. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3603. 'uncheck', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'world', 'private',
  3604. 'conferenceorbooth', 'eventorganization'
  3605. ))) {
  3606. $fakey = $pictowithouttext;
  3607. $facolor = '';
  3608. $fasize = '';
  3609. $fa = 'fas';
  3610. 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'))) {
  3611. $fa = 'far';
  3612. }
  3613. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3614. $fa = 'fab';
  3615. }
  3616. $arrayconvpictotofa = array(
  3617. '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',
  3618. 'bank_account'=>'university',
  3619. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3620. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3621. 'bom'=>'shapes',
  3622. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3623. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3624. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3625. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3626. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3627. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3628. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3629. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3630. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3631. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  3632. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3633. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3634. 'sign-out'=>'sign-out-alt',
  3635. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3636. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3637. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3638. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'currency'=>'dollar-sign', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3639. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3640. 'other'=>'square',
  3641. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3642. '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',
  3643. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3644. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3645. 'refresh'=>'redo', 'region'=>'map-marked', 'resource'=>'laptop-house', 'recurring'=>'history',
  3646. 'service'=>'concierge-bell',
  3647. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3648. 'supplier'=>'building', 'technic'=>'cogs',
  3649. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3650. 'title_agenda'=>'calendar-alt',
  3651. 'uncheck'=>'times', 'uparrow'=>'share', 'vat'=>'money-check-alt', 'vcard'=>'address-card',
  3652. 'jabber'=>'comment-o',
  3653. 'website'=>'globe-americas', 'workstation'=>'pallet', 'world'=>'globe', 'private'=>'user-lock',
  3654. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3655. );
  3656. if ($pictowithouttext == 'off') {
  3657. $fakey = 'fa-square';
  3658. $fasize = '1.3em';
  3659. } elseif ($pictowithouttext == 'on') {
  3660. $fakey = 'fa-check-square';
  3661. $fasize = '1.3em';
  3662. } elseif ($pictowithouttext == 'listlight') {
  3663. $fakey = 'fa-download';
  3664. $marginleftonlyshort = 1;
  3665. } elseif ($pictowithouttext == 'printer') {
  3666. $fakey = 'fa-print';
  3667. $fasize = '1.2em';
  3668. } elseif ($pictowithouttext == 'note') {
  3669. $fakey = 'fa-sticky-note';
  3670. $marginleftonlyshort = 1;
  3671. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3672. $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');
  3673. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3674. if (preg_match('/selected/', $pictowithouttext)) {
  3675. $facolor = '#888';
  3676. }
  3677. $marginleftonlyshort = 1;
  3678. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3679. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3680. } else {
  3681. $fakey = 'fa-'.$pictowithouttext;
  3682. }
  3683. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3684. $morecss .= ' em092';
  3685. }
  3686. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3687. $morecss .= ' em088';
  3688. }
  3689. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3690. $morecss .= ' em080';
  3691. }
  3692. // Define $marginleftonlyshort
  3693. $arrayconvpictotomarginleftonly = array(
  3694. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3695. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3696. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3697. );
  3698. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3699. $marginleftonlyshort = 0;
  3700. }
  3701. // Add CSS
  3702. $arrayconvpictotomorcess = array(
  3703. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3704. 'bank_account'=>'bg-infobox-bank_account',
  3705. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3706. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3707. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3708. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3709. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3710. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3711. 'incoterm'=>'infobox-supplier_proposal',
  3712. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  3713. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3714. 'order'=>'infobox-commande',
  3715. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3716. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_red'=>'font-status8',
  3717. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3718. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3719. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  3720. 'propal'=>'infobox-propal', 'private'=>'infobox-project',
  3721. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3722. 'resource'=>'infobox-action',
  3723. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3724. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3725. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3726. 'vat'=>'infobox-bank_account',
  3727. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3728. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3729. );
  3730. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3731. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3732. }
  3733. // Define $color
  3734. $arrayconvpictotocolor = array(
  3735. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3736. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3737. 'dynamicprice'=>'#a69944',
  3738. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3739. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3740. 'lot'=>'#a69944',
  3741. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3742. 'other'=>'#ddd', 'world'=>'#986c6a',
  3743. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3744. //'shipment'=>'#a69944',
  3745. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3746. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3747. 'website'=>'#304', 'workstation'=>'#a69944'
  3748. );
  3749. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3750. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3751. }
  3752. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3753. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3754. $morestyle = '';
  3755. $reg = array();
  3756. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3757. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3758. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3759. }
  3760. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3761. $morestyle = $reg[1];
  3762. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3763. }
  3764. $moreatt = trim($moreatt);
  3765. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3766. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3767. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3768. $enabledisablehtml .= $titlealt;
  3769. }*/
  3770. $enabledisablehtml .= '</span>';
  3771. return $enabledisablehtml;
  3772. }
  3773. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3774. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3775. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3776. $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
  3777. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3778. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3779. }
  3780. // If we ask an image into $url/$mymodule/img (instead of default path)
  3781. $regs = array();
  3782. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3783. $picto = $regs[1];
  3784. $path = $regs[2]; // $path is $mymodule
  3785. }
  3786. // Clean parameters
  3787. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3788. $picto .= '.png';
  3789. }
  3790. // If alt path are defined, define url where img file is, according to physical path
  3791. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3792. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3793. if ($type == 'main') {
  3794. continue;
  3795. }
  3796. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3797. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3798. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3799. break;
  3800. }
  3801. }
  3802. // $url is '' or '/custom', $path is current theme or
  3803. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3804. }
  3805. if ($srconly) {
  3806. return $fullpathpicto;
  3807. }
  3808. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3809. 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
  3810. }
  3811. /**
  3812. * Show a picto called object_picto (generic function)
  3813. *
  3814. * @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.
  3815. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3816. * For external modules use imagename@mymodule to search into directory "img" of module.
  3817. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3818. * @param int $pictoisfullpath If 1, image path is a full path
  3819. * @param int $srconly Return only content of the src attribute of img.
  3820. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3821. * @return string Return img tag
  3822. * @see img_picto(), img_picto_common()
  3823. */
  3824. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3825. {
  3826. if (strpos($picto, '^') === 0) {
  3827. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3828. } else {
  3829. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3830. }
  3831. }
  3832. /**
  3833. * Show weather picto
  3834. *
  3835. * @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.
  3836. * @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).
  3837. * @param string $moreatt Add more attribute on img tag
  3838. * @param int $pictoisfullpath If 1, image path is a full path
  3839. * @param string $morecss More CSS
  3840. * @return string Return img tag
  3841. * @see img_object(), img_picto()
  3842. */
  3843. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3844. {
  3845. global $conf;
  3846. if (is_numeric($picto)) {
  3847. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3848. //$picto = $leveltopicto[$picto];
  3849. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3850. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3851. $picto .= '.png';
  3852. }
  3853. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3854. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3855. }
  3856. /**
  3857. * Show picto (generic function)
  3858. *
  3859. * @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.
  3860. * @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.
  3861. * @param string $moreatt Add more attribute on img tag
  3862. * @param int $pictoisfullpath If 1, image path is a full path
  3863. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3864. * @return string Return img tag
  3865. * @see img_object(), img_picto()
  3866. */
  3867. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  3868. {
  3869. global $conf;
  3870. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3871. $picto .= '.png';
  3872. }
  3873. if ($pictoisfullpath) {
  3874. $path = $picto;
  3875. } else {
  3876. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3877. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3878. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3879. if (file_exists($themepath)) {
  3880. $path = $themepath;
  3881. }
  3882. }
  3883. }
  3884. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  3885. }
  3886. /**
  3887. * Show logo action
  3888. *
  3889. * @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.
  3890. * @param string $numaction Action id or code to show
  3891. * @param string $picto Name of image file to show ('filenew', ...)
  3892. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3893. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3894. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3895. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3896. * @return string Return an img tag
  3897. */
  3898. function img_action($titlealt, $numaction, $picto = '')
  3899. {
  3900. global $langs;
  3901. if (empty($titlealt) || $titlealt == 'default') {
  3902. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3903. $numaction = -1;
  3904. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3905. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3906. $numaction = 0;
  3907. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3908. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3909. $numaction = 1;
  3910. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3911. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3912. $numaction = 2;
  3913. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3914. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3915. $numaction = 3;
  3916. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3917. } else {
  3918. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3919. $numaction = 0;
  3920. }
  3921. }
  3922. if (!is_numeric($numaction)) {
  3923. $numaction = 0;
  3924. }
  3925. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3926. }
  3927. /**
  3928. * Show pdf logo
  3929. *
  3930. * @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.
  3931. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3932. * @return string Retourne tag img
  3933. */
  3934. function img_pdf($titlealt = 'default', $size = 3)
  3935. {
  3936. global $langs;
  3937. if ($titlealt == 'default') {
  3938. $titlealt = $langs->trans('Show');
  3939. }
  3940. return img_picto($titlealt, 'pdf'.$size.'.png');
  3941. }
  3942. /**
  3943. * Show logo +
  3944. *
  3945. * @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.
  3946. * @param string $other Add more attributes on img
  3947. * @return string Return tag img
  3948. */
  3949. function img_edit_add($titlealt = 'default', $other = '')
  3950. {
  3951. global $langs;
  3952. if ($titlealt == 'default') {
  3953. $titlealt = $langs->trans('Add');
  3954. }
  3955. return img_picto($titlealt, 'edit_add.png', $other);
  3956. }
  3957. /**
  3958. * Show logo -
  3959. *
  3960. * @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.
  3961. * @param string $other Add more attributes on img
  3962. * @return string Return tag img
  3963. */
  3964. function img_edit_remove($titlealt = 'default', $other = '')
  3965. {
  3966. global $langs;
  3967. if ($titlealt == 'default') {
  3968. $titlealt = $langs->trans('Remove');
  3969. }
  3970. return img_picto($titlealt, 'edit_remove.png', $other);
  3971. }
  3972. /**
  3973. * Show logo editer/modifier fiche
  3974. *
  3975. * @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.
  3976. * @param integer $float If you have to put the style "float: right"
  3977. * @param string $other Add more attributes on img
  3978. * @return string Return tag img
  3979. */
  3980. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3981. {
  3982. global $langs;
  3983. if ($titlealt == 'default') {
  3984. $titlealt = $langs->trans('Modify');
  3985. }
  3986. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3987. }
  3988. /**
  3989. * Show logo view card
  3990. *
  3991. * @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.
  3992. * @param integer $float If you have to put the style "float: right"
  3993. * @param string $other Add more attributes on img
  3994. * @return string Return tag img
  3995. */
  3996. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  3997. {
  3998. global $langs;
  3999. if ($titlealt == 'default') {
  4000. $titlealt = $langs->trans('View');
  4001. }
  4002. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4003. return img_picto($titlealt, 'view.png', $moreatt);
  4004. }
  4005. /**
  4006. * Show delete logo
  4007. *
  4008. * @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.
  4009. * @param string $other Add more attributes on img
  4010. * @param string $morecss More CSS
  4011. * @return string Retourne tag img
  4012. */
  4013. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4014. {
  4015. global $langs;
  4016. if ($titlealt == 'default') {
  4017. $titlealt = $langs->trans('Delete');
  4018. }
  4019. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4020. }
  4021. /**
  4022. * Show printer logo
  4023. *
  4024. * @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.
  4025. * @param string $other Add more attributes on img
  4026. * @return string Retourne tag img
  4027. */
  4028. function img_printer($titlealt = "default", $other = '')
  4029. {
  4030. global $langs;
  4031. if ($titlealt == "default") {
  4032. $titlealt = $langs->trans("Print");
  4033. }
  4034. return img_picto($titlealt, 'printer.png', $other);
  4035. }
  4036. /**
  4037. * Show split logo
  4038. *
  4039. * @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.
  4040. * @param string $other Add more attributes on img
  4041. * @return string Retourne tag img
  4042. */
  4043. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4044. {
  4045. global $langs;
  4046. if ($titlealt == 'default') {
  4047. $titlealt = $langs->trans('Split');
  4048. }
  4049. return img_picto($titlealt, 'split.png', $other);
  4050. }
  4051. /**
  4052. * Show help logo with cursor "?"
  4053. *
  4054. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4055. * @param int|string $usealttitle Text to use as alt title
  4056. * @return string Return tag img
  4057. */
  4058. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4059. {
  4060. global $langs;
  4061. if ($usealttitle) {
  4062. if (is_string($usealttitle)) {
  4063. $usealttitle = dol_escape_htmltag($usealttitle);
  4064. } else {
  4065. $usealttitle = $langs->trans('Info');
  4066. }
  4067. }
  4068. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4069. }
  4070. /**
  4071. * Show info logo
  4072. *
  4073. * @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.
  4074. * @return string Return img tag
  4075. */
  4076. function img_info($titlealt = 'default')
  4077. {
  4078. global $langs;
  4079. if ($titlealt == 'default') {
  4080. $titlealt = $langs->trans('Informations');
  4081. }
  4082. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4083. }
  4084. /**
  4085. * Show warning logo
  4086. *
  4087. * @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.
  4088. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4089. * @param string $morecss Add more CSS
  4090. * @return string Return img tag
  4091. */
  4092. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4093. {
  4094. global $langs;
  4095. if ($titlealt == 'default') {
  4096. $titlealt = $langs->trans('Warning');
  4097. }
  4098. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4099. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4100. }
  4101. /**
  4102. * Show error logo
  4103. *
  4104. * @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.
  4105. * @return string Return img tag
  4106. */
  4107. function img_error($titlealt = 'default')
  4108. {
  4109. global $langs;
  4110. if ($titlealt == 'default') {
  4111. $titlealt = $langs->trans('Error');
  4112. }
  4113. return img_picto($titlealt, 'error.png');
  4114. }
  4115. /**
  4116. * Show next logo
  4117. *
  4118. * @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.
  4119. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4120. * @return string Return img tag
  4121. */
  4122. function img_next($titlealt = 'default', $moreatt = '')
  4123. {
  4124. global $langs;
  4125. if ($titlealt == 'default') {
  4126. $titlealt = $langs->trans('Next');
  4127. }
  4128. //return img_picto($titlealt, 'next.png', $moreatt);
  4129. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4130. }
  4131. /**
  4132. * Show previous logo
  4133. *
  4134. * @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.
  4135. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4136. * @return string Return img tag
  4137. */
  4138. function img_previous($titlealt = 'default', $moreatt = '')
  4139. {
  4140. global $langs;
  4141. if ($titlealt == 'default') {
  4142. $titlealt = $langs->trans('Previous');
  4143. }
  4144. //return img_picto($titlealt, 'previous.png', $moreatt);
  4145. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4146. }
  4147. /**
  4148. * Show down arrow logo
  4149. *
  4150. * @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.
  4151. * @param int $selected Selected
  4152. * @param string $moreclass Add more CSS classes
  4153. * @return string Return img tag
  4154. */
  4155. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4156. {
  4157. global $langs;
  4158. if ($titlealt == 'default') {
  4159. $titlealt = $langs->trans('Down');
  4160. }
  4161. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4162. }
  4163. /**
  4164. * Show top arrow logo
  4165. *
  4166. * @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.
  4167. * @param int $selected Selected
  4168. * @param string $moreclass Add more CSS classes
  4169. * @return string Return img tag
  4170. */
  4171. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4172. {
  4173. global $langs;
  4174. if ($titlealt == 'default') {
  4175. $titlealt = $langs->trans('Up');
  4176. }
  4177. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4178. }
  4179. /**
  4180. * Show left arrow logo
  4181. *
  4182. * @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.
  4183. * @param int $selected Selected
  4184. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4185. * @return string Return img tag
  4186. */
  4187. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4188. {
  4189. global $langs;
  4190. if ($titlealt == 'default') {
  4191. $titlealt = $langs->trans('Left');
  4192. }
  4193. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4194. }
  4195. /**
  4196. * Show right arrow logo
  4197. *
  4198. * @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.
  4199. * @param int $selected Selected
  4200. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4201. * @return string Return img tag
  4202. */
  4203. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4204. {
  4205. global $langs;
  4206. if ($titlealt == 'default') {
  4207. $titlealt = $langs->trans('Right');
  4208. }
  4209. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4210. }
  4211. /**
  4212. * Show tick logo if allowed
  4213. *
  4214. * @param string $allow Allow
  4215. * @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.
  4216. * @return string Return img tag
  4217. */
  4218. function img_allow($allow, $titlealt = 'default')
  4219. {
  4220. global $langs;
  4221. if ($titlealt == 'default') {
  4222. $titlealt = $langs->trans('Active');
  4223. }
  4224. if ($allow == 1) {
  4225. return img_picto($titlealt, 'tick.png');
  4226. }
  4227. return '-';
  4228. }
  4229. /**
  4230. * Return image of a credit card according to its brand name
  4231. *
  4232. * @param string $brand Brand name of credit card
  4233. * @param string $morecss More CSS
  4234. * @return string Return img tag
  4235. */
  4236. function img_credit_card($brand, $morecss = null)
  4237. {
  4238. if (is_null($morecss)) {
  4239. $morecss = 'fa-2x';
  4240. }
  4241. if ($brand == 'visa' || $brand == 'Visa') {
  4242. $brand = 'cc-visa';
  4243. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4244. $brand = 'cc-mastercard';
  4245. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4246. $brand = 'cc-amex';
  4247. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4248. $brand = 'cc-discover';
  4249. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4250. $brand = 'cc-jcb';
  4251. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4252. $brand = 'cc-diners-club';
  4253. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4254. $brand = 'credit-card';
  4255. }
  4256. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4257. }
  4258. /**
  4259. * Show MIME img of a file
  4260. *
  4261. * @param string $file Filename
  4262. * @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.
  4263. * @param string $morecss More css
  4264. * @return string Return img tag
  4265. */
  4266. function img_mime($file, $titlealt = '', $morecss = '')
  4267. {
  4268. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4269. $mimetype = dol_mimetype($file, '', 1);
  4270. $mimeimg = dol_mimetype($file, '', 2);
  4271. $mimefa = dol_mimetype($file, '', 4);
  4272. if (empty($titlealt)) {
  4273. $titlealt = 'Mime type: '.$mimetype;
  4274. }
  4275. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4276. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4277. }
  4278. /**
  4279. * Show search logo
  4280. *
  4281. * @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.
  4282. * @param string $other Add more attributes on img
  4283. * @return string Retourne tag img
  4284. */
  4285. function img_search($titlealt = 'default', $other = '')
  4286. {
  4287. global $conf, $langs;
  4288. if ($titlealt == 'default') {
  4289. $titlealt = $langs->trans('Search');
  4290. }
  4291. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4292. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4293. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4294. return $input;
  4295. }
  4296. /**
  4297. * Show search logo
  4298. *
  4299. * @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.
  4300. * @param string $other Add more attributes on img
  4301. * @return string Retourne tag img
  4302. */
  4303. function img_searchclear($titlealt = 'default', $other = '')
  4304. {
  4305. global $conf, $langs;
  4306. if ($titlealt == 'default') {
  4307. $titlealt = $langs->trans('Search');
  4308. }
  4309. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4310. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4311. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4312. return $input;
  4313. }
  4314. /**
  4315. * Show information for admin users or standard users
  4316. *
  4317. * @param string $text Text info
  4318. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4319. * @param int $nodiv No div
  4320. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4321. * @param string $morecss More CSS ('', 'warning', 'error')
  4322. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4323. * @return string String with info text
  4324. */
  4325. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4326. {
  4327. global $conf, $langs;
  4328. if ($infoonimgalt) {
  4329. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4330. } else {
  4331. if (empty($conf->use_javascript_ajax)) {
  4332. $textfordropdown = '';
  4333. }
  4334. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4335. $result = ($nodiv ? '' : '<div class="'.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  4336. if ($textfordropdown) {
  4337. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4338. $tmpresult .= '<script type="text/javascript">
  4339. jQuery(document).ready(function() {
  4340. jQuery(".'.$class.'text").click(function() {
  4341. console.log("toggle text");
  4342. jQuery(".'.$class.'").toggle();
  4343. });
  4344. });
  4345. </script>';
  4346. $result = $tmpresult.$result;
  4347. }
  4348. }
  4349. return $result;
  4350. }
  4351. /**
  4352. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4353. * This function must be called when a blocking technical error is encountered.
  4354. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4355. *
  4356. * @param DoliDB|string $db Database handler
  4357. * @param string|string[] $error String or array of errors strings to show
  4358. * @param array $errors Array of errors
  4359. * @return void
  4360. * @see dol_htmloutput_errors()
  4361. */
  4362. function dol_print_error($db = '', $error = '', $errors = null)
  4363. {
  4364. global $conf, $langs, $argv;
  4365. global $dolibarr_main_prod;
  4366. $out = '';
  4367. $syslog = '';
  4368. // If error occurs before the $lang object was loaded
  4369. if (!$langs) {
  4370. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4371. $langs = new Translate('', $conf);
  4372. $langs->load("main");
  4373. }
  4374. // Load translation files required by the error messages
  4375. $langs->loadLangs(array('main', 'errors'));
  4376. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4377. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4378. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4379. $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";
  4380. }
  4381. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4382. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4383. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4384. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4385. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4386. }
  4387. if (function_exists("phpversion")) {
  4388. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4389. }
  4390. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4391. if (function_exists("php_uname")) {
  4392. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4393. }
  4394. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4395. $out .= "<br>\n";
  4396. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4397. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4398. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4399. $out .= "<br>\n";
  4400. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4401. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4402. } else // Mode CLI
  4403. {
  4404. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4405. $syslog .= "pid=".dol_getmypid();
  4406. }
  4407. if (!empty($conf->modules)) {
  4408. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4409. }
  4410. if (is_object($db)) {
  4411. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4412. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4413. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4414. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4415. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4416. $out .= "<br>\n";
  4417. } else // Mode CLI
  4418. {
  4419. // No dol_escape_htmltag for output, we are in CLI mode
  4420. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4421. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4422. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4423. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4424. }
  4425. $syslog .= ", sql=".$db->lastquery();
  4426. $syslog .= ", db_error=".$db->lasterror();
  4427. }
  4428. if ($error || $errors) {
  4429. $langs->load("errors");
  4430. // Merge all into $errors array
  4431. if (is_array($error) && is_array($errors)) {
  4432. $errors = array_merge($error, $errors);
  4433. } elseif (is_array($error)) {
  4434. $errors = $error;
  4435. } elseif (is_array($errors)) {
  4436. $errors = array_merge(array($error), $errors);
  4437. } else {
  4438. $errors = array_merge(array($error));
  4439. }
  4440. foreach ($errors as $msg) {
  4441. if (empty($msg)) {
  4442. continue;
  4443. }
  4444. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4445. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4446. } else // Mode CLI
  4447. {
  4448. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4449. }
  4450. $syslog .= ", msg=".$msg;
  4451. }
  4452. }
  4453. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4454. xdebug_print_function_stack();
  4455. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4456. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4457. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4458. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4459. $out .= "<br>\n";
  4460. }
  4461. // Return a http error code if possible
  4462. if (!headers_sent()) {
  4463. http_response_code(500);
  4464. }
  4465. if (empty($dolibarr_main_prod)) {
  4466. print $out;
  4467. } else {
  4468. if (empty($langs->defaultlang)) {
  4469. $langs->setDefaultLang();
  4470. }
  4471. $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.
  4472. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4473. 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";
  4474. print $langs->trans("DolibarrHasDetectedError").'. ';
  4475. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4476. define("MAIN_CORE_ERROR", 1);
  4477. }
  4478. dol_syslog("Error ".$syslog, LOG_ERR);
  4479. }
  4480. /**
  4481. * Show a public email and error code to contact if technical error
  4482. *
  4483. * @param string $prefixcode Prefix of public error code
  4484. * @param string $errormessage Complete error message
  4485. * @param array $errormessages Array of error messages
  4486. * @param string $morecss More css
  4487. * @param string $email Email
  4488. * @return void
  4489. */
  4490. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4491. {
  4492. global $langs, $conf;
  4493. if (empty($email)) {
  4494. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4495. }
  4496. $langs->load("errors");
  4497. $now = dol_now();
  4498. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4499. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4500. if ($errormessage) {
  4501. print '<br><br>'.$errormessage;
  4502. }
  4503. if (is_array($errormessages) && count($errormessages)) {
  4504. foreach ($errormessages as $mesgtoshow) {
  4505. print '<br><br>'.$mesgtoshow;
  4506. }
  4507. }
  4508. print '</div></div>';
  4509. }
  4510. /**
  4511. * Show title line of an array
  4512. *
  4513. * @param string $name Label of field
  4514. * @param string $file Url used when we click on sort picto
  4515. * @param string $field Field to use for new sorting
  4516. * @param string $begin ("" by defaut)
  4517. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4518. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  4519. * @param string $sortfield Current field used to sort
  4520. * @param string $sortorder Current sort order
  4521. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4522. * @param string $tooltip Tooltip
  4523. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4524. * @return void
  4525. */
  4526. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4527. {
  4528. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4529. }
  4530. /**
  4531. * Get title line of an array
  4532. *
  4533. * @param string $name Translation key of field to show or complete HTML string to show
  4534. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4535. * @param string $file Url used when we click on sort picto
  4536. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4537. * @param string $begin ("" by defaut)
  4538. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4539. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  4540. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4541. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4542. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4543. * @param string $disablesortlink 1=Disable sort link
  4544. * @param string $tooltip Tooltip
  4545. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4546. * @return string
  4547. */
  4548. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4549. {
  4550. global $conf, $langs, $form;
  4551. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4552. if ($moreattrib == 'class="right"') {
  4553. $prefix .= 'right '; // For backward compatibility
  4554. }
  4555. $sortorder = strtoupper($sortorder);
  4556. $out = '';
  4557. $sortimg = '';
  4558. $tag = 'th';
  4559. if ($thead == 2) {
  4560. $tag = 'div';
  4561. }
  4562. $tmpsortfield = explode(',', $sortfield);
  4563. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4564. $tmpfield = explode(',', $field);
  4565. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4566. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4567. $prefix = 'wrapcolumntitle '.$prefix;
  4568. }
  4569. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4570. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4571. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4572. $liste_titre = 'liste_titre';
  4573. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4574. $liste_titre = 'liste_titre_sel';
  4575. }
  4576. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4577. //$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)).'"' : '');
  4578. $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4579. $tagstart .= '>';
  4580. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4581. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4582. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4583. $options = preg_replace('/&+/i', '&', $options);
  4584. if (!preg_match('/^&/', $options)) {
  4585. $options = '&'.$options;
  4586. }
  4587. $sortordertouseinlink = '';
  4588. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4589. if (preg_match('/^DESC/i', $sortorder)) {
  4590. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4591. } else { // We reverse the var $sortordertouseinlink
  4592. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4593. }
  4594. } else { // We are on field that is the first current sorting criteria
  4595. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4596. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4597. } else {
  4598. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4599. }
  4600. }
  4601. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4602. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4603. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4604. $out .= '>';
  4605. }
  4606. if ($tooltip) {
  4607. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4608. $tmptooltip = explode(':', $tooltip);
  4609. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4610. } else {
  4611. $out .= $langs->trans($name);
  4612. }
  4613. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4614. $out .= '</a>';
  4615. }
  4616. if (empty($thead) && $field) { // If this is a sort field
  4617. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4618. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4619. $options = preg_replace('/&+/i', '&', $options);
  4620. if (!preg_match('/^&/', $options)) {
  4621. $options = '&'.$options;
  4622. }
  4623. if (!$sortorder || $field1 != $sortfield1) {
  4624. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4625. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4626. } else {
  4627. if (preg_match('/^DESC/', $sortorder)) {
  4628. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4629. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4630. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  4631. }
  4632. if (preg_match('/^ASC/', $sortorder)) {
  4633. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4634. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4635. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  4636. }
  4637. }
  4638. }
  4639. $tagend = '</'.$tag.'>';
  4640. $out = $tagstart.$sortimg.$out.$tagend;
  4641. return $out;
  4642. }
  4643. /**
  4644. * Show a title.
  4645. *
  4646. * @param string $title Title to show
  4647. * @return void
  4648. * @deprecated Use load_fiche_titre instead
  4649. * @see load_fiche_titre()
  4650. */
  4651. function print_titre($title)
  4652. {
  4653. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4654. print '<div class="titre">'.$title.'</div>';
  4655. }
  4656. /**
  4657. * Show a title with picto
  4658. *
  4659. * @param string $title Title to show
  4660. * @param string $mesg Added message to show on right
  4661. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4662. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4663. * @param int $id To force an id on html objects
  4664. * @return void
  4665. * @deprecated Use print load_fiche_titre instead
  4666. */
  4667. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4668. {
  4669. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4670. }
  4671. /**
  4672. * Load a title with picto
  4673. *
  4674. * @param string $titre Title to show
  4675. * @param string $morehtmlright Added message to show on right
  4676. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4677. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4678. * @param string $id To force an id on html objects
  4679. * @param string $morecssontable More css on table
  4680. * @param string $morehtmlcenter Added message to show on center
  4681. * @return string
  4682. * @see print_barre_liste()
  4683. */
  4684. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4685. {
  4686. global $conf;
  4687. $return = '';
  4688. if ($picto == 'setup') {
  4689. $picto = 'generic';
  4690. }
  4691. $return .= "\n";
  4692. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4693. $return .= '<tr class="titre">';
  4694. if ($picto) {
  4695. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4696. }
  4697. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4698. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4699. $return .= '</td>';
  4700. if (dol_strlen($morehtmlcenter)) {
  4701. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4702. }
  4703. if (dol_strlen($morehtmlright)) {
  4704. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4705. }
  4706. $return .= '</tr></table>'."\n";
  4707. return $return;
  4708. }
  4709. /**
  4710. * Print a title with navigation controls for pagination
  4711. *
  4712. * @param string $titre Title to show (required)
  4713. * @param int $page Numero of page to show in navigation links (required)
  4714. * @param string $file Url of page (required)
  4715. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4716. * @param string $sortfield Field to sort on ('' by default)
  4717. * @param string $sortorder Order to sort ('' by default)
  4718. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4719. * @param int $num Number of records found by select with limit+1
  4720. * @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.
  4721. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4722. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4723. * @param string $morehtmlright More html to show (after arrows)
  4724. * @param string $morecss More css to the table
  4725. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4726. * @param int $hideselectlimit Force to hide select limit
  4727. * @param int $hidenavigation Force to hide all navigation tools
  4728. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4729. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4730. * @return void
  4731. */
  4732. 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 = '')
  4733. {
  4734. global $conf, $langs;
  4735. $savlimit = $limit;
  4736. $savtotalnboflines = $totalnboflines;
  4737. $totalnboflines = abs((int) $totalnboflines);
  4738. if ($picto == 'setup') {
  4739. $picto = 'title_setup.png';
  4740. }
  4741. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4742. $picto = 'title.gif';
  4743. }
  4744. if ($limit < 0) {
  4745. $limit = $conf->liste_limit;
  4746. }
  4747. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4748. $nextpage = 1;
  4749. } else {
  4750. $nextpage = 0;
  4751. }
  4752. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4753. print "\n";
  4754. print "<!-- Begin title -->\n";
  4755. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4756. // Left
  4757. if ($picto && $titre) {
  4758. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4759. }
  4760. print '<td class="nobordernopadding valignmiddle col-title">';
  4761. print '<div class="titre inline-block">'.$titre;
  4762. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4763. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4764. }
  4765. print '</div></td>';
  4766. // Center
  4767. if ($morehtmlcenter) {
  4768. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4769. }
  4770. // Right
  4771. print '<td class="nobordernopadding valignmiddle right">';
  4772. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4773. if ($sortfield) {
  4774. $options .= "&sortfield=".urlencode($sortfield);
  4775. }
  4776. if ($sortorder) {
  4777. $options .= "&sortorder=".urlencode($sortorder);
  4778. }
  4779. // Show navigation bar
  4780. $pagelist = '';
  4781. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4782. if ($totalnboflines) { // If we know total nb of lines
  4783. // Define nb of extra page links before and after selected page + ... + first or last
  4784. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4785. if ($limit > 0) {
  4786. $nbpages = ceil($totalnboflines / $limit);
  4787. } else {
  4788. $nbpages = 1;
  4789. }
  4790. $cpt = ($page - $maxnbofpage);
  4791. if ($cpt < 0) {
  4792. $cpt = 0;
  4793. }
  4794. if ($cpt >= 1) {
  4795. if (empty($pagenavastextinput)) {
  4796. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4797. if ($cpt > 2) {
  4798. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4799. } elseif ($cpt == 2) {
  4800. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4801. }
  4802. }
  4803. }
  4804. do {
  4805. if ($pagenavastextinput) {
  4806. if ($cpt == $page) {
  4807. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4808. $pagelist .= '/';
  4809. }
  4810. } else {
  4811. if ($cpt == $page) {
  4812. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4813. } else {
  4814. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4815. }
  4816. }
  4817. $cpt++;
  4818. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4819. if (empty($pagenavastextinput)) {
  4820. if ($cpt < $nbpages) {
  4821. if ($cpt < $nbpages - 2) {
  4822. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4823. } elseif ($cpt == $nbpages - 2) {
  4824. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4825. }
  4826. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4827. }
  4828. } else {
  4829. //var_dump($page.' '.$cpt.' '.$nbpages);
  4830. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4831. }
  4832. } else {
  4833. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4834. }
  4835. }
  4836. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4837. 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
  4838. }
  4839. // js to autoselect page field on focus
  4840. if ($pagenavastextinput) {
  4841. print ajax_autoselect('.pageplusone');
  4842. }
  4843. print '</td>';
  4844. print '</tr></table>'."\n";
  4845. print "<!-- End title -->\n\n";
  4846. }
  4847. /**
  4848. * Function to show navigation arrows into lists
  4849. *
  4850. * @param int $page Number of page
  4851. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4852. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4853. * @param integer $nextpage Do we show a next page button
  4854. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4855. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4856. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4857. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4858. * @param int $hideselectlimit Force to hide select limit
  4859. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4860. * @return void
  4861. */
  4862. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4863. {
  4864. global $conf, $langs;
  4865. print '<div class="pagination"><ul>';
  4866. if ($beforearrows) {
  4867. print '<li class="paginationbeforearrows">';
  4868. print $beforearrows;
  4869. print '</li>';
  4870. }
  4871. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4872. $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';
  4873. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4874. //$pagesizechoices.=',2:2';
  4875. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4876. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4877. }
  4878. print '<li class="pagination">';
  4879. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4880. $tmpchoice = explode(',', $pagesizechoices);
  4881. $tmpkey = $limit.':'.$limit;
  4882. if (!in_array($tmpkey, $tmpchoice)) {
  4883. $tmpchoice[] = $tmpkey;
  4884. }
  4885. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4886. if (!in_array($tmpkey, $tmpchoice)) {
  4887. $tmpchoice[] = $tmpkey;
  4888. }
  4889. asort($tmpchoice, SORT_NUMERIC);
  4890. foreach ($tmpchoice as $val) {
  4891. $selected = '';
  4892. $tmp = explode(':', $val);
  4893. $key = $tmp[0];
  4894. $val = $tmp[1];
  4895. if ($key != '' && $val != '') {
  4896. if ((int) $key == (int) $limit) {
  4897. $selected = ' selected="selected"';
  4898. }
  4899. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4900. }
  4901. }
  4902. print '</select>';
  4903. if ($conf->use_javascript_ajax) {
  4904. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4905. <script>
  4906. jQuery(document).ready(function () {
  4907. jQuery(".selectlimit").change(function() {
  4908. console.log("Change limit. Send submit");
  4909. $(this).parents(\'form:first\').submit();
  4910. });
  4911. });
  4912. </script>
  4913. ';
  4914. }
  4915. print '</li>';
  4916. }
  4917. if ($page > 0) {
  4918. 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>';
  4919. }
  4920. if ($betweenarrows) {
  4921. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4922. print $betweenarrows;
  4923. print '<!--</div>-->';
  4924. }
  4925. if ($nextpage > 0) {
  4926. 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>';
  4927. }
  4928. if ($afterarrows) {
  4929. print '<li class="paginationafterarrows">';
  4930. print $afterarrows;
  4931. print '</li>';
  4932. }
  4933. print '</ul></div>'."\n";
  4934. }
  4935. /**
  4936. * Return a string with VAT rate label formated for view output
  4937. * Used into pdf and HTML pages
  4938. *
  4939. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4940. * @param boolean $addpercent Add a percent % sign in output
  4941. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4942. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4943. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4944. */
  4945. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4946. {
  4947. $morelabel = '';
  4948. if (preg_match('/%/', $rate)) {
  4949. $rate = str_replace('%', '', $rate);
  4950. $addpercent = true;
  4951. }
  4952. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  4953. $morelabel = ' ('.$reg[1].')';
  4954. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4955. }
  4956. if (preg_match('/\*/', $rate)) {
  4957. $rate = str_replace('*', '', $rate);
  4958. $info_bits |= 1;
  4959. }
  4960. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4961. if (!preg_match('/\//', $rate)) {
  4962. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4963. } else {
  4964. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4965. $ret = $rate.($addpercent ? '%' : '');
  4966. }
  4967. if (($info_bits & 1) && $usestarfornpr >= 0) {
  4968. $ret .= ' *';
  4969. }
  4970. $ret .= $morelabel;
  4971. return $ret;
  4972. }
  4973. /**
  4974. * Function to format a value into an amount for visual output
  4975. * Function used into PDF and HTML pages
  4976. *
  4977. * @param float $amount Amount to format
  4978. * @param integer $form Type of format, HTML or not (not by default)
  4979. * @param Translate|string $outlangs Object langs for output
  4980. * @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.
  4981. * @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)
  4982. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4983. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4984. * @return string String with formated amount
  4985. *
  4986. * @see price2num() Revert function of price
  4987. */
  4988. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4989. {
  4990. global $langs, $conf;
  4991. // Clean parameters
  4992. if (empty($amount)) {
  4993. $amount = 0; // To have a numeric value if amount not defined or = ''
  4994. }
  4995. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4996. if ($rounding < 0) {
  4997. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4998. }
  4999. $nbdecimal = $rounding;
  5000. // Output separators by default (french)
  5001. $dec = ',';
  5002. $thousand = ' ';
  5003. // If $outlangs not forced, we use use language
  5004. if (!is_object($outlangs)) {
  5005. $outlangs = $langs;
  5006. }
  5007. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5008. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5009. }
  5010. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5011. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5012. }
  5013. if ($thousand == 'None') {
  5014. $thousand = '';
  5015. } elseif ($thousand == 'Space') {
  5016. $thousand = ' ';
  5017. }
  5018. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5019. //print "amount=".$amount."-";
  5020. $amount = str_replace(',', '.', $amount); // should be useless
  5021. //print $amount."-";
  5022. $datas = explode('.', $amount);
  5023. $decpart = isset($datas[1]) ? $datas[1] : '';
  5024. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5025. //print "decpart=".$decpart."<br>";
  5026. $end = '';
  5027. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5028. if (dol_strlen($decpart) > $nbdecimal) {
  5029. $nbdecimal = dol_strlen($decpart);
  5030. }
  5031. // Si on depasse max
  5032. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5033. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5034. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5035. // Si un affichage est tronque, on montre des ...
  5036. $end = '...';
  5037. }
  5038. }
  5039. // If force rounding
  5040. if ($forcerounding >= 0) {
  5041. $nbdecimal = $forcerounding;
  5042. }
  5043. // Format number
  5044. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5045. if ($form) {
  5046. $output = preg_replace('/\s/', '&nbsp;', $output);
  5047. $output = preg_replace('/\'/', '&#039;', $output);
  5048. }
  5049. // Add symbol of currency if requested
  5050. $cursymbolbefore = $cursymbolafter = '';
  5051. if ($currency_code) {
  5052. if ($currency_code == 'auto') {
  5053. $currency_code = $conf->currency;
  5054. }
  5055. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  5056. $listoflanguagesbefore = array('nl_NL');
  5057. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5058. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5059. } else {
  5060. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5061. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5062. }
  5063. }
  5064. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5065. return $output;
  5066. }
  5067. /**
  5068. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5069. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5070. * should be roundtext2num().
  5071. *
  5072. * @param string|float $amount Amount to convert/clean or round
  5073. * @param string|int $rounding ''=No rounding
  5074. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5075. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5076. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5077. * 'CU'=Round to Max unit price of foreign currency accuracy
  5078. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5079. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5080. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5081. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5082. * @return string Amount with universal numeric format (Example: '99.99999').
  5083. * If conversion fails to return a numeric, it returns:
  5084. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5085. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5086. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5087. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  5088. *
  5089. * @see price() Opposite function of price2num
  5090. */
  5091. function price2num($amount, $rounding = '', $option = 0)
  5092. {
  5093. global $langs, $conf;
  5094. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5095. // Numbers must be '1234.56'
  5096. // Decimal delimiter for PHP and database SQL requests must be '.'
  5097. $dec = ',';
  5098. $thousand = ' ';
  5099. if (is_null($langs)) { // $langs is not defined, we use english values.
  5100. $dec = '.';
  5101. $thousand = ',';
  5102. } else {
  5103. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5104. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5105. }
  5106. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5107. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5108. }
  5109. }
  5110. if ($thousand == 'None') {
  5111. $thousand = '';
  5112. } elseif ($thousand == 'Space') {
  5113. $thousand = ' ';
  5114. }
  5115. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5116. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5117. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5118. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5119. if (!is_numeric($amount)) {
  5120. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5121. }
  5122. 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
  5123. $amount = str_replace($thousand, '', $amount);
  5124. }
  5125. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5126. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5127. // So if number was already a good number, it is converted into local Dolibarr setup.
  5128. if (is_numeric($amount)) {
  5129. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5130. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5131. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5132. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5133. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5134. }
  5135. //print "QQ".$amount."<br>\n";
  5136. // Now make replace (the main goal of function)
  5137. if ($thousand != ',' && $thousand != '.') {
  5138. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5139. }
  5140. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5141. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5142. $amount = str_replace($dec, '.', $amount);
  5143. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5144. }
  5145. //print ' XX'.$amount.' '.$rounding;
  5146. // Now, $amount is a real PHP float number. We make a rounding if required.
  5147. if ($rounding) {
  5148. $nbofdectoround = '';
  5149. if ($rounding == 'MU') {
  5150. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5151. } elseif ($rounding == 'MT') {
  5152. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5153. } elseif ($rounding == 'MS') {
  5154. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5155. } elseif ($rounding == 'CU') {
  5156. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5157. } elseif ($rounding == 'CT') {
  5158. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5159. } elseif (is_numeric($rounding)) {
  5160. $nbofdectoround = (int) $rounding;
  5161. }
  5162. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5163. if (dol_strlen($nbofdectoround)) {
  5164. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5165. } else {
  5166. return 'ErrorBadParameterProvidedToFunction';
  5167. }
  5168. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5169. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5170. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5171. if (is_numeric($amount)) {
  5172. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5173. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5174. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5175. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5176. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5177. }
  5178. //print "TT".$amount.'<br>';
  5179. // Always make replace because each math function (like round) replace
  5180. // with local values and we want a number that has a SQL string format x.y
  5181. if ($thousand != ',' && $thousand != '.') {
  5182. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5183. }
  5184. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5185. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5186. $amount = str_replace($dec, '.', $amount);
  5187. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5188. }
  5189. return $amount;
  5190. }
  5191. /**
  5192. * Output a dimension with best unit
  5193. *
  5194. * @param float $dimension Dimension
  5195. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5196. * @param string $type 'weight', 'volume', ...
  5197. * @param Translate $outputlangs Translate language object
  5198. * @param int $round -1 = non rounding, x = number of decimal
  5199. * @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)
  5200. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5201. * @return string String to show dimensions
  5202. */
  5203. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5204. {
  5205. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5206. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5207. $dimension = $dimension * 1000000;
  5208. $unit = $unit - 6;
  5209. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5210. $dimension = $dimension * 1000;
  5211. $unit = $unit - 3;
  5212. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5213. $dimension = $dimension / 1000000;
  5214. $unit = $unit + 6;
  5215. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5216. $dimension = $dimension / 1000;
  5217. $unit = $unit + 3;
  5218. }
  5219. // Special case when we want output unit into pound or ounce
  5220. /* TODO
  5221. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5222. {
  5223. $dimension = // convert dimension from standard unit into ounce or pound
  5224. $unit = $forceunitoutput;
  5225. }
  5226. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5227. {
  5228. $dimension = // convert dimension from standard unit into ounce or pound
  5229. $unit = $forceunitoutput;
  5230. }*/
  5231. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5232. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5233. return $ret;
  5234. }
  5235. /**
  5236. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5237. * Note: This function applies same rules than get_default_tva
  5238. *
  5239. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5240. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5241. * @param Societe $thirdparty_buyer Object of buying third party
  5242. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5243. * @param int $vatnpr If vat rate is NPR or not
  5244. * @return mixed 0 if not found, localtax rate if found
  5245. * @see get_default_tva()
  5246. */
  5247. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5248. {
  5249. global $db, $conf, $mysoc;
  5250. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5251. $thirdparty_seller = $mysoc;
  5252. }
  5253. 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);
  5254. $vatratecleaned = $vatrate;
  5255. $reg = array();
  5256. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5257. $vatratecleaned = trim($reg[1]);
  5258. $vatratecode = $reg[2];
  5259. }
  5260. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5261. {
  5262. return 0;
  5263. }*/
  5264. // Some test to guess with no need to make database access
  5265. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5266. if ($local == 1) {
  5267. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5268. return 0;
  5269. }
  5270. if ($thirdparty_seller->id == $mysoc->id) {
  5271. if (!$thirdparty_buyer->localtax1_assuj) {
  5272. return 0;
  5273. }
  5274. } else {
  5275. if (!$thirdparty_seller->localtax1_assuj) {
  5276. return 0;
  5277. }
  5278. }
  5279. }
  5280. if ($local == 2) {
  5281. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5282. if (!$mysoc->localtax2_assuj) {
  5283. return 0; // If main vat is 0, IRPF may be different than 0.
  5284. }
  5285. if ($thirdparty_seller->id == $mysoc->id) {
  5286. if (!$thirdparty_buyer->localtax2_assuj) {
  5287. return 0;
  5288. }
  5289. } else {
  5290. if (!$thirdparty_seller->localtax2_assuj) {
  5291. return 0;
  5292. }
  5293. }
  5294. }
  5295. } else {
  5296. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5297. return 0;
  5298. }
  5299. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5300. return 0;
  5301. }
  5302. }
  5303. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5304. if (in_array($mysoc->country_code, array('ES'))) {
  5305. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5306. }
  5307. // Search local taxes
  5308. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5309. if ($local == 1) {
  5310. if ($thirdparty_seller != $mysoc) {
  5311. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5312. return $thirdparty_seller->localtax1_value;
  5313. }
  5314. } else { // i am the seller
  5315. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5316. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5317. }
  5318. }
  5319. }
  5320. if ($local == 2) {
  5321. if ($thirdparty_seller != $mysoc) {
  5322. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5323. // TODO We should also return value defined on thirdparty only if defined
  5324. return $thirdparty_seller->localtax2_value;
  5325. }
  5326. } else { // i am the seller
  5327. if (in_array($mysoc->country_code, array('ES'))) {
  5328. return $thirdparty_buyer->localtax2_value;
  5329. } else {
  5330. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5331. }
  5332. }
  5333. }
  5334. }
  5335. // By default, search value of local tax on line of common tax
  5336. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5337. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5338. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5339. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5340. if (!empty($vatratecode)) {
  5341. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5342. } else {
  5343. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5344. }
  5345. $resql = $db->query($sql);
  5346. if ($resql) {
  5347. $obj = $db->fetch_object($resql);
  5348. if ($obj) {
  5349. if ($local == 1) {
  5350. return $obj->localtax1;
  5351. } elseif ($local == 2) {
  5352. return $obj->localtax2;
  5353. }
  5354. }
  5355. }
  5356. return 0;
  5357. }
  5358. /**
  5359. * Return true if LocalTax (1 or 2) is unique.
  5360. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5361. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5362. *
  5363. * @param int $local Local tax to test (1 or 2)
  5364. * @return boolean True if LocalTax have multiple values, False if not
  5365. */
  5366. function isOnlyOneLocalTax($local)
  5367. {
  5368. $tax = get_localtax_by_third($local);
  5369. $valors = explode(":", $tax);
  5370. if (count($valors) > 1) {
  5371. return false;
  5372. } else {
  5373. return true;
  5374. }
  5375. }
  5376. /**
  5377. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5378. *
  5379. * @param int $local LocalTax to get
  5380. * @return number Values of localtax
  5381. */
  5382. function get_localtax_by_third($local)
  5383. {
  5384. global $db, $mysoc;
  5385. $sql = "SELECT t.localtax1, t.localtax2 ";
  5386. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5387. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5388. $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";
  5389. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5390. $sql .= " )";
  5391. $resql = $db->query($sql);
  5392. if ($resql) {
  5393. $obj = $db->fetch_object($resql);
  5394. if ($local == 1) {
  5395. return $obj->localtax1;
  5396. } elseif ($local == 2) {
  5397. return $obj->localtax2;
  5398. }
  5399. }
  5400. return 0;
  5401. }
  5402. /**
  5403. * Get tax (VAT) main information from Id.
  5404. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5405. *
  5406. * @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.
  5407. * @param Societe $buyer Company object
  5408. * @param Societe $seller Company object
  5409. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5410. * @return array array('rowid'=> , 'code'=> ...)
  5411. * @see getLocalTaxesFromRate()
  5412. */
  5413. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5414. {
  5415. global $db, $mysoc;
  5416. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5417. // Search local taxes
  5418. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5419. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5420. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5421. if ($firstparamisid) {
  5422. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5423. } else {
  5424. $vatratecleaned = $vatrate;
  5425. $vatratecode = '';
  5426. $reg = array();
  5427. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5428. $vatratecleaned = $reg[1];
  5429. $vatratecode = $reg[2];
  5430. }
  5431. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5432. /*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 ??
  5433. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5434. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5435. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5436. if ($vatratecode) {
  5437. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5438. }
  5439. }
  5440. $resql = $db->query($sql);
  5441. if ($resql) {
  5442. $obj = $db->fetch_object($resql);
  5443. if ($obj) {
  5444. return array(
  5445. 'rowid'=>$obj->rowid,
  5446. 'code'=>$obj->code,
  5447. 'rate'=>$obj->rate,
  5448. 'localtax1'=>$obj->localtax1,
  5449. 'localtax1_type'=>$obj->localtax1_type,
  5450. 'localtax2'=>$obj->localtax2,
  5451. 'localtax2_type'=>$obj->localtax2_type,
  5452. 'npr'=>$obj->npr,
  5453. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5454. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5455. );
  5456. } else {
  5457. return array();
  5458. }
  5459. } else {
  5460. dol_print_error($db);
  5461. }
  5462. return array();
  5463. }
  5464. /**
  5465. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5466. * This does not take into account the seller setup if subject to vat or not, only country.
  5467. *
  5468. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5469. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5470. * provide the selected value to the function calcul_price_total.
  5471. *
  5472. * @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.
  5473. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5474. * @param Societe $buyer Company object
  5475. * @param Societe $seller Company object
  5476. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5477. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5478. * @see getTaxesFromId()
  5479. */
  5480. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5481. {
  5482. global $db, $mysoc;
  5483. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5484. // Search local taxes
  5485. $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";
  5486. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5487. if ($firstparamisid) {
  5488. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5489. } else {
  5490. $vatratecleaned = $vatrate;
  5491. $vatratecode = '';
  5492. $reg = array();
  5493. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5494. $vatratecleaned = $reg[1];
  5495. $vatratecode = $reg[2];
  5496. }
  5497. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5498. if ($mysoc->country_code == 'ES') {
  5499. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5500. } else {
  5501. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5502. }
  5503. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5504. if ($vatratecode) {
  5505. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5506. }
  5507. }
  5508. $resql = $db->query($sql);
  5509. if ($resql) {
  5510. $obj = $db->fetch_object($resql);
  5511. if ($obj) {
  5512. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5513. if ($local == 1) {
  5514. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5515. } elseif ($local == 2) {
  5516. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5517. } else {
  5518. 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);
  5519. }
  5520. }
  5521. }
  5522. return array();
  5523. }
  5524. /**
  5525. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5526. * Function called by get_default_tva().
  5527. *
  5528. * @param int $idprod Id of product or 0 if not a predefined product
  5529. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5530. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5531. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5532. * @see get_product_localtax_for_country()
  5533. */
  5534. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5535. {
  5536. global $db, $conf, $mysoc;
  5537. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5538. $ret = 0;
  5539. $found = 0;
  5540. if ($idprod > 0) {
  5541. // Load product
  5542. $product = new Product($db);
  5543. $result = $product->fetch($idprod);
  5544. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5545. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5546. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5547. $ret = $product->vatrate_supplier;
  5548. if ($product->default_vat_code) {
  5549. $ret .= ' ('.$product->default_vat_code.')';
  5550. }
  5551. } else {
  5552. $ret = $product->tva_tx; // Default vat of product we defined
  5553. if ($product->default_vat_code) {
  5554. $ret .= ' ('.$product->default_vat_code.')';
  5555. }
  5556. }
  5557. $found = 1;
  5558. } else {
  5559. // TODO Read default product vat according to product and another countrycode.
  5560. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5561. }
  5562. }
  5563. if (!$found) {
  5564. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5565. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5566. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5567. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5568. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5569. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5570. $sql .= $db->plimit(1);
  5571. $resql = $db->query($sql);
  5572. if ($resql) {
  5573. $obj = $db->fetch_object($resql);
  5574. if ($obj) {
  5575. $ret = $obj->vat_rate;
  5576. if ($obj->default_vat_code) {
  5577. $ret .= ' ('.$obj->default_vat_code.')';
  5578. }
  5579. }
  5580. $db->free($resql);
  5581. } else {
  5582. dol_print_error($db);
  5583. }
  5584. } else {
  5585. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5586. }
  5587. }
  5588. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5589. return $ret;
  5590. }
  5591. /**
  5592. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5593. *
  5594. * @param int $idprod Id of product
  5595. * @param int $local 1 for localtax1, 2 for localtax 2
  5596. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5597. * @return int <0 if KO, Vat rate if OK
  5598. * @see get_product_vat_for_country()
  5599. */
  5600. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5601. {
  5602. global $db, $mysoc;
  5603. if (!class_exists('Product')) {
  5604. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5605. }
  5606. $ret = 0;
  5607. $found = 0;
  5608. if ($idprod > 0) {
  5609. // Load product
  5610. $product = new Product($db);
  5611. $result = $product->fetch($idprod);
  5612. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5613. /* Not defined yet, so we don't use this
  5614. if ($local==1) $ret=$product->localtax1_tx;
  5615. elseif ($local==2) $ret=$product->localtax2_tx;
  5616. $found=1;
  5617. */
  5618. } else {
  5619. // TODO Read default product vat according to product and another countrycode.
  5620. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5621. }
  5622. }
  5623. if (!$found) {
  5624. // If vat of product for the country not found or not defined, we return higher vat of country.
  5625. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5626. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5627. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5628. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5629. $sql .= $db->plimit(1);
  5630. $resql = $db->query($sql);
  5631. if ($resql) {
  5632. $obj = $db->fetch_object($resql);
  5633. if ($obj) {
  5634. if ($local == 1) {
  5635. $ret = $obj->localtax1;
  5636. } elseif ($local == 2) {
  5637. $ret = $obj->localtax2;
  5638. }
  5639. }
  5640. } else {
  5641. dol_print_error($db);
  5642. }
  5643. }
  5644. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5645. return $ret;
  5646. }
  5647. /**
  5648. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5649. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5650. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5651. * 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.
  5652. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5653. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5654. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5655. *
  5656. * @param Societe $thirdparty_seller Objet societe vendeuse
  5657. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5658. * @param int $idprod Id product
  5659. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5660. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5661. * @see get_default_npr(), get_default_localtax()
  5662. */
  5663. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5664. {
  5665. global $conf;
  5666. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5667. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5668. $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;
  5669. $seller_country_code = $thirdparty_seller->country_code;
  5670. $seller_in_cee = isInEEC($thirdparty_seller);
  5671. $buyer_country_code = $thirdparty_buyer->country_code;
  5672. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5673. 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 : ''));
  5674. // 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)
  5675. // we use the buyer VAT.
  5676. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5677. if ($seller_in_cee && $buyer_in_cee) {
  5678. $isacompany = $thirdparty_buyer->isACompany();
  5679. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5680. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5681. if (!isValidVATID($thirdparty_buyer)) {
  5682. $isacompany = 0;
  5683. }
  5684. }
  5685. if (!$isacompany) {
  5686. //print 'VATRULE 0';
  5687. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5688. }
  5689. }
  5690. }
  5691. // If seller does not use VAT
  5692. if (!$seller_use_vat) {
  5693. //print 'VATRULE 1';
  5694. return 0;
  5695. }
  5696. // 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.
  5697. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5698. if (($seller_country_code == $buyer_country_code)
  5699. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5700. //print 'VATRULE 2';
  5701. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5702. }
  5703. // 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.
  5704. // 'VATRULE 3' - Not supported
  5705. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5706. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5707. if (($seller_in_cee && $buyer_in_cee)) {
  5708. $isacompany = $thirdparty_buyer->isACompany();
  5709. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5710. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5711. if (!isValidVATID($thirdparty_buyer)) {
  5712. $isacompany = 0;
  5713. }
  5714. }
  5715. if (!$isacompany) {
  5716. //print 'VATRULE 4';
  5717. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5718. } else {
  5719. //print 'VATRULE 5';
  5720. return 0;
  5721. }
  5722. }
  5723. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5724. // I don't see any use case that need this rule.
  5725. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5726. $isacompany = $thirdparty_buyer->isACompany();
  5727. if (!$isacompany) {
  5728. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5729. //print 'VATRULE extra';
  5730. }
  5731. }
  5732. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5733. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5734. //print 'VATRULE 6';
  5735. return 0;
  5736. }
  5737. /**
  5738. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5739. *
  5740. * @param Societe $thirdparty_seller Thirdparty seller
  5741. * @param Societe $thirdparty_buyer Thirdparty buyer
  5742. * @param int $idprod Id product
  5743. * @param int $idprodfournprice Id supplier price for product
  5744. * @return float 0 or 1
  5745. * @see get_default_tva(), get_default_localtax()
  5746. */
  5747. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5748. {
  5749. global $db;
  5750. if ($idprodfournprice > 0) {
  5751. if (!class_exists('ProductFournisseur')) {
  5752. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5753. }
  5754. $prodprice = new ProductFournisseur($db);
  5755. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5756. return $prodprice->fourn_tva_npr;
  5757. } elseif ($idprod > 0) {
  5758. if (!class_exists('Product')) {
  5759. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5760. }
  5761. $prod = new Product($db);
  5762. $prod->fetch($idprod);
  5763. return $prod->tva_npr;
  5764. }
  5765. return 0;
  5766. }
  5767. /**
  5768. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5769. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5770. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5771. * Sinon TVA proposee par defaut=0. Fin de regle.
  5772. *
  5773. * @param Societe $thirdparty_seller Thirdparty seller
  5774. * @param Societe $thirdparty_buyer Thirdparty buyer
  5775. * @param int $local Localtax to process (1 or 2)
  5776. * @param int $idprod Id product
  5777. * @return integer localtax, -1 si ne peut etre determine
  5778. * @see get_default_tva(), get_default_npr()
  5779. */
  5780. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5781. {
  5782. global $mysoc;
  5783. if (!is_object($thirdparty_seller)) {
  5784. return -1;
  5785. }
  5786. if (!is_object($thirdparty_buyer)) {
  5787. return -1;
  5788. }
  5789. if ($local == 1) { // Localtax 1
  5790. if ($mysoc->country_code == 'ES') {
  5791. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5792. return 0;
  5793. }
  5794. } else {
  5795. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5796. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5797. return 0;
  5798. }
  5799. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5800. return 0;
  5801. }
  5802. }
  5803. } elseif ($local == 2) { //I Localtax 2
  5804. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5805. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5806. return 0;
  5807. }
  5808. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5809. return 0;
  5810. }
  5811. }
  5812. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5813. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5814. }
  5815. return 0;
  5816. }
  5817. /**
  5818. * Return yes or no in current language
  5819. *
  5820. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5821. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5822. * @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.
  5823. * @return string HTML string
  5824. */
  5825. function yn($yesno, $case = 1, $color = 0)
  5826. {
  5827. global $langs;
  5828. $result = 'unknown';
  5829. $classname = '';
  5830. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5831. $result = $langs->trans('yes');
  5832. if ($case == 1 || $case == 3) {
  5833. $result = $langs->trans("Yes");
  5834. }
  5835. if ($case == 2) {
  5836. $result = '<input type="checkbox" value="1" checked disabled>';
  5837. }
  5838. if ($case == 3) {
  5839. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5840. }
  5841. $classname = 'ok';
  5842. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5843. $result = $langs->trans("no");
  5844. if ($case == 1 || $case == 3) {
  5845. $result = $langs->trans("No");
  5846. }
  5847. if ($case == 2) {
  5848. $result = '<input type="checkbox" value="0" disabled>';
  5849. }
  5850. if ($case == 3) {
  5851. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5852. }
  5853. if ($color == 2) {
  5854. $classname = 'ok';
  5855. } else {
  5856. $classname = 'error';
  5857. }
  5858. }
  5859. if ($color) {
  5860. return '<span class="'.$classname.'">'.$result.'</span>';
  5861. }
  5862. return $result;
  5863. }
  5864. /**
  5865. * Return a path to have a the directory according to object where files are stored.
  5866. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5867. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5868. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5869. * 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/"
  5870. *
  5871. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5872. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5873. * @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)
  5874. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5875. * @param Object $object Object to use to get ref to forge the path.
  5876. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5877. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5878. */
  5879. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5880. {
  5881. global $conf;
  5882. if (empty($modulepart) && !empty($object->module)) {
  5883. $modulepart = $object->module;
  5884. }
  5885. $path = '';
  5886. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5887. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5888. $arrayforoldpath[] = 'product';
  5889. }
  5890. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5891. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5892. if (empty($alpha)) {
  5893. $num = preg_replace('/([^0-9])/i', '', $num);
  5894. } else {
  5895. $num = preg_replace('/^.*\-/i', '', $num);
  5896. }
  5897. $num = substr("000".$num, -$level);
  5898. if ($level == 1) {
  5899. $path = substr($num, 0, 1);
  5900. }
  5901. if ($level == 2) {
  5902. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5903. }
  5904. if ($level == 3) {
  5905. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5906. }
  5907. } else {
  5908. // We will enhance here a common way of forging path for document storage.
  5909. // In a future, we may distribute directories on several levels depending on setup and object.
  5910. // Here, $object->id, $object->ref and $modulepart are required.
  5911. //var_dump($modulepart);
  5912. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5913. }
  5914. if (empty($withoutslash) && !empty($path)) {
  5915. $path .= '/';
  5916. }
  5917. return $path;
  5918. }
  5919. /**
  5920. * Creation of a directory (this can create recursive subdir)
  5921. *
  5922. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5923. * @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)
  5924. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5925. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5926. */
  5927. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5928. {
  5929. global $conf;
  5930. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5931. $dir_osencoded = dol_osencode($dir);
  5932. if (@is_dir($dir_osencoded)) {
  5933. return 0;
  5934. }
  5935. $nberr = 0;
  5936. $nbcreated = 0;
  5937. $ccdir = '';
  5938. if (!empty($dataroot)) {
  5939. // Remove data root from loop
  5940. $dir = str_replace($dataroot.'/', '', $dir);
  5941. $ccdir = $dataroot.'/';
  5942. }
  5943. $cdir = explode("/", $dir);
  5944. $num = count($cdir);
  5945. for ($i = 0; $i < $num; $i++) {
  5946. if ($i > 0) {
  5947. $ccdir .= '/'.$cdir[$i];
  5948. } else {
  5949. $ccdir .= $cdir[$i];
  5950. }
  5951. if (preg_match("/^.:$/", $ccdir, $regs)) {
  5952. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5953. }
  5954. // Attention, le is_dir() peut echouer bien que le rep existe.
  5955. // (ex selon config de open_basedir)
  5956. if ($ccdir) {
  5957. $ccdir_osencoded = dol_osencode($ccdir);
  5958. if (!@is_dir($ccdir_osencoded)) {
  5959. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5960. umask(0);
  5961. $dirmaskdec = octdec($newmask);
  5962. if (empty($newmask)) {
  5963. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5964. }
  5965. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5966. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  5967. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5968. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5969. $nberr++;
  5970. } else {
  5971. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5972. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5973. $nbcreated++;
  5974. }
  5975. } else {
  5976. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5977. }
  5978. }
  5979. }
  5980. return ($nberr ? -$nberr : $nbcreated);
  5981. }
  5982. /**
  5983. * Return picto saying a field is required
  5984. *
  5985. * @return string Chaine avec picto obligatoire
  5986. */
  5987. function picto_required()
  5988. {
  5989. return '<span class="fieldrequired">*</span>';
  5990. }
  5991. /**
  5992. * Clean a string from all HTML tags and entities.
  5993. * This function differs from strip_tags because:
  5994. * - <br> are replaced with \n if removelinefeed=0 or 1
  5995. * - if entities are found, they are decoded BEFORE the strip
  5996. * - you can decide to convert line feed into a space
  5997. *
  5998. * @param string $stringtoclean String to clean
  5999. * @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..."
  6000. * @param string $pagecodeto Encoding of input/output string
  6001. * @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')
  6002. * @param integer $removedoublespaces Replace double space into one space
  6003. * @return string String cleaned
  6004. *
  6005. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6006. */
  6007. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6008. {
  6009. if ($removelinefeed == 2) {
  6010. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6011. }
  6012. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6013. // 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)
  6014. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6015. $temp = str_replace('< ', '__ltspace__', $temp);
  6016. if ($strip_tags) {
  6017. $temp = strip_tags($temp);
  6018. } else {
  6019. $temp = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6020. $pattern = "/<[^<>]+>/";
  6021. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6022. $temp = preg_replace($pattern, "", $temp); // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6023. $temp = preg_replace($pattern, "", $temp); // pass 2 - $temp after pass 2: 0000-021
  6024. // 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).
  6025. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6026. }
  6027. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6028. // Remove also carriage returns
  6029. if ($removelinefeed == 1) {
  6030. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6031. }
  6032. // And double quotes
  6033. if ($removedoublespaces) {
  6034. while (strpos($temp, " ")) {
  6035. $temp = str_replace(" ", " ", $temp);
  6036. }
  6037. }
  6038. $temp = str_replace('__ltspace__', '< ', $temp);
  6039. return trim($temp);
  6040. }
  6041. /**
  6042. * Clean a string to keep only desirable HTML tags.
  6043. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  6044. *
  6045. * @param string $stringtoclean String to clean
  6046. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6047. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6048. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6049. * @param int $allowiframe Allow iframe tags.
  6050. * @return string String cleaned
  6051. *
  6052. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6053. */
  6054. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  6055. {
  6056. $allowed_tags = array(
  6057. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  6058. "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",
  6059. "comment" // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6060. );
  6061. if ($allowiframe) {
  6062. $allowed_tags[] = "iframe";
  6063. }
  6064. $allowed_tags_string = join("><", $allowed_tags);
  6065. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6066. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6067. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6068. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6069. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6070. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6071. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6072. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  6073. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </> changing string obfuscated with </> that pass injection detection into harmfull string
  6074. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6075. $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
  6076. }
  6077. if ($removeclassattribute) { // Clean for remaining html tags
  6078. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6079. }
  6080. // Remove 'javascript:' that we should not find into a text with
  6081. // 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)).
  6082. if ($cleanalsojavascript) {
  6083. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  6084. }
  6085. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6086. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6087. return $temp;
  6088. }
  6089. /**
  6090. * Clean a string from some undesirable HTML tags.
  6091. * Note: Complementary to dol_string_onlythesehtmltags().
  6092. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6093. *
  6094. * @param string $stringtoclean String to clean
  6095. * @param array $allowed_attributes Array of tags not allowed
  6096. * @return string String cleaned
  6097. *
  6098. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6099. */
  6100. 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"))
  6101. {
  6102. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6103. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6104. $dom = new DOMDocument(null, 'UTF-8');
  6105. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6106. if (is_object($dom)) {
  6107. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6108. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6109. //var_dump($attrs->item($ii));
  6110. if (! empty($attrs->item($ii)->name)) {
  6111. // Delete attribute if not into allowed_attributes
  6112. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6113. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6114. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6115. $valuetoclean = $attrs->item($ii)->value;
  6116. if (isset($valuetoclean)) {
  6117. do {
  6118. $oldvaluetoclean = $valuetoclean;
  6119. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6120. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6121. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6122. $valuetoclean = preg_replace('/display\s*://m', '', $valuetoclean);
  6123. $valuetoclean = preg_replace('/z-index\s*://m', '', $valuetoclean);
  6124. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*://m', '', $valuetoclean);
  6125. }
  6126. } while ($oldvaluetoclean != $valuetoclean);
  6127. }
  6128. $attrs->item($ii)->value = $valuetoclean;
  6129. }
  6130. }
  6131. }
  6132. }
  6133. }
  6134. $return = $dom->saveHTML();
  6135. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6136. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6137. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6138. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6139. return trim($return);
  6140. } else {
  6141. return $stringtoclean;
  6142. }
  6143. }
  6144. /**
  6145. * Clean a string from some undesirable HTML tags.
  6146. * Note. Not as secured as dol_string_onlythesehtmltags().
  6147. *
  6148. * @param string $stringtoclean String to clean
  6149. * @param array $disallowed_tags Array of tags not allowed
  6150. * @param string $cleanalsosomestyles Clean also some tags
  6151. * @return string String cleaned
  6152. *
  6153. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6154. */
  6155. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6156. {
  6157. $temp = $stringtoclean;
  6158. foreach ($disallowed_tags as $tagtoremove) {
  6159. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6160. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6161. }
  6162. if ($cleanalsosomestyles) {
  6163. $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
  6164. }
  6165. return $temp;
  6166. }
  6167. /**
  6168. * Return first line of text. Cut will depends if content is HTML or not.
  6169. *
  6170. * @param string $text Input text
  6171. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6172. * @param string $charset Charset of $text string (UTF-8 by default)
  6173. * @return string Output text
  6174. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6175. */
  6176. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6177. {
  6178. if ($nboflines == 1) {
  6179. if (dol_textishtml($text)) {
  6180. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6181. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6182. } else {
  6183. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6184. }
  6185. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  6186. } else {
  6187. $ishtml = 0;
  6188. if (dol_textishtml($text)) {
  6189. $text = preg_replace('/\n/', '', $text);
  6190. $ishtml = 1;
  6191. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6192. } else {
  6193. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6194. }
  6195. $text = strtr($text, $repTable);
  6196. if ($charset == 'UTF-8') {
  6197. $pattern = '/(<br[^>]*>)/Uu';
  6198. } else {
  6199. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6200. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6201. }
  6202. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6203. $firstline = '';
  6204. $i = 0;
  6205. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  6206. while (($i < $nba) && ($i < ($nboflines * 2))) {
  6207. if ($i % 2 == 0) {
  6208. $firstline .= $a[$i];
  6209. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  6210. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6211. }
  6212. $i++;
  6213. }
  6214. unset($a);
  6215. return $firstline.(($i < $nba) ? '...' : '');
  6216. }
  6217. }
  6218. /**
  6219. * Replace CRLF in string with a HTML BR tag.
  6220. * 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.
  6221. *
  6222. * @param string $stringtoencode String to encode
  6223. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6224. * @param bool $forxml false=Use <br>, true=Use <br />
  6225. * @return string String encoded
  6226. * @see dol_nboflines(), dolGetFirstLineOfText()
  6227. */
  6228. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6229. {
  6230. if (!$nl2brmode) {
  6231. return nl2br($stringtoencode, $forxml);
  6232. } else {
  6233. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6234. return $ret;
  6235. }
  6236. }
  6237. /**
  6238. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6239. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6240. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6241. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6242. * For PDF usage, you can show text by 2 ways:
  6243. * - writeHTMLCell -> param must be encoded into HTML.
  6244. * - MultiCell -> param must not be encoded into HTML.
  6245. * Because writeHTMLCell convert also \n into <br>, if function
  6246. * is used to build PDF, nl2brmode must be 1.
  6247. *
  6248. * @param string $stringtoencode String to encode
  6249. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6250. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6251. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6252. * @return string String encoded
  6253. */
  6254. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6255. {
  6256. $newstring = $stringtoencode;
  6257. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6258. $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.
  6259. if ($removelasteolbr) {
  6260. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6261. }
  6262. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6263. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6264. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6265. } else {
  6266. if ($removelasteolbr) {
  6267. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6268. }
  6269. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6270. }
  6271. // Other substitutions that htmlentities does not do
  6272. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6273. return $newstring;
  6274. }
  6275. /**
  6276. * This function is called to decode a HTML string (it decodes entities and br tags)
  6277. *
  6278. * @param string $stringtodecode String to decode
  6279. * @param string $pagecodeto Page code for result
  6280. * @return string String decoded
  6281. */
  6282. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6283. {
  6284. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6285. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6286. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6287. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6288. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6289. return $ret;
  6290. }
  6291. /**
  6292. * This function remove all ending \n and br at end
  6293. *
  6294. * @param string $stringtodecode String to decode
  6295. * @return string String decoded
  6296. */
  6297. function dol_htmlcleanlastbr($stringtodecode)
  6298. {
  6299. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6300. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6301. return $ret;
  6302. }
  6303. /**
  6304. * Replace html_entity_decode functions to manage errors
  6305. *
  6306. * @param string $a Operand a
  6307. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6308. * @param string $c Operand c
  6309. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6310. * @return string String decoded
  6311. */
  6312. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6313. {
  6314. $newstring = $a;
  6315. if ($keepsomeentities) {
  6316. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6317. }
  6318. $newstring = html_entity_decode($newstring, $b, $c);
  6319. if ($keepsomeentities) {
  6320. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6321. }
  6322. return $newstring;
  6323. }
  6324. /**
  6325. * Replace htmlentities functions.
  6326. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6327. *
  6328. * @param string $string The input string to encode
  6329. * @param int $flags Flags (see PHP doc above)
  6330. * @param string $encoding Encoding page code
  6331. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6332. * @return string $ret Encoded string
  6333. */
  6334. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6335. {
  6336. return htmlentities($string, $flags, $encoding, $double_encode);
  6337. }
  6338. /**
  6339. * Check if a string is a correct iso string
  6340. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6341. * Example, if string contains euro symbol that has ascii code 128
  6342. *
  6343. * @param string $s String to check
  6344. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6345. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6346. */
  6347. function dol_string_is_good_iso($s, $clean = 0)
  6348. {
  6349. $len = dol_strlen($s);
  6350. $out = '';
  6351. $ok = 1;
  6352. for ($scursor = 0; $scursor < $len; $scursor++) {
  6353. $ordchar = ord($s[$scursor]);
  6354. //print $scursor.'-'.$ordchar.'<br>';
  6355. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6356. $ok = 0;
  6357. break;
  6358. } elseif ($ordchar > 126 && $ordchar < 160) {
  6359. $ok = 0;
  6360. break;
  6361. } elseif ($clean) {
  6362. $out .= $s[$scursor];
  6363. }
  6364. }
  6365. if ($clean) {
  6366. return $out;
  6367. }
  6368. return $ok;
  6369. }
  6370. /**
  6371. * Return nb of lines of a clear text
  6372. *
  6373. * @param string $s String to check
  6374. * @param int $maxchar Not yet used
  6375. * @return int Number of lines
  6376. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6377. */
  6378. function dol_nboflines($s, $maxchar = 0)
  6379. {
  6380. if ($s == '') {
  6381. return 0;
  6382. }
  6383. $arraystring = explode("\n", $s);
  6384. $nb = count($arraystring);
  6385. return $nb;
  6386. }
  6387. /**
  6388. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6389. *
  6390. * @param string $text Text
  6391. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6392. * @param string $charset Give the charset used to encode the $text variable in memory.
  6393. * @return int Number of lines
  6394. * @see dol_nboflines(), dolGetFirstLineOfText()
  6395. */
  6396. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6397. {
  6398. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6399. if (dol_textishtml($text)) {
  6400. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6401. }
  6402. $text = strtr($text, $repTable);
  6403. if ($charset == 'UTF-8') {
  6404. $pattern = '/(<br[^>]*>)/Uu';
  6405. } else {
  6406. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6407. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6408. }
  6409. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6410. $nblines = (int) floor((count($a) + 1) / 2);
  6411. // count possible auto line breaks
  6412. if ($maxlinesize) {
  6413. foreach ($a as $line) {
  6414. if (dol_strlen($line) > $maxlinesize) {
  6415. //$line_dec = html_entity_decode(strip_tags($line));
  6416. $line_dec = html_entity_decode($line);
  6417. if (dol_strlen($line_dec) > $maxlinesize) {
  6418. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6419. $nblines += substr_count($line_dec, '\n');
  6420. }
  6421. }
  6422. }
  6423. }
  6424. unset($a);
  6425. return $nblines;
  6426. }
  6427. /**
  6428. * Return if a text is a html content
  6429. *
  6430. * @param string $msg Content to check
  6431. * @param int $option 0=Full detection, 1=Fast check
  6432. * @return boolean true/false
  6433. * @see dol_concatdesc()
  6434. */
  6435. function dol_textishtml($msg, $option = 0)
  6436. {
  6437. if ($option == 1) {
  6438. if (preg_match('/<html/i', $msg)) {
  6439. return true;
  6440. } elseif (preg_match('/<body/i', $msg)) {
  6441. return true;
  6442. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6443. return true;
  6444. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6445. return true;
  6446. } elseif (preg_match('/<br/i', $msg)) {
  6447. return true;
  6448. }
  6449. return false;
  6450. } else {
  6451. if (preg_match('/<html/i', $msg)) {
  6452. return true;
  6453. } elseif (preg_match('/<body/i', $msg)) {
  6454. return true;
  6455. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6456. return true;
  6457. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6458. return true;
  6459. } elseif (preg_match('/<br\/>/i', $msg)) {
  6460. return true;
  6461. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6462. return true;
  6463. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6464. return true;
  6465. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6466. return true; // must accept <img src="http://example.com/aaa.png" />
  6467. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6468. return true; // must accept <a href="http://example.com/aaa.png" />
  6469. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6470. return true;
  6471. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6472. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6473. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6474. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6475. }
  6476. return false;
  6477. }
  6478. }
  6479. /**
  6480. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6481. * text1 html + text2 html => text1 + '<br>' + text2
  6482. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6483. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6484. * text1 txt + text2 txt => text1 + '\n' + text2
  6485. *
  6486. * @param string $text1 Text 1
  6487. * @param string $text2 Text 2
  6488. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6489. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6490. * @return string Text 1 + new line + Text2
  6491. * @see dol_textishtml()
  6492. */
  6493. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6494. {
  6495. if (!empty($invert)) {
  6496. $tmp = $text1;
  6497. $text1 = $text2;
  6498. $text2 = $tmp;
  6499. }
  6500. $ret = '';
  6501. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6502. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6503. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6504. return $ret;
  6505. }
  6506. /**
  6507. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6508. *
  6509. * @param Translate $outputlangs Output language
  6510. * @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)
  6511. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6512. * @param Object $object Object for keys on object
  6513. * @return array Array of substitutions
  6514. * @see setSubstitFromObject()
  6515. */
  6516. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6517. {
  6518. global $db, $conf, $mysoc, $user, $extrafields;
  6519. $substitutionarray = array();
  6520. if (empty($exclude) || !in_array('user', $exclude)) {
  6521. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6522. // this will include signature content first and then replace var found into content of signature
  6523. $signature = $user->signature;
  6524. $substitutionarray = array_merge($substitutionarray, array(
  6525. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6526. ));
  6527. if (is_object($user)) {
  6528. $substitutionarray = array_merge($substitutionarray, array(
  6529. '__USER_ID__' => (string) $user->id,
  6530. '__USER_LOGIN__' => (string) $user->login,
  6531. '__USER_EMAIL__' => (string) $user->email,
  6532. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone),
  6533. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile),
  6534. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile),
  6535. '__USER_FAX__' => (string) $user->office_fax,
  6536. '__USER_LASTNAME__' => (string) $user->lastname,
  6537. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6538. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6539. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6540. '__USER_JOB__' => (string) $user->job,
  6541. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6542. ));
  6543. }
  6544. }
  6545. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6546. $substitutionarray = array_merge($substitutionarray, array(
  6547. '__MYCOMPANY_NAME__' => $mysoc->name,
  6548. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6549. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone),
  6550. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax),
  6551. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6552. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6553. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6554. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6555. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6556. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6557. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6558. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6559. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6560. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6561. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6562. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6563. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6564. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6565. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6566. ));
  6567. }
  6568. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6569. if ($onlykey) {
  6570. $substitutionarray['__ID__'] = '__ID__';
  6571. $substitutionarray['__REF__'] = '__REF__';
  6572. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6573. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6574. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6575. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6576. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6577. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6578. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6579. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6580. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6581. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6582. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6583. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6584. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6585. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6586. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6587. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6588. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6589. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6590. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6591. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6592. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6593. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6594. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6595. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6596. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6597. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6598. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6599. }
  6600. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6601. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6602. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6603. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6604. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6605. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6606. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6607. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6608. }
  6609. // add variables subtitutions ticket
  6610. if (!empty($conf->ticket->enabled) && (!is_object($object) || $object->element == 'ticket')) {
  6611. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  6612. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  6613. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  6614. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  6615. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  6616. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  6617. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  6618. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  6619. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  6620. }
  6621. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'recruitmentcandidature')) {
  6622. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6623. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6624. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6625. }
  6626. if (!empty($conf->projet->enabled)) { // Most objects
  6627. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6628. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6629. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6630. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6631. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6632. }
  6633. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6634. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6635. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6636. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6637. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6638. }
  6639. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6640. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6641. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6642. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6643. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6644. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6645. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  6646. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6647. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6648. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6649. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6650. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6651. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6652. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6653. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6654. }
  6655. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6656. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6657. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6658. }
  6659. } else {
  6660. $substitutionarray['__ID__'] = $object->id;
  6661. $substitutionarray['__REF__'] = $object->ref;
  6662. $substitutionarray['__NEWREF__'] = $object->newref;
  6663. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6664. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6665. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6666. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6667. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6668. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6669. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6670. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6671. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6672. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6673. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6674. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6675. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6676. // For backward compatibility
  6677. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6678. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6679. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6680. $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 : '')) : '');
  6681. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6682. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6683. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6684. if (method_exists($object, 'getCivilityLabel')) {
  6685. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6686. }
  6687. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6688. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6689. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6690. if (method_exists($object, 'getFullName')) {
  6691. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6692. }
  6693. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6694. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6695. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6696. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6697. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6698. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6699. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6700. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6701. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6702. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6703. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  6704. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  6705. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  6706. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6707. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6708. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  6709. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  6710. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6711. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6712. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6713. }
  6714. if (is_object($object) && $object->element == 'societe') {
  6715. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6716. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6717. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6718. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6719. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6720. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6721. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  6722. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  6723. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6724. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6725. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6726. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6727. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6728. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6729. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6730. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6731. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6732. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6733. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6734. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6735. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6736. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6737. } elseif (is_object($object->thirdparty)) {
  6738. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6739. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6740. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6741. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6742. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6743. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6744. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  6745. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  6746. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6747. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6748. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6749. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6750. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6751. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6752. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6753. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6754. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6755. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6756. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6757. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6758. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6759. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6760. }
  6761. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6762. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6763. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  6764. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  6765. }
  6766. if (is_object($object->project)) {
  6767. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6768. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6769. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6770. }
  6771. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6772. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6773. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6774. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6775. }
  6776. if (is_object($object) && $object->element == 'shipping') {
  6777. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6778. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6779. }
  6780. if (is_object($object) && $object->element == 'reception') {
  6781. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6782. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6783. }
  6784. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6785. $dateplannedstart = '';
  6786. $datenextexpiration = '';
  6787. foreach ($object->lines as $line) {
  6788. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6789. $dateplannedstart = $line->date_ouverture_prevue;
  6790. }
  6791. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6792. $datenextexpiration = $line->date_fin_prevue;
  6793. }
  6794. }
  6795. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6796. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6797. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6798. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6799. }
  6800. // add substition variable for ticket
  6801. if (is_object($object) && $object->element == 'ticket') {
  6802. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  6803. $substitutionarray['__REF__'] = $object->ref;
  6804. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  6805. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  6806. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  6807. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  6808. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  6809. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  6810. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  6811. $userstat = new User($db);
  6812. if ($object->fk_user_assign > 0) {
  6813. $userstat->fetch($object->fk_user_assign);
  6814. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  6815. }
  6816. if ($object->fk_user_create > 0) {
  6817. $userstat->fetch($object->fk_user_create);
  6818. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  6819. }
  6820. }
  6821. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6822. if ($object->table_element && $object->id > 0) {
  6823. if (!is_object($extrafields)) {
  6824. $extrafields = new ExtraFields($db);
  6825. }
  6826. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6827. if ($object->fetch_optionals() > 0) {
  6828. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6829. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6830. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6831. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6832. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6833. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6834. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6835. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6836. $datetime = $object->array_options['options_'.$key];
  6837. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6838. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6839. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6840. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6841. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  6842. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  6843. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  6844. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6845. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  6846. }
  6847. }
  6848. }
  6849. }
  6850. }
  6851. // Complete substitution array with the url to make online payment
  6852. $paymenturl = '';
  6853. if (empty($substitutionarray['__REF__'])) {
  6854. $paymenturl = '';
  6855. } else {
  6856. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6857. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6858. $outputlangs->loadLangs(array('paypal', 'other'));
  6859. $typeforonlinepayment = 'free';
  6860. if (is_object($object) && $object->element == 'commande') {
  6861. $typeforonlinepayment = 'order';
  6862. }
  6863. if (is_object($object) && $object->element == 'facture') {
  6864. $typeforonlinepayment = 'invoice';
  6865. }
  6866. if (is_object($object) && $object->element == 'member') {
  6867. $typeforonlinepayment = 'member';
  6868. }
  6869. if (is_object($object) && $object->element == 'contrat') {
  6870. $typeforonlinepayment = 'contract';
  6871. }
  6872. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6873. $paymenturl = $url;
  6874. }
  6875. if ($object->id > 0) {
  6876. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6877. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6878. if (is_object($object) && $object->element == 'propal') {
  6879. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  6880. }
  6881. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6882. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6883. } else {
  6884. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6885. }
  6886. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6887. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6888. } else {
  6889. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6890. }
  6891. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6892. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6893. } else {
  6894. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6895. }
  6896. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6897. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6898. } else {
  6899. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6900. }
  6901. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6902. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6903. } else {
  6904. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6905. }
  6906. if (is_object($object) && $object->element == 'propal') {
  6907. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6908. }
  6909. if (is_object($object) && $object->element == 'commande') {
  6910. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6911. }
  6912. if (is_object($object) && $object->element == 'facture') {
  6913. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6914. }
  6915. if (is_object($object) && $object->element == 'contrat') {
  6916. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6917. }
  6918. if (is_object($object) && $object->element == 'supplier_proposal') {
  6919. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6920. }
  6921. if (is_object($object) && $object->element == 'shipping') {
  6922. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  6923. }
  6924. }
  6925. if (is_object($object) && $object->element == 'action') {
  6926. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6927. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  6928. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  6929. }
  6930. }
  6931. }
  6932. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  6933. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  6934. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  6935. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  6936. $already_payed_all = 0;
  6937. if (is_object($object) && ($object instanceof Facture)) {
  6938. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  6939. }
  6940. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  6941. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  6942. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  6943. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  6944. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? $object->total_ttc - $already_payed_all : '';
  6945. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6946. $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)) : '';
  6947. $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)) : '';
  6948. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6949. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  6950. }
  6951. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6952. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  6953. }
  6954. // Amount keys formated in a currency
  6955. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6956. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6957. $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc - $already_payed_all, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6958. $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)) : '';
  6959. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6960. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6961. }
  6962. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6963. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6964. }
  6965. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  6966. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  6967. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  6968. // TODO Add other keys for foreign multicurrency
  6969. // For backward compatibility
  6970. if ($onlykey != 2) {
  6971. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  6972. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  6973. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6974. }
  6975. }
  6976. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  6977. if (empty($exclude) || !in_array('date', $exclude)) {
  6978. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6979. $tmp = dol_getdate(dol_now(), true);
  6980. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6981. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  6982. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6983. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  6984. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  6985. $substitutionarray = array_merge($substitutionarray, array(
  6986. '__DAY__' => (string) $tmp['mday'],
  6987. '__DAY_TEXT__' => $daytext, // Monday
  6988. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  6989. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  6990. '__MONTH__' => (string) $tmp['mon'],
  6991. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  6992. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  6993. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  6994. '__YEAR__' => (string) $tmp['year'],
  6995. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  6996. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  6997. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  6998. '__NEXT_DAY__' => (string) $tmp4['day'],
  6999. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7000. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7001. ));
  7002. }
  7003. if (!empty($conf->multicompany->enabled)) {
  7004. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7005. }
  7006. if (empty($exclude) || !in_array('system', $exclude)) {
  7007. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7008. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7009. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7010. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7011. }
  7012. return $substitutionarray;
  7013. }
  7014. /**
  7015. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7016. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7017. * Example of usage:
  7018. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7019. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7020. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7021. *
  7022. * @param string $text Source string in which we must do substitution
  7023. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7024. * @param Translate $outputlangs Output language
  7025. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7026. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7027. * @return string Output string after substitutions
  7028. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7029. */
  7030. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7031. {
  7032. global $conf, $langs;
  7033. if (!is_array($substitutionarray)) {
  7034. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7035. }
  7036. if (empty($outputlangs)) {
  7037. $outputlangs = $langs;
  7038. }
  7039. // Is initial text HTML or simple text ?
  7040. $msgishtml = 0;
  7041. if (dol_textishtml($text, 1)) {
  7042. $msgishtml = 1;
  7043. }
  7044. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7045. if (is_object($outputlangs)) {
  7046. $reg = array();
  7047. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7048. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7049. $tmp = explode('|', $reg[1]);
  7050. if (!empty($tmp[1])) {
  7051. $outputlangs->load($tmp[1]);
  7052. }
  7053. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7054. if (empty($converttextinhtmlifnecessary)) {
  7055. // convert $newval into HTML is necessary
  7056. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7057. } else {
  7058. if (! $msgishtml) {
  7059. $valueishtml = dol_textishtml($value, 1);
  7060. if ($valueishtml) {
  7061. $text = dol_htmlentitiesbr($text);
  7062. $msgishtml = 1;
  7063. }
  7064. } else {
  7065. $value = dol_nl2br("$value");
  7066. }
  7067. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7068. }
  7069. }
  7070. }
  7071. // Make substitution for constant keys.
  7072. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7073. $reg = array();
  7074. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7075. $keyfound = $reg[1];
  7076. if (isASecretKey($keyfound)) {
  7077. $value = '*****forbidden*****';
  7078. } else {
  7079. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7080. }
  7081. if (empty($converttextinhtmlifnecessary)) {
  7082. // convert $newval into HTML is necessary
  7083. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7084. } else {
  7085. if (! $msgishtml) {
  7086. $valueishtml = dol_textishtml($value, 1);
  7087. if ($valueishtml) {
  7088. $text = dol_htmlentitiesbr($text);
  7089. $msgishtml = 1;
  7090. }
  7091. } else {
  7092. $value = dol_nl2br("$value");
  7093. }
  7094. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7095. }
  7096. }
  7097. // Make substitition for array $substitutionarray
  7098. foreach ($substitutionarray as $key => $value) {
  7099. if (!isset($value)) {
  7100. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7101. }
  7102. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  7103. $value = ''; // Protection
  7104. }
  7105. if (empty($converttextinhtmlifnecessary)) {
  7106. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7107. } else {
  7108. if (! $msgishtml) {
  7109. $valueishtml = dol_textishtml($value, 1);
  7110. if ($valueishtml) {
  7111. $text = dol_htmlentitiesbr($text);
  7112. $msgishtml = 1;
  7113. }
  7114. } else {
  7115. $value = dol_nl2br("$value");
  7116. }
  7117. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7118. }
  7119. }
  7120. return $text;
  7121. }
  7122. /**
  7123. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  7124. * In this case, method completesubstitutionarray provided by module is called.
  7125. *
  7126. * @param array $substitutionarray Array substitution old value => new value value
  7127. * @param Translate $outputlangs Output language
  7128. * @param Object $object Source object
  7129. * @param mixed $parameters Add more parameters (useful to pass product lines)
  7130. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  7131. * @return void
  7132. * @see make_substitutions()
  7133. */
  7134. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  7135. {
  7136. global $conf, $user;
  7137. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7138. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7139. // Check if there is external substitution to do, requested by plugins
  7140. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7141. foreach ($dirsubstitutions as $reldir) {
  7142. $dir = dol_buildpath($reldir, 0);
  7143. // Check if directory exists
  7144. if (!dol_is_dir($dir)) {
  7145. continue;
  7146. }
  7147. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7148. foreach ($substitfiles as $substitfile) {
  7149. $reg = array();
  7150. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7151. $module = $reg[1];
  7152. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7153. // Include the user's functions file
  7154. require_once $dir.$substitfile['name'];
  7155. // Call the user's function, and only if it is defined
  7156. $function_name = $module."_".$callfunc;
  7157. if (function_exists($function_name)) {
  7158. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7159. }
  7160. }
  7161. }
  7162. }
  7163. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7164. // to list all tags in odt template
  7165. $tags = '';
  7166. foreach ($substitutionarray as $key => $value) {
  7167. $tags .= '{'.$key.'} => '.$value."\n";
  7168. }
  7169. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7170. }
  7171. }
  7172. /**
  7173. * Format output for start and end date
  7174. *
  7175. * @param int $date_start Start date
  7176. * @param int $date_end End date
  7177. * @param string $format Output format
  7178. * @param Translate $outputlangs Output language
  7179. * @return void
  7180. */
  7181. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7182. {
  7183. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7184. }
  7185. /**
  7186. * Format output for start and end date
  7187. *
  7188. * @param int $date_start Start date
  7189. * @param int $date_end End date
  7190. * @param string $format Output format
  7191. * @param Translate $outputlangs Output language
  7192. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7193. * @return string String
  7194. */
  7195. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7196. {
  7197. global $langs;
  7198. $out = '';
  7199. if (!is_object($outputlangs)) {
  7200. $outputlangs = $langs;
  7201. }
  7202. if ($date_start && $date_end) {
  7203. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7204. }
  7205. if ($date_start && !$date_end) {
  7206. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7207. }
  7208. if (!$date_start && $date_end) {
  7209. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7210. }
  7211. return $out;
  7212. }
  7213. /**
  7214. * Return firstname and lastname in correct order
  7215. *
  7216. * @param string $firstname Firstname
  7217. * @param string $lastname Lastname
  7218. * @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
  7219. * @return string Firstname + lastname or Lastname + firstname
  7220. */
  7221. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7222. {
  7223. global $conf;
  7224. $ret = '';
  7225. // If order not defined, we use the setup
  7226. if ($nameorder < 0) {
  7227. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7228. }
  7229. if ($nameorder == 1) {
  7230. $ret .= $firstname;
  7231. if ($firstname && $lastname) {
  7232. $ret .= ' ';
  7233. }
  7234. $ret .= $lastname;
  7235. } elseif ($nameorder == 2 || $nameorder == 3) {
  7236. $ret .= $firstname;
  7237. if (empty($ret) && $nameorder == 3) {
  7238. $ret .= $lastname;
  7239. }
  7240. } else { // 0, 4 or 5
  7241. $ret .= $lastname;
  7242. if (empty($ret) && $nameorder == 5) {
  7243. $ret .= $firstname;
  7244. }
  7245. if ($nameorder == 0) {
  7246. if ($firstname && $lastname) {
  7247. $ret .= ' ';
  7248. }
  7249. $ret .= $firstname;
  7250. }
  7251. }
  7252. return $ret;
  7253. }
  7254. /**
  7255. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  7256. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7257. * Note: Prefer to use setEventMessages instead.
  7258. *
  7259. * @param string|string[] $mesgs Message string or array
  7260. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7261. * @return void
  7262. * @see dol_htmloutput_events()
  7263. */
  7264. function setEventMessage($mesgs, $style = 'mesgs')
  7265. {
  7266. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  7267. if (!is_array($mesgs)) {
  7268. // If mesgs is a string
  7269. if ($mesgs) {
  7270. $_SESSION['dol_events'][$style][] = $mesgs;
  7271. }
  7272. } else {
  7273. // If mesgs is an array
  7274. foreach ($mesgs as $mesg) {
  7275. if ($mesg) {
  7276. $_SESSION['dol_events'][$style][] = $mesg;
  7277. }
  7278. }
  7279. }
  7280. }
  7281. /**
  7282. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7283. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7284. *
  7285. * @param string $mesg Message string
  7286. * @param array $mesgs Message array
  7287. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7288. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7289. * @return void
  7290. * @see dol_htmloutput_events()
  7291. */
  7292. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  7293. {
  7294. if (empty($mesg) && empty($mesgs)) {
  7295. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  7296. } else {
  7297. if ($messagekey) {
  7298. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7299. // TODO
  7300. $mesg .= '';
  7301. }
  7302. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7303. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7304. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7305. }
  7306. if (empty($mesgs)) {
  7307. setEventMessage($mesg, $style);
  7308. } else {
  7309. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7310. setEventMessage($mesg, $style); // Add message string if not already into array
  7311. }
  7312. setEventMessage($mesgs, $style);
  7313. }
  7314. }
  7315. }
  7316. }
  7317. /**
  7318. * Print formated messages to output (Used to show messages on html output).
  7319. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7320. * no need to call it explicitely.
  7321. *
  7322. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7323. * @return void
  7324. * @see dol_htmloutput_mesg()
  7325. */
  7326. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7327. {
  7328. // Show mesgs
  7329. if (isset($_SESSION['dol_events']['mesgs'])) {
  7330. if (empty($disabledoutputofmessages)) {
  7331. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7332. }
  7333. unset($_SESSION['dol_events']['mesgs']);
  7334. }
  7335. // Show errors
  7336. if (isset($_SESSION['dol_events']['errors'])) {
  7337. if (empty($disabledoutputofmessages)) {
  7338. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7339. }
  7340. unset($_SESSION['dol_events']['errors']);
  7341. }
  7342. // Show warnings
  7343. if (isset($_SESSION['dol_events']['warnings'])) {
  7344. if (empty($disabledoutputofmessages)) {
  7345. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7346. }
  7347. unset($_SESSION['dol_events']['warnings']);
  7348. }
  7349. }
  7350. /**
  7351. * Get formated messages to output (Used to show messages on html output).
  7352. * This include also the translation of the message key.
  7353. *
  7354. * @param string $mesgstring Message string or message key
  7355. * @param string[] $mesgarray Array of message strings or message keys
  7356. * @param string $style Style of message output ('ok' or 'error')
  7357. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7358. * @return string Return html output
  7359. *
  7360. * @see dol_print_error()
  7361. * @see dol_htmloutput_errors()
  7362. * @see setEventMessages()
  7363. */
  7364. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7365. {
  7366. global $conf, $langs;
  7367. $ret = 0;
  7368. $return = '';
  7369. $out = '';
  7370. $divstart = $divend = '';
  7371. // If inline message with no format, we add it.
  7372. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7373. $divstart = '<div class="'.$style.' clearboth">';
  7374. $divend = '</div>';
  7375. }
  7376. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7377. $langs->load("errors");
  7378. $out .= $divstart;
  7379. if (is_array($mesgarray) && count($mesgarray)) {
  7380. foreach ($mesgarray as $message) {
  7381. $ret++;
  7382. $out .= $langs->trans($message);
  7383. if ($ret < count($mesgarray)) {
  7384. $out .= "<br>\n";
  7385. }
  7386. }
  7387. }
  7388. if ($mesgstring) {
  7389. $langs->load("errors");
  7390. $ret++;
  7391. $out .= $langs->trans($mesgstring);
  7392. }
  7393. $out .= $divend;
  7394. }
  7395. if ($out) {
  7396. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7397. $return = '<script>
  7398. $(document).ready(function() {
  7399. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7400. if (block) {
  7401. $.dolEventValid("","'.dol_escape_js($out).'");
  7402. } else {
  7403. /* jnotify(message, preset of message type, keepmessage) */
  7404. $.jnotify("'.dol_escape_js($out).'",
  7405. "'.($style == "ok" ? 3000 : $style).'",
  7406. '.($style == "ok" ? "false" : "true").',
  7407. { remove: function (){} } );
  7408. }
  7409. });
  7410. </script>';
  7411. } else {
  7412. $return = $out;
  7413. }
  7414. }
  7415. return $return;
  7416. }
  7417. /**
  7418. * Get formated error messages to output (Used to show messages on html output).
  7419. *
  7420. * @param string $mesgstring Error message
  7421. * @param array $mesgarray Error messages array
  7422. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7423. * @return string Return html output
  7424. *
  7425. * @see dol_print_error()
  7426. * @see dol_htmloutput_mesg()
  7427. */
  7428. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7429. {
  7430. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7431. }
  7432. /**
  7433. * Print formated messages to output (Used to show messages on html output).
  7434. *
  7435. * @param string $mesgstring Message string or message key
  7436. * @param string[] $mesgarray Array of message strings or message keys
  7437. * @param string $style Which style to use ('ok', 'warning', 'error')
  7438. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7439. * @return void
  7440. *
  7441. * @see dol_print_error()
  7442. * @see dol_htmloutput_errors()
  7443. * @see setEventMessages()
  7444. */
  7445. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7446. {
  7447. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7448. return;
  7449. }
  7450. $iserror = 0;
  7451. $iswarning = 0;
  7452. if (is_array($mesgarray)) {
  7453. foreach ($mesgarray as $val) {
  7454. if ($val && preg_match('/class="error"/i', $val)) {
  7455. $iserror++;
  7456. break;
  7457. }
  7458. if ($val && preg_match('/class="warning"/i', $val)) {
  7459. $iswarning++;
  7460. break;
  7461. }
  7462. }
  7463. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7464. $iserror++;
  7465. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7466. $iswarning++;
  7467. }
  7468. if ($style == 'error') {
  7469. $iserror++;
  7470. }
  7471. if ($style == 'warning') {
  7472. $iswarning++;
  7473. }
  7474. if ($iserror || $iswarning) {
  7475. // Remove div from texts
  7476. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7477. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7478. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7479. // Remove div from texts array
  7480. if (is_array($mesgarray)) {
  7481. $newmesgarray = array();
  7482. foreach ($mesgarray as $val) {
  7483. if (is_string($val)) {
  7484. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7485. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7486. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7487. $newmesgarray[] = $tmpmesgstring;
  7488. } else {
  7489. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7490. }
  7491. }
  7492. $mesgarray = $newmesgarray;
  7493. }
  7494. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7495. } else {
  7496. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7497. }
  7498. }
  7499. /**
  7500. * Print formated error messages to output (Used to show messages on html output).
  7501. *
  7502. * @param string $mesgstring Error message
  7503. * @param array $mesgarray Error messages array
  7504. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7505. * @return void
  7506. *
  7507. * @see dol_print_error()
  7508. * @see dol_htmloutput_mesg()
  7509. */
  7510. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7511. {
  7512. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7513. }
  7514. /**
  7515. * Advanced sort array by second index function, which produces ascending (default)
  7516. * or descending output and uses optionally natural case insensitive sorting (which
  7517. * can be optionally case sensitive as well).
  7518. *
  7519. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7520. * @param string $index Key in array to use for sorting criteria
  7521. * @param int $order Sort order ('asc' or 'desc')
  7522. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7523. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7524. * @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.
  7525. * @return array Sorted array
  7526. */
  7527. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7528. {
  7529. // Clean parameters
  7530. $order = strtolower($order);
  7531. if (is_array($array)) {
  7532. $sizearray = count($array);
  7533. if ($sizearray > 0) {
  7534. $temp = array();
  7535. foreach (array_keys($array) as $key) {
  7536. if (is_object($array[$key])) {
  7537. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7538. } else {
  7539. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7540. }
  7541. }
  7542. if (!$natsort) {
  7543. if ($order == 'asc') {
  7544. asort($temp);
  7545. } else {
  7546. arsort($temp);
  7547. }
  7548. } else {
  7549. if ($case_sensitive) {
  7550. natsort($temp);
  7551. } else {
  7552. natcasesort($temp); // natecasesort is not sensible to case
  7553. }
  7554. if ($order != 'asc') {
  7555. $temp = array_reverse($temp, true);
  7556. }
  7557. }
  7558. $sorted = array();
  7559. foreach (array_keys($temp) as $key) {
  7560. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7561. }
  7562. return $sorted;
  7563. }
  7564. }
  7565. return $array;
  7566. }
  7567. /**
  7568. * Check if a string is in UTF8
  7569. *
  7570. * @param string $str String to check
  7571. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7572. */
  7573. function utf8_check($str)
  7574. {
  7575. $str = (string) $str; // Sometimes string is an int.
  7576. // We must use here a binary strlen function (so not dol_strlen)
  7577. $strLength = dol_strlen($str);
  7578. for ($i = 0; $i < $strLength; $i++) {
  7579. if (ord($str[$i]) < 0x80) {
  7580. continue; // 0bbbbbbb
  7581. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7582. $n = 1; // 110bbbbb
  7583. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7584. $n = 2; // 1110bbbb
  7585. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7586. $n = 3; // 11110bbb
  7587. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7588. $n = 4; // 111110bb
  7589. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7590. $n = 5; // 1111110b
  7591. } else {
  7592. return false; // Does not match any model
  7593. }
  7594. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7595. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7596. return false;
  7597. }
  7598. }
  7599. }
  7600. return true;
  7601. }
  7602. /**
  7603. * Check if a string is in ASCII
  7604. *
  7605. * @param string $str String to check
  7606. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7607. */
  7608. function ascii_check($str)
  7609. {
  7610. if (function_exists('mb_check_encoding')) {
  7611. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7612. if (!mb_check_encoding($str, 'ASCII')) {
  7613. return false;
  7614. }
  7615. } else {
  7616. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7617. return false; // Contains a byte > 7f
  7618. }
  7619. }
  7620. return true;
  7621. }
  7622. /**
  7623. * Return a string encoded into OS filesystem encoding. This function is used to define
  7624. * value to pass to filesystem PHP functions.
  7625. *
  7626. * @param string $str String to encode (UTF-8)
  7627. * @return string Encoded string (UTF-8, ISO-8859-1)
  7628. */
  7629. function dol_osencode($str)
  7630. {
  7631. global $conf;
  7632. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7633. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7634. $tmp = 'iso-8859-1'; // By default for windows
  7635. }
  7636. if (empty($tmp)) {
  7637. $tmp = 'utf-8'; // By default for other
  7638. }
  7639. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7640. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7641. }
  7642. if ($tmp == 'iso-8859-1') {
  7643. return utf8_decode($str);
  7644. }
  7645. return $str;
  7646. }
  7647. /**
  7648. * Return an id or code from a code or id.
  7649. * Store also Code-Id into a cache to speed up next request on same key.
  7650. *
  7651. * @param DoliDB $db Database handler
  7652. * @param string $key Code or Id to get Id or Code
  7653. * @param string $tablename Table name without prefix
  7654. * @param string $fieldkey Field to search the key into
  7655. * @param string $fieldid Field to get
  7656. * @param int $entityfilter Filter by entity
  7657. * @return int <0 if KO, Id of code if OK
  7658. * @see $langs->getLabelFromKey
  7659. */
  7660. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  7661. {
  7662. global $cache_codes;
  7663. // If key empty
  7664. if ($key == '') {
  7665. return '';
  7666. }
  7667. // Check in cache
  7668. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7669. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7670. }
  7671. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7672. $sql = "SELECT ".$fieldid." as valuetoget";
  7673. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7674. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7675. if (!empty($entityfilter)) {
  7676. $sql .= " AND entity IN (".getEntity($tablename).")";
  7677. }
  7678. $resql = $db->query($sql);
  7679. if ($resql) {
  7680. $obj = $db->fetch_object($resql);
  7681. if ($obj) {
  7682. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7683. } else {
  7684. $cache_codes[$tablename][$key][$fieldid] = '';
  7685. }
  7686. $db->free($resql);
  7687. return $cache_codes[$tablename][$key][$fieldid];
  7688. } else {
  7689. return -1;
  7690. }
  7691. }
  7692. /**
  7693. * Verify if condition in string is ok or not
  7694. *
  7695. * @param string $strToEvaluate String with condition to check
  7696. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  7697. */
  7698. function verifCond($strToEvaluate)
  7699. {
  7700. global $user, $conf, $langs;
  7701. global $leftmenu;
  7702. global $rights; // To export to dol_eval function
  7703. //print $strToEvaluate."<br>\n";
  7704. $rights = true;
  7705. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  7706. //$str = 'if(!('.$strToEvaluate.')) $rights = false;';
  7707. //dol_eval($str, 0, 1, '2'); // The dol_eval must contains all the global $xxx used into a condition
  7708. //var_dump($strToEvaluate);
  7709. $rep = dol_eval($strToEvaluate, 1, 1, '1'); // The dol_eval must contains all the global $xxx for all variables $xxx found into the string condition
  7710. $rights = (($rep && strpos($rep, 'Bad string syntax to evaluate') === false) ? true : false);
  7711. //var_dump($rights);
  7712. }
  7713. return $rights;
  7714. }
  7715. /**
  7716. * Replace eval function to add more security.
  7717. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7718. *
  7719. * @param string $s String to evaluate
  7720. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7721. * @param int $hideerrors 1=Hide errors
  7722. * @param string $onlysimplestring 0=Accept all chars, 1=Accept only simple string with char 'a-z0-9\s^$_+-.*\/>&|=!?():"\',/';', 2=Accept also ';[]'
  7723. * @return mixed Nothing or return result of eval
  7724. */
  7725. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  7726. {
  7727. // Only global variables can be changed by eval function and returned to caller
  7728. global $db, $langs, $user, $conf, $website, $websitepage;
  7729. global $action, $mainmenu, $leftmenu;
  7730. global $rights;
  7731. global $object;
  7732. global $mysoc;
  7733. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7734. global $soc; // For backward compatibility
  7735. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  7736. if ($onlysimplestring == '1') {
  7737. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL'
  7738. // We must accept: '$conf->barcode->enabled && preg_match(\'/^(AAA|BBB)/\',$leftmenu)'
  7739. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/', '/').']/i', $s)) {
  7740. if ($returnvalue) {
  7741. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  7742. } else {
  7743. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  7744. return '';
  7745. }
  7746. // TODO We can exclude all () that is not '($db)' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match('
  7747. // ...
  7748. }
  7749. } elseif ($onlysimplestring == '2') {
  7750. // We must accept: (($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"
  7751. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/;[]', '/').']/i', $s)) {
  7752. if ($returnvalue) {
  7753. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  7754. } else {
  7755. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  7756. return '';
  7757. }
  7758. }
  7759. }
  7760. if (strpos($s, '::') !== false) {
  7761. if ($returnvalue) {
  7762. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  7763. } else {
  7764. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  7765. return '';
  7766. }
  7767. }
  7768. if (strpos($s, '`') !== false) {
  7769. if ($returnvalue) {
  7770. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  7771. } else {
  7772. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  7773. return '';
  7774. }
  7775. }
  7776. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  7777. if ($returnvalue) {
  7778. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  7779. } else {
  7780. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  7781. return '';
  7782. }
  7783. }
  7784. // We block use of php exec or php file functions
  7785. $forbiddenphpstrings = array('$$');
  7786. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7787. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI", 'verifCond');
  7788. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  7789. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  7790. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  7791. do {
  7792. $oldstringtoclean = $s;
  7793. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7794. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  7795. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7796. } while ($oldstringtoclean != $s);
  7797. if (strpos($s, '__forbiddenstring__') !== false) {
  7798. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7799. if ($returnvalue) {
  7800. return 'Bad string syntax to evaluate: '.$s;
  7801. } else {
  7802. dol_syslog('Bad string syntax to evaluate: '.$s);
  7803. return '';
  7804. }
  7805. }
  7806. //print $s."<br>\n";
  7807. if ($returnvalue) {
  7808. if ($hideerrors) {
  7809. return @eval('return '.$s.';');
  7810. } else {
  7811. return eval('return '.$s.';');
  7812. }
  7813. } else {
  7814. if ($hideerrors) {
  7815. @eval($s);
  7816. } else {
  7817. eval($s);
  7818. }
  7819. }
  7820. }
  7821. /**
  7822. * Return if var element is ok
  7823. *
  7824. * @param string $element Variable to check
  7825. * @return boolean Return true of variable is not empty
  7826. */
  7827. function dol_validElement($element)
  7828. {
  7829. return (trim($element) != '');
  7830. }
  7831. /**
  7832. * Return img flag of country for a language code or country code.
  7833. *
  7834. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7835. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7836. * @param int $notitlealt No title alt
  7837. * @return string HTML img string with flag.
  7838. */
  7839. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  7840. {
  7841. if (empty($codelang)) {
  7842. return '';
  7843. }
  7844. if ($codelang == 'auto') {
  7845. return '<span class="fa fa-language"></span>';
  7846. }
  7847. $langtocountryflag = array(
  7848. 'ar_AR' => '',
  7849. 'ca_ES' => 'catalonia',
  7850. 'da_DA' => 'dk',
  7851. 'fr_CA' => 'mq',
  7852. 'sv_SV' => 'se',
  7853. 'sw_SW' => 'unknown',
  7854. 'AQ' => 'unknown',
  7855. 'CW' => 'unknown',
  7856. 'IM' => 'unknown',
  7857. 'JE' => 'unknown',
  7858. 'MF' => 'unknown',
  7859. 'BL' => 'unknown',
  7860. 'SX' => 'unknown'
  7861. );
  7862. if (isset($langtocountryflag[$codelang])) {
  7863. $flagImage = $langtocountryflag[$codelang];
  7864. } else {
  7865. $tmparray = explode('_', $codelang);
  7866. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7867. }
  7868. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  7869. }
  7870. /**
  7871. * Return default language from country code.
  7872. * Return null if not found.
  7873. *
  7874. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  7875. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  7876. */
  7877. function getLanguageCodeFromCountryCode($countrycode)
  7878. {
  7879. global $mysoc;
  7880. if (empty($countrycode)) {
  7881. return null;
  7882. }
  7883. if (strtoupper($countrycode) == 'MQ') {
  7884. return 'fr_CA';
  7885. }
  7886. if (strtoupper($countrycode) == 'SE') {
  7887. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7888. }
  7889. if (strtoupper($countrycode) == 'CH') {
  7890. if ($mysoc->country_code == 'FR') {
  7891. return 'fr_CH';
  7892. }
  7893. if ($mysoc->country_code == 'DE') {
  7894. return 'de_CH';
  7895. }
  7896. if ($mysoc->country_code == 'IT') {
  7897. return 'it_CH';
  7898. }
  7899. }
  7900. // Locale list taken from:
  7901. // http://stackoverflow.com/questions/3191664/
  7902. // list-of-all-locales-and-their-short-codes
  7903. $locales = array(
  7904. 'af-ZA',
  7905. 'am-ET',
  7906. 'ar-AE',
  7907. 'ar-BH',
  7908. 'ar-DZ',
  7909. 'ar-EG',
  7910. 'ar-IQ',
  7911. 'ar-JO',
  7912. 'ar-KW',
  7913. 'ar-LB',
  7914. 'ar-LY',
  7915. 'ar-MA',
  7916. 'ar-OM',
  7917. 'ar-QA',
  7918. 'ar-SA',
  7919. 'ar-SY',
  7920. 'ar-TN',
  7921. 'ar-YE',
  7922. //'as-IN', // Moved after en-IN
  7923. 'ba-RU',
  7924. 'be-BY',
  7925. 'bg-BG',
  7926. 'bn-BD',
  7927. //'bn-IN', // Moved after en-IN
  7928. 'bo-CN',
  7929. 'br-FR',
  7930. 'ca-ES',
  7931. 'co-FR',
  7932. 'cs-CZ',
  7933. 'cy-GB',
  7934. 'da-DK',
  7935. 'de-AT',
  7936. 'de-CH',
  7937. 'de-DE',
  7938. 'de-LI',
  7939. 'de-LU',
  7940. 'dv-MV',
  7941. 'el-GR',
  7942. 'en-AU',
  7943. 'en-BZ',
  7944. 'en-CA',
  7945. 'en-GB',
  7946. 'en-IE',
  7947. 'en-IN',
  7948. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  7949. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  7950. 'en-JM',
  7951. 'en-MY',
  7952. 'en-NZ',
  7953. 'en-PH',
  7954. 'en-SG',
  7955. 'en-TT',
  7956. 'en-US',
  7957. 'en-ZA',
  7958. 'en-ZW',
  7959. 'es-AR',
  7960. 'es-BO',
  7961. 'es-CL',
  7962. 'es-CO',
  7963. 'es-CR',
  7964. 'es-DO',
  7965. 'es-EC',
  7966. 'es-ES',
  7967. 'es-GT',
  7968. 'es-HN',
  7969. 'es-MX',
  7970. 'es-NI',
  7971. 'es-PA',
  7972. 'es-PE',
  7973. 'es-PR',
  7974. 'es-PY',
  7975. 'es-SV',
  7976. 'es-US',
  7977. 'es-UY',
  7978. 'es-VE',
  7979. 'et-EE',
  7980. 'eu-ES',
  7981. 'fa-IR',
  7982. 'fi-FI',
  7983. 'fo-FO',
  7984. 'fr-BE',
  7985. 'fr-CA',
  7986. 'fr-CH',
  7987. 'fr-FR',
  7988. 'fr-LU',
  7989. 'fr-MC',
  7990. 'fy-NL',
  7991. 'ga-IE',
  7992. 'gd-GB',
  7993. 'gl-ES',
  7994. 'gu-IN',
  7995. 'he-IL',
  7996. 'hi-IN',
  7997. 'hr-BA',
  7998. 'hr-HR',
  7999. 'hu-HU',
  8000. 'hy-AM',
  8001. 'id-ID',
  8002. 'ig-NG',
  8003. 'ii-CN',
  8004. 'is-IS',
  8005. 'it-CH',
  8006. 'it-IT',
  8007. 'ja-JP',
  8008. 'ka-GE',
  8009. 'kk-KZ',
  8010. 'kl-GL',
  8011. 'km-KH',
  8012. 'kn-IN',
  8013. 'ko-KR',
  8014. 'ky-KG',
  8015. 'lb-LU',
  8016. 'lo-LA',
  8017. 'lt-LT',
  8018. 'lv-LV',
  8019. 'mi-NZ',
  8020. 'mk-MK',
  8021. 'ml-IN',
  8022. 'mn-MN',
  8023. 'mr-IN',
  8024. 'ms-BN',
  8025. 'ms-MY',
  8026. 'mt-MT',
  8027. 'nb-NO',
  8028. 'ne-NP',
  8029. 'nl-BE',
  8030. 'nl-NL',
  8031. 'nn-NO',
  8032. 'oc-FR',
  8033. 'or-IN',
  8034. 'pa-IN',
  8035. 'pl-PL',
  8036. 'ps-AF',
  8037. 'pt-BR',
  8038. 'pt-PT',
  8039. 'rm-CH',
  8040. 'ro-MD',
  8041. 'ro-RO',
  8042. 'ru-RU',
  8043. 'rw-RW',
  8044. 'sa-IN',
  8045. 'se-FI',
  8046. 'se-NO',
  8047. 'se-SE',
  8048. 'si-LK',
  8049. 'sk-SK',
  8050. 'sl-SI',
  8051. 'sq-AL',
  8052. 'sv-FI',
  8053. 'sv-SE',
  8054. 'sw-KE',
  8055. 'ta-IN',
  8056. 'te-IN',
  8057. 'th-TH',
  8058. 'tk-TM',
  8059. 'tn-ZA',
  8060. 'tr-TR',
  8061. 'tt-RU',
  8062. 'ug-CN',
  8063. 'uk-UA',
  8064. 'ur-PK',
  8065. 'vi-VN',
  8066. 'wo-SN',
  8067. 'xh-ZA',
  8068. 'yo-NG',
  8069. 'zh-CN',
  8070. 'zh-HK',
  8071. 'zh-MO',
  8072. 'zh-SG',
  8073. 'zh-TW',
  8074. 'zu-ZA',
  8075. );
  8076. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  8077. if (in_array($buildprimarykeytotest, $locales)) {
  8078. return strtolower($countrycode).'_'.strtoupper($countrycode);
  8079. }
  8080. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  8081. foreach ($locales as $locale) {
  8082. $locale_language = locale_get_primary_language($locale);
  8083. $locale_region = locale_get_region($locale);
  8084. if (strtoupper($countrycode) == $locale_region) {
  8085. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  8086. return strtolower($locale_language).'_'.strtoupper($locale_region);
  8087. }
  8088. }
  8089. } else {
  8090. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  8091. }
  8092. return null;
  8093. }
  8094. /**
  8095. * Complete or removed entries into a head array (used to build tabs).
  8096. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  8097. * Or by change using hook completeTabsHead
  8098. *
  8099. * @param Conf $conf Object conf
  8100. * @param Translate $langs Object langs
  8101. * @param object|null $object Object object
  8102. * @param array $head Object head
  8103. * @param int $h New position to fill
  8104. * @param string $type Value for object where objectvalue can be
  8105. * 'thirdparty' to add a tab in third party view
  8106. * 'intervention' to add a tab in intervention view
  8107. * 'supplier_order' to add a tab in supplier order view
  8108. * 'supplier_invoice' to add a tab in supplier invoice view
  8109. * 'invoice' to add a tab in customer invoice view
  8110. * 'order' to add a tab in customer order view
  8111. * 'contract' to add a tabl in contract view
  8112. * 'product' to add a tab in product view
  8113. * 'propal' to add a tab in propal view
  8114. * 'user' to add a tab in user view
  8115. * 'group' to add a tab in group view
  8116. * 'member' to add a tab in fundation member view
  8117. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  8118. * 'ecm' to add a tab for another ecm view
  8119. * 'stock' to add a tab for warehouse view
  8120. * @param string $mode 'add' to complete head, 'remove' to remove entries
  8121. * @return void
  8122. */
  8123. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  8124. {
  8125. global $hookmanager, $db;
  8126. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  8127. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  8128. $values = explode(':', $value);
  8129. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  8130. if (count($values) == 6) { // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8131. if ($values[0] != $type) {
  8132. continue;
  8133. }
  8134. if (verifCond($values[4])) {
  8135. if ($values[3]) {
  8136. $langs->load($values[3]);
  8137. }
  8138. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8139. $substitutionarray = array();
  8140. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8141. $label = make_substitutions($reg[1], $substitutionarray);
  8142. } else {
  8143. $labeltemp = explode(':', $values[2]);
  8144. $label = $langs->trans($labeltemp[0]);
  8145. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  8146. dol_include_once($labeltemp[2]);
  8147. $classtoload = $labeltemp[1];
  8148. if (class_exists($classtoload)) {
  8149. $obj = new $classtoload($db);
  8150. $function = $labeltemp[3];
  8151. if ($obj && $function && method_exists($obj, $function)) {
  8152. $nbrec = $obj->$function($object->id, $obj);
  8153. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  8154. }
  8155. }
  8156. }
  8157. }
  8158. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  8159. $head[$h][1] = $label;
  8160. $head[$h][2] = str_replace('+', '', $values[1]);
  8161. $h++;
  8162. }
  8163. } elseif (count($values) == 5) { // deprecated
  8164. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  8165. if ($values[0] != $type) {
  8166. continue;
  8167. }
  8168. if ($values[3]) {
  8169. $langs->load($values[3]);
  8170. }
  8171. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8172. $substitutionarray = array();
  8173. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8174. $label = make_substitutions($reg[1], $substitutionarray);
  8175. } else {
  8176. $label = $langs->trans($values[2]);
  8177. }
  8178. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  8179. $head[$h][1] = $label;
  8180. $head[$h][2] = str_replace('+', '', $values[1]);
  8181. $h++;
  8182. }
  8183. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  8184. if ($values[0] != $type) {
  8185. continue;
  8186. }
  8187. $tabname = str_replace('-', '', $values[1]);
  8188. foreach ($head as $key => $val) {
  8189. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  8190. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  8191. if ($head[$key][2] == $tabname && $condition) {
  8192. unset($head[$key]);
  8193. break;
  8194. }
  8195. }
  8196. }
  8197. }
  8198. }
  8199. // No need to make a return $head. Var is modified as a reference
  8200. if (!empty($hookmanager)) {
  8201. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  8202. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  8203. if ($reshook > 0) { // Hook ask to replace completely the array
  8204. $head = $hookmanager->resArray;
  8205. } else { // Hook
  8206. $head = array_merge($head, $hookmanager->resArray);
  8207. }
  8208. $h = count($head);
  8209. }
  8210. }
  8211. /**
  8212. * Print common footer :
  8213. * conf->global->MAIN_HTML_FOOTER
  8214. * js for switch of menu hider
  8215. * js for conf->global->MAIN_GOOGLE_AN_ID
  8216. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  8217. * js for conf->logbuffer
  8218. *
  8219. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  8220. * @return void
  8221. */
  8222. function printCommonFooter($zone = 'private')
  8223. {
  8224. global $conf, $hookmanager, $user, $debugbar;
  8225. global $action;
  8226. global $micro_start_time;
  8227. if ($zone == 'private') {
  8228. print "\n".'<!-- Common footer for private page -->'."\n";
  8229. } else {
  8230. print "\n".'<!-- Common footer for public page -->'."\n";
  8231. }
  8232. // A div to store page_y POST parameter so we can read it using javascript
  8233. print "\n<!-- A div to store page_y POST parameter -->\n";
  8234. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  8235. $parameters = array();
  8236. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  8237. if (empty($reshook)) {
  8238. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  8239. print $conf->global->MAIN_HTML_FOOTER."\n";
  8240. }
  8241. print "\n";
  8242. if (!empty($conf->use_javascript_ajax)) {
  8243. print '<script>'."\n";
  8244. print 'jQuery(document).ready(function() {'."\n";
  8245. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  8246. print "\n";
  8247. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  8248. print 'jQuery("li.menuhider").click(function(event) {';
  8249. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  8250. print ' console.log("We click on .menuhider");'."\n";
  8251. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  8252. print '});'."\n";
  8253. }
  8254. // Management of focus and mandatory for fields
  8255. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  8256. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  8257. $relativepathstring = $_SERVER["PHP_SELF"];
  8258. // Clean $relativepathstring
  8259. if (constant('DOL_URL_ROOT')) {
  8260. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  8261. }
  8262. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  8263. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  8264. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  8265. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  8266. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  8267. $qualified = 0;
  8268. if ($defkey != '_noquery_') {
  8269. $tmpqueryarraytohave = explode('&', $defkey);
  8270. $foundintru = 0;
  8271. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8272. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8273. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8274. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8275. $foundintru = 1;
  8276. }
  8277. }
  8278. if (!$foundintru) {
  8279. $qualified = 1;
  8280. }
  8281. //var_dump($defkey.'-'.$qualified);
  8282. } else {
  8283. $qualified = 1;
  8284. }
  8285. if ($qualified) {
  8286. foreach ($defval as $paramkey => $paramval) {
  8287. // Set focus on field
  8288. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  8289. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  8290. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  8291. }
  8292. }
  8293. }
  8294. }
  8295. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  8296. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  8297. $qualified = 0;
  8298. if ($defkey != '_noquery_') {
  8299. $tmpqueryarraytohave = explode('&', $defkey);
  8300. $foundintru = 0;
  8301. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8302. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8303. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8304. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8305. $foundintru = 1;
  8306. }
  8307. }
  8308. if (!$foundintru) {
  8309. $qualified = 1;
  8310. }
  8311. //var_dump($defkey.'-'.$qualified);
  8312. } else {
  8313. $qualified = 1;
  8314. }
  8315. if ($qualified) {
  8316. foreach ($defval as $paramkey => $paramval) {
  8317. // Add property 'required' on input
  8318. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8319. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8320. 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";
  8321. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8322. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  8323. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  8324. // Add 'field required' class on closest td for all input elements : input, textarea and select
  8325. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  8326. }
  8327. }
  8328. }
  8329. }
  8330. }
  8331. print '});'."\n";
  8332. // End of tuning
  8333. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  8334. print "\n";
  8335. print "/* JS CODE TO ENABLE to add memory info */\n";
  8336. print 'window.console && console.log("';
  8337. if (!empty($conf->global->MEMCACHED_SERVER)) {
  8338. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  8339. }
  8340. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  8341. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  8342. $micro_end_time = microtime(true);
  8343. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  8344. }
  8345. if (function_exists("memory_get_usage")) {
  8346. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  8347. }
  8348. if (function_exists("memory_get_peak_usage")) {
  8349. print ' - Real mem peak: '.memory_get_peak_usage(true);
  8350. }
  8351. if (function_exists("zend_loader_file_encoded")) {
  8352. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8353. }
  8354. print '");'."\n";
  8355. }
  8356. print "\n".'</script>'."\n";
  8357. // Google Analytics
  8358. // TODO Add a hook here
  8359. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8360. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8361. foreach ($tmptagarray as $tmptag) {
  8362. print "\n";
  8363. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8364. print "
  8365. <!-- Global site tag (gtag.js) - Google Analytics -->
  8366. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  8367. <script>
  8368. window.dataLayer = window.dataLayer || [];
  8369. function gtag(){dataLayer.push(arguments);}
  8370. gtag('js', new Date());
  8371. gtag('config', '".trim($tmptag)."');
  8372. </script>";
  8373. print "\n";
  8374. }
  8375. }
  8376. }
  8377. // Add Xdebug coverage of code
  8378. if (defined('XDEBUGCOVERAGE')) {
  8379. print_r(xdebug_get_code_coverage());
  8380. }
  8381. // Add DebugBar data
  8382. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8383. $debugbar['time']->stopMeasure('pageaftermaster');
  8384. print '<!-- Output debugbar data -->'."\n";
  8385. $renderer = $debugbar->getRenderer();
  8386. print $debugbar->getRenderer()->render();
  8387. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8388. print "\n";
  8389. print "<!-- Start of log output\n";
  8390. //print '<div class="hidden">'."\n";
  8391. foreach ($conf->logbuffer as $logline) {
  8392. print $logline."<br>\n";
  8393. }
  8394. //print '</div>'."\n";
  8395. print "End of log output -->\n";
  8396. }
  8397. }
  8398. }
  8399. /**
  8400. * Split a string with 2 keys into key array.
  8401. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8402. *
  8403. * @param string $string String to explode
  8404. * @param string $delimiter Delimiter between each couple of data
  8405. * @param string $kv Delimiter between key and value
  8406. * @return array Array of data exploded
  8407. */
  8408. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8409. {
  8410. if ($a = explode($delimiter, $string)) {
  8411. $ka = array();
  8412. foreach ($a as $s) { // each part
  8413. if ($s) {
  8414. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8415. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8416. } else { // key delimiter not found
  8417. $ka[] = trim($s);
  8418. }
  8419. }
  8420. }
  8421. return $ka;
  8422. }
  8423. return array();
  8424. }
  8425. /**
  8426. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  8427. *
  8428. * @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.
  8429. * @return void
  8430. */
  8431. function dol_set_focus($selector)
  8432. {
  8433. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8434. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8435. }
  8436. /**
  8437. * Return getmypid() or random PID when function is disabled
  8438. * Some web hosts disable this php function for security reasons
  8439. * and sometimes we can't redeclare function
  8440. *
  8441. * @return int
  8442. */
  8443. function dol_getmypid()
  8444. {
  8445. if (!function_exists('getmypid')) {
  8446. return mt_rand(1, 32768);
  8447. } else {
  8448. return getmypid();
  8449. }
  8450. }
  8451. /**
  8452. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8453. *
  8454. * @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")
  8455. * @param string $value The value to look for.
  8456. * If param $mode is 0, can contains several keywords separated with a space or |
  8457. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8458. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8459. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8460. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8461. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8462. * @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')
  8463. * 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'
  8464. * @param integer $nofirstand 1=Do not output the first 'AND'
  8465. * @return string $res The statement to append to the SQL query
  8466. * @see dolSqlDateFilter()
  8467. */
  8468. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8469. {
  8470. global $db, $langs;
  8471. $value = trim($value);
  8472. if ($mode == 0) {
  8473. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8474. }
  8475. if ($mode == 1) {
  8476. $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
  8477. }
  8478. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8479. $crits = explode(' ', $value);
  8480. $res = '';
  8481. if (!is_array($fields)) {
  8482. $fields = array($fields);
  8483. }
  8484. $j = 0;
  8485. foreach ($crits as $crit) {
  8486. $crit = trim($crit);
  8487. $i = 0;
  8488. $i2 = 0;
  8489. $newres = '';
  8490. foreach ($fields as $field) {
  8491. if ($mode == 1) {
  8492. $operator = '=';
  8493. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8494. $reg = array();
  8495. preg_match('/([<>=]+)/', $crit, $reg);
  8496. if (!empty($reg[1])) {
  8497. $operator = $reg[1];
  8498. }
  8499. if ($newcrit != '') {
  8500. $numnewcrit = price2num($newcrit);
  8501. if (is_numeric($numnewcrit)) {
  8502. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  8503. } else {
  8504. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8505. }
  8506. $i2++; // a criteria was added to string
  8507. }
  8508. } elseif ($mode == 2 || $mode == -2) {
  8509. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8510. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8511. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8512. if ($mode == -2) {
  8513. $newres .= ' OR '.$field.' IS NULL';
  8514. }
  8515. $i2++; // a criteria was added to string
  8516. } elseif ($mode == 3 || $mode == -3) {
  8517. $tmparray = explode(',', $crit);
  8518. if (count($tmparray)) {
  8519. $listofcodes = '';
  8520. foreach ($tmparray as $val) {
  8521. $val = trim($val);
  8522. if ($val) {
  8523. $listofcodes .= ($listofcodes ? ',' : '');
  8524. $listofcodes .= "'".$db->escape($val)."'";
  8525. }
  8526. }
  8527. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8528. $i2++; // a criteria was added to string
  8529. }
  8530. if ($mode == -3) {
  8531. $newres .= ' OR '.$field.' IS NULL';
  8532. }
  8533. } elseif ($mode == 4) {
  8534. $tmparray = explode(',', $crit);
  8535. if (count($tmparray)) {
  8536. $listofcodes = '';
  8537. foreach ($tmparray as $val) {
  8538. $val = trim($val);
  8539. if ($val) {
  8540. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8541. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8542. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8543. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8544. $newres .= ')';
  8545. $i2++;
  8546. }
  8547. }
  8548. }
  8549. } else // $mode=0
  8550. {
  8551. $tmpcrits = explode('|', $crit);
  8552. $i3 = 0;
  8553. foreach ($tmpcrits as $tmpcrit) {
  8554. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8555. continue;
  8556. }
  8557. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8558. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8559. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? ((float) trim($tmpcrit)) : '0');
  8560. } else {
  8561. $tmpcrit = trim($tmpcrit);
  8562. $tmpcrit2 = $tmpcrit;
  8563. $tmpbefore = '%';
  8564. $tmpafter = '%';
  8565. if (preg_match('/^!/', $tmpcrit)) {
  8566. $newres .= $field." NOT LIKE '"; // ! as exclude character
  8567. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  8568. } else $newres .= $field." LIKE '";
  8569. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8570. $tmpbefore = '';
  8571. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8572. }
  8573. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8574. $tmpafter = '';
  8575. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8576. }
  8577. $newres .= $tmpbefore;
  8578. $newres .= $db->escape($tmpcrit2);
  8579. $newres .= $tmpafter;
  8580. $newres .= "'";
  8581. if ($tmpcrit2 == '') {
  8582. $newres .= " OR ".$field." IS NULL";
  8583. }
  8584. }
  8585. $i3++;
  8586. }
  8587. $i2++; // a criteria was added to string
  8588. }
  8589. $i++;
  8590. }
  8591. if ($newres) {
  8592. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8593. }
  8594. $j++;
  8595. }
  8596. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8597. //print 'xx'.$res.'yy';
  8598. return $res;
  8599. }
  8600. /**
  8601. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8602. *
  8603. * @param Object $object Object
  8604. * @return string Url string
  8605. */
  8606. function showDirectDownloadLink($object)
  8607. {
  8608. global $conf, $langs;
  8609. $out = '';
  8610. $url = $object->getLastMainDocLink($object->element);
  8611. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8612. if ($url) {
  8613. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8614. $out .= ajax_autoselect("directdownloadlink", 0);
  8615. } else {
  8616. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8617. }
  8618. return $out;
  8619. }
  8620. /**
  8621. * Return the filename of file to get the thumbs
  8622. *
  8623. * @param string $file Original filename (full or relative path)
  8624. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8625. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8626. * @return string New file name (full or relative path, including the thumbs/)
  8627. */
  8628. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8629. {
  8630. $dirName = dirname($file);
  8631. if ($dirName == '.') {
  8632. $dirName = '';
  8633. }
  8634. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8635. $fileName = basename($fileName);
  8636. if (empty($extImgTarget)) {
  8637. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8638. }
  8639. if (empty($extImgTarget)) {
  8640. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8641. }
  8642. if (empty($extImgTarget)) {
  8643. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8644. }
  8645. if (empty($extImgTarget)) {
  8646. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8647. }
  8648. if (empty($extImgTarget)) {
  8649. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8650. }
  8651. if (empty($extImgTarget)) {
  8652. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8653. }
  8654. if (!$extImgTarget) {
  8655. return $file;
  8656. }
  8657. $subdir = '';
  8658. if ($extName) {
  8659. $subdir = 'thumbs/';
  8660. }
  8661. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8662. }
  8663. /**
  8664. * Return URL we can use for advanced preview links
  8665. *
  8666. * @param string $modulepart propal, facture, facture_fourn, ...
  8667. * @param string $relativepath Relative path of docs.
  8668. * @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)
  8669. * @param string $param More param on http links
  8670. * @return string|array Output string with href link or array with all components of link
  8671. */
  8672. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8673. {
  8674. global $conf, $langs;
  8675. if (empty($conf->use_javascript_ajax)) {
  8676. return '';
  8677. }
  8678. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8679. if ($alldata == 1) {
  8680. if ($isAllowedForPreview) {
  8681. 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));
  8682. } else {
  8683. return array();
  8684. }
  8685. }
  8686. // old behavior, return a string
  8687. if ($isAllowedForPreview) {
  8688. 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')).'\')';
  8689. } else {
  8690. return '';
  8691. }
  8692. }
  8693. /**
  8694. * Make content of an input box selected when we click into input field.
  8695. *
  8696. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8697. * @param string $addlink Add a 'link to' after
  8698. * @param string $textonlink Text to show on link or 'image'
  8699. * @return string
  8700. */
  8701. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  8702. {
  8703. global $langs;
  8704. $out = '<script>
  8705. jQuery(document).ready(function () {
  8706. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8707. });
  8708. </script>';
  8709. if ($addlink) {
  8710. if ($textonlink === 'image') {
  8711. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  8712. } else {
  8713. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  8714. }
  8715. }
  8716. return $out;
  8717. }
  8718. /**
  8719. * Return if a file is qualified for preview
  8720. *
  8721. * @param string $file Filename we looking for information
  8722. * @return int 1 If allowed, 0 otherwise
  8723. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8724. */
  8725. function dolIsAllowedForPreview($file)
  8726. {
  8727. global $conf;
  8728. // Check .noexe extension in filename
  8729. if (preg_match('/\.noexe$/i', $file)) {
  8730. return 0;
  8731. }
  8732. // Check mime types
  8733. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8734. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8735. $mime_preview[] = 'svg+xml';
  8736. }
  8737. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8738. //$mime_preview[]='archive';
  8739. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8740. if ($num_mime !== false) {
  8741. return 1;
  8742. }
  8743. // By default, not allowed for preview
  8744. return 0;
  8745. }
  8746. /**
  8747. * Return MIME type of a file from its name with extension.
  8748. *
  8749. * @param string $file Filename we looking for MIME type
  8750. * @param string $default Default mime type if extension not found in known list
  8751. * @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
  8752. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8753. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8754. */
  8755. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8756. {
  8757. $mime = $default;
  8758. $imgmime = 'other.png';
  8759. $famime = 'file-o';
  8760. $srclang = '';
  8761. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8762. // Plain text files
  8763. if (preg_match('/\.txt$/i', $tmpfile)) {
  8764. $mime = 'text/plain';
  8765. $imgmime = 'text.png';
  8766. $famime = 'file-text-o';
  8767. }
  8768. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8769. $mime = 'text/richtext';
  8770. $imgmime = 'text.png';
  8771. $famime = 'file-text-o';
  8772. }
  8773. if (preg_match('/\.csv$/i', $tmpfile)) {
  8774. $mime = 'text/csv';
  8775. $imgmime = 'text.png';
  8776. $famime = 'file-text-o';
  8777. }
  8778. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8779. $mime = 'text/tab-separated-values';
  8780. $imgmime = 'text.png';
  8781. $famime = 'file-text-o';
  8782. }
  8783. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8784. $mime = 'text/plain';
  8785. $imgmime = 'text.png';
  8786. $famime = 'file-text-o';
  8787. }
  8788. if (preg_match('/\.ini$/i', $tmpfile)) {
  8789. $mime = 'text/plain';
  8790. $imgmime = 'text.png';
  8791. $srclang = 'ini';
  8792. $famime = 'file-text-o';
  8793. }
  8794. if (preg_match('/\.md$/i', $tmpfile)) {
  8795. $mime = 'text/plain';
  8796. $imgmime = 'text.png';
  8797. $srclang = 'md';
  8798. $famime = 'file-text-o';
  8799. }
  8800. if (preg_match('/\.css$/i', $tmpfile)) {
  8801. $mime = 'text/css';
  8802. $imgmime = 'css.png';
  8803. $srclang = 'css';
  8804. $famime = 'file-text-o';
  8805. }
  8806. if (preg_match('/\.lang$/i', $tmpfile)) {
  8807. $mime = 'text/plain';
  8808. $imgmime = 'text.png';
  8809. $srclang = 'lang';
  8810. $famime = 'file-text-o';
  8811. }
  8812. // Certificate files
  8813. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8814. $mime = 'text/plain';
  8815. $imgmime = 'text.png';
  8816. $famime = 'file-text-o';
  8817. }
  8818. // XML based (HTML/XML/XAML)
  8819. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8820. $mime = 'text/html';
  8821. $imgmime = 'html.png';
  8822. $srclang = 'html';
  8823. $famime = 'file-text-o';
  8824. }
  8825. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8826. $mime = 'text/xml';
  8827. $imgmime = 'other.png';
  8828. $srclang = 'xml';
  8829. $famime = 'file-text-o';
  8830. }
  8831. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8832. $mime = 'text/xml';
  8833. $imgmime = 'other.png';
  8834. $srclang = 'xaml';
  8835. $famime = 'file-text-o';
  8836. }
  8837. // Languages
  8838. if (preg_match('/\.bas$/i', $tmpfile)) {
  8839. $mime = 'text/plain';
  8840. $imgmime = 'text.png';
  8841. $srclang = 'bas';
  8842. $famime = 'file-code-o';
  8843. }
  8844. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8845. $mime = 'text/plain';
  8846. $imgmime = 'text.png';
  8847. $srclang = 'c';
  8848. $famime = 'file-code-o';
  8849. }
  8850. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8851. $mime = 'text/plain';
  8852. $imgmime = 'text.png';
  8853. $srclang = 'cpp';
  8854. $famime = 'file-code-o';
  8855. }
  8856. if (preg_match('/\.cs$/i', $tmpfile)) {
  8857. $mime = 'text/plain';
  8858. $imgmime = 'text.png';
  8859. $srclang = 'cs';
  8860. $famime = 'file-code-o';
  8861. }
  8862. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8863. $mime = 'text/plain';
  8864. $imgmime = 'text.png';
  8865. $srclang = 'h';
  8866. $famime = 'file-code-o';
  8867. }
  8868. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8869. $mime = 'text/plain';
  8870. $imgmime = 'text.png';
  8871. $srclang = 'java';
  8872. $famime = 'file-code-o';
  8873. }
  8874. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8875. $mime = 'text/plain';
  8876. $imgmime = 'php.png';
  8877. $srclang = 'php';
  8878. $famime = 'file-code-o';
  8879. }
  8880. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8881. $mime = 'text/plain';
  8882. $imgmime = 'php.png';
  8883. $srclang = 'php';
  8884. $famime = 'file-code-o';
  8885. }
  8886. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8887. $mime = 'text/plain';
  8888. $imgmime = 'pl.png';
  8889. $srclang = 'perl';
  8890. $famime = 'file-code-o';
  8891. }
  8892. if (preg_match('/\.sql$/i', $tmpfile)) {
  8893. $mime = 'text/plain';
  8894. $imgmime = 'text.png';
  8895. $srclang = 'sql';
  8896. $famime = 'file-code-o';
  8897. }
  8898. if (preg_match('/\.js$/i', $tmpfile)) {
  8899. $mime = 'text/x-javascript';
  8900. $imgmime = 'jscript.png';
  8901. $srclang = 'js';
  8902. $famime = 'file-code-o';
  8903. }
  8904. // Open office
  8905. if (preg_match('/\.odp$/i', $tmpfile)) {
  8906. $mime = 'application/vnd.oasis.opendocument.presentation';
  8907. $imgmime = 'ooffice.png';
  8908. $famime = 'file-powerpoint-o';
  8909. }
  8910. if (preg_match('/\.ods$/i', $tmpfile)) {
  8911. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8912. $imgmime = 'ooffice.png';
  8913. $famime = 'file-excel-o';
  8914. }
  8915. if (preg_match('/\.odt$/i', $tmpfile)) {
  8916. $mime = 'application/vnd.oasis.opendocument.text';
  8917. $imgmime = 'ooffice.png';
  8918. $famime = 'file-word-o';
  8919. }
  8920. // MS Office
  8921. if (preg_match('/\.mdb$/i', $tmpfile)) {
  8922. $mime = 'application/msaccess';
  8923. $imgmime = 'mdb.png';
  8924. $famime = 'file-o';
  8925. }
  8926. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  8927. $mime = 'application/msword';
  8928. $imgmime = 'doc.png';
  8929. $famime = 'file-word-o';
  8930. }
  8931. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  8932. $mime = 'application/msword';
  8933. $imgmime = 'doc.png';
  8934. $famime = 'file-word-o';
  8935. }
  8936. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  8937. $mime = 'application/vnd.ms-excel';
  8938. $imgmime = 'xls.png';
  8939. $famime = 'file-excel-o';
  8940. }
  8941. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  8942. $mime = 'application/vnd.ms-excel';
  8943. $imgmime = 'xls.png';
  8944. $famime = 'file-excel-o';
  8945. }
  8946. if (preg_match('/\.xls$/i', $tmpfile)) {
  8947. $mime = 'application/vnd.ms-excel';
  8948. $imgmime = 'xls.png';
  8949. $famime = 'file-excel-o';
  8950. }
  8951. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  8952. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  8953. $imgmime = 'xls.png';
  8954. $famime = 'file-excel-o';
  8955. }
  8956. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  8957. $mime = 'application/vnd.ms-powerpoint';
  8958. $imgmime = 'ppt.png';
  8959. $famime = 'file-powerpoint-o';
  8960. }
  8961. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  8962. $mime = 'application/x-mspowerpoint';
  8963. $imgmime = 'ppt.png';
  8964. $famime = 'file-powerpoint-o';
  8965. }
  8966. // Other
  8967. if (preg_match('/\.pdf$/i', $tmpfile)) {
  8968. $mime = 'application/pdf';
  8969. $imgmime = 'pdf.png';
  8970. $famime = 'file-pdf-o';
  8971. }
  8972. // Scripts
  8973. if (preg_match('/\.bat$/i', $tmpfile)) {
  8974. $mime = 'text/x-bat';
  8975. $imgmime = 'script.png';
  8976. $srclang = 'dos';
  8977. $famime = 'file-code-o';
  8978. }
  8979. if (preg_match('/\.sh$/i', $tmpfile)) {
  8980. $mime = 'text/x-sh';
  8981. $imgmime = 'script.png';
  8982. $srclang = 'bash';
  8983. $famime = 'file-code-o';
  8984. }
  8985. if (preg_match('/\.ksh$/i', $tmpfile)) {
  8986. $mime = 'text/x-ksh';
  8987. $imgmime = 'script.png';
  8988. $srclang = 'bash';
  8989. $famime = 'file-code-o';
  8990. }
  8991. if (preg_match('/\.bash$/i', $tmpfile)) {
  8992. $mime = 'text/x-bash';
  8993. $imgmime = 'script.png';
  8994. $srclang = 'bash';
  8995. $famime = 'file-code-o';
  8996. }
  8997. // Images
  8998. if (preg_match('/\.ico$/i', $tmpfile)) {
  8999. $mime = 'image/x-icon';
  9000. $imgmime = 'image.png';
  9001. $famime = 'file-image-o';
  9002. }
  9003. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  9004. $mime = 'image/jpeg';
  9005. $imgmime = 'image.png';
  9006. $famime = 'file-image-o';
  9007. }
  9008. if (preg_match('/\.png$/i', $tmpfile)) {
  9009. $mime = 'image/png';
  9010. $imgmime = 'image.png';
  9011. $famime = 'file-image-o';
  9012. }
  9013. if (preg_match('/\.gif$/i', $tmpfile)) {
  9014. $mime = 'image/gif';
  9015. $imgmime = 'image.png';
  9016. $famime = 'file-image-o';
  9017. }
  9018. if (preg_match('/\.bmp$/i', $tmpfile)) {
  9019. $mime = 'image/bmp';
  9020. $imgmime = 'image.png';
  9021. $famime = 'file-image-o';
  9022. }
  9023. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  9024. $mime = 'image/tiff';
  9025. $imgmime = 'image.png';
  9026. $famime = 'file-image-o';
  9027. }
  9028. if (preg_match('/\.svg$/i', $tmpfile)) {
  9029. $mime = 'image/svg+xml';
  9030. $imgmime = 'image.png';
  9031. $famime = 'file-image-o';
  9032. }
  9033. if (preg_match('/\.webp$/i', $tmpfile)) {
  9034. $mime = 'image/webp';
  9035. $imgmime = 'image.png';
  9036. $famime = 'file-image-o';
  9037. }
  9038. // Calendar
  9039. if (preg_match('/\.vcs$/i', $tmpfile)) {
  9040. $mime = 'text/calendar';
  9041. $imgmime = 'other.png';
  9042. $famime = 'file-text-o';
  9043. }
  9044. if (preg_match('/\.ics$/i', $tmpfile)) {
  9045. $mime = 'text/calendar';
  9046. $imgmime = 'other.png';
  9047. $famime = 'file-text-o';
  9048. }
  9049. // Other
  9050. if (preg_match('/\.torrent$/i', $tmpfile)) {
  9051. $mime = 'application/x-bittorrent';
  9052. $imgmime = 'other.png';
  9053. $famime = 'file-o';
  9054. }
  9055. // Audio
  9056. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  9057. $mime = 'audio';
  9058. $imgmime = 'audio.png';
  9059. $famime = 'file-audio-o';
  9060. }
  9061. // Video
  9062. if (preg_match('/\.mp4$/i', $tmpfile)) {
  9063. $mime = 'video/mp4';
  9064. $imgmime = 'video.png';
  9065. $famime = 'file-video-o';
  9066. }
  9067. if (preg_match('/\.ogv$/i', $tmpfile)) {
  9068. $mime = 'video/ogg';
  9069. $imgmime = 'video.png';
  9070. $famime = 'file-video-o';
  9071. }
  9072. if (preg_match('/\.webm$/i', $tmpfile)) {
  9073. $mime = 'video/webm';
  9074. $imgmime = 'video.png';
  9075. $famime = 'file-video-o';
  9076. }
  9077. if (preg_match('/\.avi$/i', $tmpfile)) {
  9078. $mime = 'video/x-msvideo';
  9079. $imgmime = 'video.png';
  9080. $famime = 'file-video-o';
  9081. }
  9082. if (preg_match('/\.divx$/i', $tmpfile)) {
  9083. $mime = 'video/divx';
  9084. $imgmime = 'video.png';
  9085. $famime = 'file-video-o';
  9086. }
  9087. if (preg_match('/\.xvid$/i', $tmpfile)) {
  9088. $mime = 'video/xvid';
  9089. $imgmime = 'video.png';
  9090. $famime = 'file-video-o';
  9091. }
  9092. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  9093. $mime = 'video';
  9094. $imgmime = 'video.png';
  9095. $famime = 'file-video-o';
  9096. }
  9097. // Archive
  9098. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  9099. $mime = 'archive';
  9100. $imgmime = 'archive.png';
  9101. $famime = 'file-archive-o';
  9102. } // application/xxx where zzz is zip, ...
  9103. // Exe
  9104. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  9105. $mime = 'application/octet-stream';
  9106. $imgmime = 'other.png';
  9107. $famime = 'file-o';
  9108. }
  9109. // Lib
  9110. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  9111. $mime = 'library';
  9112. $imgmime = 'library.png';
  9113. $famime = 'file-o';
  9114. }
  9115. // Err
  9116. if (preg_match('/\.err$/i', $tmpfile)) {
  9117. $mime = 'error';
  9118. $imgmime = 'error.png';
  9119. $famime = 'file-text-o';
  9120. }
  9121. // Return string
  9122. if ($mode == 1) {
  9123. $tmp = explode('/', $mime);
  9124. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  9125. }
  9126. if ($mode == 2) {
  9127. return $imgmime;
  9128. }
  9129. if ($mode == 3) {
  9130. return $srclang;
  9131. }
  9132. if ($mode == 4) {
  9133. return $famime;
  9134. }
  9135. return $mime;
  9136. }
  9137. /**
  9138. * Return the value of a filed into a dictionary for the record $id.
  9139. * This also set all the values into a cache for a next search.
  9140. *
  9141. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  9142. * @param string $field The name of field where to find the value to return
  9143. * @param int $id Id of line record
  9144. * @param bool $checkentity Add filter on entity
  9145. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  9146. * @return string The value of field $field. This also set $dictvalues cache.
  9147. */
  9148. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  9149. {
  9150. global $conf, $db;
  9151. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  9152. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  9153. if (is_null($dictvalues)) {
  9154. $dictvalues = array();
  9155. $sql = "SELECT * FROM ".MAIN_DB_PREFIX.$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  9156. if ($checkentity) {
  9157. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  9158. }
  9159. $resql = $db->query($sql);
  9160. if ($resql) {
  9161. while ($obj = $db->fetch_object($resql)) {
  9162. $dictvalues[$obj->{$rowidfield}] = $obj;
  9163. }
  9164. } else {
  9165. dol_print_error($db);
  9166. }
  9167. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  9168. }
  9169. if (!empty($dictvalues[$id])) {
  9170. // Found
  9171. return $dictvalues[$id]->{$field};
  9172. } else {
  9173. // Not found
  9174. return '';
  9175. }
  9176. }
  9177. /**
  9178. * Return true if the color is light
  9179. *
  9180. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  9181. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  9182. */
  9183. function colorIsLight($stringcolor)
  9184. {
  9185. $stringcolor = str_replace('#', '', $stringcolor);
  9186. $res = -1;
  9187. if (!empty($stringcolor)) {
  9188. $res = 0;
  9189. $tmp = explode(',', $stringcolor);
  9190. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  9191. $r = $tmp[0];
  9192. $g = $tmp[1];
  9193. $b = $tmp[2];
  9194. } else {
  9195. $hexr = $stringcolor[0].$stringcolor[1];
  9196. $hexg = $stringcolor[2].$stringcolor[3];
  9197. $hexb = $stringcolor[4].$stringcolor[5];
  9198. $r = hexdec($hexr);
  9199. $g = hexdec($hexg);
  9200. $b = hexdec($hexb);
  9201. }
  9202. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  9203. if ($bright > 0.6) {
  9204. $res = 1;
  9205. }
  9206. }
  9207. return $res;
  9208. }
  9209. /**
  9210. * Function to test if an entry is enabled or not
  9211. *
  9212. * @param string $type_user 0=We test for internal user, 1=We test for external user
  9213. * @param array $menuentry Array for feature entry to test
  9214. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  9215. * @return int 0=Hide, 1=Show, 2=Show gray
  9216. */
  9217. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  9218. {
  9219. global $conf;
  9220. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  9221. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  9222. if (empty($menuentry['enabled'])) {
  9223. return 0; // Entry disabled by condition
  9224. }
  9225. if ($type_user && $menuentry['module']) {
  9226. $tmploops = explode('|', $menuentry['module']);
  9227. $found = 0;
  9228. foreach ($tmploops as $tmploop) {
  9229. if (in_array($tmploop, $listofmodulesforexternal)) {
  9230. $found++;
  9231. break;
  9232. }
  9233. }
  9234. if (!$found) {
  9235. return 0; // Entry is for menus all excluded to external users
  9236. }
  9237. }
  9238. if (!$menuentry['perms'] && $type_user) {
  9239. return 0; // No permissions and user is external
  9240. }
  9241. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  9242. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  9243. }
  9244. if (!$menuentry['perms']) {
  9245. return 2; // No permissions and user is external
  9246. }
  9247. return 1;
  9248. }
  9249. /**
  9250. * Round to next multiple.
  9251. *
  9252. * @param double $n Number to round up
  9253. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  9254. * @return integer Value rounded.
  9255. */
  9256. function roundUpToNextMultiple($n, $x = 5)
  9257. {
  9258. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  9259. }
  9260. /**
  9261. * Function dolGetBadge
  9262. *
  9263. * @param string $label label of badge no html : use in alt attribute for accessibility
  9264. * @param string $html optional : label of badge with html
  9265. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  9266. * @param string $mode default '' , 'pill', 'dot'
  9267. * @param string $url the url for link
  9268. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  9269. * @return string Html badge
  9270. */
  9271. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  9272. {
  9273. $attr = array(
  9274. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  9275. );
  9276. if (empty($html)) {
  9277. $html = $label;
  9278. }
  9279. if (!empty($url)) {
  9280. $attr['href'] = $url;
  9281. }
  9282. if ($mode === 'dot') {
  9283. $attr['class'] .= ' classfortooltip';
  9284. $attr['title'] = $html;
  9285. $attr['aria-label'] = $label;
  9286. $html = '';
  9287. }
  9288. // Override attr
  9289. if (!empty($params['attr']) && is_array($params['attr'])) {
  9290. foreach ($params['attr'] as $key => $value) {
  9291. if ($key == 'class') {
  9292. $attr['class'] .= ' '.$value;
  9293. } elseif ($key == 'classOverride') {
  9294. $attr['class'] = $value;
  9295. } else {
  9296. $attr[$key] = $value;
  9297. }
  9298. }
  9299. }
  9300. // TODO: add hook
  9301. // escape all attribute
  9302. $attr = array_map('dol_escape_htmltag', $attr);
  9303. $TCompiledAttr = array();
  9304. foreach ($attr as $key => $value) {
  9305. $TCompiledAttr[] = $key.'="'.$value.'"';
  9306. }
  9307. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9308. $tag = !empty($url) ? 'a' : 'span';
  9309. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  9310. }
  9311. /**
  9312. * Output the badge of a status.
  9313. *
  9314. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  9315. * @param string $statusLabelShort Short label of badge no html
  9316. * @param string $html Optional : label of badge with html
  9317. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  9318. * @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
  9319. * @param string $url The url for link
  9320. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  9321. * @return string Html status string
  9322. */
  9323. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  9324. {
  9325. global $conf;
  9326. $return = '';
  9327. $dolGetBadgeParams = array();
  9328. if (!empty($params['badgeParams'])) {
  9329. $dolGetBadgeParams = $params['badgeParams'];
  9330. }
  9331. // TODO : add a hook
  9332. if ($displayMode == 0) {
  9333. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  9334. } elseif ($displayMode == 1) {
  9335. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9336. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  9337. // Use status with images (for backward compatibility)
  9338. $return = '';
  9339. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  9340. $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>' : '');
  9341. // For small screen, we always use the short label instead of long label.
  9342. if (!empty($conf->dol_optimize_smallscreen)) {
  9343. if ($displayMode == 0) {
  9344. $displayMode = 1;
  9345. } elseif ($displayMode == 4) {
  9346. $displayMode = 2;
  9347. } elseif ($displayMode == 6) {
  9348. $displayMode = 5;
  9349. }
  9350. }
  9351. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  9352. $statusImg = array(
  9353. 'status0' => 'statut0',
  9354. 'status1' => 'statut1',
  9355. 'status2' => 'statut2',
  9356. 'status3' => 'statut3',
  9357. 'status4' => 'statut4',
  9358. 'status5' => 'statut5',
  9359. 'status6' => 'statut6',
  9360. 'status7' => 'statut7',
  9361. 'status8' => 'statut8',
  9362. 'status9' => 'statut9'
  9363. );
  9364. if (!empty($statusImg[$statusType])) {
  9365. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  9366. } else {
  9367. $htmlImg = img_picto($statusLabel, $statusType);
  9368. }
  9369. if ($displayMode === 2) {
  9370. $return = $htmlImg.' '.$htmlLabelShort;
  9371. } elseif ($displayMode === 3) {
  9372. $return = $htmlImg;
  9373. } elseif ($displayMode === 4) {
  9374. $return = $htmlImg.' '.$htmlLabel;
  9375. } elseif ($displayMode === 5) {
  9376. $return = $htmlLabelShort.' '.$htmlImg;
  9377. } else { // $displayMode >= 6
  9378. $return = $htmlLabel.' '.$htmlImg;
  9379. }
  9380. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9381. // Use new badge
  9382. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9383. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9384. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9385. if ($displayMode == 3) {
  9386. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9387. } elseif ($displayMode === 5) {
  9388. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9389. } else {
  9390. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9391. }
  9392. }
  9393. return $return;
  9394. }
  9395. /**
  9396. * Function dolGetButtonAction
  9397. *
  9398. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  9399. * @param string $html optional : content with html
  9400. * @param string $actionType default, delete, danger
  9401. * @param string $url the url for link
  9402. * @param string $id attribute id of button
  9403. * @param int $userRight user action right
  9404. * // phpcs:disable
  9405. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  9406. * 'attr' => [ // to add or override button attributes
  9407. * 'xxxxx' => '', // your xxxxx attribute you want
  9408. * 'class' => '', // to add more css class to the button class attribute
  9409. * 'classOverride' => '' // to replace class attribute of the button
  9410. * ],
  9411. * 'confirm' => [
  9412. * '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.
  9413. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  9414. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  9415. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  9416. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  9417. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  9418. * ],
  9419. * ]
  9420. * // phpcs:enable
  9421. * @return string html button
  9422. */
  9423. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  9424. {
  9425. global $hookmanager, $action, $object, $langs;
  9426. $class = 'butAction';
  9427. if ($actionType == 'danger' || $actionType == 'delete') {
  9428. $class = 'butActionDelete';
  9429. if (!empty($url) && strpos($url, 'token=') === false) $url .= '&token='.newToken();
  9430. }
  9431. $attr = array(
  9432. 'class' => $class,
  9433. 'href' => empty($url) ? '' : $url,
  9434. 'title' => $label
  9435. );
  9436. if (empty($html)) {
  9437. $html = $label;
  9438. $attr['title'] = ''; // if html not set, leave label on title is redundant
  9439. } else {
  9440. $attr['aria-label'] = $label;
  9441. }
  9442. if (empty($userRight)) {
  9443. $attr['class'] = 'butActionRefused';
  9444. $attr['href'] = '';
  9445. }
  9446. if (!empty($id)) {
  9447. $attr['id'] = $id;
  9448. }
  9449. // Override attr
  9450. if (!empty($params['attr']) && is_array($params['attr'])) {
  9451. foreach ($params['attr'] as $key => $value) {
  9452. if ($key == 'class') {
  9453. $attr['class'] .= ' '.$value;
  9454. } elseif ($key == 'classOverride') {
  9455. $attr['class'] = $value;
  9456. } else {
  9457. $attr[$key] = $value;
  9458. }
  9459. }
  9460. }
  9461. // automatic add tooltip when title is detected
  9462. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  9463. $attr['class'].= ' classfortooltip';
  9464. }
  9465. // Js Confirm button
  9466. if ($userRight && !empty($params['confirm'])) {
  9467. if (!is_array($params['confirm'])) {
  9468. $params['confirm'] = array();
  9469. }
  9470. if (empty($params['confirm']['url'])) {
  9471. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  9472. }
  9473. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9474. $attr['data-confirm-url'] = $params['confirm']['url'];
  9475. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9476. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9477. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9478. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9479. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9480. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9481. $attr['class'].= ' butActionConfirm';
  9482. }
  9483. if (isset($attr['href']) && empty($attr['href'])) {
  9484. unset($attr['href']);
  9485. }
  9486. // escape all attribute
  9487. $attr = array_map('dol_escape_htmltag', $attr);
  9488. $TCompiledAttr = array();
  9489. foreach ($attr as $key => $value) {
  9490. $TCompiledAttr[] = $key.'="'.$value.'"';
  9491. }
  9492. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9493. $tag = !empty($attr['href']) ? 'a' : 'span';
  9494. $parameters = array(
  9495. 'TCompiledAttr' => $TCompiledAttr,
  9496. 'compiledAttributes' => $compiledAttributes,
  9497. 'attr' => $attr,
  9498. 'tag' => $tag,
  9499. 'label' => $label,
  9500. 'html' => $html,
  9501. 'actionType' => $actionType,
  9502. 'url' => $url,
  9503. 'id' => $id,
  9504. 'userRight' => $userRight,
  9505. 'params' => $params
  9506. );
  9507. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9508. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9509. if (empty($reshook)) {
  9510. return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
  9511. } else {
  9512. return $hookmanager->resPrint;
  9513. }
  9514. }
  9515. /**
  9516. * Add space between dolGetButtonTitle
  9517. *
  9518. * @param string $moreClass more css class label
  9519. * @return string html of title separator
  9520. */
  9521. function dolGetButtonTitleSeparator($moreClass = "")
  9522. {
  9523. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9524. }
  9525. /**
  9526. * get field error icon
  9527. *
  9528. * @param string $fieldValidationErrorMsg message to add in tooltip
  9529. * @return string html output
  9530. */
  9531. function getFieldErrorIcon($fieldValidationErrorMsg)
  9532. {
  9533. $out = '';
  9534. if (!empty($fieldValidationErrorMsg)) {
  9535. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9536. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9537. $out.= '</span>';
  9538. }
  9539. return $out;
  9540. }
  9541. /**
  9542. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9543. *
  9544. * @param string $label label of button
  9545. * @param string $helpText optional : content for help tooltip
  9546. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9547. * @param string $url the url for link
  9548. * @param string $id attribute id of button
  9549. * @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
  9550. * @param array $params various params for future : recommended rather than adding more function arguments
  9551. * @return string html button
  9552. */
  9553. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9554. {
  9555. global $langs, $conf, $user;
  9556. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9557. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9558. return '';
  9559. }
  9560. $class = 'btnTitle';
  9561. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots'))) {
  9562. $class .= ' btnTitlePlus';
  9563. }
  9564. $useclassfortooltip = 1;
  9565. if (!empty($params['morecss'])) {
  9566. $class .= ' '.$params['morecss'];
  9567. }
  9568. $attr = array(
  9569. 'class' => $class,
  9570. 'href' => empty($url) ? '' : $url
  9571. );
  9572. if (!empty($helpText)) {
  9573. $attr['title'] = dol_escape_htmltag($helpText);
  9574. } elseif (empty($attr['title']) && $label) {
  9575. $attr['title'] = $label;
  9576. $useclassfortooltip = 0;
  9577. }
  9578. if ($status == 2) {
  9579. $attr['class'] .= ' btnTitleSelected';
  9580. } elseif ($status <= 0) {
  9581. $attr['class'] .= ' refused';
  9582. $attr['href'] = '';
  9583. if ($status == -1) { // disable
  9584. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9585. } elseif ($status == 0) { // Not enough permissions
  9586. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9587. }
  9588. }
  9589. if (!empty($attr['title']) && $useclassfortooltip) {
  9590. $attr['class'] .= ' classfortooltip';
  9591. }
  9592. if (!empty($id)) {
  9593. $attr['id'] = $id;
  9594. }
  9595. // Override attr
  9596. if (!empty($params['attr']) && is_array($params['attr'])) {
  9597. foreach ($params['attr'] as $key => $value) {
  9598. if ($key == 'class') {
  9599. $attr['class'] .= ' '.$value;
  9600. } elseif ($key == 'classOverride') {
  9601. $attr['class'] = $value;
  9602. } else {
  9603. $attr[$key] = $value;
  9604. }
  9605. }
  9606. }
  9607. if (isset($attr['href']) && empty($attr['href'])) {
  9608. unset($attr['href']);
  9609. }
  9610. // TODO : add a hook
  9611. // escape all attribute
  9612. $attr = array_map('dol_escape_htmltag', $attr);
  9613. $TCompiledAttr = array();
  9614. foreach ($attr as $key => $value) {
  9615. $TCompiledAttr[] = $key.'="'.$value.'"';
  9616. }
  9617. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9618. $tag = (empty($attr['href']) ? 'span' : 'a');
  9619. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9620. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9621. if (!empty($params['forcenohideoftext'])) {
  9622. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9623. }
  9624. $button .= '</'.$tag.'>';
  9625. return $button;
  9626. }
  9627. /**
  9628. * Get an array with properties of an element.
  9629. * Called by fetchObjectByElement.
  9630. *
  9631. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9632. * @return array (module, classpath, element, subelement, classfile, classname)
  9633. */
  9634. function getElementProperties($element_type)
  9635. {
  9636. $regs = array();
  9637. $classfile = $classname = $classpath = '';
  9638. // Parse element/subelement (ex: project_task)
  9639. $module = $element_type;
  9640. $element = $element_type;
  9641. $subelement = $element_type;
  9642. // If we ask an resource form external module (instead of default path)
  9643. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9644. $element = $subelement = $regs[1];
  9645. $module = $regs[2];
  9646. }
  9647. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9648. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9649. $module = $element = $regs[1];
  9650. $subelement = $regs[2];
  9651. }
  9652. // For compat
  9653. if ($element_type == "action") {
  9654. $classpath = 'comm/action/class';
  9655. $subelement = 'Actioncomm';
  9656. $module = 'agenda';
  9657. }
  9658. // To work with non standard path
  9659. if ($element_type == 'facture' || $element_type == 'invoice') {
  9660. $classpath = 'compta/facture/class';
  9661. $module = 'facture';
  9662. $subelement = 'facture';
  9663. }
  9664. if ($element_type == 'commande' || $element_type == 'order') {
  9665. $classpath = 'commande/class';
  9666. $module = 'commande';
  9667. $subelement = 'commande';
  9668. }
  9669. if ($element_type == 'propal') {
  9670. $classpath = 'comm/propal/class';
  9671. }
  9672. if ($element_type == 'supplier_proposal') {
  9673. $classpath = 'supplier_proposal/class';
  9674. }
  9675. if ($element_type == 'shipping') {
  9676. $classpath = 'expedition/class';
  9677. $subelement = 'expedition';
  9678. $module = 'expedition_bon';
  9679. }
  9680. if ($element_type == 'delivery') {
  9681. $classpath = 'delivery/class';
  9682. $subelement = 'delivery';
  9683. $module = 'delivery_note';
  9684. }
  9685. if ($element_type == 'contract') {
  9686. $classpath = 'contrat/class';
  9687. $module = 'contrat';
  9688. $subelement = 'contrat';
  9689. }
  9690. if ($element_type == 'member') {
  9691. $classpath = 'adherents/class';
  9692. $module = 'adherent';
  9693. $subelement = 'adherent';
  9694. }
  9695. if ($element_type == 'cabinetmed_cons') {
  9696. $classpath = 'cabinetmed/class';
  9697. $module = 'cabinetmed';
  9698. $subelement = 'cabinetmedcons';
  9699. }
  9700. if ($element_type == 'fichinter') {
  9701. $classpath = 'fichinter/class';
  9702. $module = 'ficheinter';
  9703. $subelement = 'fichinter';
  9704. }
  9705. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9706. $classpath = 'resource/class';
  9707. $module = 'resource';
  9708. $subelement = 'dolresource';
  9709. }
  9710. if ($element_type == 'propaldet') {
  9711. $classpath = 'comm/propal/class';
  9712. $module = 'propal';
  9713. $subelement = 'propaleligne';
  9714. }
  9715. if ($element_type == 'order_supplier') {
  9716. $classpath = 'fourn/class';
  9717. $module = 'fournisseur';
  9718. $subelement = 'commandefournisseur';
  9719. $classfile = 'fournisseur.commande';
  9720. }
  9721. if ($element_type == 'invoice_supplier') {
  9722. $classpath = 'fourn/class';
  9723. $module = 'fournisseur';
  9724. $subelement = 'facturefournisseur';
  9725. $classfile = 'fournisseur.facture';
  9726. }
  9727. if ($element_type == "service") {
  9728. $classpath = 'product/class';
  9729. $subelement = 'product';
  9730. }
  9731. if (empty($classfile)) {
  9732. $classfile = strtolower($subelement);
  9733. }
  9734. if (empty($classname)) {
  9735. $classname = ucfirst($subelement);
  9736. }
  9737. if (empty($classpath)) {
  9738. $classpath = $module.'/class';
  9739. }
  9740. $element_properties = array(
  9741. 'module' => $module,
  9742. 'classpath' => $classpath,
  9743. 'element' => $element,
  9744. 'subelement' => $subelement,
  9745. 'classfile' => $classfile,
  9746. 'classname' => $classname
  9747. );
  9748. return $element_properties;
  9749. }
  9750. /**
  9751. * Fetch an object from its id and element_type
  9752. * Inclusion of classes is automatic
  9753. *
  9754. * @param int $element_id Element id
  9755. * @param string $element_type Element type
  9756. * @param string $element_ref Element ref (Use this or element_id but not both)
  9757. * @return int|object object || 0 || -1 if error
  9758. */
  9759. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9760. {
  9761. global $conf, $db;
  9762. $element_prop = getElementProperties($element_type);
  9763. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9764. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9765. $objecttmp = new $element_prop['classname']($db);
  9766. $ret = $objecttmp->fetch($element_id, $element_ref);
  9767. if ($ret >= 0) {
  9768. return $objecttmp;
  9769. }
  9770. }
  9771. return 0;
  9772. }
  9773. /**
  9774. * Return if a file can contains executable content
  9775. *
  9776. * @param string $filename File name to test
  9777. * @return boolean True if yes, False if no
  9778. */
  9779. function isAFileWithExecutableContent($filename)
  9780. {
  9781. 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)) {
  9782. return true;
  9783. }
  9784. return false;
  9785. }
  9786. /**
  9787. * Return the value of token currently saved into session with name 'newtoken'.
  9788. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9789. *
  9790. * @return string
  9791. */
  9792. function newToken()
  9793. {
  9794. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  9795. }
  9796. /**
  9797. * Return the value of token currently saved into session with name 'token'.
  9798. * For ajax call, you must use this token as a parameter of the call into the js calling script (the called ajax php page must also set constant NOTOKENRENEWAL).
  9799. *
  9800. * @return string
  9801. */
  9802. function currentToken()
  9803. {
  9804. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  9805. }
  9806. /**
  9807. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9808. *
  9809. * @param string $header The first left header of the table (automatic translated)
  9810. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9811. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9812. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9813. * @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"
  9814. * @return void
  9815. *
  9816. * @see finishSimpleTable()
  9817. */
  9818. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9819. {
  9820. global $langs;
  9821. print '<div class="div-table-responsive-no-min">';
  9822. print '<table class="noborder centpercent">';
  9823. print '<tr class="liste_titre">';
  9824. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9825. print $langs->trans($header);
  9826. // extra space between the first header and the number
  9827. if ($number > -1) {
  9828. print ' ';
  9829. }
  9830. if (!empty($link)) {
  9831. if (!empty($arguments)) {
  9832. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9833. } else {
  9834. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9835. }
  9836. }
  9837. if ($number > -1) {
  9838. print '<span class="badge">'.$number.'</span>';
  9839. }
  9840. if (!empty($link)) {
  9841. print '</a>';
  9842. }
  9843. print '</th>';
  9844. if ($number < 0 && !empty($link)) {
  9845. print '<th class="right">';
  9846. if (!empty($arguments)) {
  9847. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9848. } else {
  9849. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9850. }
  9851. print $langs->trans("FullList");
  9852. print '</a>';
  9853. print '</th>';
  9854. }
  9855. print '</tr>';
  9856. }
  9857. /**
  9858. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9859. *
  9860. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9861. * @return void
  9862. *
  9863. * @see startSimpleTable()
  9864. */
  9865. function finishSimpleTable($addLineBreak = false)
  9866. {
  9867. print '</table>';
  9868. print '</div>';
  9869. if ($addLineBreak) {
  9870. print '<br>';
  9871. }
  9872. }
  9873. /**
  9874. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9875. *
  9876. * @param integer $tableColumnCount The complete count columns of the table
  9877. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9878. * @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)
  9879. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9880. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9881. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9882. * @return void
  9883. */
  9884. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9885. {
  9886. global $langs;
  9887. if ($num === 0) {
  9888. print '<tr class="oddeven">';
  9889. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9890. print '</tr>';
  9891. return;
  9892. }
  9893. if ($nbofloop === 0) {
  9894. // don't show a summary line
  9895. return;
  9896. }
  9897. if ($num === 0) {
  9898. $colspan = $tableColumnCount;
  9899. } elseif ($num > $nbofloop) {
  9900. $colspan = $tableColumnCount;
  9901. } else {
  9902. $colspan = $tableColumnCount - 1;
  9903. }
  9904. if ($extraRightColumn) {
  9905. $colspan--;
  9906. }
  9907. print '<tr class="liste_total">';
  9908. if ($nbofloop > 0 && $num > $nbofloop) {
  9909. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9910. } else {
  9911. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  9912. print '<td class="right" width="100">'.price($total).'</td>';
  9913. }
  9914. if ($extraRightColumn) {
  9915. print '<td></td>';
  9916. }
  9917. print '</tr>';
  9918. }
  9919. /**
  9920. * Return a file on output using a low memory. It can return very large files with no need of memory.
  9921. * WARNING: This close output buffers.
  9922. *
  9923. * @param string $fullpath_original_file_osencoded Full path of file to return.
  9924. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  9925. * @return void
  9926. */
  9927. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  9928. {
  9929. global $conf;
  9930. if ($method == -1) {
  9931. $method = 0;
  9932. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  9933. $method = 1;
  9934. }
  9935. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  9936. $method = 2;
  9937. }
  9938. }
  9939. // Be sure we don't have output buffering enabled to have readfile working correctly
  9940. while (ob_get_level()) {
  9941. ob_end_flush();
  9942. }
  9943. // Solution 0
  9944. if ($method == 0) {
  9945. readfile($fullpath_original_file_osencoded);
  9946. } elseif ($method == 1) {
  9947. // Solution 1
  9948. $handle = fopen($fullpath_original_file_osencoded, "rb");
  9949. while (!feof($handle)) {
  9950. print fread($handle, 8192);
  9951. }
  9952. fclose($handle);
  9953. } elseif ($method == 2) {
  9954. // Solution 2
  9955. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  9956. $handle2 = fopen("php://output", "wb");
  9957. stream_copy_to_stream($handle1, $handle2);
  9958. fclose($handle1);
  9959. fclose($handle2);
  9960. }
  9961. }
  9962. /**
  9963. * Create a button to copy $valuetocopy in the clipboard.
  9964. * Code that handle the click is inside lib_foot.jsp.php.
  9965. *
  9966. * @param string $valuetocopy The value to print
  9967. * @param int $showonlyonhover Show the copy-paste button only on hover
  9968. * @param string $texttoshow Replace the value to show with this text
  9969. * @return string The string to print for the button
  9970. */
  9971. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  9972. {
  9973. /*
  9974. global $conf;
  9975. if (!empty($conf->dol_no_mouse_hover)) {
  9976. $showonlyonhover = 0;
  9977. }*/
  9978. $tag = 'span'; // Using div does not work when using the js copy code.
  9979. if ($texttoshow) {
  9980. $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>';
  9981. } else {
  9982. $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>';
  9983. }
  9984. return $result;
  9985. }
  9986. /**
  9987. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  9988. *
  9989. * @param string $stringtodecode String to decode (json or serialize coded)
  9990. * @return mixed The decoded object.
  9991. */
  9992. function jsonOrUnserialize($stringtodecode)
  9993. {
  9994. $result = json_decode($stringtodecode);
  9995. if ($result === null) {
  9996. $result = unserialize($stringtodecode);
  9997. }
  9998. return $result;
  9999. }
  10000. /**
  10001. * Return if a $sqlfilters parameter is valid and will pass the preg_replace_callback() to replace Generic filter string with SQL filter string
  10002. * Example of usage:
  10003. * if ($sqlfilters) {
  10004. * $errormessage = '';
  10005. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  10006. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  10007. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  10008. * }
  10009. * }
  10010. *
  10011. * @param string $sqlfilters sqlfilter string
  10012. * @param string $error Error message
  10013. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  10014. */
  10015. function dolCheckFilters($sqlfilters, &$error = '')
  10016. {
  10017. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  10018. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  10019. $tmp = $sqlfilters;
  10020. $i = 0; $nb = strlen($tmp);
  10021. $counter = 0;
  10022. while ($i < $nb) {
  10023. if ($tmp[$i] == '(') {
  10024. $counter++;
  10025. }
  10026. if ($tmp[$i] == ')') {
  10027. $counter--;
  10028. }
  10029. if ($counter < 0) {
  10030. $error = "Bad sqlfilters=".$sqlfilters;
  10031. dol_syslog($error, LOG_WARNING);
  10032. return false;
  10033. }
  10034. $i++;
  10035. }
  10036. return true;
  10037. }
  10038. /**
  10039. * Function to forge a SQL criteria from a Generic filter string.
  10040. * Example of usage:
  10041. * if ($sqlfilters) {
  10042. * $errormessage = '';
  10043. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  10044. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  10045. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  10046. * }
  10047. * }
  10048. *
  10049. * @param array $matches Array of found string by regex search.
  10050. * 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"
  10051. * @return string Forged criteria. Example: "t.field like 'abc%'"
  10052. */
  10053. function dolForgeCriteriaCallback($matches)
  10054. {
  10055. global $db;
  10056. dol_syslog("Convert matches ".$matches[1]);
  10057. if (empty($matches[1])) {
  10058. return '';
  10059. }
  10060. $tmp = explode(':', $matches[1], 3);
  10061. if (count($tmp) < 3) {
  10062. return '';
  10063. }
  10064. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  10065. $operator = strtoupper(preg_replace('/[^a-z<>=]/i', '', trim($tmp[1])));
  10066. if ($operator == 'NOTLIKE') {
  10067. $operator = 'NOT LIKE';
  10068. }
  10069. $tmpescaped = trim($tmp[2]);
  10070. $regbis = array();
  10071. if ($operator == 'IN') {
  10072. $tmpescaped = "(".$db->sanitize($tmpescaped, 1).")";
  10073. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  10074. $tmpescaped = "'".$db->escape($regbis[1])."'";
  10075. } else {
  10076. $tmpescaped = $db->sanitize($db->escape($tmpescaped));
  10077. }
  10078. return $db->escape($operand).' '.$db->escape($operator)." ".$tmpescaped;
  10079. }