functions.lib.php 418 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. *
  21. * This program is free software; you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation; either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  33. * or see https://www.gnu.org/
  34. */
  35. /**
  36. * \file htdocs/core/lib/functions.lib.php
  37. * \brief A set of functions for Dolibarr
  38. * This file contains all frequently used functions.
  39. */
  40. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  41. /**
  42. * Return dolibarr global constant string value
  43. * @param string $key key to return value, return '' if not set
  44. * @return string
  45. */
  46. function getDolGlobalString($key)
  47. {
  48. global $conf;
  49. // return $conf->global->$key ?? '';
  50. return (string) (empty($conf->global->$key) ? '' : $conf->global->$key);
  51. }
  52. /**
  53. * Return dolibarr global constant int value
  54. * @param string $key key to return value, return 0 if not set
  55. * @return int
  56. */
  57. function getDolGlobalInt($key)
  58. {
  59. global $conf;
  60. // return $conf->global->$key ?? 0;
  61. return (int) (empty($conf->global->$key) ? 0 : $conf->global->$key);
  62. }
  63. /**
  64. * Return a DoliDB instance (database handler).
  65. *
  66. * @param string $type Type of database (mysql, pgsql...)
  67. * @param string $host Address of database server
  68. * @param string $user Authorized username
  69. * @param string $pass Password
  70. * @param string $name Name of database
  71. * @param int $port Port of database server
  72. * @return DoliDB A DoliDB instance
  73. */
  74. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  75. {
  76. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  77. $class = 'DoliDB'.ucfirst($type);
  78. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  79. return $dolidb;
  80. }
  81. /**
  82. * Get list of entity id to use.
  83. *
  84. * @param string $element Current element
  85. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  86. * 'product', 'productprice', 'stock', 'bom', 'mo',
  87. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  88. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  89. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  90. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  91. * 'email_template', 'event', 'donation'
  92. * 'c_paiement', 'c_payment_term', ...
  93. * @param int $shared 0=Return id of current entity only,
  94. * 1=Return id of current entity + shared entities (default)
  95. * @param object $currentobject Current object if needed
  96. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  97. */
  98. function getEntity($element, $shared = 1, $currentobject = null)
  99. {
  100. global $conf, $mc;
  101. // fix different element names (France to English)
  102. switch ($element) {
  103. case 'contrat':
  104. $element = 'contract';
  105. break; // "/contrat/class/contrat.class.php"
  106. case 'order_supplier':
  107. $element = 'supplier_order';
  108. break; // "/fourn/class/fournisseur.commande.class.php"
  109. }
  110. if (is_object($mc)) {
  111. return $mc->getEntity($element, $shared, $currentobject);
  112. } else {
  113. $out = '';
  114. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  115. if (in_array($element, $addzero)) {
  116. $out .= '0,';
  117. }
  118. $out .= ((int) $conf->entity);
  119. return $out;
  120. }
  121. }
  122. /**
  123. * Set entity id to use when to create an object
  124. *
  125. * @param object $currentobject Current object
  126. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  127. */
  128. function setEntity($currentobject)
  129. {
  130. global $conf, $mc;
  131. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  132. return $mc->setEntity($currentobject);
  133. } else {
  134. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  135. }
  136. }
  137. /**
  138. * Return if string has a name dedicated to store a secret
  139. *
  140. * @param string $keyname Name of key to test
  141. * @return boolean True if key is used to store a secret
  142. */
  143. function isASecretKey($keyname)
  144. {
  145. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  146. }
  147. /**
  148. * Return information about user browser
  149. *
  150. * Returns array with the following format:
  151. * array(
  152. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  153. * 'browserversion' => Browser version. Empty if unknown
  154. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  155. * 'layout' => (tablet|phone|classic)
  156. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  157. * 'tablet' => true/false
  158. * )
  159. *
  160. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  161. * @return array Check function documentation
  162. */
  163. function getBrowserInfo($user_agent)
  164. {
  165. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  166. $name = 'unknown';
  167. $version = '';
  168. $os = 'unknown';
  169. $phone = '';
  170. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  171. $detectmobile = new Mobile_Detect(null, $user_agent);
  172. $tablet = $detectmobile->isTablet();
  173. if ($detectmobile->isMobile()) {
  174. $phone = 'unknown';
  175. // If phone/smartphone, we set phone os name.
  176. if ($detectmobile->is('AndroidOS')) {
  177. $os = $phone = 'android';
  178. } elseif ($detectmobile->is('BlackBerryOS')) {
  179. $os = $phone = 'blackberry';
  180. } elseif ($detectmobile->is('iOS')) {
  181. $os = 'ios';
  182. $phone = 'iphone';
  183. } elseif ($detectmobile->is('PalmOS')) {
  184. $os = $phone = 'palm';
  185. } elseif ($detectmobile->is('SymbianOS')) {
  186. $os = 'symbian';
  187. } elseif ($detectmobile->is('webOS')) {
  188. $os = 'webos';
  189. } elseif ($detectmobile->is('MaemoOS')) {
  190. $os = 'maemo';
  191. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  192. $os = 'windows';
  193. }
  194. }
  195. // OS
  196. if (preg_match('/linux/i', $user_agent)) {
  197. $os = 'linux';
  198. } elseif (preg_match('/macintosh/i', $user_agent)) {
  199. $os = 'macintosh';
  200. } elseif (preg_match('/windows/i', $user_agent)) {
  201. $os = 'windows';
  202. }
  203. // Name
  204. $reg = array();
  205. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  206. $name = 'firefox';
  207. $version = $reg[2];
  208. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  209. $name = 'edge';
  210. $version = $reg[2];
  211. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  212. $name = 'chrome';
  213. $version = $reg[2];
  214. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  215. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  216. $name = 'chrome';
  217. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  218. $name = 'iceweasel';
  219. } elseif (preg_match('/epiphany/i', $user_agent)) {
  220. $name = 'epiphany';
  221. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  222. $name = 'safari';
  223. $version = $reg[2];
  224. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  225. // Safari is often present in string for mobile but its not.
  226. $name = 'opera';
  227. $version = $reg[2];
  228. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  229. $name = 'ie';
  230. $version = end($reg);
  231. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  232. // MS products at end
  233. $name = 'ie';
  234. $version = end($reg);
  235. } elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  236. // MS products at end
  237. $name = 'lynxlinks';
  238. $version = $reg[4];
  239. }
  240. if ($tablet) {
  241. $layout = 'tablet';
  242. } elseif ($phone) {
  243. $layout = 'phone';
  244. } else {
  245. $layout = 'classic';
  246. }
  247. return array(
  248. 'browsername' => $name,
  249. 'browserversion' => $version,
  250. 'browseros' => $os,
  251. 'layout' => $layout,
  252. 'phone' => $phone,
  253. 'tablet' => $tablet
  254. );
  255. }
  256. /**
  257. * Function called at end of web php process
  258. *
  259. * @return void
  260. */
  261. function dol_shutdown()
  262. {
  263. global $conf, $user, $langs, $db;
  264. $disconnectdone = false;
  265. $depth = 0;
  266. if (is_object($db) && !empty($db->connected)) {
  267. $depth = $db->transaction_opened;
  268. $disconnectdone = $db->close();
  269. }
  270. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  271. }
  272. /**
  273. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  274. *
  275. * @param string $paramname Name or parameter to test
  276. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  277. */
  278. function GETPOSTISSET($paramname)
  279. {
  280. $isset = false;
  281. $relativepathstring = $_SERVER["PHP_SELF"];
  282. // Clean $relativepathstring
  283. if (constant('DOL_URL_ROOT')) {
  284. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  285. }
  286. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  287. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  288. //var_dump($relativepathstring);
  289. //var_dump($user->default_values);
  290. // Code for search criteria persistence.
  291. // Retrieve values if restore_lastsearch_values
  292. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  293. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  294. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  295. if (is_array($tmp)) {
  296. foreach ($tmp as $key => $val) {
  297. if ($key == $paramname) { // We are on the requested parameter
  298. $isset = true;
  299. break;
  300. }
  301. }
  302. }
  303. }
  304. // If there is saved contextpage, page or limit
  305. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  306. $isset = true;
  307. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  308. $isset = true;
  309. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  310. $isset = true;
  311. }
  312. } else {
  313. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  314. }
  315. return $isset;
  316. }
  317. /**
  318. * Return value of a param into GET or POST supervariable.
  319. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  320. * Note: The property $user->default_values is loaded by main.php when loading the user.
  321. *
  322. * @param string $paramname Name of parameter to found
  323. * @param string $check Type of check
  324. * ''=no check (deprecated)
  325. * 'none'=no check (only for param that should have very rich content)
  326. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  327. * 'int'=check it's numeric (integer or float)
  328. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  329. * 'alpha'=Same than alphanohtml since v13
  330. * 'alphawithlgt'=alpha with lgt
  331. * 'alphanohtml'=check there is no html content and no " and no ../
  332. * 'aZ'=check it's a-z only
  333. * 'aZ09'=check it's simple alpha string (recommended for keys)
  334. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  335. * 'nohtml'=check there is no html content and no " and no ../
  336. * 'restricthtml'=check html content is restricted to some tags only
  337. * 'custom'= custom filter specify $filter and $options)
  338. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  339. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  340. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  341. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  342. * @return string|array Value found (string or array), or '' if check fails
  343. */
  344. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  345. {
  346. global $mysoc, $user, $conf;
  347. if (empty($paramname)) {
  348. return 'BadFirstParameterForGETPOST';
  349. }
  350. if (empty($check)) {
  351. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  352. // Enable this line to know who call the GETPOST with '' $check parameter.
  353. //var_dump(debug_backtrace()[0]);
  354. }
  355. if (empty($method)) {
  356. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  357. } elseif ($method == 1) {
  358. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  359. } elseif ($method == 2) {
  360. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  361. } elseif ($method == 3) {
  362. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  363. } else {
  364. return 'BadThirdParameterForGETPOST';
  365. }
  366. if (empty($method) || $method == 3 || $method == 4) {
  367. $relativepathstring = $_SERVER["PHP_SELF"];
  368. // Clean $relativepathstring
  369. if (constant('DOL_URL_ROOT')) {
  370. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  371. }
  372. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  373. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  374. //var_dump($relativepathstring);
  375. //var_dump($user->default_values);
  376. // Code for search criteria persistence.
  377. // Retrieve values if restore_lastsearch_values
  378. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  379. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  380. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  381. if (is_array($tmp)) {
  382. foreach ($tmp as $key => $val) {
  383. if ($key == $paramname) { // We are on the requested parameter
  384. $out = $val;
  385. break;
  386. }
  387. }
  388. }
  389. }
  390. // If there is saved contextpage, page or limit
  391. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  392. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  393. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  394. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  395. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  396. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  397. }
  398. } elseif (!isset($_GET['sortfield'])) {
  399. // Else, retrieve default values if we are not doing a sort
  400. // 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
  401. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  402. // Search default value from $object->field
  403. global $object;
  404. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  405. $out = $object->fields[$paramname]['default'];
  406. }
  407. }
  408. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  409. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  410. // Now search in setup to overwrite default values
  411. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  412. if (isset($user->default_values[$relativepathstring]['createform'])) {
  413. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  414. $qualified = 0;
  415. if ($defkey != '_noquery_') {
  416. $tmpqueryarraytohave = explode('&', $defkey);
  417. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  418. $foundintru = 0;
  419. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  420. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  421. $foundintru = 1;
  422. }
  423. }
  424. if (!$foundintru) {
  425. $qualified = 1;
  426. }
  427. //var_dump($defkey.'-'.$qualified);
  428. } else {
  429. $qualified = 1;
  430. }
  431. if ($qualified) {
  432. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  433. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  434. break;
  435. }
  436. }
  437. }
  438. }
  439. }
  440. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  441. // Management of default search_filters and sort order
  442. if (!empty($user->default_values)) {
  443. // $user->default_values defined from menu 'Setup - Default values'
  444. //var_dump($user->default_values[$relativepathstring]);
  445. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  446. // Sorted on which fields ? ASC or DESC ?
  447. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  448. // Even if paramname is sortfield, data are stored into ['sortorder...']
  449. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  450. $qualified = 0;
  451. if ($defkey != '_noquery_') {
  452. $tmpqueryarraytohave = explode('&', $defkey);
  453. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  454. $foundintru = 0;
  455. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  456. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  457. $foundintru = 1;
  458. }
  459. }
  460. if (!$foundintru) {
  461. $qualified = 1;
  462. }
  463. //var_dump($defkey.'-'.$qualified);
  464. } else {
  465. $qualified = 1;
  466. }
  467. if ($qualified) {
  468. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  469. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  470. if ($out) {
  471. $out .= ', ';
  472. }
  473. if ($paramname == 'sortfield') {
  474. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  475. }
  476. if ($paramname == 'sortorder') {
  477. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  478. }
  479. }
  480. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  481. }
  482. }
  483. }
  484. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  485. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  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. // We must keep $_POST and $_GET here
  505. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  506. // We made a search from quick search menu, do we still use default filter ?
  507. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  508. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  509. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  510. }
  511. } else {
  512. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  513. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  514. }
  515. break;
  516. }
  517. }
  518. }
  519. }
  520. }
  521. }
  522. }
  523. }
  524. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  525. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  526. // 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.
  527. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  528. $reg = array();
  529. $maxloop = 20;
  530. $loopnb = 0; // Protection against infinite loop
  531. 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.
  532. $loopnb++;
  533. $newout = '';
  534. if ($reg[1] == 'DAY') {
  535. $tmp = dol_getdate(dol_now(), true);
  536. $newout = $tmp['mday'];
  537. } elseif ($reg[1] == 'MONTH') {
  538. $tmp = dol_getdate(dol_now(), true);
  539. $newout = $tmp['mon'];
  540. } elseif ($reg[1] == 'YEAR') {
  541. $tmp = dol_getdate(dol_now(), true);
  542. $newout = $tmp['year'];
  543. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  544. $tmp = dol_getdate(dol_now(), true);
  545. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  546. $newout = $tmp2['day'];
  547. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  548. $tmp = dol_getdate(dol_now(), true);
  549. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  550. $newout = $tmp2['month'];
  551. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  552. $tmp = dol_getdate(dol_now(), true);
  553. $newout = ($tmp['year'] - 1);
  554. } elseif ($reg[1] == 'NEXT_DAY') {
  555. $tmp = dol_getdate(dol_now(), true);
  556. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  557. $newout = $tmp2['day'];
  558. } elseif ($reg[1] == 'NEXT_MONTH') {
  559. $tmp = dol_getdate(dol_now(), true);
  560. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  561. $newout = $tmp2['month'];
  562. } elseif ($reg[1] == 'NEXT_YEAR') {
  563. $tmp = dol_getdate(dol_now(), true);
  564. $newout = ($tmp['year'] + 1);
  565. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  566. $newout = $mysoc->country_id;
  567. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  568. $newout = $user->id;
  569. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  570. $newout = $user->fk_user;
  571. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  572. $newout = $conf->entity;
  573. } else {
  574. $newout = ''; // Key not found, we replace with empty string
  575. }
  576. //var_dump('__'.$reg[1].'__ -> '.$newout);
  577. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  578. }
  579. }
  580. // Check rule
  581. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09'
  582. if (!is_array($out) || empty($out)) {
  583. $out = array();
  584. } else {
  585. $tmparray = explode(':', $check);
  586. if (!empty($tmparray[1])) {
  587. $tmpcheck = $tmparray[1];
  588. } else {
  589. $tmpcheck = 'alphanohtml';
  590. }
  591. foreach ($out as $outkey => $outval) {
  592. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  593. }
  594. }
  595. } else {
  596. $out = checkVal($out, $check, $filter, $options);
  597. }
  598. // Sanitizing for special parameters.
  599. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL.
  600. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  601. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  602. $out = str_replace(array(':', ';', '@'), '', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  603. do {
  604. $oldstringtoclean = $out;
  605. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  606. } while ($oldstringtoclean != $out);
  607. $out = preg_replace(array('/^[a-z]*\/\/+/i'), '', $out); // We remove schema*// to remove external URL
  608. }
  609. // Code for search criteria persistence.
  610. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  611. if (empty($method) || $method == 3 || $method == 4) {
  612. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  613. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  614. // We save search key only if $out not empty that means:
  615. // - posted value not empty, or
  616. // - 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).
  617. if ($out != '') { // $out = '0' or 'abc', it is a search criteria to keep
  618. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  619. }
  620. }
  621. }
  622. return $out;
  623. }
  624. /**
  625. * Return value of a param into GET or POST supervariable.
  626. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  627. * Note: The property $user->default_values is loaded by main.php when loading the user.
  628. *
  629. * @param string $paramname Name of parameter to found
  630. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  631. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  632. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  633. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  634. * @return int Value found (int)
  635. */
  636. function GETPOSTINT($paramname, $method = 0, $filter = null, $options = null, $noreplace = 0)
  637. {
  638. return (int) GETPOST($paramname, 'int', $method, $filter, $options, $noreplace);
  639. }
  640. /**
  641. * Return a value after checking on a rule. A sanitization may also have been done.
  642. *
  643. * @param string $out Value to check/clear.
  644. * @param string $check Type of check/sanitizing
  645. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  646. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  647. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  648. */
  649. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  650. {
  651. global $conf;
  652. // Check is done after replacement
  653. switch ($check) {
  654. case 'none':
  655. break;
  656. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  657. if (!is_numeric($out)) {
  658. $out = '';
  659. }
  660. break;
  661. case 'intcomma':
  662. if (preg_match('/[^0-9,-]+/i', $out)) {
  663. $out = '';
  664. }
  665. break;
  666. case 'san_alpha':
  667. $out = filter_var($out, FILTER_SANITIZE_STRING);
  668. break;
  669. case 'email':
  670. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  671. break;
  672. case 'aZ':
  673. if (!is_array($out)) {
  674. $out = trim($out);
  675. if (preg_match('/[^a-z]+/i', $out)) {
  676. $out = '';
  677. }
  678. }
  679. break;
  680. case 'aZ09':
  681. if (!is_array($out)) {
  682. $out = trim($out);
  683. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  684. $out = '';
  685. }
  686. }
  687. break;
  688. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  689. if (!is_array($out)) {
  690. $out = trim($out);
  691. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  692. $out = '';
  693. }
  694. }
  695. break;
  696. case 'nohtml': // No html
  697. $out = dol_string_nohtmltag($out, 0);
  698. break;
  699. case 'alpha': // No html and no ../ and "
  700. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  701. if (!is_array($out)) {
  702. $out = trim($out);
  703. do {
  704. $oldstringtoclean = $out;
  705. // Remove html tags
  706. $out = dol_string_nohtmltag($out, 0);
  707. // Remove also other dangerous string sequences
  708. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  709. // '../' or '..\' is dangerous because it allows dir transversals
  710. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  711. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  712. } while ($oldstringtoclean != $out);
  713. // keep lines feed
  714. }
  715. break;
  716. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>"
  717. if (!is_array($out)) {
  718. $out = trim($out);
  719. do {
  720. $oldstringtoclean = $out;
  721. // Remove html tags
  722. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  723. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  724. // '../' or '..\' is dangerous because it allows dir transversals
  725. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  726. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  727. } while ($oldstringtoclean != $out);
  728. }
  729. break;
  730. case 'restricthtml': // Recommended for most html textarea
  731. case 'restricthtmlallowunvalid':
  732. do {
  733. $oldstringtoclean = $out;
  734. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  735. try {
  736. $dom = new DOMDocument;
  737. // Add a trick to solve pb with text without parent tag
  738. // like '<h1>Foo</h1><p>bar</p>' that ends up with '<h1>Foo<p>bar</p></h1>'
  739. // like 'abc' that ends up with '<p>abc</p>'
  740. $out = '<div class="tricktoremove">'.$out.'</div>';
  741. $dom->loadHTML($out, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  742. $out = trim($dom->saveHTML());
  743. // Remove the trick added to solve pb with text without parent tag
  744. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  745. $out = preg_replace('/<\/div>$/', '', $out);
  746. } catch (Exception $e) {
  747. //print $e->getMessage();
  748. return 'InvalidHTMLString';
  749. }
  750. }
  751. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  752. // encoded using text entities) so we can then exclude all numeric entities.
  753. $out = preg_replace('/&#39;/i', '&apos;', $out);
  754. // 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).
  755. // 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
  756. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  757. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', 'realCharForNumericEntities', $out);
  758. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  759. $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'.
  760. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  761. // We should also exclude non expected attributes
  762. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  763. // 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.
  764. $out = trim(dol_string_onlythesehtmlattributes($out));
  765. }
  766. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  767. $out = preg_replace('/&apos;/i', "&#39;", $out);
  768. } while ($oldstringtoclean != $out);
  769. break;
  770. case 'custom':
  771. if (empty($filter)) {
  772. return 'BadFourthParameterForGETPOST';
  773. }
  774. $out = filter_var($out, $filter, $options);
  775. break;
  776. }
  777. return $out;
  778. }
  779. if (!function_exists('dol_getprefix')) {
  780. /**
  781. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  782. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  783. * or two instances in same virtual servers.
  784. *
  785. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  786. * @return string A calculated prefix
  787. */
  788. function dol_getprefix($mode = '')
  789. {
  790. // If prefix is for email (we need to have $conf alreayd loaded for this case)
  791. if ($mode == 'email') {
  792. global $conf;
  793. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  794. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  795. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  796. } elseif (isset($_SERVER["SERVER_NAME"])) {
  797. return $_SERVER["SERVER_NAME"];
  798. }
  799. }
  800. // The recommended value (may be not defined for old versions)
  801. if (!empty($conf->file->instance_unique_id)) {
  802. return $conf->file->instance_unique_id;
  803. }
  804. // For backward compatibility
  805. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  806. }
  807. // If prefix is for session (no need to have $conf loaded)
  808. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  809. $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
  810. // The recommended value (may be not defined for old versions)
  811. if (!empty($tmp_instance_unique_id)) {
  812. return $tmp_instance_unique_id;
  813. }
  814. // For backward compatibility
  815. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  816. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  817. }
  818. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  819. }
  820. }
  821. /**
  822. * Make an include_once using default root and alternate root if it fails.
  823. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  824. * To link to a module file from a module file, use include './mymodulefile';
  825. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  826. *
  827. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  828. * @param string $classname Class name (deprecated)
  829. * @return bool True if load is a success, False if it fails
  830. */
  831. function dol_include_once($relpath, $classname = '')
  832. {
  833. 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']
  834. $fullpath = dol_buildpath($relpath);
  835. if (!file_exists($fullpath)) {
  836. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  837. return false;
  838. }
  839. if (!empty($classname) && !class_exists($classname)) {
  840. return include $fullpath;
  841. } else {
  842. return include_once $fullpath;
  843. }
  844. }
  845. /**
  846. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  847. *
  848. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  849. * @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)
  850. * @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)
  851. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  852. * 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
  853. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  854. */
  855. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  856. {
  857. global $conf;
  858. $path = preg_replace('/^\//', '', $path);
  859. if (empty($type)) { // For a filesystem path
  860. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  861. if (is_array($conf->file->dol_document_root)) {
  862. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  863. if ($key == 'main') {
  864. continue;
  865. }
  866. if (file_exists($dirroot.'/'.$path)) {
  867. $res = $dirroot.'/'.$path;
  868. return $res;
  869. }
  870. }
  871. }
  872. if ($returnemptyifnotfound) {
  873. // Not found into alternate dir
  874. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  875. return '';
  876. }
  877. }
  878. } else {
  879. // For an url path
  880. // We try to get local path of file on filesystem from url
  881. // Note that trying to know if a file on disk exist by forging path on disk from url
  882. // works only for some web server and some setup. This is bugged when
  883. // using proxy, rewriting, virtual path, etc...
  884. $res = '';
  885. if ($type == 1) {
  886. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  887. }
  888. if ($type == 2) {
  889. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  890. }
  891. if ($type == 3) {
  892. $res = DOL_URL_ROOT.'/'.$path;
  893. }
  894. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  895. if ($key == 'main') {
  896. if ($type == 3) {
  897. global $dolibarr_main_url_root;
  898. // Define $urlwithroot
  899. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  900. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  901. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  902. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  903. }
  904. continue;
  905. }
  906. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  907. if (!empty($regs[1])) {
  908. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  909. if (file_exists($dirroot.'/'.$regs[1])) {
  910. if ($type == 1) {
  911. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  912. }
  913. if ($type == 2) {
  914. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  915. }
  916. if ($type == 3) {
  917. global $dolibarr_main_url_root;
  918. // Define $urlwithroot
  919. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  920. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  921. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  922. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax
  923. }
  924. break;
  925. }
  926. }
  927. }
  928. }
  929. return $res;
  930. }
  931. /**
  932. * Create a clone of instance of object (new instance with same value for properties)
  933. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  934. * 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.
  935. *
  936. * @param object $object Object to clone
  937. * @param int $native 0=Full isolation method, 1=Native PHP method
  938. * @return object Clone object
  939. * @see https://php.net/manual/language.oop5.cloning.php
  940. */
  941. function dol_clone($object, $native = 0)
  942. {
  943. if (empty($native)) {
  944. $myclone = unserialize(serialize($object)); // serialize then unserialize is hack to be sure to have a new object for all fields
  945. } else {
  946. $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)
  947. }
  948. return $myclone;
  949. }
  950. /**
  951. * Optimize a size for some browsers (phone, smarphone, ...)
  952. *
  953. * @param int $size Size we want
  954. * @param string $type Type of optimizing:
  955. * '' = function used to define a size for truncation
  956. * 'width' = function is used to define a width
  957. * @return int New size after optimizing
  958. */
  959. function dol_size($size, $type = '')
  960. {
  961. global $conf;
  962. if (empty($conf->dol_optimize_smallscreen)) {
  963. return $size;
  964. }
  965. if ($type == 'width' && $size > 250) {
  966. return 250;
  967. } else {
  968. return 10;
  969. }
  970. }
  971. /**
  972. * Clean a string to use it as a file name.
  973. * Replace also '--' and ' -' strings, they are used for parameters separation.
  974. *
  975. * @param string $str String to clean
  976. * @param string $newstr String to replace bad chars with.
  977. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  978. * @return string String cleaned (a-zA-Z_)
  979. *
  980. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  981. */
  982. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  983. {
  984. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  985. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  986. // Char '/' and '\' are file delimiters.
  987. // 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
  988. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  989. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  990. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  991. $tmp = preg_replace('/\s+\-/', ' _', $tmp);
  992. return $tmp;
  993. }
  994. /**
  995. * Clean a string to use it as a path name.
  996. * Replace also '--' and ' -' strings, they are used for parameters separation.
  997. *
  998. * @param string $str String to clean
  999. * @param string $newstr String to replace bad chars with
  1000. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1001. * @return string String cleaned (a-zA-Z_)
  1002. *
  1003. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1004. */
  1005. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1006. {
  1007. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1008. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1009. // 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
  1010. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1011. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1012. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1013. $tmp = preg_replace('/\s+\-/', ' _', $tmp);
  1014. return $tmp;
  1015. }
  1016. /**
  1017. * Clean a string to use it as an URL (into a href or src attribute)
  1018. *
  1019. * @param string $stringtoclean String to clean
  1020. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1021. * @return string Escaped string.
  1022. */
  1023. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1024. {
  1025. // 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)
  1026. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1027. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1028. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1029. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1030. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1031. if ($type == 1) {
  1032. // removing : should disable links to external url like http:aaa)
  1033. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1034. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1035. }
  1036. do {
  1037. $oldstringtoclean = $stringtoclean;
  1038. // removing '&colon' should disable links to external url like http:aaa)
  1039. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1040. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1041. } while ($oldstringtoclean != $stringtoclean);
  1042. if ($type == 1) {
  1043. // removing '//' should disable links to external url like //aaa or http//)
  1044. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1045. }
  1046. return $stringtoclean;
  1047. }
  1048. /**
  1049. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1050. *
  1051. * @param string $str String to clean
  1052. * @return string Cleaned string
  1053. *
  1054. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1055. */
  1056. function dol_string_unaccent($str)
  1057. {
  1058. if (utf8_check($str)) {
  1059. // See http://www.utf8-chartable.de/
  1060. $string = rawurlencode($str);
  1061. $replacements = array(
  1062. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1063. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1064. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1065. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1066. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1067. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1068. '%C3%A7' => 'c',
  1069. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1070. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1071. '%C3%B1' => 'n',
  1072. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1073. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1074. '%C3%BF' => 'y'
  1075. );
  1076. $string = strtr($string, $replacements);
  1077. return rawurldecode($string);
  1078. } else {
  1079. // See http://www.ascii-code.com/
  1080. $string = strtr(
  1081. $str,
  1082. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1083. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1084. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1085. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1086. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1087. \xF9\xFA\xFB\xFC\xFD\xFF",
  1088. "AAAAAAC
  1089. EEEEIIIIDN
  1090. OOOOOUUUY
  1091. aaaaaaceeee
  1092. iiiidnooooo
  1093. uuuuyy"
  1094. );
  1095. $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"));
  1096. return $string;
  1097. }
  1098. }
  1099. /**
  1100. * Clean a string from all punctuation characters to use it as a ref or login.
  1101. * This is a more complete function than dol_sanitizeFileName.
  1102. *
  1103. * @param string $str String to clean
  1104. * @param string $newstr String to replace forbidden chars with
  1105. * @param array|string $badcharstoreplace List of forbidden characters to replace
  1106. * @param array|string $badcharstoremove List of forbidden characters to remove
  1107. * @return string Cleaned string
  1108. *
  1109. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1110. */
  1111. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1112. {
  1113. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1114. $forbidden_chars_to_remove = array();
  1115. //$forbidden_chars_to_remove=array("(",")");
  1116. if (is_array($badcharstoreplace)) {
  1117. $forbidden_chars_to_replace = $badcharstoreplace;
  1118. }
  1119. if (is_array($badcharstoremove)) {
  1120. $forbidden_chars_to_remove = $badcharstoremove;
  1121. }
  1122. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1123. }
  1124. /**
  1125. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1126. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1127. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1128. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1129. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1130. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1131. * @param string $str String to clean
  1132. * @param int $removetabcrlf Remove also CR-LF
  1133. * @return string Cleaned string
  1134. *
  1135. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1136. */
  1137. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1138. {
  1139. if ($removetabcrlf) {
  1140. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1141. } else {
  1142. 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
  1143. }
  1144. }
  1145. /**
  1146. * Returns text escaped for inclusion into javascript code
  1147. *
  1148. * @param string $stringtoescape String to escape
  1149. * @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 \
  1150. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1151. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1152. */
  1153. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1154. {
  1155. // escape quotes and backslashes, newlines, etc.
  1156. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1157. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1158. if (empty($noescapebackslashn)) {
  1159. $substitjs["\n"] = '\\n';
  1160. $substitjs['\\'] = '\\\\';
  1161. }
  1162. if (empty($mode)) {
  1163. $substitjs["'"] = "\\'";
  1164. $substitjs['"'] = "\\'";
  1165. } elseif ($mode == 1) {
  1166. $substitjs["'"] = "\\'";
  1167. } elseif ($mode == 2) {
  1168. $substitjs['"'] = '\\"';
  1169. } elseif ($mode == 3) {
  1170. $substitjs["'"] = "\\'";
  1171. $substitjs['"'] = "\\\"";
  1172. }
  1173. return strtr($stringtoescape, $substitjs);
  1174. }
  1175. /**
  1176. * Returns text escaped for inclusion into javascript code
  1177. *
  1178. * @param string $stringtoescape String to escape
  1179. * @return string Escaped string for json content.
  1180. */
  1181. function dol_escape_json($stringtoescape)
  1182. {
  1183. return str_replace('"', '\"', $stringtoescape);
  1184. }
  1185. /**
  1186. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1187. *
  1188. * @param string $stringtoescape String to escape
  1189. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1190. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1191. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes to tag.
  1192. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1193. * @return string Escaped string
  1194. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1195. */
  1196. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1197. {
  1198. if ($noescapetags == 'common') {
  1199. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1200. }
  1201. // escape quotes and backslashes, newlines, etc.
  1202. if ($escapeonlyhtmltags) {
  1203. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1204. } else {
  1205. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1206. }
  1207. if (!$keepb) {
  1208. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1209. }
  1210. if (!$keepn) {
  1211. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1212. }
  1213. if ($escapeonlyhtmltags) {
  1214. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1215. } else {
  1216. // Escape tags to keep
  1217. // TODO Does not works yet when there is attributes to tag
  1218. $tmparrayoftags = array();
  1219. if ($noescapetags) {
  1220. $tmparrayoftags = explode(',', $noescapetags);
  1221. }
  1222. if (count($tmparrayoftags)) {
  1223. foreach ($tmparrayoftags as $tagtoreplace) {
  1224. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1225. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1226. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1227. }
  1228. }
  1229. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1230. if (count($tmparrayoftags)) {
  1231. foreach ($tmparrayoftags as $tagtoreplace) {
  1232. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1233. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1234. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1235. }
  1236. }
  1237. return $result;
  1238. }
  1239. }
  1240. /**
  1241. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1242. *
  1243. * @param string $string String to encode
  1244. * @param string $encoding Character set encoding
  1245. * @return string String converted
  1246. */
  1247. function dol_strtolower($string, $encoding = "UTF-8")
  1248. {
  1249. if (function_exists('mb_strtolower')) {
  1250. return mb_strtolower($string, $encoding);
  1251. } else {
  1252. return strtolower($string);
  1253. }
  1254. }
  1255. /**
  1256. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1257. *
  1258. * @param string $string String to encode
  1259. * @param string $encoding Character set encoding
  1260. * @return string String converted
  1261. */
  1262. function dol_strtoupper($string, $encoding = "UTF-8")
  1263. {
  1264. if (function_exists('mb_strtoupper')) {
  1265. return mb_strtoupper($string, $encoding);
  1266. } else {
  1267. return strtoupper($string);
  1268. }
  1269. }
  1270. /**
  1271. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1272. *
  1273. * @param string $string String to encode
  1274. * @param string $encoding Character set encodign
  1275. * @return string String converted
  1276. */
  1277. function dol_ucfirst($string, $encoding = "UTF-8")
  1278. {
  1279. if (function_exists('mb_substr')) {
  1280. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1281. } else {
  1282. return ucfirst($string);
  1283. }
  1284. }
  1285. /**
  1286. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1287. *
  1288. * @param string $string String to encode
  1289. * @param string $encoding Character set encodign
  1290. * @return string String converted
  1291. */
  1292. function dol_ucwords($string, $encoding = "UTF-8")
  1293. {
  1294. if (function_exists('mb_convert_case')) {
  1295. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1296. } else {
  1297. return ucwords($string);
  1298. }
  1299. }
  1300. /**
  1301. * Write log message into outputs. Possible outputs can be:
  1302. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1303. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1304. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1305. * this, use logging to files instead of syslog (see setup of module).
  1306. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1307. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1308. * This function works only if syslog module is enabled.
  1309. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1310. *
  1311. * @param string $message Line to log. ''=Show nothing
  1312. * @param int $level Log level
  1313. * 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
  1314. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1315. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1316. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1317. * @param string $restricttologhandler Force output of log only to this log handler
  1318. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1319. * @return void
  1320. */
  1321. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1322. {
  1323. global $conf, $user, $debugbar;
  1324. // If syslog module enabled
  1325. if (empty($conf->syslog->enabled)) {
  1326. return;
  1327. }
  1328. // Check if we are into execution of code of a website
  1329. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1330. global $website, $websitekey;
  1331. if (is_object($website) && !empty($website->ref)) {
  1332. $suffixinfilename .= '_website_'.$website->ref;
  1333. } elseif (!empty($websitekey)) {
  1334. $suffixinfilename .= '_website_'.$websitekey;
  1335. }
  1336. }
  1337. if ($ident < 0) {
  1338. foreach ($conf->loghandlers as $loghandlerinstance) {
  1339. $loghandlerinstance->setIdent($ident);
  1340. }
  1341. }
  1342. if (!empty($message)) {
  1343. // Test log level
  1344. $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');
  1345. if (!array_key_exists($level, $logLevels)) {
  1346. throw new Exception('Incorrect log level');
  1347. }
  1348. if ($level > $conf->global->SYSLOG_LEVEL) {
  1349. return;
  1350. }
  1351. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1352. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1353. }
  1354. // If adding log inside HTML page is required
  1355. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1356. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1357. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1358. }
  1359. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1360. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1361. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1362. print "\n\n<!-- Log start\n";
  1363. print dol_escape_htmltag($message)."\n";
  1364. print "Log end -->\n";
  1365. }
  1366. $data = array(
  1367. 'message' => $message,
  1368. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1369. 'level' => $level,
  1370. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1371. 'ip' => false
  1372. );
  1373. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1374. if (!empty($remoteip)) {
  1375. $data['ip'] = $remoteip;
  1376. // This is when server run behind a reverse proxy
  1377. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1378. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1379. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1380. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1381. }
  1382. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1383. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1384. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1385. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1386. // 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).
  1387. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1388. } elseif (!empty($_SERVER['LOGNAME'])) {
  1389. // 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).
  1390. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1391. }
  1392. // Loop on each log handler and send output
  1393. foreach ($conf->loghandlers as $loghandlerinstance) {
  1394. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1395. continue;
  1396. }
  1397. $loghandlerinstance->export($data, $suffixinfilename);
  1398. }
  1399. unset($data);
  1400. }
  1401. if ($ident > 0) {
  1402. foreach ($conf->loghandlers as $loghandlerinstance) {
  1403. $loghandlerinstance->setIdent($ident);
  1404. }
  1405. }
  1406. }
  1407. /**
  1408. * Return HTML code to output a button to open a dialog popup box.
  1409. * Such buttons must be included inside a HTML form.
  1410. *
  1411. * @param string $name A name for the html component
  1412. * @param string $label Label of button
  1413. * @param string $buttonstring button string
  1414. * @param string $url Url to open
  1415. * @param string $disabled Disabled text
  1416. * @return string HTML component with button
  1417. */
  1418. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1419. {
  1420. if (strpos($url, '?') > 0) {
  1421. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1422. } else {
  1423. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1424. }
  1425. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1426. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1427. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1428. $out .= '<script language="javascript">
  1429. jQuery(document).ready(function () {
  1430. jQuery(".button_'.$name.'").click(function () {
  1431. console.log("Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'")
  1432. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1433. .dialog({
  1434. autoOpen: false,
  1435. modal: true,
  1436. height: (window.innerHeight - 150),
  1437. width: \'80%\',
  1438. title: "'.dol_escape_js($label).'"
  1439. });
  1440. $dialog.dialog(\'open\');
  1441. });
  1442. });
  1443. </script>';
  1444. return $out;
  1445. }
  1446. /**
  1447. * Show tab header of a card
  1448. *
  1449. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1450. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1451. * @param string $title Title
  1452. * @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)
  1453. * @param string $picto Add a picto on tab title
  1454. * @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.
  1455. * @param string $morehtmlright Add more html content on right of tabs title
  1456. * @param string $morecss More Css
  1457. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1458. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1459. * @return void
  1460. * @deprecated Use print dol_get_fiche_head() instead
  1461. */
  1462. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1463. {
  1464. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1465. }
  1466. /**
  1467. * Show tabs of a record
  1468. *
  1469. * @param array $links Array of tabs
  1470. * @param string $active Active tab name
  1471. * @param string $title Title
  1472. * @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)
  1473. * @param string $picto Add a picto on tab title
  1474. * @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.
  1475. * @param string $morehtmlright Add more html content on right of tabs title
  1476. * @param string $morecss More Css
  1477. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1478. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1479. * @return string
  1480. */
  1481. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1482. {
  1483. global $conf, $langs, $hookmanager;
  1484. // Show title
  1485. $showtitle = 1;
  1486. if (!empty($conf->dol_optimize_smallscreen)) {
  1487. $showtitle = 0;
  1488. }
  1489. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1490. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1491. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1492. }
  1493. // Show right part
  1494. if ($morehtmlright) {
  1495. $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.
  1496. }
  1497. // Show title
  1498. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1499. $limittitle = 30;
  1500. $out .= '<a class="tabTitle">';
  1501. if ($picto) {
  1502. $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1503. }
  1504. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1505. $out .= '</a>';
  1506. }
  1507. // Show tabs
  1508. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1509. $maxkey = -1;
  1510. if (is_array($links) && !empty($links)) {
  1511. $keys = array_keys($links);
  1512. if (count($keys)) {
  1513. $maxkey = max($keys);
  1514. }
  1515. }
  1516. // Show tabs
  1517. // if =0 we don't use the feature
  1518. if (empty($limittoshow)) {
  1519. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1520. }
  1521. if (!empty($conf->dol_optimize_smallscreen)) {
  1522. $limittoshow = 2;
  1523. }
  1524. $displaytab = 0;
  1525. $nbintab = 0;
  1526. $popuptab = 0;
  1527. $outmore = '';
  1528. for ($i = 0; $i <= $maxkey; $i++) {
  1529. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1530. // If active tab is already present
  1531. if ($i >= $limittoshow) {
  1532. $limittoshow--;
  1533. }
  1534. }
  1535. }
  1536. for ($i = 0; $i <= $maxkey; $i++) {
  1537. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1538. $isactive = true;
  1539. } else {
  1540. $isactive = false;
  1541. }
  1542. if ($i < $limittoshow || $isactive) {
  1543. // Add a new entry
  1544. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : $links[$i][2]).' -->';
  1545. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1546. if (!empty($links[$i][0])) {
  1547. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1548. } else {
  1549. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1550. }
  1551. } elseif (!empty($links[$i][1])) {
  1552. //print "x $i $active ".$links[$i][2]." z";
  1553. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1554. if (!empty($links[$i][0])) {
  1555. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1556. }
  1557. $out .= $links[$i][1];
  1558. if (!empty($links[$i][0])) {
  1559. $out .= '</a>'."\n";
  1560. }
  1561. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1562. $out .= '</div>';
  1563. }
  1564. $out .= '</div>';
  1565. } else {
  1566. // The popup with the other tabs
  1567. if (!$popuptab) {
  1568. $popuptab = 1;
  1569. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1570. }
  1571. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1572. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1573. if (!empty($links[$i][0])) {
  1574. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1575. } else {
  1576. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1577. }
  1578. } elseif (!empty($links[$i][1])) {
  1579. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1580. $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.
  1581. $outmore .= '</a>'."\n";
  1582. }
  1583. $outmore .= '</div>';
  1584. $nbintab++;
  1585. }
  1586. $displaytab = $i;
  1587. }
  1588. if ($popuptab) {
  1589. $outmore .= '</div>';
  1590. }
  1591. if ($popuptab) { // If there is some tabs not shown
  1592. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1593. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1594. $widthofpopup = 200;
  1595. $tabsname = $moretabssuffix;
  1596. if (empty($tabsname)) {
  1597. $tabsname = str_replace("@", "", $picto);
  1598. }
  1599. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1600. $out .= '<a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a>'; // Do not use "reposition" class in the "More".
  1601. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1602. $out .= $outmore;
  1603. $out .= '</div>';
  1604. $out .= '<div></div>';
  1605. $out .= "</div>\n";
  1606. $out .= "<script>";
  1607. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1608. var x = this.offsetLeft, y = this.offsetTop;
  1609. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1610. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1611. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1612. }
  1613. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1614. });
  1615. ";
  1616. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1617. $out .= "</script>";
  1618. }
  1619. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1620. $out .= "</div>\n";
  1621. }
  1622. if (!$notab || $notab == -1 || $notab == -2) {
  1623. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1624. }
  1625. $parameters = array('tabname' => $active, 'out' => $out);
  1626. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1627. if ($reshook > 0) {
  1628. $out = $hookmanager->resPrint;
  1629. }
  1630. return $out;
  1631. }
  1632. /**
  1633. * Show tab footer of a card
  1634. *
  1635. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1636. * @return void
  1637. * @deprecated Use print dol_get_fiche_end() instead
  1638. */
  1639. function dol_fiche_end($notab = 0)
  1640. {
  1641. print dol_get_fiche_end($notab);
  1642. }
  1643. /**
  1644. * Return tab footer of a card
  1645. *
  1646. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1647. * @return string
  1648. */
  1649. function dol_get_fiche_end($notab = 0)
  1650. {
  1651. if (!$notab || $notab == -1) {
  1652. return "\n</div>\n";
  1653. } else {
  1654. return '';
  1655. }
  1656. }
  1657. /**
  1658. * Show tab footer of a card.
  1659. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1660. *
  1661. * @param Object $object Object to show
  1662. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1663. * @param string $morehtml More html content to output just before the nav bar
  1664. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1665. * @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.
  1666. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1667. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1668. * @param string $moreparam More param to add in nav link url.
  1669. * @param int $nodbprefix Do not include DB prefix to forge table name
  1670. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1671. * @param string $morehtmlstatus More html code to show under navigation arrows
  1672. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1673. * @param string $morehtmlright More html code to show before navigation arrows
  1674. * @return void
  1675. */
  1676. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1677. {
  1678. global $conf, $form, $user, $langs;
  1679. $error = 0;
  1680. $maxvisiblephotos = 1;
  1681. $showimage = 1;
  1682. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1683. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1684. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1685. $showbarcode = 0;
  1686. }
  1687. $modulepart = 'unknown';
  1688. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1689. $modulepart = $object->element;
  1690. } elseif ($object->element == 'member') {
  1691. $modulepart = 'memberphoto';
  1692. } elseif ($object->element == 'user') {
  1693. $modulepart = 'userphoto';
  1694. }
  1695. if (class_exists("Imagick")) {
  1696. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1697. $modulepart = $object->element;
  1698. } elseif ($object->element == 'fichinter') {
  1699. $modulepart = 'ficheinter';
  1700. } elseif ($object->element == 'contrat') {
  1701. $modulepart = 'contract';
  1702. } elseif ($object->element == 'order_supplier') {
  1703. $modulepart = 'supplier_order';
  1704. } elseif ($object->element == 'invoice_supplier') {
  1705. $modulepart = 'supplier_invoice';
  1706. }
  1707. }
  1708. if ($object->element == 'product') {
  1709. $width = 80;
  1710. $cssclass = 'photoref';
  1711. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1712. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1713. if ($conf->browser->layout == 'phone') {
  1714. $maxvisiblephotos = 1;
  1715. }
  1716. if ($showimage) {
  1717. $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>';
  1718. } else {
  1719. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1720. $nophoto = '';
  1721. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1722. } else { // Show no photo link
  1723. $nophoto = '/public/theme/common/nophoto.png';
  1724. $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>';
  1725. }
  1726. }
  1727. } elseif ($object->element == 'ticket') {
  1728. $width = 80;
  1729. $cssclass = 'photoref';
  1730. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1731. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1732. if ($conf->browser->layout == 'phone') {
  1733. $maxvisiblephotos = 1;
  1734. }
  1735. if ($showimage) {
  1736. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1737. if ($object->nbphoto > 0) {
  1738. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1739. } else {
  1740. $showimage = 0;
  1741. }
  1742. }
  1743. if (!$showimage) {
  1744. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1745. $nophoto = '';
  1746. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1747. } else { // Show no photo link
  1748. $nophoto = img_picto('No photo', 'object_ticket');
  1749. $morehtmlleft .= '<!-- No photo to show -->';
  1750. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1751. $morehtmlleft .= $nophoto;
  1752. $morehtmlleft .= '</div></div>';
  1753. }
  1754. }
  1755. } else {
  1756. if ($showimage) {
  1757. if ($modulepart != 'unknown') {
  1758. $phototoshow = '';
  1759. // Check if a preview file is available
  1760. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1761. $objectref = dol_sanitizeFileName($object->ref);
  1762. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1763. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1764. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1765. $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
  1766. } else {
  1767. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1768. }
  1769. if (empty($subdir)) {
  1770. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1771. }
  1772. $filepath = $dir_output.$subdir."/";
  1773. $filepdf = $filepath.$objectref.".pdf";
  1774. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1775. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1776. $fileimage = $filepdf.'_preview.png';
  1777. $relativepathimage = $relativepath.'_preview.png';
  1778. $pdfexists = file_exists($filepdf);
  1779. // If PDF file exists
  1780. if ($pdfexists) {
  1781. // Conversion du PDF en image png si fichier png non existant
  1782. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1783. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1784. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1785. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1786. if ($ret < 0) {
  1787. $error++;
  1788. }
  1789. }
  1790. }
  1791. }
  1792. if ($pdfexists && !$error) {
  1793. $heightforphotref = 80;
  1794. if (!empty($conf->dol_optimize_smallscreen)) {
  1795. $heightforphotref = 60;
  1796. }
  1797. // If the preview file is found
  1798. if (file_exists($fileimage)) {
  1799. $phototoshow = '<div class="photoref">';
  1800. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1801. $phototoshow .= '</div>';
  1802. }
  1803. }
  1804. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1805. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1806. }
  1807. if ($phototoshow) {
  1808. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1809. $morehtmlleft .= $phototoshow;
  1810. $morehtmlleft .= '</div>';
  1811. }
  1812. }
  1813. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1814. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1815. if ($object->element == 'action') {
  1816. $width = 80;
  1817. $cssclass = 'photorefcenter';
  1818. $nophoto = img_picto('No photo', 'title_agenda');
  1819. } else {
  1820. $width = 14;
  1821. $cssclass = 'photorefcenter';
  1822. $picto = $object->picto;
  1823. if ($object->element == 'project' && !$object->public) {
  1824. $picto = 'project'; // instead of projectpub
  1825. }
  1826. $nophoto = img_picto('No photo', 'object_'.$picto);
  1827. }
  1828. $morehtmlleft .= '<!-- No photo to show -->';
  1829. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1830. $morehtmlleft .= $nophoto;
  1831. $morehtmlleft .= '</div></div>';
  1832. $morehtmlleft .= '</div>';
  1833. }
  1834. }
  1835. }
  1836. if ($showbarcode) {
  1837. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref').'</div>';
  1838. }
  1839. if ($object->element == 'societe') {
  1840. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1841. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1842. } else {
  1843. $morehtmlstatus .= $object->getLibStatut(6);
  1844. }
  1845. } elseif ($object->element == 'product') {
  1846. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1847. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1848. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1849. } else {
  1850. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1851. }
  1852. $morehtmlstatus .= ' &nbsp; ';
  1853. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1854. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1855. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1856. } else {
  1857. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1858. }
  1859. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  1860. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1861. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1862. $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1863. }
  1864. $morehtmlstatus .= $tmptxt;
  1865. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  1866. if ($object->statut == 0) {
  1867. $morehtmlstatus .= $object->getLibStatut(5);
  1868. } else {
  1869. $morehtmlstatus .= $object->getLibStatut(4);
  1870. }
  1871. } elseif ($object->element == 'facturerec') {
  1872. if ($object->frequency == 0) {
  1873. $morehtmlstatus .= $object->getLibStatut(2);
  1874. } else {
  1875. $morehtmlstatus .= $object->getLibStatut(5);
  1876. }
  1877. } elseif ($object->element == 'project_task') {
  1878. $object->fk_statut = 1;
  1879. if ($object->progress > 0) {
  1880. $object->fk_statut = 2;
  1881. }
  1882. if ($object->progress >= 100) {
  1883. $object->fk_statut = 3;
  1884. }
  1885. $tmptxt = $object->getLibStatut(5);
  1886. $morehtmlstatus .= $tmptxt; // No status on task
  1887. } else { // Generic case
  1888. $tmptxt = $object->getLibStatut(6);
  1889. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1890. $tmptxt = $object->getLibStatut(5);
  1891. }
  1892. $morehtmlstatus .= $tmptxt;
  1893. }
  1894. // Add if object was dispatched "into accountancy"
  1895. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  1896. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  1897. if (method_exists($object, 'getVentilExportCompta')) {
  1898. $accounted = $object->getVentilExportCompta();
  1899. $langs->load("accountancy");
  1900. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1901. }
  1902. }
  1903. // Add alias for thirdparty
  1904. if (!empty($object->name_alias)) {
  1905. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1906. }
  1907. // Add label
  1908. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  1909. if (!empty($object->label)) {
  1910. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1911. }
  1912. }
  1913. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  1914. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1915. if ($moreaddress) {
  1916. $morehtmlref .= '<div class="refidno">';
  1917. $morehtmlref .= $moreaddress;
  1918. $morehtmlref .= '</div>';
  1919. }
  1920. }
  1921. 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)) {
  1922. $morehtmlref .= '<div style="clear: both;"></div>';
  1923. $morehtmlref .= '<div class="refidno">';
  1924. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1925. $morehtmlref .= '</div>';
  1926. }
  1927. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1928. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1929. print '</div>';
  1930. print '<div class="underrefbanner clearboth"></div>';
  1931. }
  1932. /**
  1933. * Show a string with the label tag dedicated to the HTML edit field.
  1934. *
  1935. * @param string $langkey Translation key
  1936. * @param string $fieldkey Key of the html select field the text refers to
  1937. * @param int $fieldrequired 1=Field is mandatory
  1938. * @return string
  1939. * @deprecated Form::editfieldkey
  1940. */
  1941. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1942. {
  1943. global $langs;
  1944. $ret = '';
  1945. if ($fieldrequired) {
  1946. $ret .= '<span class="fieldrequired">';
  1947. }
  1948. $ret .= '<label for="'.$fieldkey.'">';
  1949. $ret .= $langs->trans($langkey);
  1950. $ret .= '</label>';
  1951. if ($fieldrequired) {
  1952. $ret .= '</span>';
  1953. }
  1954. return $ret;
  1955. }
  1956. /**
  1957. * Return string to add class property on html element with pair/impair.
  1958. *
  1959. * @param string $var 0 or 1
  1960. * @param string $moreclass More class to add
  1961. * @return string String to add class onto HTML element
  1962. */
  1963. function dol_bc($var, $moreclass = '')
  1964. {
  1965. global $bc;
  1966. $ret = ' '.$bc[$var];
  1967. if ($moreclass) {
  1968. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  1969. }
  1970. return $ret;
  1971. }
  1972. /**
  1973. * Return a formated address (part address/zip/town/state) according to country rules.
  1974. * See https://en.wikipedia.org/wiki/Address
  1975. *
  1976. * @param Object $object A company or contact object
  1977. * @param int $withcountry 1=Add country into address string
  1978. * @param string $sep Separator to use to build string
  1979. * @param Translate $outputlangs Object lang that contains language for text translation.
  1980. * @param int $mode 0=Standard output, 1=Remove address
  1981. * @param string $extralangcode User extralanguage $langcode as values for address, town
  1982. * @return string Formated string
  1983. * @see dol_print_address()
  1984. */
  1985. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  1986. {
  1987. global $conf, $langs;
  1988. $ret = '';
  1989. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1990. // See format of addresses on https://en.wikipedia.org/wiki/Address
  1991. // Address
  1992. if (empty($mode)) {
  1993. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  1994. }
  1995. // Zip/Town/State
  1996. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  1997. // US: title firstname name \n address lines \n town, state, zip \n country
  1998. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  1999. $ret .= ($ret ? $sep : '').$town;
  2000. if (!empty($object->state)) {
  2001. $ret .= ($ret ? ", " : '').$object->state;
  2002. }
  2003. if (!empty($object->zip)) {
  2004. $ret .= ($ret ? ", " : '').$object->zip;
  2005. }
  2006. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2007. // UK: title firstname name \n address lines \n town state \n zip \n country
  2008. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2009. $ret .= ($ret ? $sep : '').$town;
  2010. if (!empty($object->state)) {
  2011. $ret .= ($ret ? ", " : '').$object->state;
  2012. }
  2013. if (!empty($object->zip)) {
  2014. $ret .= ($ret ? $sep : '').$object->zip;
  2015. }
  2016. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2017. // ES: title firstname name \n address lines \n zip town \n state \n country
  2018. $ret .= ($ret ? $sep : '').$object->zip;
  2019. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2020. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2021. if (!empty($object->state)) {
  2022. $ret .= "\n".$object->state;
  2023. }
  2024. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2025. // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  2026. $ret .= ($ret ? $sep : '').$object->zip;
  2027. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2028. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2029. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2030. } else { // Other: title firstname name \n address lines \n zip town \n country
  2031. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2032. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2033. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2034. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2035. $ret .= ($ret ? ", " : '').$object->state;
  2036. }
  2037. }
  2038. if (!is_object($outputlangs)) {
  2039. $outputlangs = $langs;
  2040. }
  2041. if ($withcountry) {
  2042. $langs->load("dict");
  2043. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2044. }
  2045. return $ret;
  2046. }
  2047. /**
  2048. * Format a string.
  2049. *
  2050. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2051. * @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)
  2052. * @param int $is_gmt See comment of timestamp parameter
  2053. * @return string A formatted string
  2054. */
  2055. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2056. {
  2057. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2058. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2059. } else {
  2060. return 'Error date into a not supported range';
  2061. }
  2062. }
  2063. /**
  2064. * Output date in a string format according to outputlangs (or langs if not defined).
  2065. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2066. *
  2067. * @param int $time GM Timestamps date
  2068. * @param string $format Output date format (tag of strftime function)
  2069. * "%d %b %Y",
  2070. * "%d/%m/%Y %H:%M",
  2071. * "%d/%m/%Y %H:%M:%S",
  2072. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2073. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2074. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2075. * false or 'tzserver' => output string is for local PHP server TZ usage
  2076. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2077. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  2078. * @param Translate $outputlangs Object lang that contains language for text translation.
  2079. * @param boolean $encodetooutput false=no convert into output pagecode
  2080. * @return string Formated date or '' if time is null
  2081. *
  2082. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2083. */
  2084. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2085. {
  2086. global $conf, $langs;
  2087. if ($tzoutput === 'auto') {
  2088. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2089. }
  2090. // Clean parameters
  2091. $to_gmt = false;
  2092. $offsettz = $offsetdst = 0;
  2093. if ($tzoutput) {
  2094. $to_gmt = true; // For backward compatibility
  2095. if (is_string($tzoutput)) {
  2096. if ($tzoutput == 'tzserver') {
  2097. $to_gmt = false;
  2098. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2099. $offsettz = 0; // Timezone offset with server timezone, so 0
  2100. $offsetdst = 0; // Dst offset with server timezone, so 0
  2101. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2102. $to_gmt = true;
  2103. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2104. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2105. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2106. }
  2107. }
  2108. }
  2109. if (!is_object($outputlangs)) {
  2110. $outputlangs = $langs;
  2111. }
  2112. if (!$format) {
  2113. $format = 'daytextshort';
  2114. }
  2115. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2116. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2117. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2118. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2119. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2120. if ($formatwithoutreduce != $format) {
  2121. $format = $formatwithoutreduce;
  2122. $reduceformat = 1;
  2123. } // so format 'dayreduceformat' is processed like day
  2124. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2125. // TODO Add format daysmallyear and dayhoursmallyear
  2126. if ($format == 'day') {
  2127. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2128. } elseif ($format == 'hour') {
  2129. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2130. } elseif ($format == 'hourduration') {
  2131. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2132. } elseif ($format == 'daytext') {
  2133. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2134. } elseif ($format == 'daytextshort') {
  2135. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2136. } elseif ($format == 'dayhour') {
  2137. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2138. } elseif ($format == 'dayhoursec') {
  2139. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2140. } elseif ($format == 'dayhourtext') {
  2141. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2142. } elseif ($format == 'dayhourtextshort') {
  2143. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2144. } elseif ($format == 'dayhourlog') {
  2145. // Format not sensitive to language
  2146. $format = '%Y%m%d%H%M%S';
  2147. } elseif ($format == 'dayhourldap') {
  2148. $format = '%Y%m%d%H%M%SZ';
  2149. } elseif ($format == 'dayhourxcard') {
  2150. $format = '%Y%m%dT%H%M%SZ';
  2151. } elseif ($format == 'dayxcard') {
  2152. $format = '%Y%m%d';
  2153. } elseif ($format == 'dayrfc') {
  2154. $format = '%Y-%m-%d'; // DATE_RFC3339
  2155. } elseif ($format == 'dayhourrfc') {
  2156. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2157. } elseif ($format == 'standard') {
  2158. $format = '%Y-%m-%d %H:%M:%S';
  2159. }
  2160. if ($reduceformat) {
  2161. $format = str_replace('%Y', '%y', $format);
  2162. $format = str_replace('yyyy', 'yy', $format);
  2163. }
  2164. // If date undefined or "", we return ""
  2165. if (dol_strlen($time) == 0) {
  2166. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2167. }
  2168. // Clean format
  2169. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2170. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2171. $format = str_replace('%b', '__b__', $format);
  2172. $format = str_replace('%B', '__B__', $format);
  2173. }
  2174. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2175. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2176. $format = str_replace('%a', '__a__', $format);
  2177. $format = str_replace('%A', '__A__', $format);
  2178. }
  2179. // Analyze date
  2180. $reg = array();
  2181. 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
  2182. dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2183. return '';
  2184. } 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
  2185. // This part of code should not be used anymore.
  2186. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2187. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2188. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2189. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2190. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2191. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2192. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2193. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2194. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2195. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2196. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2197. } else {
  2198. // Date is a timestamps
  2199. if ($time < 100000000000) { // Protection against bad date values
  2200. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2201. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2202. } else {
  2203. $ret = 'Bad value '.$time.' for date';
  2204. }
  2205. }
  2206. if (preg_match('/__b__/i', $format)) {
  2207. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2208. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2209. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2210. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2211. if ($encodetooutput) {
  2212. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2213. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2214. } else {
  2215. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2216. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2217. }
  2218. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2219. $ret = str_replace('__b__', $monthtextshort, $ret);
  2220. $ret = str_replace('__B__', $monthtext, $ret);
  2221. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2222. //return $ret;
  2223. }
  2224. if (preg_match('/__a__/i', $format)) {
  2225. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2226. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2227. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2228. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2229. $ret = str_replace('__A__', $dayweek, $ret);
  2230. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2231. }
  2232. return $ret;
  2233. }
  2234. /**
  2235. * Return an array with locale date info.
  2236. * WARNING: This function use PHP server timezone by default to return locale informations.
  2237. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2238. *
  2239. * @param int $timestamp Timestamp
  2240. * @param boolean $fast Fast mode. deprecated.
  2241. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2242. * @return array Array of informations
  2243. * 'seconds' => $secs,
  2244. * 'minutes' => $min,
  2245. * 'hours' => $hour,
  2246. * 'mday' => $day,
  2247. * 'wday' => $dow, 0=sunday, 6=saturday
  2248. * 'mon' => $month,
  2249. * 'year' => $year,
  2250. * 'yday' => floor($secsInYear/$_day_power)
  2251. * '0' => original timestamp
  2252. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2253. */
  2254. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2255. {
  2256. //$datetimeobj = new DateTime('@'.$timestamp);
  2257. $datetimeobj = new DateTime();
  2258. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2259. if ($forcetimezone) {
  2260. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2261. }
  2262. $arrayinfo = array(
  2263. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2264. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2265. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2266. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2267. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2268. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2269. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2270. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2271. '0'=>$timestamp
  2272. );
  2273. return $arrayinfo;
  2274. }
  2275. /**
  2276. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2277. * Replace function mktime not available under Windows if year < 1970
  2278. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2279. *
  2280. * @param int $hour Hour (can be -1 for undefined)
  2281. * @param int $minute Minute (can be -1 for undefined)
  2282. * @param int $second Second (can be -1 for undefined)
  2283. * @param int $month Month (1 to 12)
  2284. * @param int $day Day (1 to 31)
  2285. * @param int $year Year
  2286. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2287. * False or 0 or 'tzserver' = local to server TZ
  2288. * 'auto'
  2289. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2290. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user.
  2291. * 'tz,TimeZone' = use specified timezone
  2292. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2293. * @return int|string Date as a timestamp, '' or false if error
  2294. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2295. */
  2296. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2297. {
  2298. global $conf;
  2299. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2300. //print 'gm:'.$gm.' gm==auto:'.($gm == 'auto').'<br>';
  2301. if ($gm === 'auto') {
  2302. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2303. }
  2304. // Clean parameters
  2305. if ($hour == -1 || empty($hour)) {
  2306. $hour = 0;
  2307. }
  2308. if ($minute == -1 || empty($minute)) {
  2309. $minute = 0;
  2310. }
  2311. if ($second == -1 || empty($second)) {
  2312. $second = 0;
  2313. }
  2314. // Check parameters
  2315. if ($check) {
  2316. if (!$month || !$day) {
  2317. return '';
  2318. }
  2319. if ($day > 31) {
  2320. return '';
  2321. }
  2322. if ($month > 12) {
  2323. return '';
  2324. }
  2325. if ($hour < 0 || $hour > 24) {
  2326. return '';
  2327. }
  2328. if ($minute < 0 || $minute > 60) {
  2329. return '';
  2330. }
  2331. if ($second < 0 || $second > 60) {
  2332. return '';
  2333. }
  2334. }
  2335. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2336. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2337. $localtz = new DateTimeZone($default_timezone);
  2338. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2339. // We use dol_tz_string first because it is more reliable.
  2340. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2341. try {
  2342. $localtz = new DateTimeZone($default_timezone);
  2343. } catch (Exception $e) {
  2344. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2345. $default_timezone = @date_default_timezone_get();
  2346. }
  2347. } elseif (strrpos($gm, "tz,") !== false) {
  2348. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2349. try {
  2350. $localtz = new DateTimeZone($timezone);
  2351. } catch (Exception $e) {
  2352. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2353. }
  2354. }
  2355. if (empty($localtz)) {
  2356. $localtz = new DateTimeZone('UTC');
  2357. }
  2358. //var_dump($localtz);
  2359. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2360. $dt = new DateTime(null, $localtz);
  2361. $dt->setDate((int) $year, (int) $month, (int) $day);
  2362. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2363. $date = $dt->getTimestamp(); // should include daylight saving time
  2364. //var_dump($date);
  2365. return $date;
  2366. }
  2367. /**
  2368. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2369. *
  2370. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2371. * 'gmt' => we return GMT timestamp,
  2372. * 'tzserver' => we add the PHP server timezone
  2373. * 'tzref' => we add the company timezone. Not implemented.
  2374. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2375. * @return int $date Timestamp
  2376. */
  2377. function dol_now($mode = 'auto')
  2378. {
  2379. $ret = 0;
  2380. if ($mode === 'auto') {
  2381. $mode = 'gmt';
  2382. }
  2383. if ($mode == 'gmt') {
  2384. $ret = time(); // Time for now at greenwich.
  2385. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2386. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2387. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2388. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2389. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2390. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2391. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2392. // $ret=dol_now('gmt')+($tzsecond*3600);
  2393. //}
  2394. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2395. // Time for now with user timezone added
  2396. //print 'time: '.time();
  2397. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2398. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2399. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2400. }
  2401. return $ret;
  2402. }
  2403. /**
  2404. * Return string with formated size
  2405. *
  2406. * @param int $size Size to print
  2407. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2408. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2409. * @return string Link
  2410. */
  2411. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2412. {
  2413. global $conf, $langs;
  2414. $level = 1024;
  2415. if (!empty($conf->dol_optimize_smallscreen)) {
  2416. $shortunit = 1;
  2417. }
  2418. // Set value text
  2419. if (empty($shortvalue) || $size < ($level * 10)) {
  2420. $ret = $size;
  2421. $textunitshort = $langs->trans("b");
  2422. $textunitlong = $langs->trans("Bytes");
  2423. } else {
  2424. $ret = round($size / $level, 0);
  2425. $textunitshort = $langs->trans("Kb");
  2426. $textunitlong = $langs->trans("KiloBytes");
  2427. }
  2428. // Use long or short text unit
  2429. if (empty($shortunit)) {
  2430. $ret .= ' '.$textunitlong;
  2431. } else {
  2432. $ret .= ' '.$textunitshort;
  2433. }
  2434. return $ret;
  2435. }
  2436. /**
  2437. * Show Url link
  2438. *
  2439. * @param string $url Url to show
  2440. * @param string $target Target for link
  2441. * @param int $max Max number of characters to show
  2442. * @param int $withpicto With picto
  2443. * @return string HTML Link
  2444. */
  2445. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2446. {
  2447. global $langs;
  2448. if (empty($url)) {
  2449. return '';
  2450. }
  2451. $link = '<a href="';
  2452. if (!preg_match('/^http/i', $url)) {
  2453. $link .= 'http://';
  2454. }
  2455. $link .= $url;
  2456. $link .= '"';
  2457. if ($target) {
  2458. $link .= ' target="'.$target.'"';
  2459. }
  2460. $link .= '>';
  2461. if (!preg_match('/^http/i', $url)) {
  2462. $link .= 'http://';
  2463. }
  2464. $link .= dol_trunc($url, $max);
  2465. $link .= '</a>';
  2466. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2467. }
  2468. /**
  2469. * Show EMail link formatted for HTML output.
  2470. *
  2471. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2472. * @param int $cid Id of contact if known
  2473. * @param int $socid Id of third party if known
  2474. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2475. * @param int $max Max number of characters to show
  2476. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2477. * @param int $withpicto Show picto
  2478. * @return string HTML Link
  2479. */
  2480. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2481. {
  2482. global $conf, $user, $langs, $hookmanager;
  2483. $newemail = dol_escape_htmltag($email);
  2484. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2485. $withpicto = 0;
  2486. }
  2487. if (empty($email)) {
  2488. return '&nbsp;';
  2489. }
  2490. if (!empty($addlink)) {
  2491. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2492. if (!preg_match('/^mailto:/i', $email)) {
  2493. $newemail .= 'mailto:';
  2494. }
  2495. $newemail .= $email;
  2496. $newemail .= '">';
  2497. $newemail .= dol_trunc($email, $max);
  2498. $newemail .= '</a>';
  2499. if ($showinvalid && !isValidEmail($email)) {
  2500. $langs->load("errors");
  2501. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2502. }
  2503. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2504. $type = 'AC_EMAIL';
  2505. $link = '';
  2506. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2507. $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>';
  2508. }
  2509. if ($link) {
  2510. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2511. }
  2512. }
  2513. } else {
  2514. if ($showinvalid && !isValidEmail($email)) {
  2515. $langs->load("errors");
  2516. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2517. }
  2518. }
  2519. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2520. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2521. //$rep .= '</div>';
  2522. if ($hookmanager) {
  2523. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2524. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2525. if ($reshook > 0) {
  2526. $rep = '';
  2527. }
  2528. $rep .= $hookmanager->resPrint;
  2529. }
  2530. return $rep;
  2531. }
  2532. /**
  2533. * Get array of social network dictionary
  2534. *
  2535. * @return array Array of Social Networks Dictionary
  2536. */
  2537. function getArrayOfSocialNetworks()
  2538. {
  2539. global $conf, $db;
  2540. $socialnetworks = array();
  2541. // Enable caching of array
  2542. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2543. $cachekey = 'socialnetworks_' . $conf->entity;
  2544. $dataretrieved = dol_getcache($cachekey);
  2545. if (!is_null($dataretrieved)) {
  2546. $socialnetworks = $dataretrieved;
  2547. } else {
  2548. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2549. $sql .= " WHERE entity=".$conf->entity;
  2550. $resql = $db->query($sql);
  2551. if ($resql) {
  2552. while ($obj = $db->fetch_object($resql)) {
  2553. $socialnetworks[$obj->code] = array(
  2554. 'rowid' => $obj->rowid,
  2555. 'label' => $obj->label,
  2556. 'url' => $obj->url,
  2557. 'icon' => $obj->icon,
  2558. 'active' => $obj->active,
  2559. );
  2560. }
  2561. }
  2562. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2563. }
  2564. return $socialnetworks;
  2565. }
  2566. /**
  2567. * Show social network link
  2568. *
  2569. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2570. * @param int $cid Id of contact if known
  2571. * @param int $socid Id of third party if known
  2572. * @param string $type 'skype','facebook',...
  2573. * @param array $dictsocialnetworks socialnetworks availables
  2574. * @return string HTML Link
  2575. */
  2576. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2577. {
  2578. global $conf, $user, $langs;
  2579. $htmllink = $value;
  2580. if (empty($value)) {
  2581. return '&nbsp;';
  2582. }
  2583. if (!empty($type)) {
  2584. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2585. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2586. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2587. if ($type == 'skype') {
  2588. $htmllink .= $value;
  2589. $htmllink .= '&nbsp;';
  2590. $htmllink .= '<a href="skype:';
  2591. $htmllink .= $value;
  2592. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2593. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2594. $htmllink .= '</a><a href="skype:';
  2595. $htmllink .= $value;
  2596. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2597. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2598. $htmllink .= '</a>';
  2599. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2600. $addlink = 'AC_SKYPE';
  2601. $link = '';
  2602. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2603. $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>';
  2604. }
  2605. $htmllink .= ($link ? ' '.$link : '');
  2606. }
  2607. } else {
  2608. if (!empty($dictsocialnetworks[$type]['url'])) {
  2609. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2610. $htmllink .= '&nbsp;<a href="'.$link.'" target="_blank">'.$value.'</a>';
  2611. } else {
  2612. $htmllink .= $value;
  2613. }
  2614. }
  2615. $htmllink .= '</div>';
  2616. } else {
  2617. $langs->load("errors");
  2618. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2619. }
  2620. return $htmllink;
  2621. }
  2622. /**
  2623. * Format phone numbers according to country
  2624. *
  2625. * @param string $phone Phone number to format
  2626. * @param string $countrycode Country code to use for formatting
  2627. * @param int $cid Id of contact if known
  2628. * @param int $socid Id of third party if known
  2629. * @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)
  2630. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2631. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2632. * @param string $titlealt Text to show on alt
  2633. * @param int $adddivfloat Add div float around phone.
  2634. * @return string Formated phone number
  2635. */
  2636. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2637. {
  2638. global $conf, $user, $langs, $mysoc, $hookmanager;
  2639. // Clean phone parameter
  2640. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2641. if (empty($phone)) {
  2642. return '';
  2643. }
  2644. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2645. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2646. }
  2647. if (empty($countrycode)) {
  2648. $countrycode = $mysoc->country_code;
  2649. }
  2650. // Short format for small screens
  2651. if ($conf->dol_optimize_smallscreen) {
  2652. $separ = '';
  2653. }
  2654. $newphone = $phone;
  2655. if (strtoupper($countrycode) == "FR") {
  2656. // France
  2657. if (dol_strlen($phone) == 10) {
  2658. $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);
  2659. } elseif (dol_strlen($phone) == 7) {
  2660. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2661. } elseif (dol_strlen($phone) == 9) {
  2662. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2663. } elseif (dol_strlen($phone) == 11) {
  2664. $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);
  2665. } elseif (dol_strlen($phone) == 12) {
  2666. $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);
  2667. }
  2668. } elseif (strtoupper($countrycode) == "CA") {
  2669. if (dol_strlen($phone) == 10) {
  2670. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2671. }
  2672. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2673. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2674. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2675. }
  2676. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2677. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2678. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2679. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2680. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2681. }
  2682. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2683. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2684. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2685. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2686. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2687. }
  2688. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2689. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2690. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2691. }
  2692. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2693. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2694. $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);
  2695. }
  2696. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2697. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2698. $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);
  2699. }
  2700. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2701. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2702. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2703. }
  2704. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2705. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2706. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2707. }
  2708. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2709. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2710. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2711. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2712. $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);
  2713. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2714. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2715. }
  2716. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2717. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2718. $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);
  2719. }
  2720. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2721. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2722. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2723. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2724. $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);
  2725. }
  2726. } elseif (strtoupper($countrycode) == "MU") {
  2727. //Maurice
  2728. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  2729. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2730. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  2731. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2732. }
  2733. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  2734. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  2735. $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);
  2736. }
  2737. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  2738. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  2739. $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);
  2740. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  2741. $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);
  2742. }
  2743. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  2744. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  2745. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2746. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  2747. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2748. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  2749. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2750. }
  2751. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  2752. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  2753. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2754. }
  2755. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  2756. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  2757. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2758. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  2759. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2760. }
  2761. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  2762. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  2763. $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);
  2764. }
  2765. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  2766. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  2767. $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);
  2768. }
  2769. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  2770. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  2771. $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);
  2772. }
  2773. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  2774. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  2775. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2776. }
  2777. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  2778. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
  2779. $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);
  2780. }
  2781. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  2782. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  2783. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2784. }
  2785. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  2786. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  2787. $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);
  2788. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  2789. $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);
  2790. }
  2791. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  2792. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  2793. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2794. }
  2795. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  2796. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2797. $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);
  2798. }
  2799. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  2800. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2801. $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);
  2802. }
  2803. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  2804. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2805. $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);
  2806. }
  2807. } elseif (strtoupper($countrycode) == "IT") {//Italie
  2808. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  2809. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2810. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  2811. $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);
  2812. }
  2813. } elseif (strtoupper($countrycode) == "AU") {
  2814. //Australie
  2815. if (dol_strlen($phone) == 12) {
  2816. //ex: +61_A_BCDE_FGHI
  2817. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2818. }
  2819. }
  2820. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2821. 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
  2822. $newphoneform = $newphone;
  2823. $newphone = '<a href="tel:'.$phone.'"';
  2824. $newphone .= '>'.$newphoneform.'</a>';
  2825. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  2826. if (empty($user->clicktodial_loaded)) {
  2827. $user->fetch_clicktodial();
  2828. }
  2829. // Define urlmask
  2830. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2831. if (!empty($conf->global->CLICKTODIAL_URL)) {
  2832. $urlmask = $conf->global->CLICKTODIAL_URL;
  2833. }
  2834. if (!empty($user->clicktodial_url)) {
  2835. $urlmask = $user->clicktodial_url;
  2836. }
  2837. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2838. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2839. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2840. // This line is for backward compatibility
  2841. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2842. // Thoose lines are for substitution
  2843. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2844. '__PHONETO__'=>urlencode($phone),
  2845. '__LOGIN__'=>$clicktodial_login,
  2846. '__PASS__'=>$clicktodial_password);
  2847. $url = make_substitutions($url, $substitarray);
  2848. $newphonesav = $newphone;
  2849. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  2850. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  2851. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  2852. $newphone .= '>'.$newphonesav.'</a>';
  2853. } else {
  2854. // Old method
  2855. $newphone = '<a href="'.$url.'"';
  2856. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  2857. $newphone .= ' target="_blank"';
  2858. }
  2859. $newphone .= '>'.$newphonesav.'</a>';
  2860. }
  2861. }
  2862. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2863. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2864. $type = 'AC_TEL';
  2865. $link = '';
  2866. if ($addlink == 'AC_FAX') {
  2867. $type = 'AC_FAX';
  2868. }
  2869. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  2870. $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>';
  2871. }
  2872. if ($link) {
  2873. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2874. }
  2875. }
  2876. }
  2877. if (empty($titlealt)) {
  2878. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2879. }
  2880. $rep = '';
  2881. if ($hookmanager) {
  2882. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2883. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2884. $rep .= $hookmanager->resPrint;
  2885. }
  2886. if (empty($reshook)) {
  2887. $picto = '';
  2888. if ($withpicto) {
  2889. if ($withpicto == 'fax') {
  2890. $picto = 'phoning_fax';
  2891. } elseif ($withpicto == 'phone') {
  2892. $picto = 'phoning';
  2893. } elseif ($withpicto == 'mobile') {
  2894. $picto = 'phoning_mobile';
  2895. } else {
  2896. $picto = '';
  2897. }
  2898. }
  2899. if ($adddivfloat) {
  2900. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2901. } else {
  2902. $rep .= '<span style="margin-right: 10px;">';
  2903. }
  2904. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2905. if ($adddivfloat) {
  2906. $rep .= '</div>';
  2907. } else {
  2908. $rep .= '</span>';
  2909. }
  2910. }
  2911. return $rep;
  2912. }
  2913. /**
  2914. * Return an IP formated to be shown on screen
  2915. *
  2916. * @param string $ip IP
  2917. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2918. * @return string Formated IP, with country if GeoIP module is enabled
  2919. */
  2920. function dol_print_ip($ip, $mode = 0)
  2921. {
  2922. global $conf, $langs;
  2923. $ret = '';
  2924. if (empty($mode)) {
  2925. $ret .= $ip;
  2926. }
  2927. if ($mode != 2) {
  2928. $countrycode = dolGetCountryCodeFromIp($ip);
  2929. if ($countrycode) { // If success, countrycode is us, fr, ...
  2930. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  2931. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2932. } else {
  2933. $ret .= ' ('.$countrycode.')';
  2934. }
  2935. } else {
  2936. // Nothing
  2937. }
  2938. }
  2939. return $ret;
  2940. }
  2941. /**
  2942. * Return the IP of remote user.
  2943. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2944. * Then HTTP_CLIENT_IP if defined (rare)
  2945. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2946. *
  2947. * @return string Ip of remote user.
  2948. */
  2949. function getUserRemoteIP()
  2950. {
  2951. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  2952. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  2953. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  2954. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  2955. } else {
  2956. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  2957. }
  2958. } else {
  2959. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  2960. }
  2961. } else {
  2962. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  2963. }
  2964. return $ip;
  2965. }
  2966. /**
  2967. * Return if we are using a HTTPS connexion
  2968. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  2969. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  2970. * Then HTTP_X_FORWARDED_SSL
  2971. *
  2972. * @return boolean True if user is using HTTPS
  2973. */
  2974. function isHTTPS()
  2975. {
  2976. $isSecure = false;
  2977. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  2978. $isSecure = true;
  2979. } 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') {
  2980. $isSecure = true;
  2981. }
  2982. return $isSecure;
  2983. }
  2984. /**
  2985. * Return a country code from IP. Empty string if not found.
  2986. *
  2987. * @param string $ip IP
  2988. * @return string Country code ('us', 'fr', ...)
  2989. */
  2990. function dolGetCountryCodeFromIp($ip)
  2991. {
  2992. global $conf;
  2993. $countrycode = '';
  2994. if (!empty($conf->geoipmaxmind->enabled)) {
  2995. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2996. //$ip='24.24.24.24';
  2997. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  2998. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2999. $geoip = new DolGeoIP('country', $datafile);
  3000. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3001. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3002. }
  3003. return $countrycode;
  3004. }
  3005. /**
  3006. * Return country code for current user.
  3007. * If software is used inside a local network, detection may fails (we need a public ip)
  3008. *
  3009. * @return string Country code (fr, es, it, us, ...)
  3010. */
  3011. function dol_user_country()
  3012. {
  3013. global $conf, $langs, $user;
  3014. //$ret=$user->xxx;
  3015. $ret = '';
  3016. if (!empty($conf->geoipmaxmind->enabled)) {
  3017. $ip = getUserRemoteIP();
  3018. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3019. //$ip='24.24.24.24';
  3020. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3021. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3022. $geoip = new DolGeoIP('country', $datafile);
  3023. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3024. $ret = $countrycode;
  3025. }
  3026. return $ret;
  3027. }
  3028. /**
  3029. * Format address string
  3030. *
  3031. * @param string $address Address string, already formatted with dol_format_address()
  3032. * @param int $htmlid Html ID (for example 'gmap')
  3033. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3034. * @param int $id Id of object
  3035. * @param int $noprint No output. Result is the function return
  3036. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3037. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3038. * @see dol_format_address()
  3039. */
  3040. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3041. {
  3042. global $conf, $user, $langs, $hookmanager;
  3043. $out = '';
  3044. if ($address) {
  3045. if ($hookmanager) {
  3046. $parameters = array('element' => $element, 'id' => $id);
  3047. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3048. $out .= $hookmanager->resPrint;
  3049. }
  3050. if (empty($reshook)) {
  3051. if (empty($charfornl)) {
  3052. $out .= nl2br($address);
  3053. } else {
  3054. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3055. }
  3056. // TODO Remove this block, we can add this using the hook now
  3057. $showgmap = $showomap = 0;
  3058. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3059. $showgmap = 1;
  3060. }
  3061. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3062. $showgmap = 1;
  3063. }
  3064. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3065. $showgmap = 1;
  3066. }
  3067. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3068. $showomap = 1;
  3069. }
  3070. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3071. $showomap = 1;
  3072. }
  3073. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3074. $showomap = 1;
  3075. }
  3076. if ($showgmap) {
  3077. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3078. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3079. }
  3080. if ($showomap) {
  3081. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3082. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3083. }
  3084. }
  3085. }
  3086. if ($noprint) {
  3087. return $out;
  3088. } else {
  3089. print $out;
  3090. }
  3091. }
  3092. /**
  3093. * Return true if email syntax is ok.
  3094. *
  3095. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3096. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3097. * @return boolean true if email syntax is OK, false if KO or empty string
  3098. * @see isValidMXRecord()
  3099. */
  3100. function isValidEmail($address, $acceptsupervisorkey = 0)
  3101. {
  3102. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3103. return true;
  3104. }
  3105. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3106. return true;
  3107. }
  3108. return false;
  3109. }
  3110. /**
  3111. * Return if the domain name has a valid MX record.
  3112. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3113. *
  3114. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3115. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3116. * @see isValidEmail()
  3117. */
  3118. function isValidMXRecord($domain)
  3119. {
  3120. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3121. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3122. return 0;
  3123. }
  3124. if (function_exists('getmxrr')) {
  3125. $mxhosts = array();
  3126. $weight = array();
  3127. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3128. if (count($mxhosts) > 1) {
  3129. return 1;
  3130. }
  3131. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3132. return 1;
  3133. }
  3134. return 0;
  3135. }
  3136. }
  3137. return -1;
  3138. }
  3139. /**
  3140. * Return true if phone number syntax is ok
  3141. * TODO Decide what to do with this
  3142. *
  3143. * @param string $phone phone (Ex: "0601010101")
  3144. * @return boolean true if phone syntax is OK, false if KO or empty string
  3145. */
  3146. function isValidPhone($phone)
  3147. {
  3148. return true;
  3149. }
  3150. /**
  3151. * Make a strlen call. Works even if mbstring module not enabled
  3152. *
  3153. * @param string $string String to calculate length
  3154. * @param string $stringencoding Encoding of string
  3155. * @return int Length of string
  3156. */
  3157. function dol_strlen($string, $stringencoding = 'UTF-8')
  3158. {
  3159. if (function_exists('mb_strlen')) {
  3160. return mb_strlen($string, $stringencoding);
  3161. } else {
  3162. return strlen($string);
  3163. }
  3164. }
  3165. /**
  3166. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3167. *
  3168. * @param string $string String to scan
  3169. * @param string $start Start position
  3170. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3171. * @param string $stringencoding Page code used for input string encoding
  3172. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3173. * @return string substring
  3174. */
  3175. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3176. {
  3177. global $langs;
  3178. if (empty($stringencoding)) {
  3179. $stringencoding = $langs->charset_output;
  3180. }
  3181. $ret = '';
  3182. if (empty($trunconbytes)) {
  3183. if (function_exists('mb_substr')) {
  3184. $ret = mb_substr($string, $start, $length, $stringencoding);
  3185. } else {
  3186. $ret = substr($string, $start, $length);
  3187. }
  3188. } else {
  3189. if (function_exists('mb_strcut')) {
  3190. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3191. } else {
  3192. $ret = substr($string, $start, $length);
  3193. }
  3194. }
  3195. return $ret;
  3196. }
  3197. /**
  3198. * Truncate a string to a particular length adding '…' if string larger than length.
  3199. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3200. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3201. *
  3202. * @param string $string String to truncate
  3203. * @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 ...)
  3204. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3205. * @param string $stringencoding Tell what is source string encoding
  3206. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3207. * @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)
  3208. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3209. */
  3210. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3211. {
  3212. global $conf;
  3213. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3214. return $string;
  3215. }
  3216. if (empty($stringencoding)) {
  3217. $stringencoding = 'UTF-8';
  3218. }
  3219. // reduce for small screen
  3220. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3221. $size = round($size / 3);
  3222. }
  3223. // We go always here
  3224. if ($trunc == 'right') {
  3225. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3226. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3227. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3228. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3229. } else {
  3230. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3231. return $string;
  3232. }
  3233. } elseif ($trunc == 'middle') {
  3234. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3235. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3236. $size1 = round($size / 2);
  3237. $size2 = round($size / 2);
  3238. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3239. } else {
  3240. return $string;
  3241. }
  3242. } elseif ($trunc == 'left') {
  3243. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3244. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3245. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3246. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3247. } else {
  3248. return $string;
  3249. }
  3250. } elseif ($trunc == 'wrap') {
  3251. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3252. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3253. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3254. } else {
  3255. return $string;
  3256. }
  3257. } else {
  3258. return 'BadParam3CallingDolTrunc';
  3259. }
  3260. }
  3261. /**
  3262. * Show picto whatever it's its name (generic function)
  3263. *
  3264. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3265. * @param string $picto Name of image file to show ('filenew', ...)
  3266. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3267. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3268. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3269. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3270. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3271. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3272. * @param int $srconly Return only content of the src attribute of img.
  3273. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3274. * @param string $alt Force alt for bind people
  3275. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3276. * @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.
  3277. * @return string Return img tag
  3278. * @see img_object(), img_picto_common()
  3279. */
  3280. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3281. {
  3282. global $conf, $langs;
  3283. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3284. $url = DOL_URL_ROOT;
  3285. $theme = isset($conf->theme) ? $conf->theme : null;
  3286. $path = 'theme/'.$theme;
  3287. // Define fullpathpicto to use into src
  3288. if ($pictoisfullpath) {
  3289. // Clean parameters
  3290. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3291. $picto .= '.png';
  3292. }
  3293. $fullpathpicto = $picto;
  3294. $reg = array();
  3295. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3296. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3297. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3298. }
  3299. } else {
  3300. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3301. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3302. if (empty($srconly) && in_array($pictowithouttext, array(
  3303. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3304. 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3305. 'bank_account', 'barcode', 'bank', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'bug', 'building',
  3306. 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3307. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3308. 'multicurrency',
  3309. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3310. 'edit', 'ellipsis-h', 'email', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3311. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3312. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3313. 'help', 'holiday',
  3314. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3315. 'label', 'language', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3316. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3317. 'off', 'on', 'order',
  3318. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'stock', 'resize', 'service', 'stats', 'trip',
  3319. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3320. 'github', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3321. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3322. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3323. 'partnership', 'payment', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3324. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3325. 'technic', 'ticket',
  3326. 'error', 'warning',
  3327. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource',
  3328. 'shapes', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3329. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3330. 'uncheck', 'user-cog', 'website', 'workstation',
  3331. 'conferenceorbooth', 'eventorganization'
  3332. ))) {
  3333. $fakey = $pictowithouttext;
  3334. $facolor = '';
  3335. $fasize = '';
  3336. $fa = 'fas';
  3337. if (in_array($pictowithouttext, array('clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3338. $fa = 'far';
  3339. }
  3340. if (in_array($pictowithouttext, array('black-tie', 'github', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3341. $fa = 'fab';
  3342. }
  3343. $arrayconvpictotofa = array(
  3344. 'account'=>'university', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  3345. 'bank_account'=>'university',
  3346. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3347. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3348. 'bom'=>'shapes',
  3349. 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3350. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3351. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3352. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3353. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3354. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3355. 'email'=>'at', 'establishment'=>'building',
  3356. 'edit'=>'pencil-alt', 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3357. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3358. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'loan'=>'money-bill-alt',
  3359. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3360. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3361. 'sign-out'=>'sign-out-alt',
  3362. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star',
  3363. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter',
  3364. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3365. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3366. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3367. 'other'=>'square',
  3368. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3369. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell',
  3370. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3371. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3372. 'refresh'=>'redo', 'region'=>'map-marked', 'resource'=>'laptop-house',
  3373. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3374. 'supplier'=>'building', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt',
  3375. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3376. 'title_agenda'=>'calendar-alt',
  3377. 'uncheck'=>'times', 'uparrow'=>'share', 'vcard'=>'address-card',
  3378. 'jabber'=>'comment-o',
  3379. 'website'=>'globe-americas', 'workstation'=>'pallet',
  3380. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3381. );
  3382. if ($pictowithouttext == 'off') {
  3383. $fakey = 'fa-square';
  3384. $fasize = '1.3em';
  3385. } elseif ($pictowithouttext == 'on') {
  3386. $fakey = 'fa-check-square';
  3387. $fasize = '1.3em';
  3388. } elseif ($pictowithouttext == 'listlight') {
  3389. $fakey = 'fa-download';
  3390. $marginleftonlyshort = 1;
  3391. } elseif ($pictowithouttext == 'printer') {
  3392. $fakey = 'fa-print';
  3393. $fasize = '1.2em';
  3394. } elseif ($pictowithouttext == 'note') {
  3395. $fakey = 'fa-sticky-note';
  3396. $marginleftonlyshort = 1;
  3397. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3398. $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');
  3399. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3400. if (preg_match('/selected/', $pictowithouttext)) {
  3401. $facolor = '#888';
  3402. }
  3403. $marginleftonlyshort = 1;
  3404. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3405. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3406. } else {
  3407. $fakey = 'fa-'.$pictowithouttext;
  3408. }
  3409. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3410. $morecss .= ' em092';
  3411. }
  3412. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3413. $morecss .= ' em088';
  3414. }
  3415. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3416. $morecss .= ' em080';
  3417. }
  3418. // Define $marginleftonlyshort
  3419. $arrayconvpictotomarginleftonly = array(
  3420. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3421. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_off',
  3422. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3423. );
  3424. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3425. $marginleftonlyshort = 0;
  3426. }
  3427. // Add CSS
  3428. $arrayconvpictotomorcess = array(
  3429. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3430. 'bank_account'=>'bg-infobox-bank_account',
  3431. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3432. 'conferenceorbooth'=>'infobox-project',
  3433. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3434. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3435. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3436. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3437. 'incoterm'=>'infobox-supplier_proposal',
  3438. 'multicurrency'=>'infobox-bank_account',
  3439. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3440. 'order'=>'infobox-commande',
  3441. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3442. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4',
  3443. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3444. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3445. 'payment'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  3446. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3447. 'resource'=>'infobox-action',
  3448. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3449. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3450. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3451. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3452. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3453. );
  3454. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3455. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3456. }
  3457. // Define $color
  3458. $arrayconvpictotocolor = array(
  3459. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3460. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3461. 'dynamicprice'=>'#a69944',
  3462. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3463. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3464. 'lot'=>'#a69944',
  3465. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3466. 'other'=>'#ddd',
  3467. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3468. //'shipment'=>'#a69944',
  3469. 'security'=>'#999', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3470. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3471. 'website'=>'#304', 'workstation'=>'#a69944'
  3472. );
  3473. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3474. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3475. }
  3476. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3477. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3478. $morestyle = '';
  3479. $reg = array();
  3480. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3481. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3482. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3483. }
  3484. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3485. $morestyle = $reg[1];
  3486. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3487. }
  3488. $moreatt = trim($moreatt);
  3489. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3490. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3491. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3492. $enabledisablehtml .= $titlealt;
  3493. }*/
  3494. $enabledisablehtml .= '</span>';
  3495. return $enabledisablehtml;
  3496. }
  3497. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3498. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3499. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3500. $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
  3501. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3502. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3503. }
  3504. // If we ask an image into $url/$mymodule/img (instead of default path)
  3505. $regs = array();
  3506. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3507. $picto = $regs[1];
  3508. $path = $regs[2]; // $path is $mymodule
  3509. }
  3510. // Clean parameters
  3511. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3512. $picto .= '.png';
  3513. }
  3514. // If alt path are defined, define url where img file is, according to physical path
  3515. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3516. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3517. if ($type == 'main') {
  3518. continue;
  3519. }
  3520. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3521. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3522. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3523. break;
  3524. }
  3525. }
  3526. // $url is '' or '/custom', $path is current theme or
  3527. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3528. }
  3529. if ($srconly) {
  3530. return $fullpathpicto;
  3531. }
  3532. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3533. 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
  3534. }
  3535. /**
  3536. * Show a picto called object_picto (generic function)
  3537. *
  3538. * @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.
  3539. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3540. * For external modules use imagename@mymodule to search into directory "img" of module.
  3541. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3542. * @param int $pictoisfullpath If 1, image path is a full path
  3543. * @param int $srconly Return only content of the src attribute of img.
  3544. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3545. * @return string Return img tag
  3546. * @see img_picto(), img_picto_common()
  3547. */
  3548. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3549. {
  3550. if (strpos($picto, '^') === 0) {
  3551. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3552. } else {
  3553. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3554. }
  3555. }
  3556. /**
  3557. * Show weather picto
  3558. *
  3559. * @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.
  3560. * @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).
  3561. * @param string $moreatt Add more attribute on img tag
  3562. * @param int $pictoisfullpath If 1, image path is a full path
  3563. * @param string $morecss More CSS
  3564. * @return string Return img tag
  3565. * @see img_object(), img_picto()
  3566. */
  3567. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3568. {
  3569. global $conf;
  3570. if (is_numeric($picto)) {
  3571. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3572. //$picto = $leveltopicto[$picto];
  3573. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3574. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3575. $picto .= '.png';
  3576. }
  3577. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3578. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3579. }
  3580. /**
  3581. * Show picto (generic function)
  3582. *
  3583. * @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.
  3584. * @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.
  3585. * @param string $moreatt Add more attribute on img tag
  3586. * @param int $pictoisfullpath If 1, image path is a full path
  3587. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3588. * @return string Return img tag
  3589. * @see img_object(), img_picto()
  3590. */
  3591. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  3592. {
  3593. global $conf;
  3594. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3595. $picto .= '.png';
  3596. }
  3597. if ($pictoisfullpath) {
  3598. $path = $picto;
  3599. } else {
  3600. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3601. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3602. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3603. if (file_exists($themepath)) {
  3604. $path = $themepath;
  3605. }
  3606. }
  3607. }
  3608. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  3609. }
  3610. /**
  3611. * Show logo action
  3612. *
  3613. * @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.
  3614. * @param string $numaction Action id or code to show
  3615. * @param string $picto Name of image file to show ('filenew', ...)
  3616. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3617. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3618. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3619. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3620. * @return string Return an img tag
  3621. */
  3622. function img_action($titlealt, $numaction, $picto = '')
  3623. {
  3624. global $langs;
  3625. if (empty($titlealt) || $titlealt == 'default') {
  3626. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3627. $numaction = -1;
  3628. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3629. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3630. $numaction = 0;
  3631. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3632. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3633. $numaction = 1;
  3634. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3635. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3636. $numaction = 2;
  3637. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3638. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3639. $numaction = 3;
  3640. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3641. } else {
  3642. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3643. $numaction = 0;
  3644. }
  3645. }
  3646. if (!is_numeric($numaction)) {
  3647. $numaction = 0;
  3648. }
  3649. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3650. }
  3651. /**
  3652. * Show pdf logo
  3653. *
  3654. * @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.
  3655. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3656. * @return string Retourne tag img
  3657. */
  3658. function img_pdf($titlealt = 'default', $size = 3)
  3659. {
  3660. global $langs;
  3661. if ($titlealt == 'default') {
  3662. $titlealt = $langs->trans('Show');
  3663. }
  3664. return img_picto($titlealt, 'pdf'.$size.'.png');
  3665. }
  3666. /**
  3667. * Show logo +
  3668. *
  3669. * @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.
  3670. * @param string $other Add more attributes on img
  3671. * @return string Return tag img
  3672. */
  3673. function img_edit_add($titlealt = 'default', $other = '')
  3674. {
  3675. global $langs;
  3676. if ($titlealt == 'default') {
  3677. $titlealt = $langs->trans('Add');
  3678. }
  3679. return img_picto($titlealt, 'edit_add.png', $other);
  3680. }
  3681. /**
  3682. * Show logo -
  3683. *
  3684. * @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.
  3685. * @param string $other Add more attributes on img
  3686. * @return string Return tag img
  3687. */
  3688. function img_edit_remove($titlealt = 'default', $other = '')
  3689. {
  3690. global $langs;
  3691. if ($titlealt == 'default') {
  3692. $titlealt = $langs->trans('Remove');
  3693. }
  3694. return img_picto($titlealt, 'edit_remove.png', $other);
  3695. }
  3696. /**
  3697. * Show logo editer/modifier fiche
  3698. *
  3699. * @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.
  3700. * @param integer $float If you have to put the style "float: right"
  3701. * @param string $other Add more attributes on img
  3702. * @return string Return tag img
  3703. */
  3704. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3705. {
  3706. global $langs;
  3707. if ($titlealt == 'default') {
  3708. $titlealt = $langs->trans('Modify');
  3709. }
  3710. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3711. }
  3712. /**
  3713. * Show logo view card
  3714. *
  3715. * @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.
  3716. * @param integer $float If you have to put the style "float: right"
  3717. * @param string $other Add more attributes on img
  3718. * @return string Return tag img
  3719. */
  3720. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  3721. {
  3722. global $langs;
  3723. if ($titlealt == 'default') {
  3724. $titlealt = $langs->trans('View');
  3725. }
  3726. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3727. return img_picto($titlealt, 'view.png', $moreatt);
  3728. }
  3729. /**
  3730. * Show delete logo
  3731. *
  3732. * @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.
  3733. * @param string $other Add more attributes on img
  3734. * @param string $morecss More CSS
  3735. * @return string Retourne tag img
  3736. */
  3737. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3738. {
  3739. global $langs;
  3740. if ($titlealt == 'default') {
  3741. $titlealt = $langs->trans('Delete');
  3742. }
  3743. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3744. }
  3745. /**
  3746. * Show printer logo
  3747. *
  3748. * @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.
  3749. * @param string $other Add more attributes on img
  3750. * @return string Retourne tag img
  3751. */
  3752. function img_printer($titlealt = "default", $other = '')
  3753. {
  3754. global $langs;
  3755. if ($titlealt == "default") {
  3756. $titlealt = $langs->trans("Print");
  3757. }
  3758. return img_picto($titlealt, 'printer.png', $other);
  3759. }
  3760. /**
  3761. * Show split logo
  3762. *
  3763. * @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.
  3764. * @param string $other Add more attributes on img
  3765. * @return string Retourne tag img
  3766. */
  3767. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3768. {
  3769. global $langs;
  3770. if ($titlealt == 'default') {
  3771. $titlealt = $langs->trans('Split');
  3772. }
  3773. return img_picto($titlealt, 'split.png', $other);
  3774. }
  3775. /**
  3776. * Show help logo with cursor "?"
  3777. *
  3778. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3779. * @param int|string $usealttitle Text to use as alt title
  3780. * @return string Return tag img
  3781. */
  3782. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3783. {
  3784. global $langs;
  3785. if ($usealttitle) {
  3786. if (is_string($usealttitle)) {
  3787. $usealttitle = dol_escape_htmltag($usealttitle);
  3788. } else {
  3789. $usealttitle = $langs->trans('Info');
  3790. }
  3791. }
  3792. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3793. }
  3794. /**
  3795. * Show info logo
  3796. *
  3797. * @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.
  3798. * @return string Return img tag
  3799. */
  3800. function img_info($titlealt = 'default')
  3801. {
  3802. global $langs;
  3803. if ($titlealt == 'default') {
  3804. $titlealt = $langs->trans('Informations');
  3805. }
  3806. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3807. }
  3808. /**
  3809. * Show warning logo
  3810. *
  3811. * @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.
  3812. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3813. * @param string $morecss Add more CSS
  3814. * @return string Return img tag
  3815. */
  3816. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3817. {
  3818. global $langs;
  3819. if ($titlealt == 'default') {
  3820. $titlealt = $langs->trans('Warning');
  3821. }
  3822. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3823. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3824. }
  3825. /**
  3826. * Show error logo
  3827. *
  3828. * @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.
  3829. * @return string Return img tag
  3830. */
  3831. function img_error($titlealt = 'default')
  3832. {
  3833. global $langs;
  3834. if ($titlealt == 'default') {
  3835. $titlealt = $langs->trans('Error');
  3836. }
  3837. return img_picto($titlealt, 'error.png');
  3838. }
  3839. /**
  3840. * Show next logo
  3841. *
  3842. * @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.
  3843. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3844. * @return string Return img tag
  3845. */
  3846. function img_next($titlealt = 'default', $moreatt = '')
  3847. {
  3848. global $langs;
  3849. if ($titlealt == 'default') {
  3850. $titlealt = $langs->trans('Next');
  3851. }
  3852. //return img_picto($titlealt, 'next.png', $moreatt);
  3853. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3854. }
  3855. /**
  3856. * Show previous logo
  3857. *
  3858. * @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.
  3859. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3860. * @return string Return img tag
  3861. */
  3862. function img_previous($titlealt = 'default', $moreatt = '')
  3863. {
  3864. global $langs;
  3865. if ($titlealt == 'default') {
  3866. $titlealt = $langs->trans('Previous');
  3867. }
  3868. //return img_picto($titlealt, 'previous.png', $moreatt);
  3869. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3870. }
  3871. /**
  3872. * Show down arrow logo
  3873. *
  3874. * @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.
  3875. * @param int $selected Selected
  3876. * @param string $moreclass Add more CSS classes
  3877. * @return string Return img tag
  3878. */
  3879. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3880. {
  3881. global $langs;
  3882. if ($titlealt == 'default') {
  3883. $titlealt = $langs->trans('Down');
  3884. }
  3885. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3886. }
  3887. /**
  3888. * Show top arrow logo
  3889. *
  3890. * @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.
  3891. * @param int $selected Selected
  3892. * @param string $moreclass Add more CSS classes
  3893. * @return string Return img tag
  3894. */
  3895. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3896. {
  3897. global $langs;
  3898. if ($titlealt == 'default') {
  3899. $titlealt = $langs->trans('Up');
  3900. }
  3901. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3902. }
  3903. /**
  3904. * Show left arrow logo
  3905. *
  3906. * @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.
  3907. * @param int $selected Selected
  3908. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3909. * @return string Return img tag
  3910. */
  3911. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3912. {
  3913. global $langs;
  3914. if ($titlealt == 'default') {
  3915. $titlealt = $langs->trans('Left');
  3916. }
  3917. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3918. }
  3919. /**
  3920. * Show right arrow logo
  3921. *
  3922. * @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.
  3923. * @param int $selected Selected
  3924. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3925. * @return string Return img tag
  3926. */
  3927. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3928. {
  3929. global $langs;
  3930. if ($titlealt == 'default') {
  3931. $titlealt = $langs->trans('Right');
  3932. }
  3933. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3934. }
  3935. /**
  3936. * Show tick logo if allowed
  3937. *
  3938. * @param string $allow Allow
  3939. * @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.
  3940. * @return string Return img tag
  3941. */
  3942. function img_allow($allow, $titlealt = 'default')
  3943. {
  3944. global $langs;
  3945. if ($titlealt == 'default') {
  3946. $titlealt = $langs->trans('Active');
  3947. }
  3948. if ($allow == 1) {
  3949. return img_picto($titlealt, 'tick.png');
  3950. }
  3951. return '-';
  3952. }
  3953. /**
  3954. * Return image of a credit card according to its brand name
  3955. *
  3956. * @param string $brand Brand name of credit card
  3957. * @param string $morecss More CSS
  3958. * @return string Return img tag
  3959. */
  3960. function img_credit_card($brand, $morecss = null)
  3961. {
  3962. if (is_null($morecss)) {
  3963. $morecss = 'fa-2x';
  3964. }
  3965. if ($brand == 'visa' || $brand == 'Visa') {
  3966. $brand = 'cc-visa';
  3967. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  3968. $brand = 'cc-mastercard';
  3969. } elseif ($brand == 'amex' || $brand == 'American Express') {
  3970. $brand = 'cc-amex';
  3971. } elseif ($brand == 'discover' || $brand == 'Discover') {
  3972. $brand = 'cc-discover';
  3973. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  3974. $brand = 'cc-jcb';
  3975. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  3976. $brand = 'cc-diners-club';
  3977. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  3978. $brand = 'credit-card';
  3979. }
  3980. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  3981. }
  3982. /**
  3983. * Show MIME img of a file
  3984. *
  3985. * @param string $file Filename
  3986. * @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.
  3987. * @param string $morecss More css
  3988. * @return string Return img tag
  3989. */
  3990. function img_mime($file, $titlealt = '', $morecss = '')
  3991. {
  3992. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3993. $mimetype = dol_mimetype($file, '', 1);
  3994. $mimeimg = dol_mimetype($file, '', 2);
  3995. $mimefa = dol_mimetype($file, '', 4);
  3996. if (empty($titlealt)) {
  3997. $titlealt = 'Mime type: '.$mimetype;
  3998. }
  3999. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4000. return '<i class="fa fa-'.$mimefa.' paddingright"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4001. }
  4002. /**
  4003. * Show search logo
  4004. *
  4005. * @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.
  4006. * @param string $other Add more attributes on img
  4007. * @return string Retourne tag img
  4008. */
  4009. function img_search($titlealt = 'default', $other = '')
  4010. {
  4011. global $conf, $langs;
  4012. if ($titlealt == 'default') {
  4013. $titlealt = $langs->trans('Search');
  4014. }
  4015. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4016. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4017. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4018. return $input;
  4019. }
  4020. /**
  4021. * Show search logo
  4022. *
  4023. * @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.
  4024. * @param string $other Add more attributes on img
  4025. * @return string Retourne tag img
  4026. */
  4027. function img_searchclear($titlealt = 'default', $other = '')
  4028. {
  4029. global $conf, $langs;
  4030. if ($titlealt == 'default') {
  4031. $titlealt = $langs->trans('Search');
  4032. }
  4033. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4034. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4035. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4036. return $input;
  4037. }
  4038. /**
  4039. * Show information for admin users or standard users
  4040. *
  4041. * @param string $text Text info
  4042. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4043. * @param int $nodiv No div
  4044. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4045. * @param string $morecss More CSS ('', 'warning', 'error')
  4046. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4047. * @return string String with info text
  4048. */
  4049. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  4050. {
  4051. global $conf, $langs;
  4052. if ($infoonimgalt) {
  4053. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  4054. } else {
  4055. if (empty($conf->use_javascript_ajax)) {
  4056. $textfordropdown = '';
  4057. }
  4058. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4059. $result = ($nodiv ? '' : '<div class="'.$class.' hideonsmartphone'.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  4060. if ($textfordropdown) {
  4061. $tmpresult .= '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4062. $tmpresult .= '<script type="text/javascript" language="javascript">
  4063. jQuery(document).ready(function() {
  4064. jQuery(".'.$class.'text").click(function() {
  4065. console.log("toggle text");
  4066. jQuery(".'.$class.'").toggle();
  4067. });
  4068. });
  4069. </script>';
  4070. $result = $tmpresult.$result;
  4071. }
  4072. }
  4073. return $result;
  4074. }
  4075. /**
  4076. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4077. * This function must be called when a blocking technical error is encountered.
  4078. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4079. *
  4080. * @param DoliDB $db Database handler
  4081. * @param string|string[] $error String or array of errors strings to show
  4082. * @param array $errors Array of errors
  4083. * @return void
  4084. * @see dol_htmloutput_errors()
  4085. */
  4086. function dol_print_error($db = '', $error = '', $errors = null)
  4087. {
  4088. global $conf, $langs, $argv;
  4089. global $dolibarr_main_prod;
  4090. $out = '';
  4091. $syslog = '';
  4092. // If error occurs before the $lang object was loaded
  4093. if (!$langs) {
  4094. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4095. $langs = new Translate('', $conf);
  4096. $langs->load("main");
  4097. }
  4098. // Load translation files required by the error messages
  4099. $langs->loadLangs(array('main', 'errors'));
  4100. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4101. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4102. if (!empty($conf->global->MAIN_FEATURES_LEVEL)) {
  4103. $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";
  4104. }
  4105. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4106. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4107. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4108. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4109. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".dol_htmlentities($conf->global->MAIN_FEATURES_LEVEL, ENT_COMPAT)."<br>\n";
  4110. }
  4111. if (function_exists("phpversion")) {
  4112. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4113. }
  4114. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4115. if (function_exists("php_uname")) {
  4116. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4117. }
  4118. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4119. $out .= "<br>\n";
  4120. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4121. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4122. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4123. $out .= "<br>\n";
  4124. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4125. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4126. } else // Mode CLI
  4127. {
  4128. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4129. $syslog .= "pid=".dol_getmypid();
  4130. }
  4131. if (!empty($conf->modules)) {
  4132. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4133. }
  4134. if (is_object($db)) {
  4135. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4136. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4137. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4138. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4139. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4140. $out .= "<br>\n";
  4141. } else // Mode CLI
  4142. {
  4143. // No dol_escape_htmltag for output, we are in CLI mode
  4144. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4145. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4146. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4147. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4148. }
  4149. $syslog .= ", sql=".$db->lastquery();
  4150. $syslog .= ", db_error=".$db->lasterror();
  4151. }
  4152. if ($error || $errors) {
  4153. $langs->load("errors");
  4154. // Merge all into $errors array
  4155. if (is_array($error) && is_array($errors)) {
  4156. $errors = array_merge($error, $errors);
  4157. } elseif (is_array($error)) {
  4158. $errors = $error;
  4159. } elseif (is_array($errors)) {
  4160. $errors = array_merge(array($error), $errors);
  4161. } else {
  4162. $errors = array_merge(array($error));
  4163. }
  4164. foreach ($errors as $msg) {
  4165. if (empty($msg)) {
  4166. continue;
  4167. }
  4168. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4169. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4170. } else // Mode CLI
  4171. {
  4172. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4173. }
  4174. $syslog .= ", msg=".$msg;
  4175. }
  4176. }
  4177. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4178. xdebug_print_function_stack();
  4179. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4180. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4181. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4182. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4183. $out .= "<br>\n";
  4184. }
  4185. // Return a http error code if possible
  4186. if (!headers_sent()) {
  4187. http_response_code(500);
  4188. }
  4189. if (empty($dolibarr_main_prod)) {
  4190. print $out;
  4191. } else {
  4192. if (empty($langs->defaultlang)) {
  4193. $langs->setDefaultLang();
  4194. }
  4195. $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.
  4196. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4197. 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";
  4198. print $langs->trans("DolibarrHasDetectedError").'. ';
  4199. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4200. define("MAIN_CORE_ERROR", 1);
  4201. }
  4202. dol_syslog("Error ".$syslog, LOG_ERR);
  4203. }
  4204. /**
  4205. * Show a public email and error code to contact if technical error
  4206. *
  4207. * @param string $prefixcode Prefix of public error code
  4208. * @param string $errormessage Complete error message
  4209. * @param array $errormessages Array of error messages
  4210. * @param string $morecss More css
  4211. * @param string $email Email
  4212. * @return void
  4213. */
  4214. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4215. {
  4216. global $langs, $conf;
  4217. if (empty($email)) {
  4218. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4219. }
  4220. $langs->load("errors");
  4221. $now = dol_now();
  4222. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4223. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4224. if ($errormessage) {
  4225. print '<br><br>'.$errormessage;
  4226. }
  4227. if (is_array($errormessages) && count($errormessages)) {
  4228. foreach ($errormessages as $mesgtoshow) {
  4229. print '<br><br>'.$mesgtoshow;
  4230. }
  4231. }
  4232. print '</div></div>';
  4233. }
  4234. /**
  4235. * Show title line of an array
  4236. *
  4237. * @param string $name Label of field
  4238. * @param string $file Url used when we click on sort picto
  4239. * @param string $field Field to use for new sorting
  4240. * @param string $begin ("" by defaut)
  4241. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4242. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  4243. * @param string $sortfield Current field used to sort
  4244. * @param string $sortorder Current sort order
  4245. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4246. * @param string $tooltip Tooltip
  4247. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4248. * @return void
  4249. */
  4250. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4251. {
  4252. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4253. }
  4254. /**
  4255. * Get title line of an array
  4256. *
  4257. * @param string $name Translation key of field to show or complete HTML string to show
  4258. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4259. * @param string $file Url used when we click on sort picto
  4260. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4261. * @param string $begin ("" by defaut)
  4262. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4263. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  4264. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4265. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4266. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4267. * @param string $disablesortlink 1=Disable sort link
  4268. * @param string $tooltip Tooltip
  4269. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4270. * @return string
  4271. */
  4272. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4273. {
  4274. global $conf, $langs, $form;
  4275. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4276. if ($moreattrib == 'class="right"') {
  4277. $prefix .= 'right '; // For backward compatibility
  4278. }
  4279. $sortorder = strtoupper($sortorder);
  4280. $out = '';
  4281. $sortimg = '';
  4282. $tag = 'th';
  4283. if ($thead == 2) {
  4284. $tag = 'div';
  4285. }
  4286. $tmpsortfield = explode(',', $sortfield);
  4287. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4288. $tmpfield = explode(',', $field);
  4289. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4290. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4291. $prefix = 'wrapcolumntitle '.$prefix;
  4292. }
  4293. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4294. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4295. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4296. $liste_titre = 'liste_titre';
  4297. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4298. $liste_titre = 'liste_titre_sel';
  4299. }
  4300. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4301. //$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)).'"' : '');
  4302. $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4303. $out .= '>';
  4304. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4305. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4306. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4307. $options = preg_replace('/&+/i', '&', $options);
  4308. if (!preg_match('/^&/', $options)) {
  4309. $options = '&'.$options;
  4310. }
  4311. $sortordertouseinlink = '';
  4312. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4313. if (preg_match('/^DESC/i', $sortorder)) {
  4314. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4315. } else // We reverse the var $sortordertouseinlink
  4316. {
  4317. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4318. }
  4319. } else // We are on field that is the first current sorting criteria
  4320. {
  4321. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4322. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4323. } else {
  4324. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4325. }
  4326. }
  4327. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4328. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4329. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4330. $out .= '>';
  4331. }
  4332. if ($tooltip) {
  4333. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4334. $tmptooltip = explode(':', $tooltip);
  4335. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4336. } else {
  4337. $out .= $langs->trans($name);
  4338. }
  4339. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4340. $out .= '</a>';
  4341. }
  4342. if (empty($thead) && $field) { // If this is a sort field
  4343. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4344. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4345. $options = preg_replace('/&+/i', '&', $options);
  4346. if (!preg_match('/^&/', $options)) {
  4347. $options = '&'.$options;
  4348. }
  4349. if (!$sortorder || $field1 != $sortfield1) {
  4350. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4351. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4352. } else {
  4353. if (preg_match('/^DESC/', $sortorder)) {
  4354. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4355. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4356. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  4357. }
  4358. if (preg_match('/^ASC/', $sortorder)) {
  4359. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4360. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4361. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  4362. }
  4363. }
  4364. }
  4365. $out .= $sortimg;
  4366. $out .= '</'.$tag.'>';
  4367. return $out;
  4368. }
  4369. /**
  4370. * Show a title.
  4371. *
  4372. * @param string $title Title to show
  4373. * @return string Title to show
  4374. * @deprecated Use load_fiche_titre instead
  4375. * @see load_fiche_titre()
  4376. */
  4377. function print_titre($title)
  4378. {
  4379. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4380. print '<div class="titre">'.$title.'</div>';
  4381. }
  4382. /**
  4383. * Show a title with picto
  4384. *
  4385. * @param string $title Title to show
  4386. * @param string $mesg Added message to show on right
  4387. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4388. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4389. * @param int $id To force an id on html objects
  4390. * @return void
  4391. * @deprecated Use print load_fiche_titre instead
  4392. */
  4393. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4394. {
  4395. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4396. }
  4397. /**
  4398. * Load a title with picto
  4399. *
  4400. * @param string $titre Title to show
  4401. * @param string $morehtmlright Added message to show on right
  4402. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4403. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4404. * @param string $id To force an id on html objects
  4405. * @param string $morecssontable More css on table
  4406. * @param string $morehtmlcenter Added message to show on center
  4407. * @return string
  4408. * @see print_barre_liste()
  4409. */
  4410. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4411. {
  4412. global $conf;
  4413. $return = '';
  4414. if ($picto == 'setup') {
  4415. $picto = 'generic';
  4416. }
  4417. $return .= "\n";
  4418. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4419. $return .= '<tr class="titre">';
  4420. if ($picto) {
  4421. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4422. }
  4423. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4424. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4425. $return .= '</td>';
  4426. if (dol_strlen($morehtmlcenter)) {
  4427. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4428. }
  4429. if (dol_strlen($morehtmlright)) {
  4430. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4431. }
  4432. $return .= '</tr></table>'."\n";
  4433. return $return;
  4434. }
  4435. /**
  4436. * Print a title with navigation controls for pagination
  4437. *
  4438. * @param string $titre Title to show (required)
  4439. * @param int $page Numero of page to show in navigation links (required)
  4440. * @param string $file Url of page (required)
  4441. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4442. * @param string $sortfield Field to sort on ('' by default)
  4443. * @param string $sortorder Order to sort ('' by default)
  4444. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4445. * @param int $num Number of records found by select with limit+1
  4446. * @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.
  4447. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4448. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4449. * @param string $morehtmlright More html to show (after arrows)
  4450. * @param string $morecss More css to the table
  4451. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4452. * @param int $hideselectlimit Force to hide select limit
  4453. * @param int $hidenavigation Force to hide all navigation tools
  4454. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4455. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4456. * @return void
  4457. */
  4458. 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 = '')
  4459. {
  4460. global $conf, $langs;
  4461. $savlimit = $limit;
  4462. $savtotalnboflines = $totalnboflines;
  4463. $totalnboflines = abs((int) $totalnboflines);
  4464. if ($picto == 'setup') {
  4465. $picto = 'title_setup.png';
  4466. }
  4467. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4468. $picto = 'title.gif';
  4469. }
  4470. if ($limit < 0) {
  4471. $limit = $conf->liste_limit;
  4472. }
  4473. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4474. $nextpage = 1;
  4475. } else {
  4476. $nextpage = 0;
  4477. }
  4478. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4479. print "\n";
  4480. print "<!-- Begin title -->\n";
  4481. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4482. // Left
  4483. if ($picto && $titre) {
  4484. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4485. }
  4486. print '<td class="nobordernopadding valignmiddle col-title">';
  4487. print '<div class="titre inline-block">'.$titre;
  4488. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4489. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4490. }
  4491. print '</div></td>';
  4492. // Center
  4493. if ($morehtmlcenter) {
  4494. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4495. }
  4496. // Right
  4497. print '<td class="nobordernopadding valignmiddle right">';
  4498. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4499. if ($sortfield) {
  4500. $options .= "&sortfield=".urlencode($sortfield);
  4501. }
  4502. if ($sortorder) {
  4503. $options .= "&sortorder=".urlencode($sortorder);
  4504. }
  4505. // Show navigation bar
  4506. $pagelist = '';
  4507. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4508. if ($totalnboflines) { // If we know total nb of lines
  4509. // Define nb of extra page links before and after selected page + ... + first or last
  4510. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4511. if ($limit > 0) {
  4512. $nbpages = ceil($totalnboflines / $limit);
  4513. } else {
  4514. $nbpages = 1;
  4515. }
  4516. $cpt = ($page - $maxnbofpage);
  4517. if ($cpt < 0) {
  4518. $cpt = 0;
  4519. }
  4520. if ($cpt >= 1) {
  4521. if (empty($pagenavastextinput)) {
  4522. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4523. if ($cpt > 2) {
  4524. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4525. } elseif ($cpt == 2) {
  4526. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4527. }
  4528. }
  4529. }
  4530. do {
  4531. if ($pagenavastextinput) {
  4532. if ($cpt == $page) {
  4533. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4534. $pagelist .= '/';
  4535. //if (($cpt + 1) < $nbpages) $pagelist .= '/';
  4536. }
  4537. } else {
  4538. if ($cpt == $page) {
  4539. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4540. } else {
  4541. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4542. }
  4543. }
  4544. $cpt++;
  4545. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4546. if (empty($pagenavastextinput)) {
  4547. if ($cpt < $nbpages) {
  4548. if ($cpt < $nbpages - 2) {
  4549. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4550. } elseif ($cpt == $nbpages - 2) {
  4551. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4552. }
  4553. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4554. }
  4555. } else {
  4556. //var_dump($page.' '.$cpt.' '.$nbpages);
  4557. //if (($page + 1) < $nbpages) {
  4558. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4559. //}
  4560. }
  4561. } else {
  4562. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4563. }
  4564. }
  4565. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4566. 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
  4567. }
  4568. // js to autoselect page field on focus
  4569. if ($pagenavastextinput) {
  4570. print ajax_autoselect('.pageplusone');
  4571. }
  4572. print '</td>';
  4573. print '</tr></table>'."\n";
  4574. print "<!-- End title -->\n\n";
  4575. }
  4576. /**
  4577. * Function to show navigation arrows into lists
  4578. *
  4579. * @param int $page Number of page
  4580. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4581. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4582. * @param integer $nextpage Do we show a next page button
  4583. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4584. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4585. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4586. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4587. * @param int $hideselectlimit Force to hide select limit
  4588. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4589. * @return void
  4590. */
  4591. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4592. {
  4593. global $conf, $langs;
  4594. print '<div class="pagination"><ul>';
  4595. if ($beforearrows) {
  4596. print '<li class="paginationbeforearrows">';
  4597. print $beforearrows;
  4598. print '</li>';
  4599. }
  4600. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4601. $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';
  4602. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4603. //$pagesizechoices.=',2:2';
  4604. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4605. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4606. }
  4607. print '<li class="pagination">';
  4608. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4609. $tmpchoice = explode(',', $pagesizechoices);
  4610. $tmpkey = $limit.':'.$limit;
  4611. if (!in_array($tmpkey, $tmpchoice)) {
  4612. $tmpchoice[] = $tmpkey;
  4613. }
  4614. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4615. if (!in_array($tmpkey, $tmpchoice)) {
  4616. $tmpchoice[] = $tmpkey;
  4617. }
  4618. asort($tmpchoice, SORT_NUMERIC);
  4619. foreach ($tmpchoice as $val) {
  4620. $selected = '';
  4621. $tmp = explode(':', $val);
  4622. $key = $tmp[0];
  4623. $val = $tmp[1];
  4624. if ($key != '' && $val != '') {
  4625. if ((int) $key == (int) $limit) {
  4626. $selected = ' selected="selected"';
  4627. }
  4628. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4629. }
  4630. }
  4631. print '</select>';
  4632. if ($conf->use_javascript_ajax) {
  4633. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4634. <script>
  4635. jQuery(document).ready(function () {
  4636. jQuery(".selectlimit").change(function() {
  4637. console.log("Change limit. Send submit");
  4638. $(this).parents(\'form:first\').submit();
  4639. });
  4640. });
  4641. </script>
  4642. ';
  4643. }
  4644. print '</li>';
  4645. }
  4646. if ($page > 0) {
  4647. 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>';
  4648. }
  4649. if ($betweenarrows) {
  4650. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4651. print $betweenarrows;
  4652. print '<!--</div>-->';
  4653. }
  4654. if ($nextpage > 0) {
  4655. 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>';
  4656. }
  4657. if ($afterarrows) {
  4658. print '<li class="paginationafterarrows">';
  4659. print $afterarrows;
  4660. print '</li>';
  4661. }
  4662. print '</ul></div>'."\n";
  4663. }
  4664. /**
  4665. * Return a string with VAT rate label formated for view output
  4666. * Used into pdf and HTML pages
  4667. *
  4668. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4669. * @param boolean $addpercent Add a percent % sign in output
  4670. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4671. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4672. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4673. */
  4674. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4675. {
  4676. $morelabel = '';
  4677. if (preg_match('/%/', $rate)) {
  4678. $rate = str_replace('%', '', $rate);
  4679. $addpercent = true;
  4680. }
  4681. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  4682. $morelabel = ' ('.$reg[1].')';
  4683. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4684. }
  4685. if (preg_match('/\*/', $rate)) {
  4686. $rate = str_replace('*', '', $rate);
  4687. $info_bits |= 1;
  4688. }
  4689. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4690. if (!preg_match('/\//', $rate)) {
  4691. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4692. } else {
  4693. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4694. $ret = $rate.($addpercent ? '%' : '');
  4695. }
  4696. if (($info_bits & 1) && $usestarfornpr >= 0) {
  4697. $ret .= ' *';
  4698. }
  4699. $ret .= $morelabel;
  4700. return $ret;
  4701. }
  4702. /**
  4703. * Function to format a value into an amount for visual output
  4704. * Function used into PDF and HTML pages
  4705. *
  4706. * @param float $amount Amount to format
  4707. * @param integer $form Type of format, HTML or not (not by default)
  4708. * @param Translate $outlangs Object langs for output
  4709. * @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.
  4710. * @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)
  4711. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4712. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4713. * @return string Chaine avec montant formate
  4714. *
  4715. * @see price2num() Revert function of price
  4716. */
  4717. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4718. {
  4719. global $langs, $conf;
  4720. // Clean parameters
  4721. if (empty($amount)) {
  4722. $amount = 0; // To have a numeric value if amount not defined or = ''
  4723. }
  4724. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4725. if ($rounding < 0) {
  4726. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4727. }
  4728. $nbdecimal = $rounding;
  4729. // Output separators by default (french)
  4730. $dec = ',';
  4731. $thousand = ' ';
  4732. // If $outlangs not forced, we use use language
  4733. if (!is_object($outlangs)) {
  4734. $outlangs = $langs;
  4735. }
  4736. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4737. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4738. }
  4739. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4740. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4741. }
  4742. if ($thousand == 'None') {
  4743. $thousand = '';
  4744. } elseif ($thousand == 'Space') {
  4745. $thousand = ' ';
  4746. }
  4747. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4748. //print "amount=".$amount."-";
  4749. $amount = str_replace(',', '.', $amount); // should be useless
  4750. //print $amount."-";
  4751. $datas = explode('.', $amount);
  4752. $decpart = isset($datas[1]) ? $datas[1] : '';
  4753. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4754. //print "decpart=".$decpart."<br>";
  4755. $end = '';
  4756. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4757. if (dol_strlen($decpart) > $nbdecimal) {
  4758. $nbdecimal = dol_strlen($decpart);
  4759. }
  4760. // Si on depasse max
  4761. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  4762. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4763. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  4764. // Si un affichage est tronque, on montre des ...
  4765. $end = '...';
  4766. }
  4767. }
  4768. // If force rounding
  4769. if ($forcerounding >= 0) {
  4770. $nbdecimal = $forcerounding;
  4771. }
  4772. // Format number
  4773. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4774. if ($form) {
  4775. $output = preg_replace('/\s/', '&nbsp;', $output);
  4776. $output = preg_replace('/\'/', '&#039;', $output);
  4777. }
  4778. // Add symbol of currency if requested
  4779. $cursymbolbefore = $cursymbolafter = '';
  4780. if ($currency_code) {
  4781. if ($currency_code == 'auto') {
  4782. $currency_code = $conf->currency;
  4783. }
  4784. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4785. $listoflanguagesbefore = array('nl_NL');
  4786. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  4787. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4788. } else {
  4789. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4790. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4791. }
  4792. }
  4793. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4794. return $output;
  4795. }
  4796. /**
  4797. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4798. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4799. * should be roundtext2num().
  4800. *
  4801. * @param string|float $amount Amount to convert/clean or round
  4802. * @param string|int $rounding ''=No rounding
  4803. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4804. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4805. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4806. * 'CU'=Round to Max unit price of foreign currency accuracy
  4807. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  4808. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  4809. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4810. * Put 2 if you know that number is a user input (so we know we don't have to fix decimal separator).
  4811. * @return string Amount with universal numeric format (Example: '99.99999').
  4812. * If conversion fails to return a numeric, it returns:
  4813. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  4814. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  4815. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  4816. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  4817. *
  4818. * @see price() Opposite function of price2num
  4819. */
  4820. function price2num($amount, $rounding = '', $option = 0)
  4821. {
  4822. global $langs, $conf;
  4823. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4824. // Numbers must be '1234.56'
  4825. // Decimal delimiter for PHP and database SQL requests must be '.'
  4826. $dec = ',';
  4827. $thousand = ' ';
  4828. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4829. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4830. }
  4831. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4832. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4833. }
  4834. if ($thousand == 'None') {
  4835. $thousand = '';
  4836. } elseif ($thousand == 'Space') {
  4837. $thousand = ' ';
  4838. }
  4839. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4840. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4841. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4842. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4843. if (!is_numeric($amount)) {
  4844. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  4845. }
  4846. 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
  4847. $amount = str_replace($thousand, '', $amount);
  4848. }
  4849. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4850. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4851. // So if number was already a good number, it is converted into local Dolibarr setup.
  4852. if (is_numeric($amount)) {
  4853. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4854. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4855. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4856. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4857. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4858. }
  4859. //print "QQ".$amount."<br>\n";
  4860. // Now make replace (the main goal of function)
  4861. if ($thousand != ',' && $thousand != '.') {
  4862. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4863. }
  4864. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4865. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4866. $amount = str_replace($dec, '.', $amount);
  4867. }
  4868. //print ' XX'.$amount.' '.$rounding;
  4869. // Now, make a rounding if required
  4870. if ($rounding) {
  4871. $nbofdectoround = '';
  4872. if ($rounding == 'MU') {
  4873. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4874. } elseif ($rounding == 'MT') {
  4875. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4876. } elseif ($rounding == 'MS') {
  4877. $nbofdectoround = empty($conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : $conf->global->MAIN_MAX_DECIMALS_STOCK;
  4878. } elseif ($rounding == 'CU') {
  4879. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  4880. } elseif ($rounding == 'CT') {
  4881. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  4882. } elseif (is_numeric($rounding)) {
  4883. $nbofdectoround = (int) $rounding;
  4884. }
  4885. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  4886. if (dol_strlen($nbofdectoround)) {
  4887. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  4888. } else {
  4889. return 'ErrorBadParameterProvidedToFunction';
  4890. }
  4891. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4892. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4893. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4894. if (is_numeric($amount)) {
  4895. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4896. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4897. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4898. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4899. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4900. }
  4901. //print "TT".$amount.'<br>';
  4902. // Always make replace because each math function (like round) replace
  4903. // with local values and we want a number that has a SQL string format x.y
  4904. if ($thousand != ',' && $thousand != '.') {
  4905. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4906. }
  4907. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4908. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4909. $amount = str_replace($dec, '.', $amount);
  4910. }
  4911. return $amount;
  4912. }
  4913. /**
  4914. * Output a dimension with best unit
  4915. *
  4916. * @param float $dimension Dimension
  4917. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4918. * @param string $type 'weight', 'volume', ...
  4919. * @param Translate $outputlangs Translate language object
  4920. * @param int $round -1 = non rounding, x = number of decimal
  4921. * @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)
  4922. * @return string String to show dimensions
  4923. */
  4924. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
  4925. {
  4926. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4927. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  4928. $dimension = $dimension * 1000000;
  4929. $unit = $unit - 6;
  4930. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  4931. $dimension = $dimension * 1000;
  4932. $unit = $unit - 3;
  4933. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  4934. $dimension = $dimension / 1000000;
  4935. $unit = $unit + 6;
  4936. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  4937. $dimension = $dimension / 1000;
  4938. $unit = $unit + 3;
  4939. }
  4940. // Special case when we want output unit into pound or ounce
  4941. /* TODO
  4942. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4943. {
  4944. $dimension = // convert dimension from standard unit into ounce or pound
  4945. $unit = $forceunitoutput;
  4946. }
  4947. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4948. {
  4949. $dimension = // convert dimension from standard unit into ounce or pound
  4950. $unit = $forceunitoutput;
  4951. }*/
  4952. $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuringUnitString(0, $type, $unit);
  4953. return $ret;
  4954. }
  4955. /**
  4956. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4957. * Note: This function applies same rules than get_default_tva
  4958. *
  4959. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4960. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4961. * @param Societe $thirdparty_buyer Object of buying third party
  4962. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4963. * @param int $vatnpr If vat rate is NPR or not
  4964. * @return mixed 0 if not found, localtax rate if found
  4965. * @see get_default_tva()
  4966. */
  4967. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  4968. {
  4969. global $db, $conf, $mysoc;
  4970. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  4971. $thirdparty_seller = $mysoc;
  4972. }
  4973. 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);
  4974. $vatratecleaned = $vatrate;
  4975. $reg = array();
  4976. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  4977. $vatratecleaned = trim($reg[1]);
  4978. $vatratecode = $reg[2];
  4979. }
  4980. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4981. {
  4982. return 0;
  4983. }*/
  4984. // Some test to guess with no need to make database access
  4985. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4986. if ($local == 1) {
  4987. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  4988. return 0;
  4989. }
  4990. if ($thirdparty_seller->id == $mysoc->id) {
  4991. if (!$thirdparty_buyer->localtax1_assuj) {
  4992. return 0;
  4993. }
  4994. } else {
  4995. if (!$thirdparty_seller->localtax1_assuj) {
  4996. return 0;
  4997. }
  4998. }
  4999. }
  5000. if ($local == 2) {
  5001. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5002. if (!$mysoc->localtax2_assuj) {
  5003. return 0; // If main vat is 0, IRPF may be different than 0.
  5004. }
  5005. if ($thirdparty_seller->id == $mysoc->id) {
  5006. if (!$thirdparty_buyer->localtax2_assuj) {
  5007. return 0;
  5008. }
  5009. } else {
  5010. if (!$thirdparty_seller->localtax2_assuj) {
  5011. return 0;
  5012. }
  5013. }
  5014. }
  5015. } else {
  5016. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5017. return 0;
  5018. }
  5019. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5020. return 0;
  5021. }
  5022. }
  5023. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5024. if (in_array($mysoc->country_code, array('ES'))) {
  5025. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5026. }
  5027. // Search local taxes
  5028. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5029. if ($local == 1) {
  5030. if ($thirdparty_seller != $mysoc) {
  5031. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5032. return $thirdparty_seller->localtax1_value;
  5033. }
  5034. } else { // i am the seller
  5035. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5036. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5037. }
  5038. }
  5039. }
  5040. if ($local == 2) {
  5041. if ($thirdparty_seller != $mysoc) {
  5042. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5043. // TODO We should also return value defined on thirdparty only if defined
  5044. return $thirdparty_seller->localtax2_value;
  5045. }
  5046. } else { // i am the seller
  5047. if (in_array($mysoc->country_code, array('ES'))) {
  5048. return $thirdparty_buyer->localtax2_value;
  5049. } else {
  5050. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5051. }
  5052. }
  5053. }
  5054. }
  5055. // By default, search value of local tax on line of common tax
  5056. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5057. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5058. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5059. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5060. if (!empty($vatratecode)) {
  5061. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5062. } else {
  5063. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5064. }
  5065. $resql = $db->query($sql);
  5066. if ($resql) {
  5067. $obj = $db->fetch_object($resql);
  5068. if ($obj) {
  5069. if ($local == 1) {
  5070. return $obj->localtax1;
  5071. } elseif ($local == 2) {
  5072. return $obj->localtax2;
  5073. }
  5074. }
  5075. }
  5076. return 0;
  5077. }
  5078. /**
  5079. * Return true if LocalTax (1 or 2) is unique.
  5080. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5081. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5082. *
  5083. * @param int $local Local tax to test (1 or 2)
  5084. * @return boolean True if LocalTax have multiple values, False if not
  5085. */
  5086. function isOnlyOneLocalTax($local)
  5087. {
  5088. $tax = get_localtax_by_third($local);
  5089. $valors = explode(":", $tax);
  5090. if (count($valors) > 1) {
  5091. return false;
  5092. } else {
  5093. return true;
  5094. }
  5095. }
  5096. /**
  5097. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5098. *
  5099. * @param int $local LocalTax to get
  5100. * @return number Values of localtax
  5101. */
  5102. function get_localtax_by_third($local)
  5103. {
  5104. global $db, $mysoc;
  5105. $sql = "SELECT t.localtax1, t.localtax2 ";
  5106. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5107. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5108. $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";
  5109. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5110. $sql .= " )";
  5111. $resql = $db->query($sql);
  5112. if ($resql) {
  5113. $obj = $db->fetch_object($resql);
  5114. if ($local == 1) {
  5115. return $obj->localtax1;
  5116. } elseif ($local == 2) {
  5117. return $obj->localtax2;
  5118. }
  5119. }
  5120. return 0;
  5121. }
  5122. /**
  5123. * Get tax (VAT) main information from Id.
  5124. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5125. *
  5126. * @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.
  5127. * @param Societe $buyer Company object
  5128. * @param Societe $seller Company object
  5129. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5130. * @return array array('rowid'=> , 'code'=> ...)
  5131. * @see getLocalTaxesFromRate()
  5132. */
  5133. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5134. {
  5135. global $db, $mysoc;
  5136. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5137. // Search local taxes
  5138. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5139. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5140. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5141. if ($firstparamisid) {
  5142. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5143. } else {
  5144. $vatratecleaned = $vatrate;
  5145. $vatratecode = '';
  5146. $reg = array();
  5147. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5148. $vatratecleaned = $reg[1];
  5149. $vatratecode = $reg[2];
  5150. }
  5151. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5152. /*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 ??
  5153. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5154. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5155. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5156. if ($vatratecode) {
  5157. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5158. }
  5159. }
  5160. $resql = $db->query($sql);
  5161. if ($resql) {
  5162. $obj = $db->fetch_object($resql);
  5163. if ($obj) {
  5164. return array(
  5165. 'rowid'=>$obj->rowid,
  5166. 'code'=>$obj->code,
  5167. 'rate'=>$obj->rate,
  5168. 'localtax1'=>$obj->localtax1,
  5169. 'localtax1_type'=>$obj->localtax1_type,
  5170. 'localtax2'=>$obj->localtax2,
  5171. 'localtax2_type'=>$obj->localtax2_type,
  5172. 'npr'=>$obj->npr,
  5173. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5174. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5175. );
  5176. } else {
  5177. return array();
  5178. }
  5179. } else {
  5180. dol_print_error($db);
  5181. }
  5182. return array();
  5183. }
  5184. /**
  5185. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5186. * This does not take into account the seller setup if subject to vat or not, only country.
  5187. *
  5188. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5189. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5190. * provide the selected value to the function calcul_price_total.
  5191. *
  5192. * @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.
  5193. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5194. * @param Societe $buyer Company object
  5195. * @param Societe $seller Company object
  5196. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5197. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5198. * @see getTaxesFromId()
  5199. */
  5200. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5201. {
  5202. global $db, $mysoc;
  5203. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5204. // Search local taxes
  5205. $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";
  5206. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5207. if ($firstparamisid) {
  5208. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5209. } else {
  5210. $vatratecleaned = $vatrate;
  5211. $vatratecode = '';
  5212. $reg = array();
  5213. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5214. $vatratecleaned = $reg[1];
  5215. $vatratecode = $reg[2];
  5216. }
  5217. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5218. if ($mysoc->country_code == 'ES') {
  5219. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5220. } else {
  5221. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5222. }
  5223. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5224. if ($vatratecode) {
  5225. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5226. }
  5227. }
  5228. $resql = $db->query($sql);
  5229. if ($resql) {
  5230. $obj = $db->fetch_object($resql);
  5231. if ($obj) {
  5232. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5233. if ($local == 1) {
  5234. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5235. } elseif ($local == 2) {
  5236. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5237. } else {
  5238. 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);
  5239. }
  5240. }
  5241. }
  5242. return array();
  5243. }
  5244. /**
  5245. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5246. * Function called by get_default_tva().
  5247. *
  5248. * @param int $idprod Id of product or 0 if not a predefined product
  5249. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5250. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5251. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5252. * @see get_product_localtax_for_country()
  5253. */
  5254. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5255. {
  5256. global $db, $conf, $mysoc;
  5257. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5258. $ret = 0;
  5259. $found = 0;
  5260. if ($idprod > 0) {
  5261. // Load product
  5262. $product = new Product($db);
  5263. $result = $product->fetch($idprod);
  5264. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5265. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5266. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5267. $ret = $product->vatrate_supplier;
  5268. if ($product->default_vat_code) {
  5269. $ret .= ' ('.$product->default_vat_code.')';
  5270. }
  5271. } else {
  5272. $ret = $product->tva_tx; // Default vat of product we defined
  5273. if ($product->default_vat_code) {
  5274. $ret .= ' ('.$product->default_vat_code.')';
  5275. }
  5276. }
  5277. $found = 1;
  5278. } else {
  5279. // TODO Read default product vat according to product and another countrycode.
  5280. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5281. }
  5282. }
  5283. if (!$found) {
  5284. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5285. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5286. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5287. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5288. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5289. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5290. $sql .= $db->plimit(1);
  5291. $resql = $db->query($sql);
  5292. if ($resql) {
  5293. $obj = $db->fetch_object($resql);
  5294. if ($obj) {
  5295. $ret = $obj->vat_rate;
  5296. if ($obj->default_vat_code) {
  5297. $ret .= ' ('.$obj->default_vat_code.')';
  5298. }
  5299. }
  5300. $db->free($sql);
  5301. } else {
  5302. dol_print_error($db);
  5303. }
  5304. } else {
  5305. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5306. }
  5307. }
  5308. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5309. return $ret;
  5310. }
  5311. /**
  5312. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5313. *
  5314. * @param int $idprod Id of product
  5315. * @param int $local 1 for localtax1, 2 for localtax 2
  5316. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5317. * @return int <0 if KO, Vat rate if OK
  5318. * @see get_product_vat_for_country()
  5319. */
  5320. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5321. {
  5322. global $db, $mysoc;
  5323. if (!class_exists('Product')) {
  5324. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5325. }
  5326. $ret = 0;
  5327. $found = 0;
  5328. if ($idprod > 0) {
  5329. // Load product
  5330. $product = new Product($db);
  5331. $result = $product->fetch($idprod);
  5332. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5333. /* Not defined yet, so we don't use this
  5334. if ($local==1) $ret=$product->localtax1_tx;
  5335. elseif ($local==2) $ret=$product->localtax2_tx;
  5336. $found=1;
  5337. */
  5338. } else {
  5339. // TODO Read default product vat according to product and another countrycode.
  5340. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5341. }
  5342. }
  5343. if (!$found) {
  5344. // If vat of product for the country not found or not defined, we return higher vat of country.
  5345. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5346. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5347. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5348. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5349. $sql .= $db->plimit(1);
  5350. $resql = $db->query($sql);
  5351. if ($resql) {
  5352. $obj = $db->fetch_object($resql);
  5353. if ($obj) {
  5354. if ($local == 1) {
  5355. $ret = $obj->localtax1;
  5356. } elseif ($local == 2) {
  5357. $ret = $obj->localtax2;
  5358. }
  5359. }
  5360. } else {
  5361. dol_print_error($db);
  5362. }
  5363. }
  5364. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5365. return $ret;
  5366. }
  5367. /**
  5368. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5369. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5370. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5371. * 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.
  5372. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5373. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5374. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5375. *
  5376. * @param Societe $thirdparty_seller Objet societe vendeuse
  5377. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5378. * @param int $idprod Id product
  5379. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5380. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5381. * @see get_default_npr(), get_default_localtax()
  5382. */
  5383. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5384. {
  5385. global $conf;
  5386. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5387. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5388. $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;
  5389. $seller_country_code = $thirdparty_seller->country_code;
  5390. $seller_in_cee = isInEEC($thirdparty_seller);
  5391. $buyer_country_code = $thirdparty_buyer->country_code;
  5392. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5393. 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 : ''));
  5394. // 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)
  5395. // we use the buyer VAT.
  5396. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5397. if ($seller_in_cee && $buyer_in_cee) {
  5398. $isacompany = $thirdparty_buyer->isACompany();
  5399. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5400. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5401. if (!isValidVATID($thirdparty_buyer)) {
  5402. $isacompany = 0;
  5403. }
  5404. }
  5405. if (!$isacompany) {
  5406. //print 'VATRULE 0';
  5407. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5408. }
  5409. }
  5410. }
  5411. // If seller does not use VAT
  5412. if (!$seller_use_vat) {
  5413. //print 'VATRULE 1';
  5414. return 0;
  5415. }
  5416. // 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.
  5417. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5418. if (($seller_country_code == $buyer_country_code)
  5419. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5420. //print 'VATRULE 2';
  5421. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5422. }
  5423. // 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.
  5424. // 'VATRULE 3' - Not supported
  5425. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5426. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5427. if (($seller_in_cee && $buyer_in_cee)) {
  5428. $isacompany = $thirdparty_buyer->isACompany();
  5429. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5430. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5431. if (!isValidVATID($thirdparty_buyer)) {
  5432. $isacompany = 0;
  5433. }
  5434. }
  5435. if (!$isacompany) {
  5436. //print 'VATRULE 4';
  5437. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5438. } else {
  5439. //print 'VATRULE 5';
  5440. return 0;
  5441. }
  5442. }
  5443. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5444. // I don't see any use case that need this rule.
  5445. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5446. $isacompany = $thirdparty_buyer->isACompany();
  5447. if (!$isacompany) {
  5448. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5449. //print 'VATRULE extra';
  5450. }
  5451. }
  5452. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5453. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5454. //print 'VATRULE 6';
  5455. return 0;
  5456. }
  5457. /**
  5458. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5459. *
  5460. * @param Societe $thirdparty_seller Thirdparty seller
  5461. * @param Societe $thirdparty_buyer Thirdparty buyer
  5462. * @param int $idprod Id product
  5463. * @param int $idprodfournprice Id supplier price for product
  5464. * @return float 0 or 1
  5465. * @see get_default_tva(), get_default_localtax()
  5466. */
  5467. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5468. {
  5469. global $db;
  5470. if ($idprodfournprice > 0) {
  5471. if (!class_exists('ProductFournisseur')) {
  5472. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5473. }
  5474. $prodprice = new ProductFournisseur($db);
  5475. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5476. return $prodprice->fourn_tva_npr;
  5477. } elseif ($idprod > 0) {
  5478. if (!class_exists('Product')) {
  5479. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5480. }
  5481. $prod = new Product($db);
  5482. $prod->fetch($idprod);
  5483. return $prod->tva_npr;
  5484. }
  5485. return 0;
  5486. }
  5487. /**
  5488. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5489. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5490. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5491. * Sinon TVA proposee par defaut=0. Fin de regle.
  5492. *
  5493. * @param Societe $thirdparty_seller Thirdparty seller
  5494. * @param Societe $thirdparty_buyer Thirdparty buyer
  5495. * @param int $local Localtax to process (1 or 2)
  5496. * @param int $idprod Id product
  5497. * @return integer localtax, -1 si ne peut etre determine
  5498. * @see get_default_tva(), get_default_npr()
  5499. */
  5500. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5501. {
  5502. global $mysoc;
  5503. if (!is_object($thirdparty_seller)) {
  5504. return -1;
  5505. }
  5506. if (!is_object($thirdparty_buyer)) {
  5507. return -1;
  5508. }
  5509. if ($local == 1) { // Localtax 1
  5510. if ($mysoc->country_code == 'ES') {
  5511. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5512. return 0;
  5513. }
  5514. } else {
  5515. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5516. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5517. return 0;
  5518. }
  5519. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5520. return 0;
  5521. }
  5522. }
  5523. } elseif ($local == 2) { //I Localtax 2
  5524. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5525. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5526. return 0;
  5527. }
  5528. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5529. return 0;
  5530. }
  5531. }
  5532. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5533. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5534. }
  5535. return 0;
  5536. }
  5537. /**
  5538. * Return yes or no in current language
  5539. *
  5540. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5541. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5542. * @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.
  5543. * @return string HTML string
  5544. */
  5545. function yn($yesno, $case = 1, $color = 0)
  5546. {
  5547. global $langs;
  5548. $result = 'unknown';
  5549. $classname = '';
  5550. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5551. $result = $langs->trans('yes');
  5552. if ($case == 1 || $case == 3) {
  5553. $result = $langs->trans("Yes");
  5554. }
  5555. if ($case == 2) {
  5556. $result = '<input type="checkbox" value="1" checked disabled>';
  5557. }
  5558. if ($case == 3) {
  5559. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5560. }
  5561. $classname = 'ok';
  5562. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5563. $result = $langs->trans("no");
  5564. if ($case == 1 || $case == 3) {
  5565. $result = $langs->trans("No");
  5566. }
  5567. if ($case == 2) {
  5568. $result = '<input type="checkbox" value="0" disabled>';
  5569. }
  5570. if ($case == 3) {
  5571. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5572. }
  5573. if ($color == 2) {
  5574. $classname = 'ok';
  5575. } else {
  5576. $classname = 'error';
  5577. }
  5578. }
  5579. if ($color) {
  5580. return '<font class="'.$classname.'">'.$result.'</font>';
  5581. }
  5582. return $result;
  5583. }
  5584. /**
  5585. * Return a path to have a the directory according to object where files are stored.
  5586. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5587. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5588. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5589. * 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/"
  5590. *
  5591. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5592. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5593. * @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)
  5594. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5595. * @param Object $object Object to use to get ref to forge the path.
  5596. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5597. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5598. */
  5599. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5600. {
  5601. global $conf;
  5602. if (empty($modulepart) && !empty($object->module)) {
  5603. $modulepart = $object->module;
  5604. }
  5605. $path = '';
  5606. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5607. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5608. $arrayforoldpath[] = 'product';
  5609. }
  5610. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5611. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5612. if (empty($alpha)) {
  5613. $num = preg_replace('/([^0-9])/i', '', $num);
  5614. } else {
  5615. $num = preg_replace('/^.*\-/i', '', $num);
  5616. }
  5617. $num = substr("000".$num, -$level);
  5618. if ($level == 1) {
  5619. $path = substr($num, 0, 1);
  5620. }
  5621. if ($level == 2) {
  5622. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5623. }
  5624. if ($level == 3) {
  5625. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5626. }
  5627. } else {
  5628. // We will enhance here a common way of forging path for document storage.
  5629. // In a future, we may distribute directories on several levels depending on setup and object.
  5630. // Here, $object->id, $object->ref and $modulepart are required.
  5631. //var_dump($modulepart);
  5632. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5633. }
  5634. if (empty($withoutslash) && !empty($path)) {
  5635. $path .= '/';
  5636. }
  5637. return $path;
  5638. }
  5639. /**
  5640. * Creation of a directory (this can create recursive subdir)
  5641. *
  5642. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5643. * @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)
  5644. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5645. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5646. */
  5647. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5648. {
  5649. global $conf;
  5650. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5651. $dir_osencoded = dol_osencode($dir);
  5652. if (@is_dir($dir_osencoded)) {
  5653. return 0;
  5654. }
  5655. $nberr = 0;
  5656. $nbcreated = 0;
  5657. $ccdir = '';
  5658. if (!empty($dataroot)) {
  5659. // Remove data root from loop
  5660. $dir = str_replace($dataroot.'/', '', $dir);
  5661. $ccdir = $dataroot.'/';
  5662. }
  5663. $cdir = explode("/", $dir);
  5664. $num = count($cdir);
  5665. for ($i = 0; $i < $num; $i++) {
  5666. if ($i > 0) {
  5667. $ccdir .= '/'.$cdir[$i];
  5668. } else {
  5669. $ccdir .= $cdir[$i];
  5670. }
  5671. if (preg_match("/^.:$/", $ccdir, $regs)) {
  5672. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5673. }
  5674. // Attention, le is_dir() peut echouer bien que le rep existe.
  5675. // (ex selon config de open_basedir)
  5676. if ($ccdir) {
  5677. $ccdir_osencoded = dol_osencode($ccdir);
  5678. if (!@is_dir($ccdir_osencoded)) {
  5679. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5680. umask(0);
  5681. $dirmaskdec = octdec($newmask);
  5682. if (empty($newmask)) {
  5683. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5684. }
  5685. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5686. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  5687. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5688. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5689. $nberr++;
  5690. } else {
  5691. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5692. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5693. $nbcreated++;
  5694. }
  5695. } else {
  5696. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5697. }
  5698. }
  5699. }
  5700. return ($nberr ? -$nberr : $nbcreated);
  5701. }
  5702. /**
  5703. * Return picto saying a field is required
  5704. *
  5705. * @return string Chaine avec picto obligatoire
  5706. */
  5707. function picto_required()
  5708. {
  5709. return '<span class="fieldrequired">*</span>';
  5710. }
  5711. /**
  5712. * Clean a string from all HTML tags and entities.
  5713. * This function differs from strip_tags because:
  5714. * - <br> are replaced with \n if removelinefeed=0 or 1
  5715. * - if entities are found, they are decoded BEFORE the strip
  5716. * - you can decide to convert line feed into a space
  5717. *
  5718. * @param string $stringtoclean String to clean
  5719. * @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..."
  5720. * @param string $pagecodeto Encoding of input/output string
  5721. * @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')
  5722. * @param integer $removedoublespaces Replace double space into one space
  5723. * @return string String cleaned
  5724. *
  5725. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5726. */
  5727. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5728. {
  5729. if ($removelinefeed == 2) {
  5730. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5731. }
  5732. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5733. // 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)
  5734. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5735. $temp = str_replace('< ', '__ltspace__', $temp);
  5736. if ($strip_tags) {
  5737. $temp = strip_tags($temp);
  5738. } else {
  5739. $temp = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  5740. $pattern = "/<[^<>]+>/";
  5741. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5742. $temp = preg_replace($pattern, "", $temp); // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5743. $temp = preg_replace($pattern, "", $temp); // pass 2 - $temp after pass 2: 0000-021
  5744. // 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).
  5745. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  5746. }
  5747. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5748. // Remove also carriage returns
  5749. if ($removelinefeed == 1) {
  5750. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5751. }
  5752. // And double quotes
  5753. if ($removedoublespaces) {
  5754. while (strpos($temp, " ")) {
  5755. $temp = str_replace(" ", " ", $temp);
  5756. }
  5757. }
  5758. $temp = str_replace('__ltspace__', '< ', $temp);
  5759. return trim($temp);
  5760. }
  5761. /**
  5762. * Clean a string to keep only desirable HTML tags.
  5763. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  5764. *
  5765. * @param string $stringtoclean String to clean
  5766. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5767. * @param int $removeclassattribute 1=Remove the class attribute from tags
  5768. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  5769. * @param int $allowiframe Allow iframe tags.
  5770. * @return string String cleaned
  5771. *
  5772. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5773. */
  5774. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  5775. {
  5776. $allowed_tags = array(
  5777. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5778. "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"
  5779. );
  5780. if ($allowiframe) {
  5781. $allowed_tags[] = "iframe";
  5782. }
  5783. $allowed_tags_string = join("><", $allowed_tags);
  5784. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5785. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  5786. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5787. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  5788. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5789. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  5790. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  5791. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </> changing string obfuscated with </> that pass injection detection into harmfull string
  5792. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5793. $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
  5794. }
  5795. if ($removeclassattribute) { // Clean for remaining html tags
  5796. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5797. }
  5798. // Remove 'javascript:' that we should not find into a text with
  5799. // 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)).
  5800. if ($cleanalsojavascript) {
  5801. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5802. }
  5803. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  5804. return $temp;
  5805. }
  5806. /**
  5807. * Clean a string from some undesirable HTML tags.
  5808. * Note. Not as secured as dol_string_onlythesehtmltags().
  5809. *
  5810. * @param string $stringtoclean String to clean
  5811. * @param array $allowed_attributes Array of tags not allowed
  5812. * @return string String cleaned
  5813. *
  5814. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  5815. */
  5816. 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"))
  5817. {
  5818. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  5819. $stringtoclean = '<html><body>'.$stringtoclean.'</body></html>';
  5820. $dom = new DOMDocument();
  5821. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  5822. if (is_object($dom)) {
  5823. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  5824. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  5825. // Delete attribute if not into allowed_attributes
  5826. if (! empty($attrs->item($ii)->name) && ! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  5827. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  5828. }
  5829. }
  5830. }
  5831. }
  5832. $return = $dom->saveHTML();
  5833. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  5834. $return = preg_replace('/^<html><body>/', '', $return);
  5835. $return = preg_replace('/<\/body><\/html>$/', '', $return);
  5836. return $return;
  5837. } else {
  5838. return $stringtoclean;
  5839. }
  5840. }
  5841. /**
  5842. * Clean a string from some undesirable HTML tags.
  5843. * Note. Not as secured as dol_string_onlythesehtmltags().
  5844. *
  5845. * @param string $stringtoclean String to clean
  5846. * @param array $disallowed_tags Array of tags not allowed
  5847. * @param string $cleanalsosomestyles Clean also some tags
  5848. * @return string String cleaned
  5849. *
  5850. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  5851. */
  5852. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5853. {
  5854. $temp = $stringtoclean;
  5855. foreach ($disallowed_tags as $tagtoremove) {
  5856. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5857. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5858. }
  5859. if ($cleanalsosomestyles) {
  5860. $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
  5861. }
  5862. return $temp;
  5863. }
  5864. /**
  5865. * Return first line of text. Cut will depends if content is HTML or not.
  5866. *
  5867. * @param string $text Input text
  5868. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5869. * @param string $charset Charset of $text string (UTF-8 by default)
  5870. * @return string Output text
  5871. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5872. */
  5873. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5874. {
  5875. if ($nboflines == 1) {
  5876. if (dol_textishtml($text)) {
  5877. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5878. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5879. } else {
  5880. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5881. }
  5882. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5883. } else {
  5884. $ishtml = 0;
  5885. if (dol_textishtml($text)) {
  5886. $text = preg_replace('/\n/', '', $text);
  5887. $ishtml = 1;
  5888. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5889. } else {
  5890. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5891. }
  5892. $text = strtr($text, $repTable);
  5893. if ($charset == 'UTF-8') {
  5894. $pattern = '/(<br[^>]*>)/Uu';
  5895. } else {
  5896. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5897. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5898. }
  5899. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5900. $firstline = '';
  5901. $i = 0;
  5902. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5903. while (($i < $nba) && ($i < ($nboflines * 2))) {
  5904. if ($i % 2 == 0) {
  5905. $firstline .= $a[$i];
  5906. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  5907. $firstline .= ($ishtml ? "<br>\n" : "\n");
  5908. }
  5909. $i++;
  5910. }
  5911. unset($a);
  5912. return $firstline.(($i < $nba) ? '...' : '');
  5913. }
  5914. }
  5915. /**
  5916. * Replace CRLF in string with a HTML BR tag.
  5917. * 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.
  5918. *
  5919. * @param string $stringtoencode String to encode
  5920. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5921. * @param bool $forxml false=Use <br>, true=Use <br />
  5922. * @return string String encoded
  5923. * @see dol_nboflines(), dolGetFirstLineOfText()
  5924. */
  5925. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5926. {
  5927. if (!$nl2brmode) {
  5928. return nl2br($stringtoencode, $forxml);
  5929. } else {
  5930. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  5931. return $ret;
  5932. }
  5933. }
  5934. /**
  5935. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5936. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5937. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5938. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5939. * For PDF usage, you can show text by 2 ways:
  5940. * - writeHTMLCell -> param must be encoded into HTML.
  5941. * - MultiCell -> param must not be encoded into HTML.
  5942. * Because writeHTMLCell convert also \n into <br>, if function
  5943. * is used to build PDF, nl2brmode must be 1.
  5944. *
  5945. * @param string $stringtoencode String to encode
  5946. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5947. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5948. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5949. * @return string String encoded
  5950. */
  5951. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  5952. {
  5953. $newstring = $stringtoencode;
  5954. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  5955. $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.
  5956. if ($removelasteolbr) {
  5957. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  5958. }
  5959. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  5960. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  5961. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  5962. } else {
  5963. if ($removelasteolbr) {
  5964. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  5965. }
  5966. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  5967. }
  5968. // Other substitutions that htmlentities does not do
  5969. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5970. return $newstring;
  5971. }
  5972. /**
  5973. * This function is called to decode a HTML string (it decodes entities and br tags)
  5974. *
  5975. * @param string $stringtodecode String to decode
  5976. * @param string $pagecodeto Page code for result
  5977. * @return string String decoded
  5978. */
  5979. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  5980. {
  5981. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5982. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  5983. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  5984. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  5985. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  5986. return $ret;
  5987. }
  5988. /**
  5989. * This function remove all ending \n and br at end
  5990. *
  5991. * @param string $stringtodecode String to decode
  5992. * @return string String decoded
  5993. */
  5994. function dol_htmlcleanlastbr($stringtodecode)
  5995. {
  5996. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
  5997. return $ret;
  5998. }
  5999. /**
  6000. * Replace html_entity_decode functions to manage errors
  6001. *
  6002. * @param string $a Operand a
  6003. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6004. * @param string $c Operand c
  6005. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6006. * @return string String decoded
  6007. */
  6008. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6009. {
  6010. $newstring = $a;
  6011. if ($keepsomeentities) {
  6012. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6013. }
  6014. $newstring = html_entity_decode($newstring, $b, $c);
  6015. if ($keepsomeentities) {
  6016. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6017. }
  6018. return $newstring;
  6019. }
  6020. /**
  6021. * Replace htmlentities functions.
  6022. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6023. *
  6024. * @param string $string The input string to encode
  6025. * @param int $flags Flags (see PHP doc above)
  6026. * @param string $encoding Encoding page code
  6027. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6028. * @return string $ret Encoded string
  6029. */
  6030. function dol_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = false)
  6031. {
  6032. return htmlentities($string, $flags, $encoding, $double_encode);
  6033. }
  6034. /**
  6035. * Check if a string is a correct iso string
  6036. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6037. * Example, if string contains euro symbol that has ascii code 128
  6038. *
  6039. * @param string $s String to check
  6040. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6041. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6042. */
  6043. function dol_string_is_good_iso($s, $clean = 0)
  6044. {
  6045. $len = dol_strlen($s);
  6046. $out = '';
  6047. $ok = 1;
  6048. for ($scursor = 0; $scursor < $len; $scursor++) {
  6049. $ordchar = ord($s[$scursor]);
  6050. //print $scursor.'-'.$ordchar.'<br>';
  6051. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6052. $ok = 0;
  6053. break;
  6054. } elseif ($ordchar > 126 && $ordchar < 160) {
  6055. $ok = 0;
  6056. break;
  6057. } elseif ($clean) {
  6058. $out .= $s[$scursor];
  6059. }
  6060. }
  6061. if ($clean) {
  6062. return $out;
  6063. }
  6064. return $ok;
  6065. }
  6066. /**
  6067. * Return nb of lines of a clear text
  6068. *
  6069. * @param string $s String to check
  6070. * @param int $maxchar Not yet used
  6071. * @return int Number of lines
  6072. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6073. */
  6074. function dol_nboflines($s, $maxchar = 0)
  6075. {
  6076. if ($s == '') {
  6077. return 0;
  6078. }
  6079. $arraystring = explode("\n", $s);
  6080. $nb = count($arraystring);
  6081. return $nb;
  6082. }
  6083. /**
  6084. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6085. *
  6086. * @param string $text Text
  6087. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6088. * @param string $charset Give the charset used to encode the $text variable in memory.
  6089. * @return int Number of lines
  6090. * @see dol_nboflines(), dolGetFirstLineOfText()
  6091. */
  6092. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6093. {
  6094. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6095. if (dol_textishtml($text)) {
  6096. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6097. }
  6098. $text = strtr($text, $repTable);
  6099. if ($charset == 'UTF-8') {
  6100. $pattern = '/(<br[^>]*>)/Uu';
  6101. } else {
  6102. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6103. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6104. }
  6105. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6106. $nblines = (int) floor((count($a) + 1) / 2);
  6107. // count possible auto line breaks
  6108. if ($maxlinesize) {
  6109. foreach ($a as $line) {
  6110. if (dol_strlen($line) > $maxlinesize) {
  6111. //$line_dec = html_entity_decode(strip_tags($line));
  6112. $line_dec = html_entity_decode($line);
  6113. if (dol_strlen($line_dec) > $maxlinesize) {
  6114. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6115. $nblines += substr_count($line_dec, '\n');
  6116. }
  6117. }
  6118. }
  6119. }
  6120. unset($a);
  6121. return $nblines;
  6122. }
  6123. /**
  6124. * Return if a text is a html content
  6125. *
  6126. * @param string $msg Content to check
  6127. * @param int $option 0=Full detection, 1=Fast check
  6128. * @return boolean true/false
  6129. * @see dol_concatdesc()
  6130. */
  6131. function dol_textishtml($msg, $option = 0)
  6132. {
  6133. if ($option == 1) {
  6134. if (preg_match('/<html/i', $msg)) {
  6135. return true;
  6136. } elseif (preg_match('/<body/i', $msg)) {
  6137. return true;
  6138. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6139. return true;
  6140. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6141. return true;
  6142. } elseif (preg_match('/<br/i', $msg)) {
  6143. return true;
  6144. }
  6145. return false;
  6146. } else {
  6147. if (preg_match('/<html/i', $msg)) {
  6148. return true;
  6149. } elseif (preg_match('/<body/i', $msg)) {
  6150. return true;
  6151. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6152. return true;
  6153. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6154. return true;
  6155. } elseif (preg_match('/<br\/>/i', $msg)) {
  6156. return true;
  6157. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6158. return true;
  6159. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6160. return true;
  6161. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6162. return true; // must accept <img src="http://example.com/aaa.png" />
  6163. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6164. return true; // must accept <a href="http://example.com/aaa.png" />
  6165. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6166. return true;
  6167. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6168. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6169. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6170. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6171. }
  6172. return false;
  6173. }
  6174. }
  6175. /**
  6176. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6177. * text1 html + text2 html => text1 + '<br>' + text2
  6178. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6179. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6180. * text1 txt + text2 txt => text1 + '\n' + text2
  6181. *
  6182. * @param string $text1 Text 1
  6183. * @param string $text2 Text 2
  6184. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6185. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6186. * @return string Text 1 + new line + Text2
  6187. * @see dol_textishtml()
  6188. */
  6189. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6190. {
  6191. if (!empty($invert)) {
  6192. $tmp = $text1;
  6193. $text1 = $text2;
  6194. $text2 = $tmp;
  6195. }
  6196. $ret = '';
  6197. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6198. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6199. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6200. return $ret;
  6201. }
  6202. /**
  6203. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6204. *
  6205. * @param Translate $outputlangs Output language
  6206. * @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)
  6207. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6208. * @param Object $object Object for keys on object
  6209. * @return array Array of substitutions
  6210. * @see setSubstitFromObject()
  6211. */
  6212. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6213. {
  6214. global $db, $conf, $mysoc, $user, $extrafields;
  6215. $substitutionarray = array();
  6216. if (empty($exclude) || !in_array('user', $exclude)) {
  6217. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6218. // this will include signature content first and then replace var found into content of signature
  6219. $signature = $user->signature;
  6220. $substitutionarray = array_merge($substitutionarray, array(
  6221. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6222. ));
  6223. if (is_object($user)) {
  6224. $substitutionarray = array_merge($substitutionarray, array(
  6225. '__USER_ID__' => (string) $user->id,
  6226. '__USER_LOGIN__' => (string) $user->login,
  6227. '__USER_EMAIL__' => (string) $user->email,
  6228. '__USER_LASTNAME__' => (string) $user->lastname,
  6229. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6230. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6231. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6232. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6233. ));
  6234. }
  6235. }
  6236. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6237. $substitutionarray = array_merge($substitutionarray, array(
  6238. '__MYCOMPANY_NAME__' => $mysoc->name,
  6239. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6240. '__MYCOMPANY_PHONE__' => $mysoc->phone,
  6241. '__MYCOMPANY_FAX__' => $mysoc->fax,
  6242. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6243. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6244. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6245. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6246. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6247. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6248. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6249. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6250. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6251. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6252. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6253. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6254. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6255. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6256. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6257. ));
  6258. }
  6259. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6260. if ($onlykey) {
  6261. $substitutionarray['__ID__'] = '__ID__';
  6262. $substitutionarray['__REF__'] = '__REF__';
  6263. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6264. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6265. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6266. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6267. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6268. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6269. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6270. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6271. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6272. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6273. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6274. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6275. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6276. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6277. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6278. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6279. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6280. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6281. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6282. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6283. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6284. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6285. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6286. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6287. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6288. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6289. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6290. }
  6291. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6292. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6293. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6294. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6295. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6296. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6297. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6298. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6299. }
  6300. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature')) {
  6301. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6302. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6303. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6304. }
  6305. if (!empty($conf->projet->enabled)) { // Most objects
  6306. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6307. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6308. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6309. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6310. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6311. }
  6312. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6313. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6314. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6315. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6316. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6317. }
  6318. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6319. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6320. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6321. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6322. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6323. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6324. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  6325. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6326. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6327. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6328. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6329. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6330. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6331. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6332. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6333. }
  6334. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6335. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6336. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6337. }
  6338. } else {
  6339. $substitutionarray['__ID__'] = $object->id;
  6340. $substitutionarray['__REF__'] = $object->ref;
  6341. $substitutionarray['__NEWREF__'] = $object->newref;
  6342. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6343. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6344. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6345. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6346. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6347. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6348. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6349. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6350. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6351. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6352. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6353. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6354. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6355. // For backward compatibility
  6356. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6357. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6358. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6359. $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 : '')) : '');
  6360. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6361. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6362. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6363. if (method_exists($object, 'getCivilityLabel')) {
  6364. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6365. }
  6366. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6367. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6368. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6369. if (method_exists($object, 'getFullName')) {
  6370. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6371. }
  6372. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6373. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6374. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6375. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6376. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6377. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6378. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6379. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6380. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6381. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6382. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  6383. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  6384. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  6385. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6386. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6387. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  6388. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  6389. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6390. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6391. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6392. }
  6393. if (is_object($object) && $object->element == 'societe') {
  6394. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6395. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6396. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6397. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6398. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6399. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6400. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  6401. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  6402. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6403. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6404. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6405. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6406. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6407. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6408. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6409. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6410. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6411. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6412. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6413. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6414. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6415. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6416. } elseif (is_object($object->thirdparty)) {
  6417. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6418. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6419. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6420. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6421. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6422. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6423. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  6424. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  6425. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6426. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6427. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6428. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6429. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6430. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6431. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6432. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6433. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6434. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6435. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6436. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6437. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6438. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6439. }
  6440. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6441. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6442. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  6443. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  6444. }
  6445. if (is_object($object->project)) {
  6446. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6447. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6448. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6449. }
  6450. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6451. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6452. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6453. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6454. }
  6455. if (is_object($object) && $object->element == 'shipping') {
  6456. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6457. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6458. }
  6459. if (is_object($object) && $object->element == 'reception') {
  6460. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6461. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6462. }
  6463. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6464. $dateplannedstart = '';
  6465. $datenextexpiration = '';
  6466. foreach ($object->lines as $line) {
  6467. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6468. $dateplannedstart = $line->date_ouverture_prevue;
  6469. }
  6470. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6471. $datenextexpiration = $line->date_fin_prevue;
  6472. }
  6473. }
  6474. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6475. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6476. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6477. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6478. }
  6479. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6480. if ($object->table_element && $object->id > 0) {
  6481. if (!is_object($extrafields)) {
  6482. $extrafields = new ExtraFields($db);
  6483. }
  6484. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6485. if ($object->fetch_optionals() > 0) {
  6486. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6487. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6488. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6489. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6490. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6491. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6492. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6493. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6494. $datetime = $object->array_options['options_'.$key];
  6495. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6496. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6497. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6498. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6499. }
  6500. }
  6501. }
  6502. }
  6503. }
  6504. // Complete substitution array with the url to make online payment
  6505. $paymenturl = '';
  6506. if (empty($substitutionarray['__REF__'])) {
  6507. $paymenturl = '';
  6508. } else {
  6509. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6510. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6511. $outputlangs->loadLangs(array('paypal', 'other'));
  6512. $typeforonlinepayment = 'free';
  6513. if (is_object($object) && $object->element == 'commande') {
  6514. $typeforonlinepayment = 'order';
  6515. }
  6516. if (is_object($object) && $object->element == 'facture') {
  6517. $typeforonlinepayment = 'invoice';
  6518. }
  6519. if (is_object($object) && $object->element == 'member') {
  6520. $typeforonlinepayment = 'member';
  6521. }
  6522. if (is_object($object) && $object->element == 'contrat') {
  6523. $typeforonlinepayment = 'contract';
  6524. }
  6525. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6526. $paymenturl = $url;
  6527. }
  6528. if ($object->id > 0) {
  6529. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6530. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6531. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6532. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6533. } else {
  6534. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6535. }
  6536. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6537. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6538. } else {
  6539. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6540. }
  6541. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6542. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6543. } else {
  6544. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6545. }
  6546. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6547. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6548. } else {
  6549. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6550. }
  6551. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6552. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6553. } else {
  6554. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6555. }
  6556. if (is_object($object) && $object->element == 'propal') {
  6557. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6558. }
  6559. if (is_object($object) && $object->element == 'commande') {
  6560. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6561. }
  6562. if (is_object($object) && $object->element == 'facture') {
  6563. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6564. }
  6565. if (is_object($object) && $object->element == 'contrat') {
  6566. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6567. }
  6568. if (is_object($object) && $object->element == 'supplier_proposal') {
  6569. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6570. }
  6571. if (is_object($object) && $object->element == 'shipping') {
  6572. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  6573. }
  6574. }
  6575. if (is_object($object) && $object->element == 'action') {
  6576. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6577. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  6578. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  6579. }
  6580. }
  6581. }
  6582. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  6583. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  6584. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  6585. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  6586. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  6587. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  6588. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  6589. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  6590. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6591. $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)) : '';
  6592. $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)) : '';
  6593. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6594. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  6595. }
  6596. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6597. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  6598. }
  6599. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6600. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6601. $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)) : '';
  6602. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6603. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6604. }
  6605. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6606. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6607. }
  6608. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  6609. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  6610. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  6611. // TODO Add other keys for foreign multicurrency
  6612. // For backward compatibility
  6613. if ($onlykey != 2) {
  6614. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  6615. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  6616. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6617. }
  6618. }
  6619. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  6620. if (empty($exclude) || !in_array('date', $exclude)) {
  6621. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6622. $tmp = dol_getdate(dol_now(), true);
  6623. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6624. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  6625. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6626. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  6627. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  6628. $substitutionarray = array_merge($substitutionarray, array(
  6629. '__DAY__' => (string) $tmp['mday'],
  6630. '__DAY_TEXT__' => $daytext, // Monday
  6631. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  6632. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  6633. '__MONTH__' => (string) $tmp['mon'],
  6634. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  6635. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  6636. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  6637. '__YEAR__' => (string) $tmp['year'],
  6638. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  6639. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  6640. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  6641. '__NEXT_DAY__' => (string) $tmp4['day'],
  6642. '__NEXT_MONTH__' => (string) $tmp5['month'],
  6643. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  6644. ));
  6645. }
  6646. if (!empty($conf->multicompany->enabled)) {
  6647. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  6648. }
  6649. if (empty($exclude) || !in_array('system', $exclude)) {
  6650. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  6651. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  6652. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  6653. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  6654. }
  6655. return $substitutionarray;
  6656. }
  6657. /**
  6658. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  6659. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  6660. * Example of usage:
  6661. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  6662. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  6663. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  6664. *
  6665. * @param string $text Source string in which we must do substitution
  6666. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  6667. * @param Translate $outputlangs Output language
  6668. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  6669. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  6670. * @return string Output string after substitutions
  6671. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  6672. */
  6673. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  6674. {
  6675. global $conf, $langs;
  6676. if (!is_array($substitutionarray)) {
  6677. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  6678. }
  6679. if (empty($outputlangs)) {
  6680. $outputlangs = $langs;
  6681. }
  6682. // Is initial text HTML or simple text ?
  6683. $msgishtml = 0;
  6684. if (dol_textishtml($text, 1)) {
  6685. $msgishtml = 1;
  6686. }
  6687. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  6688. if (is_object($outputlangs)) {
  6689. $reg = array();
  6690. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  6691. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  6692. $tmp = explode('|', $reg[1]);
  6693. if (!empty($tmp[1])) {
  6694. $outputlangs->load($tmp[1]);
  6695. }
  6696. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  6697. if (empty($converttextinhtmlifnecessary)) {
  6698. // convert $newval into HTML is necessary
  6699. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6700. } else {
  6701. if (! $msgishtml) {
  6702. $valueishtml = dol_textishtml($value, 1);
  6703. if ($valueishtml) {
  6704. $text = dol_htmlentitiesbr($text);
  6705. $msgishtml = 1;
  6706. }
  6707. } else {
  6708. $value = dol_nl2br("$value");
  6709. }
  6710. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  6711. }
  6712. }
  6713. }
  6714. // Make substitution for constant keys.
  6715. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  6716. $reg = array();
  6717. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  6718. $keyfound = $reg[1];
  6719. if (isASecretKey($keyfound)) {
  6720. $value = '*****forbidden*****';
  6721. } else {
  6722. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  6723. }
  6724. if (empty($converttextinhtmlifnecessary)) {
  6725. // convert $newval into HTML is necessary
  6726. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6727. } else {
  6728. if (! $msgishtml) {
  6729. $valueishtml = dol_textishtml($value, 1);
  6730. if ($valueishtml) {
  6731. $text = dol_htmlentitiesbr($text);
  6732. $msgishtml = 1;
  6733. }
  6734. } else {
  6735. $value = dol_nl2br("$value");
  6736. }
  6737. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  6738. }
  6739. }
  6740. // Make substitition for array $substitutionarray
  6741. foreach ($substitutionarray as $key => $value) {
  6742. if (!isset($value)) {
  6743. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  6744. }
  6745. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  6746. $value = ''; // Protection
  6747. }
  6748. if (empty($converttextinhtmlifnecessary)) {
  6749. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6750. } else {
  6751. if (! $msgishtml) {
  6752. $valueishtml = dol_textishtml($value, 1);
  6753. if ($valueishtml) {
  6754. $text = dol_htmlentitiesbr($text);
  6755. $msgishtml = 1;
  6756. }
  6757. } else {
  6758. $value = dol_nl2br("$value");
  6759. }
  6760. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6761. }
  6762. }
  6763. return $text;
  6764. }
  6765. /**
  6766. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6767. * In this case, method completesubstitutionarray provided by module is called.
  6768. *
  6769. * @param array $substitutionarray Array substitution old value => new value value
  6770. * @param Translate $outputlangs Output language
  6771. * @param Object $object Source object
  6772. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6773. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6774. * @return void
  6775. * @see make_substitutions()
  6776. */
  6777. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6778. {
  6779. global $conf, $user;
  6780. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6781. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  6782. // Check if there is external substitution to do, requested by plugins
  6783. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  6784. foreach ($dirsubstitutions as $reldir) {
  6785. $dir = dol_buildpath($reldir, 0);
  6786. // Check if directory exists
  6787. if (!dol_is_dir($dir)) {
  6788. continue;
  6789. }
  6790. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  6791. foreach ($substitfiles as $substitfile) {
  6792. $reg = array();
  6793. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  6794. $module = $reg[1];
  6795. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  6796. // Include the user's functions file
  6797. require_once $dir.$substitfile['name'];
  6798. // Call the user's function, and only if it is defined
  6799. $function_name = $module."_".$callfunc;
  6800. if (function_exists($function_name)) {
  6801. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  6802. }
  6803. }
  6804. }
  6805. }
  6806. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  6807. // to list all tags in odt template
  6808. $tags = '';
  6809. foreach ($substitutionarray as $key => $value) {
  6810. $tags .= '{'.$key.'} => '.$value."\n";
  6811. }
  6812. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  6813. }
  6814. }
  6815. /**
  6816. * Format output for start and end date
  6817. *
  6818. * @param int $date_start Start date
  6819. * @param int $date_end End date
  6820. * @param string $format Output format
  6821. * @param Translate $outputlangs Output language
  6822. * @return void
  6823. */
  6824. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  6825. {
  6826. print get_date_range($date_start, $date_end, $format, $outputlangs);
  6827. }
  6828. /**
  6829. * Format output for start and end date
  6830. *
  6831. * @param int $date_start Start date
  6832. * @param int $date_end End date
  6833. * @param string $format Output format
  6834. * @param Translate $outputlangs Output language
  6835. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  6836. * @return string String
  6837. */
  6838. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  6839. {
  6840. global $langs;
  6841. $out = '';
  6842. if (!is_object($outputlangs)) {
  6843. $outputlangs = $langs;
  6844. }
  6845. if ($date_start && $date_end) {
  6846. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6847. }
  6848. if ($date_start && !$date_end) {
  6849. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6850. }
  6851. if (!$date_start && $date_end) {
  6852. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6853. }
  6854. return $out;
  6855. }
  6856. /**
  6857. * Return firstname and lastname in correct order
  6858. *
  6859. * @param string $firstname Firstname
  6860. * @param string $lastname Lastname
  6861. * @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
  6862. * @return string Firstname + lastname or Lastname + firstname
  6863. */
  6864. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  6865. {
  6866. global $conf;
  6867. $ret = '';
  6868. // If order not defined, we use the setup
  6869. if ($nameorder < 0) {
  6870. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  6871. }
  6872. if ($nameorder == 1) {
  6873. $ret .= $firstname;
  6874. if ($firstname && $lastname) {
  6875. $ret .= ' ';
  6876. }
  6877. $ret .= $lastname;
  6878. } elseif ($nameorder == 2 || $nameorder == 3) {
  6879. $ret .= $firstname;
  6880. if (empty($ret) && $nameorder == 3) {
  6881. $ret .= $lastname;
  6882. }
  6883. } else { // 0, 4 or 5
  6884. $ret .= $lastname;
  6885. if (empty($ret) && $nameorder == 5) {
  6886. $ret .= $firstname;
  6887. }
  6888. if ($nameorder == 0) {
  6889. if ($firstname && $lastname) {
  6890. $ret .= ' ';
  6891. }
  6892. $ret .= $firstname;
  6893. }
  6894. }
  6895. return $ret;
  6896. }
  6897. /**
  6898. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  6899. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6900. * Note: Prefer to use setEventMessages instead.
  6901. *
  6902. * @param string|string[] $mesgs Message string or array
  6903. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6904. * @return void
  6905. * @see dol_htmloutput_events()
  6906. */
  6907. function setEventMessage($mesgs, $style = 'mesgs')
  6908. {
  6909. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  6910. if (!is_array($mesgs)) {
  6911. // If mesgs is a string
  6912. if ($mesgs) {
  6913. $_SESSION['dol_events'][$style][] = $mesgs;
  6914. }
  6915. } else {
  6916. // If mesgs is an array
  6917. foreach ($mesgs as $mesg) {
  6918. if ($mesg) {
  6919. $_SESSION['dol_events'][$style][] = $mesg;
  6920. }
  6921. }
  6922. }
  6923. }
  6924. /**
  6925. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  6926. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6927. *
  6928. * @param string $mesg Message string
  6929. * @param array $mesgs Message array
  6930. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6931. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  6932. * @return void
  6933. * @see dol_htmloutput_events()
  6934. */
  6935. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  6936. {
  6937. if (empty($mesg) && empty($mesgs)) {
  6938. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  6939. } else {
  6940. if ($messagekey) {
  6941. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  6942. // TODO
  6943. $mesg .= '';
  6944. }
  6945. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  6946. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  6947. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  6948. }
  6949. if (empty($mesgs)) {
  6950. setEventMessage($mesg, $style);
  6951. } else {
  6952. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  6953. setEventMessage($mesg, $style); // Add message string if not already into array
  6954. }
  6955. setEventMessage($mesgs, $style);
  6956. }
  6957. }
  6958. }
  6959. }
  6960. /**
  6961. * Print formated messages to output (Used to show messages on html output).
  6962. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  6963. * no need to call it explicitely.
  6964. *
  6965. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  6966. * @return void
  6967. * @see dol_htmloutput_mesg()
  6968. */
  6969. function dol_htmloutput_events($disabledoutputofmessages = 0)
  6970. {
  6971. // Show mesgs
  6972. if (isset($_SESSION['dol_events']['mesgs'])) {
  6973. if (empty($disabledoutputofmessages)) {
  6974. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  6975. }
  6976. unset($_SESSION['dol_events']['mesgs']);
  6977. }
  6978. // Show errors
  6979. if (isset($_SESSION['dol_events']['errors'])) {
  6980. if (empty($disabledoutputofmessages)) {
  6981. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  6982. }
  6983. unset($_SESSION['dol_events']['errors']);
  6984. }
  6985. // Show warnings
  6986. if (isset($_SESSION['dol_events']['warnings'])) {
  6987. if (empty($disabledoutputofmessages)) {
  6988. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  6989. }
  6990. unset($_SESSION['dol_events']['warnings']);
  6991. }
  6992. }
  6993. /**
  6994. * Get formated messages to output (Used to show messages on html output).
  6995. * This include also the translation of the message key.
  6996. *
  6997. * @param string $mesgstring Message string or message key
  6998. * @param string[] $mesgarray Array of message strings or message keys
  6999. * @param string $style Style of message output ('ok' or 'error')
  7000. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7001. * @return string Return html output
  7002. *
  7003. * @see dol_print_error()
  7004. * @see dol_htmloutput_errors()
  7005. * @see setEventMessages()
  7006. */
  7007. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7008. {
  7009. global $conf, $langs;
  7010. $ret = 0;
  7011. $return = '';
  7012. $out = '';
  7013. $divstart = $divend = '';
  7014. // If inline message with no format, we add it.
  7015. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7016. $divstart = '<div class="'.$style.' clearboth">';
  7017. $divend = '</div>';
  7018. }
  7019. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7020. $langs->load("errors");
  7021. $out .= $divstart;
  7022. if (is_array($mesgarray) && count($mesgarray)) {
  7023. foreach ($mesgarray as $message) {
  7024. $ret++;
  7025. $out .= $langs->trans($message);
  7026. if ($ret < count($mesgarray)) {
  7027. $out .= "<br>\n";
  7028. }
  7029. }
  7030. }
  7031. if ($mesgstring) {
  7032. $langs->load("errors");
  7033. $ret++;
  7034. $out .= $langs->trans($mesgstring);
  7035. }
  7036. $out .= $divend;
  7037. }
  7038. if ($out) {
  7039. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7040. $return = '<script>
  7041. $(document).ready(function() {
  7042. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7043. if (block) {
  7044. $.dolEventValid("","'.dol_escape_js($out).'");
  7045. } else {
  7046. /* jnotify(message, preset of message type, keepmessage) */
  7047. $.jnotify("'.dol_escape_js($out).'",
  7048. "'.($style == "ok" ? 3000 : $style).'",
  7049. '.($style == "ok" ? "false" : "true").',
  7050. { remove: function (){} } );
  7051. }
  7052. });
  7053. </script>';
  7054. } else {
  7055. $return = $out;
  7056. }
  7057. }
  7058. return $return;
  7059. }
  7060. /**
  7061. * Get formated error messages to output (Used to show messages on html output).
  7062. *
  7063. * @param string $mesgstring Error message
  7064. * @param array $mesgarray Error messages array
  7065. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7066. * @return string Return html output
  7067. *
  7068. * @see dol_print_error()
  7069. * @see dol_htmloutput_mesg()
  7070. */
  7071. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7072. {
  7073. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7074. }
  7075. /**
  7076. * Print formated messages to output (Used to show messages on html output).
  7077. *
  7078. * @param string $mesgstring Message string or message key
  7079. * @param string[] $mesgarray Array of message strings or message keys
  7080. * @param string $style Which style to use ('ok', 'warning', 'error')
  7081. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7082. * @return void
  7083. *
  7084. * @see dol_print_error()
  7085. * @see dol_htmloutput_errors()
  7086. * @see setEventMessages()
  7087. */
  7088. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7089. {
  7090. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7091. return;
  7092. }
  7093. $iserror = 0;
  7094. $iswarning = 0;
  7095. if (is_array($mesgarray)) {
  7096. foreach ($mesgarray as $val) {
  7097. if ($val && preg_match('/class="error"/i', $val)) {
  7098. $iserror++;
  7099. break;
  7100. }
  7101. if ($val && preg_match('/class="warning"/i', $val)) {
  7102. $iswarning++;
  7103. break;
  7104. }
  7105. }
  7106. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7107. $iserror++;
  7108. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7109. $iswarning++;
  7110. }
  7111. if ($style == 'error') {
  7112. $iserror++;
  7113. }
  7114. if ($style == 'warning') {
  7115. $iswarning++;
  7116. }
  7117. if ($iserror || $iswarning) {
  7118. // Remove div from texts
  7119. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7120. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7121. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7122. // Remove div from texts array
  7123. if (is_array($mesgarray)) {
  7124. $newmesgarray = array();
  7125. foreach ($mesgarray as $val) {
  7126. if (is_string($val)) {
  7127. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7128. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7129. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7130. $newmesgarray[] = $tmpmesgstring;
  7131. } else {
  7132. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7133. }
  7134. }
  7135. $mesgarray = $newmesgarray;
  7136. }
  7137. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7138. } else {
  7139. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7140. }
  7141. }
  7142. /**
  7143. * Print formated error messages to output (Used to show messages on html output).
  7144. *
  7145. * @param string $mesgstring Error message
  7146. * @param array $mesgarray Error messages array
  7147. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7148. * @return void
  7149. *
  7150. * @see dol_print_error()
  7151. * @see dol_htmloutput_mesg()
  7152. */
  7153. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7154. {
  7155. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7156. }
  7157. /**
  7158. * Advanced sort array by second index function, which produces ascending (default)
  7159. * or descending output and uses optionally natural case insensitive sorting (which
  7160. * can be optionally case sensitive as well).
  7161. *
  7162. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7163. * @param string $index Key in array to use for sorting criteria
  7164. * @param int $order Sort order ('asc' or 'desc')
  7165. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7166. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7167. * @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.
  7168. * @return array Sorted array
  7169. */
  7170. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7171. {
  7172. // Clean parameters
  7173. $order = strtolower($order);
  7174. if (is_array($array)) {
  7175. $sizearray = count($array);
  7176. if ($sizearray > 0) {
  7177. $temp = array();
  7178. foreach (array_keys($array) as $key) {
  7179. if (is_object($array[$key])) {
  7180. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7181. } else {
  7182. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7183. }
  7184. }
  7185. if (!$natsort) {
  7186. if ($order == 'asc') {
  7187. asort($temp);
  7188. } else {
  7189. arsort($temp);
  7190. }
  7191. } else {
  7192. if ($case_sensitive) {
  7193. natsort($temp);
  7194. } else {
  7195. natcasesort($temp); // natecasesort is not sensible to case
  7196. }
  7197. if ($order != 'asc') {
  7198. $temp = array_reverse($temp, true);
  7199. }
  7200. }
  7201. $sorted = array();
  7202. foreach (array_keys($temp) as $key) {
  7203. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7204. }
  7205. return $sorted;
  7206. }
  7207. }
  7208. return $array;
  7209. }
  7210. /**
  7211. * Check if a string is in UTF8
  7212. *
  7213. * @param string $str String to check
  7214. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7215. */
  7216. function utf8_check($str)
  7217. {
  7218. $str = (string) $str; // Sometimes string is an int.
  7219. // We must use here a binary strlen function (so not dol_strlen)
  7220. $strLength = dol_strlen($str);
  7221. for ($i = 0; $i < $strLength; $i++) {
  7222. if (ord($str[$i]) < 0x80) {
  7223. continue; // 0bbbbbbb
  7224. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7225. $n = 1; // 110bbbbb
  7226. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7227. $n = 2; // 1110bbbb
  7228. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7229. $n = 3; // 11110bbb
  7230. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7231. $n = 4; // 111110bb
  7232. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7233. $n = 5; // 1111110b
  7234. } else {
  7235. return false; // Does not match any model
  7236. }
  7237. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7238. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7239. return false;
  7240. }
  7241. }
  7242. }
  7243. return true;
  7244. }
  7245. /**
  7246. * Check if a string is in ASCII
  7247. *
  7248. * @param string $str String to check
  7249. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7250. */
  7251. function ascii_check($str)
  7252. {
  7253. if (function_exists('mb_check_encoding')) {
  7254. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7255. if (!mb_check_encoding($str, 'ASCII')) {
  7256. return false;
  7257. }
  7258. } else {
  7259. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7260. return false; // Contains a byte > 7f
  7261. }
  7262. }
  7263. return true;
  7264. }
  7265. /**
  7266. * Return a string encoded into OS filesystem encoding. This function is used to define
  7267. * value to pass to filesystem PHP functions.
  7268. *
  7269. * @param string $str String to encode (UTF-8)
  7270. * @return string Encoded string (UTF-8, ISO-8859-1)
  7271. */
  7272. function dol_osencode($str)
  7273. {
  7274. global $conf;
  7275. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7276. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7277. $tmp = 'iso-8859-1'; // By default for windows
  7278. }
  7279. if (empty($tmp)) {
  7280. $tmp = 'utf-8'; // By default for other
  7281. }
  7282. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7283. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7284. }
  7285. if ($tmp == 'iso-8859-1') {
  7286. return utf8_decode($str);
  7287. }
  7288. return $str;
  7289. }
  7290. /**
  7291. * Return an id or code from a code or id.
  7292. * Store also Code-Id into a cache to speed up next request on same key.
  7293. *
  7294. * @param DoliDB $db Database handler
  7295. * @param string $key Code or Id to get Id or Code
  7296. * @param string $tablename Table name without prefix
  7297. * @param string $fieldkey Field to search the key into
  7298. * @param string $fieldid Field to get
  7299. * @param int $entityfilter Filter by entity
  7300. * @return int <0 if KO, Id of code if OK
  7301. * @see $langs->getLabelFromKey
  7302. */
  7303. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  7304. {
  7305. global $cache_codes;
  7306. // If key empty
  7307. if ($key == '') {
  7308. return '';
  7309. }
  7310. // Check in cache
  7311. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7312. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7313. }
  7314. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7315. $sql = "SELECT ".$fieldid." as valuetoget";
  7316. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7317. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7318. if (!empty($entityfilter)) {
  7319. $sql .= " AND entity IN (".getEntity($tablename).")";
  7320. }
  7321. $resql = $db->query($sql);
  7322. if ($resql) {
  7323. $obj = $db->fetch_object($resql);
  7324. if ($obj) {
  7325. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7326. } else {
  7327. $cache_codes[$tablename][$key][$fieldid] = '';
  7328. }
  7329. $db->free($resql);
  7330. return $cache_codes[$tablename][$key][$fieldid];
  7331. } else {
  7332. return -1;
  7333. }
  7334. }
  7335. /**
  7336. * Verify if condition in string is ok or not
  7337. *
  7338. * @param string $strRights String with condition to check
  7339. * @return boolean True or False. Return True if strRights is ''
  7340. */
  7341. function verifCond($strRights)
  7342. {
  7343. global $user, $conf, $langs;
  7344. global $leftmenu;
  7345. global $rights; // To export to dol_eval function
  7346. //print $strRights."<br>\n";
  7347. $rights = true;
  7348. if ($strRights != '') {
  7349. $str = 'if(!('.$strRights.')) { $rights = false; }';
  7350. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  7351. }
  7352. return $rights;
  7353. }
  7354. /**
  7355. * Replace eval function to add more security.
  7356. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7357. *
  7358. * @param string $s String to evaluate
  7359. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7360. * @param int $hideerrors 1=Hide errors
  7361. * @return mixed Nothing or return result of eval
  7362. */
  7363. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  7364. {
  7365. // Only global variables can be changed by eval function and returned to caller
  7366. global $db, $langs, $user, $conf, $website, $websitepage;
  7367. global $action, $mainmenu, $leftmenu;
  7368. global $rights;
  7369. global $object;
  7370. global $mysoc;
  7371. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7372. global $soc; // For backward compatibility
  7373. // Replace dangerous char (used for RCE), we allow only PHP variable testing.
  7374. if (strpos($s, '`') !== false) {
  7375. return 'Bad string syntax to evaluate: '.$s;
  7376. }
  7377. // We block using of php exec or php file functions
  7378. $forbiddenphpstrings = array("exec(", "passthru(", "shell_exec(", "system(", "proc_open(", "popen(", "eval(", "dol_eval(", "executeCLI(");
  7379. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array("fopen(", "file_put_contents(", "fputs(", "fputscsv(", "fwrite(", "fpassthru(", "unlink(", "mkdir(", "rmdir(", "symlink(", "touch(", "umask("));
  7380. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('function(', '$$', 'call_user_func('));
  7381. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7382. $forbiddenphpregex = 'global\s+\$';
  7383. do {
  7384. $oldstringtoclean = $s;
  7385. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7386. $s = preg_replace('/'.$forbiddenphpregex.'/', '__forbiddenstring__', $s);
  7387. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7388. } while ($oldstringtoclean != $s);
  7389. if (strpos($s, '__forbiddenstring__') !== false) {
  7390. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7391. return 'Bad string syntax to evaluate: '.$s;
  7392. }
  7393. //print $s."<br>\n";
  7394. if ($returnvalue) {
  7395. if ($hideerrors) {
  7396. return @eval('return '.$s.';');
  7397. } else {
  7398. return eval('return '.$s.';');
  7399. }
  7400. } else {
  7401. if ($hideerrors) {
  7402. @eval($s);
  7403. } else {
  7404. eval($s);
  7405. }
  7406. }
  7407. }
  7408. /**
  7409. * Return if var element is ok
  7410. *
  7411. * @param string $element Variable to check
  7412. * @return boolean Return true of variable is not empty
  7413. */
  7414. function dol_validElement($element)
  7415. {
  7416. return (trim($element) != '');
  7417. }
  7418. /**
  7419. * Return img flag of country for a language code or country code.
  7420. *
  7421. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7422. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7423. * @param int $notitlealt No title alt
  7424. * @return string HTML img string with flag.
  7425. */
  7426. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  7427. {
  7428. if (empty($codelang)) {
  7429. return '';
  7430. }
  7431. if ($codelang == 'auto') {
  7432. return '<span class="fa fa-language"></span>';
  7433. }
  7434. $langtocountryflag = array(
  7435. 'ar_AR' => '',
  7436. 'ca_ES' => 'catalonia',
  7437. 'da_DA' => 'dk',
  7438. 'fr_CA' => 'mq',
  7439. 'sv_SV' => 'se',
  7440. 'sw_SW' => 'unknown',
  7441. 'AQ' => 'unknown',
  7442. 'CW' => 'unknown',
  7443. 'IM' => 'unknown',
  7444. 'JE' => 'unknown',
  7445. 'MF' => 'unknown',
  7446. 'BL' => 'unknown',
  7447. 'SX' => 'unknown'
  7448. );
  7449. if (isset($langtocountryflag[$codelang])) {
  7450. $flagImage = $langtocountryflag[$codelang];
  7451. } else {
  7452. $tmparray = explode('_', $codelang);
  7453. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7454. }
  7455. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  7456. }
  7457. /**
  7458. * Return default language from country code.
  7459. * Return null if not found.
  7460. *
  7461. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'MX', ...
  7462. * @return string Value of locale like 'en_US', 'fr_FR', ...
  7463. */
  7464. function getLanguageCodeFromCountryCode($countrycode)
  7465. {
  7466. global $mysoc;
  7467. if (empty($countrycode)) {
  7468. return null;
  7469. }
  7470. if (strtoupper($countrycode) == 'MQ') {
  7471. return 'fr_CA';
  7472. }
  7473. if (strtoupper($countrycode) == 'SE') {
  7474. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7475. }
  7476. if (strtoupper($countrycode) == 'CH') {
  7477. if ($mysoc->country_code == 'FR') {
  7478. return 'fr_CH';
  7479. }
  7480. if ($mysoc->country_code == 'DE') {
  7481. return 'de_CH';
  7482. }
  7483. if ($mysoc->country_code == 'IT') {
  7484. return 'it_CH';
  7485. }
  7486. }
  7487. // Locale list taken from:
  7488. // http://stackoverflow.com/questions/3191664/
  7489. // list-of-all-locales-and-their-short-codes
  7490. $locales = array(
  7491. 'af-ZA',
  7492. 'am-ET',
  7493. 'ar-AE',
  7494. 'ar-BH',
  7495. 'ar-DZ',
  7496. 'ar-EG',
  7497. 'ar-IQ',
  7498. 'ar-JO',
  7499. 'ar-KW',
  7500. 'ar-LB',
  7501. 'ar-LY',
  7502. 'ar-MA',
  7503. 'ar-OM',
  7504. 'ar-QA',
  7505. 'ar-SA',
  7506. 'ar-SY',
  7507. 'ar-TN',
  7508. 'ar-YE',
  7509. 'as-IN',
  7510. 'ba-RU',
  7511. 'be-BY',
  7512. 'bg-BG',
  7513. 'bn-BD',
  7514. 'bn-IN',
  7515. 'bo-CN',
  7516. 'br-FR',
  7517. 'ca-ES',
  7518. 'co-FR',
  7519. 'cs-CZ',
  7520. 'cy-GB',
  7521. 'da-DK',
  7522. 'de-AT',
  7523. 'de-CH',
  7524. 'de-DE',
  7525. 'de-LI',
  7526. 'de-LU',
  7527. 'dv-MV',
  7528. 'el-GR',
  7529. 'en-AU',
  7530. 'en-BZ',
  7531. 'en-CA',
  7532. 'en-GB',
  7533. 'en-IE',
  7534. 'en-IN',
  7535. 'en-JM',
  7536. 'en-MY',
  7537. 'en-NZ',
  7538. 'en-PH',
  7539. 'en-SG',
  7540. 'en-TT',
  7541. 'en-US',
  7542. 'en-ZA',
  7543. 'en-ZW',
  7544. 'es-AR',
  7545. 'es-BO',
  7546. 'es-CL',
  7547. 'es-CO',
  7548. 'es-CR',
  7549. 'es-DO',
  7550. 'es-EC',
  7551. 'es-ES',
  7552. 'es-GT',
  7553. 'es-HN',
  7554. 'es-MX',
  7555. 'es-NI',
  7556. 'es-PA',
  7557. 'es-PE',
  7558. 'es-PR',
  7559. 'es-PY',
  7560. 'es-SV',
  7561. 'es-US',
  7562. 'es-UY',
  7563. 'es-VE',
  7564. 'et-EE',
  7565. 'eu-ES',
  7566. 'fa-IR',
  7567. 'fi-FI',
  7568. 'fo-FO',
  7569. 'fr-BE',
  7570. 'fr-CA',
  7571. 'fr-CH',
  7572. 'fr-FR',
  7573. 'fr-LU',
  7574. 'fr-MC',
  7575. 'fy-NL',
  7576. 'ga-IE',
  7577. 'gd-GB',
  7578. 'gl-ES',
  7579. 'gu-IN',
  7580. 'he-IL',
  7581. 'hi-IN',
  7582. 'hr-BA',
  7583. 'hr-HR',
  7584. 'hu-HU',
  7585. 'hy-AM',
  7586. 'id-ID',
  7587. 'ig-NG',
  7588. 'ii-CN',
  7589. 'is-IS',
  7590. 'it-CH',
  7591. 'it-IT',
  7592. 'ja-JP',
  7593. 'ka-GE',
  7594. 'kk-KZ',
  7595. 'kl-GL',
  7596. 'km-KH',
  7597. 'kn-IN',
  7598. 'ko-KR',
  7599. 'ky-KG',
  7600. 'lb-LU',
  7601. 'lo-LA',
  7602. 'lt-LT',
  7603. 'lv-LV',
  7604. 'mi-NZ',
  7605. 'mk-MK',
  7606. 'ml-IN',
  7607. 'mn-MN',
  7608. 'mr-IN',
  7609. 'ms-BN',
  7610. 'ms-MY',
  7611. 'mt-MT',
  7612. 'nb-NO',
  7613. 'ne-NP',
  7614. 'nl-BE',
  7615. 'nl-NL',
  7616. 'nn-NO',
  7617. 'oc-FR',
  7618. 'or-IN',
  7619. 'pa-IN',
  7620. 'pl-PL',
  7621. 'ps-AF',
  7622. 'pt-BR',
  7623. 'pt-PT',
  7624. 'rm-CH',
  7625. 'ro-MD',
  7626. 'ro-RO',
  7627. 'ru-RU',
  7628. 'rw-RW',
  7629. 'sa-IN',
  7630. 'se-FI',
  7631. 'se-NO',
  7632. 'se-SE',
  7633. 'si-LK',
  7634. 'sk-SK',
  7635. 'sl-SI',
  7636. 'sq-AL',
  7637. 'sv-FI',
  7638. 'sv-SE',
  7639. 'sw-KE',
  7640. 'ta-IN',
  7641. 'te-IN',
  7642. 'th-TH',
  7643. 'tk-TM',
  7644. 'tn-ZA',
  7645. 'tr-TR',
  7646. 'tt-RU',
  7647. 'ug-CN',
  7648. 'uk-UA',
  7649. 'ur-PK',
  7650. 'vi-VN',
  7651. 'wo-SN',
  7652. 'xh-ZA',
  7653. 'yo-NG',
  7654. 'zh-CN',
  7655. 'zh-HK',
  7656. 'zh-MO',
  7657. 'zh-SG',
  7658. 'zh-TW',
  7659. 'zu-ZA',
  7660. );
  7661. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  7662. if (in_array($buildprimarykeytotest, $locales)) {
  7663. return strtolower($countrycode).'_'.strtoupper($countrycode);
  7664. }
  7665. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  7666. foreach ($locales as $locale) {
  7667. $locale_language = locale_get_primary_language($locale);
  7668. $locale_region = locale_get_region($locale);
  7669. if (strtoupper($countrycode) == $locale_region) {
  7670. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  7671. return strtolower($locale_language).'_'.strtoupper($locale_region);
  7672. }
  7673. }
  7674. } else {
  7675. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  7676. }
  7677. return null;
  7678. }
  7679. /**
  7680. * Complete or removed entries into a head array (used to build tabs).
  7681. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  7682. * Or by change using hook completeTabsHead
  7683. *
  7684. * @param Conf $conf Object conf
  7685. * @param Translate $langs Object langs
  7686. * @param object|null $object Object object
  7687. * @param array $head Object head
  7688. * @param int $h New position to fill
  7689. * @param string $type Value for object where objectvalue can be
  7690. * 'thirdparty' to add a tab in third party view
  7691. * 'intervention' to add a tab in intervention view
  7692. * 'supplier_order' to add a tab in supplier order view
  7693. * 'supplier_invoice' to add a tab in supplier invoice view
  7694. * 'invoice' to add a tab in customer invoice view
  7695. * 'order' to add a tab in customer order view
  7696. * 'contract' to add a tabl in contract view
  7697. * 'product' to add a tab in product view
  7698. * 'propal' to add a tab in propal view
  7699. * 'user' to add a tab in user view
  7700. * 'group' to add a tab in group view
  7701. * 'member' to add a tab in fundation member view
  7702. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  7703. * 'ecm' to add a tab for another ecm view
  7704. * 'stock' to add a tab for warehouse view
  7705. * @param string $mode 'add' to complete head, 'remove' to remove entries
  7706. * @return void
  7707. */
  7708. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  7709. {
  7710. global $hookmanager;
  7711. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  7712. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  7713. $values = explode(':', $value);
  7714. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  7715. if (count($values) == 6) { // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  7716. if ($values[0] != $type) {
  7717. continue;
  7718. }
  7719. if (verifCond($values[4])) {
  7720. if ($values[3]) {
  7721. $langs->load($values[3]);
  7722. }
  7723. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7724. $substitutionarray = array();
  7725. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7726. $label = make_substitutions($reg[1], $substitutionarray);
  7727. } else {
  7728. $label = $langs->trans($values[2]);
  7729. }
  7730. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  7731. $head[$h][1] = $label;
  7732. $head[$h][2] = str_replace('+', '', $values[1]);
  7733. $h++;
  7734. }
  7735. } elseif (count($values) == 5) { // deprecated
  7736. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  7737. if ($values[0] != $type) {
  7738. continue;
  7739. }
  7740. if ($values[3]) {
  7741. $langs->load($values[3]);
  7742. }
  7743. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7744. $substitutionarray = array();
  7745. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7746. $label = make_substitutions($reg[1], $substitutionarray);
  7747. } else {
  7748. $label = $langs->trans($values[2]);
  7749. }
  7750. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  7751. $head[$h][1] = $label;
  7752. $head[$h][2] = str_replace('+', '', $values[1]);
  7753. $h++;
  7754. }
  7755. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  7756. if ($values[0] != $type) {
  7757. continue;
  7758. }
  7759. $tabname = str_replace('-', '', $values[1]);
  7760. foreach ($head as $key => $val) {
  7761. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  7762. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  7763. if ($head[$key][2] == $tabname && $condition) {
  7764. unset($head[$key]);
  7765. break;
  7766. }
  7767. }
  7768. }
  7769. }
  7770. }
  7771. // No need to make a return $head. Var is modified as a reference
  7772. if (!empty($hookmanager)) {
  7773. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  7774. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  7775. if ($reshook > 0) { // Hook ask to replace completely the array
  7776. $head = $hookmanager->resArray;
  7777. } else { // Hook
  7778. $head = array_merge($head, $hookmanager->resArray);
  7779. }
  7780. $h = count($head);
  7781. }
  7782. }
  7783. /**
  7784. * Print common footer :
  7785. * conf->global->MAIN_HTML_FOOTER
  7786. * js for switch of menu hider
  7787. * js for conf->global->MAIN_GOOGLE_AN_ID
  7788. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  7789. * js for conf->logbuffer
  7790. *
  7791. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  7792. * @return void
  7793. */
  7794. function printCommonFooter($zone = 'private')
  7795. {
  7796. global $conf, $hookmanager, $user, $debugbar;
  7797. global $action;
  7798. global $micro_start_time;
  7799. if ($zone == 'private') {
  7800. print "\n".'<!-- Common footer for private page -->'."\n";
  7801. } else {
  7802. print "\n".'<!-- Common footer for public page -->'."\n";
  7803. }
  7804. // A div to store page_y POST parameter so we can read it using javascript
  7805. print "\n<!-- A div to store page_y POST parameter -->\n";
  7806. print '<div id="page_y" style="display: none;">'.(empty($_POST['page_y']) ? '' : $_POST['page_y']).'</div>'."\n";
  7807. $parameters = array();
  7808. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  7809. if (empty($reshook)) {
  7810. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  7811. print $conf->global->MAIN_HTML_FOOTER."\n";
  7812. }
  7813. print "\n";
  7814. if (!empty($conf->use_javascript_ajax)) {
  7815. print '<script>'."\n";
  7816. print 'jQuery(document).ready(function() {'."\n";
  7817. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  7818. print "\n";
  7819. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  7820. print 'jQuery("li.menuhider").click(function(event) {';
  7821. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  7822. print ' console.log("We click on .menuhider");'."\n";
  7823. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  7824. print '});'."\n";
  7825. }
  7826. // Management of focus and mandatory for fields
  7827. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  7828. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  7829. $relativepathstring = $_SERVER["PHP_SELF"];
  7830. // Clean $relativepathstring
  7831. if (constant('DOL_URL_ROOT')) {
  7832. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  7833. }
  7834. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  7835. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  7836. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  7837. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  7838. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  7839. $qualified = 0;
  7840. if ($defkey != '_noquery_') {
  7841. $tmpqueryarraytohave = explode('&', $defkey);
  7842. $foundintru = 0;
  7843. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7844. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7845. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7846. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7847. $foundintru = 1;
  7848. }
  7849. }
  7850. if (!$foundintru) {
  7851. $qualified = 1;
  7852. }
  7853. //var_dump($defkey.'-'.$qualified);
  7854. } else {
  7855. $qualified = 1;
  7856. }
  7857. if ($qualified) {
  7858. foreach ($defval as $paramkey => $paramval) {
  7859. // Set focus on field
  7860. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  7861. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  7862. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  7863. }
  7864. }
  7865. }
  7866. }
  7867. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  7868. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  7869. $qualified = 0;
  7870. if ($defkey != '_noquery_') {
  7871. $tmpqueryarraytohave = explode('&', $defkey);
  7872. $foundintru = 0;
  7873. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7874. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7875. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7876. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7877. $foundintru = 1;
  7878. }
  7879. }
  7880. if (!$foundintru) {
  7881. $qualified = 1;
  7882. }
  7883. //var_dump($defkey.'-'.$qualified);
  7884. } else {
  7885. $qualified = 1;
  7886. }
  7887. if ($qualified) {
  7888. foreach ($defval as $paramkey => $paramval) {
  7889. // Add property 'required' on input
  7890. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7891. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7892. 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";
  7893. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7894. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  7895. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  7896. }
  7897. }
  7898. }
  7899. }
  7900. }
  7901. print '});'."\n";
  7902. // End of tuning
  7903. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  7904. print "\n";
  7905. print "/* JS CODE TO ENABLE to add memory info */\n";
  7906. print 'window.console && console.log("';
  7907. if (!empty($conf->global->MEMCACHED_SERVER)) {
  7908. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  7909. }
  7910. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  7911. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  7912. $micro_end_time = microtime(true);
  7913. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  7914. }
  7915. if (function_exists("memory_get_usage")) {
  7916. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  7917. }
  7918. if (function_exists("memory_get_peak_usage")) {
  7919. print ' - Real mem peak: '.memory_get_peak_usage(true);
  7920. }
  7921. if (function_exists("zend_loader_file_encoded")) {
  7922. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  7923. }
  7924. print '");'."\n";
  7925. }
  7926. print "\n".'</script>'."\n";
  7927. // Google Analytics
  7928. // TODO Add a hook here
  7929. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  7930. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  7931. foreach ($tmptagarray as $tmptag) {
  7932. print "\n";
  7933. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  7934. print "
  7935. <!-- Global site tag (gtag.js) - Google Analytics -->
  7936. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  7937. <script>
  7938. window.dataLayer = window.dataLayer || [];
  7939. function gtag(){dataLayer.push(arguments);}
  7940. gtag('js', new Date());
  7941. gtag('config', '".trim($tmptag)."');
  7942. </script>";
  7943. print "\n";
  7944. }
  7945. }
  7946. }
  7947. // Add Xdebug coverage of code
  7948. if (defined('XDEBUGCOVERAGE')) {
  7949. print_r(xdebug_get_code_coverage());
  7950. }
  7951. // Add DebugBar data
  7952. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  7953. $debugbar['time']->stopMeasure('pageaftermaster');
  7954. print '<!-- Output debugbar data -->'."\n";
  7955. $renderer = $debugbar->getRenderer();
  7956. print $debugbar->getRenderer()->render();
  7957. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  7958. print "\n";
  7959. print "<!-- Start of log output\n";
  7960. //print '<div class="hidden">'."\n";
  7961. foreach ($conf->logbuffer as $logline) {
  7962. print $logline."<br>\n";
  7963. }
  7964. //print '</div>'."\n";
  7965. print "End of log output -->\n";
  7966. }
  7967. }
  7968. }
  7969. /**
  7970. * Split a string with 2 keys into key array.
  7971. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  7972. *
  7973. * @param string $string String to explode
  7974. * @param string $delimiter Delimiter between each couple of data
  7975. * @param string $kv Delimiter between key and value
  7976. * @return array Array of data exploded
  7977. */
  7978. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  7979. {
  7980. if ($a = explode($delimiter, $string)) {
  7981. $ka = array();
  7982. foreach ($a as $s) { // each part
  7983. if ($s) {
  7984. if ($pos = strpos($s, $kv)) { // key/value delimiter
  7985. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  7986. } else { // key delimiter not found
  7987. $ka[] = trim($s);
  7988. }
  7989. }
  7990. }
  7991. return $ka;
  7992. }
  7993. return array();
  7994. }
  7995. /**
  7996. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  7997. *
  7998. * @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.
  7999. * @return string HTML code to set focus
  8000. */
  8001. function dol_set_focus($selector)
  8002. {
  8003. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8004. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8005. }
  8006. /**
  8007. * Return getmypid() or random PID when function is disabled
  8008. * Some web hosts disable this php function for security reasons
  8009. * and sometimes we can't redeclare function
  8010. *
  8011. * @return int
  8012. */
  8013. function dol_getmypid()
  8014. {
  8015. if (!function_exists('getmypid')) {
  8016. return mt_rand(1, 32768);
  8017. } else {
  8018. return getmypid();
  8019. }
  8020. }
  8021. /**
  8022. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8023. *
  8024. * @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")
  8025. * @param string $value The value to look for.
  8026. * If param $mode is 0, can contains several keywords separated with a space or |
  8027. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8028. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8029. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8030. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8031. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8032. * @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')
  8033. * 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'
  8034. * @param integer $nofirstand 1=Do not output the first 'AND'
  8035. * @return string $res The statement to append to the SQL query
  8036. */
  8037. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8038. {
  8039. global $db, $langs;
  8040. $value = trim($value);
  8041. if ($mode == 0) {
  8042. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8043. }
  8044. if ($mode == 1) {
  8045. $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
  8046. }
  8047. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8048. $crits = explode(' ', $value);
  8049. $res = '';
  8050. if (!is_array($fields)) {
  8051. $fields = array($fields);
  8052. }
  8053. $j = 0;
  8054. foreach ($crits as $crit) {
  8055. $crit = trim($crit);
  8056. $i = 0;
  8057. $i2 = 0;
  8058. $newres = '';
  8059. foreach ($fields as $field) {
  8060. if ($mode == 1) {
  8061. $operator = '=';
  8062. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8063. $reg = array();
  8064. preg_match('/([<>=]+)/', $crit, $reg);
  8065. if ($reg[1]) {
  8066. $operator = $reg[1];
  8067. }
  8068. if ($newcrit != '') {
  8069. $numnewcrit = price2num($newcrit);
  8070. if (is_numeric($numnewcrit)) {
  8071. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric
  8072. } else {
  8073. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8074. }
  8075. $i2++; // a criteria was added to string
  8076. }
  8077. } elseif ($mode == 2 || $mode == -2) {
  8078. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8079. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8080. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8081. if ($mode == -2) {
  8082. $newres .= ' OR '.$field.' IS NULL';
  8083. }
  8084. $i2++; // a criteria was added to string
  8085. } elseif ($mode == 3 || $mode == -3) {
  8086. $tmparray = explode(',', $crit);
  8087. if (count($tmparray)) {
  8088. $listofcodes = '';
  8089. foreach ($tmparray as $val) {
  8090. $val = trim($val);
  8091. if ($val) {
  8092. $listofcodes .= ($listofcodes ? ',' : '');
  8093. $listofcodes .= "'".$db->escape($val)."'";
  8094. }
  8095. }
  8096. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8097. $i2++; // a criteria was added to string
  8098. }
  8099. if ($mode == -3) {
  8100. $newres .= ' OR '.$field.' IS NULL';
  8101. }
  8102. } elseif ($mode == 4) {
  8103. $tmparray = explode(',', $crit);
  8104. if (count($tmparray)) {
  8105. $listofcodes = '';
  8106. foreach ($tmparray as $val) {
  8107. $val = trim($val);
  8108. if ($val) {
  8109. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8110. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8111. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8112. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8113. $newres .= ')';
  8114. $i2++;
  8115. }
  8116. }
  8117. }
  8118. } else // $mode=0
  8119. {
  8120. $tmpcrits = explode('|', $crit);
  8121. $i3 = 0;
  8122. foreach ($tmpcrits as $tmpcrit) {
  8123. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8124. continue;
  8125. }
  8126. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8127. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8128. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ?trim($tmpcrit) : '0');
  8129. } else {
  8130. $newres .= $field." LIKE '";
  8131. $tmpcrit = trim($tmpcrit);
  8132. $tmpcrit2 = $tmpcrit;
  8133. $tmpbefore = '%';
  8134. $tmpafter = '%';
  8135. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8136. $tmpbefore = '';
  8137. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8138. }
  8139. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8140. $tmpafter = '';
  8141. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8142. }
  8143. $newres .= $tmpbefore;
  8144. $newres .= $db->escape($tmpcrit2);
  8145. $newres .= $tmpafter;
  8146. $newres .= "'";
  8147. if ($tmpcrit2 == '') {
  8148. $newres .= " OR ".$field." IS NULL";
  8149. }
  8150. }
  8151. $i3++;
  8152. }
  8153. $i2++; // a criteria was added to string
  8154. }
  8155. $i++;
  8156. }
  8157. if ($newres) {
  8158. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8159. }
  8160. $j++;
  8161. }
  8162. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8163. //print 'xx'.$res.'yy';
  8164. return $res;
  8165. }
  8166. /**
  8167. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8168. *
  8169. * @param Object $object Object
  8170. * @return string Url string
  8171. */
  8172. function showDirectDownloadLink($object)
  8173. {
  8174. global $conf, $langs;
  8175. $out = '';
  8176. $url = $object->getLastMainDocLink($object->element);
  8177. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8178. if ($url) {
  8179. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8180. $out .= ajax_autoselect("directdownloadlink", 0);
  8181. } else {
  8182. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8183. }
  8184. return $out;
  8185. }
  8186. /**
  8187. * Return the filename of file to get the thumbs
  8188. *
  8189. * @param string $file Original filename (full or relative path)
  8190. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8191. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8192. * @return string New file name (full or relative path, including the thumbs/)
  8193. */
  8194. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8195. {
  8196. $dirName = dirname($file);
  8197. if ($dirName == '.') {
  8198. $dirName = '';
  8199. }
  8200. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8201. $fileName = basename($fileName);
  8202. if (empty($extImgTarget)) {
  8203. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8204. }
  8205. if (empty($extImgTarget)) {
  8206. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8207. }
  8208. if (empty($extImgTarget)) {
  8209. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8210. }
  8211. if (empty($extImgTarget)) {
  8212. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8213. }
  8214. if (empty($extImgTarget)) {
  8215. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8216. }
  8217. if (empty($extImgTarget)) {
  8218. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8219. }
  8220. if (!$extImgTarget) {
  8221. return $file;
  8222. }
  8223. $subdir = '';
  8224. if ($extName) {
  8225. $subdir = 'thumbs/';
  8226. }
  8227. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8228. }
  8229. /**
  8230. * Return URL we can use for advanced preview links
  8231. *
  8232. * @param string $modulepart propal, facture, facture_fourn, ...
  8233. * @param string $relativepath Relative path of docs.
  8234. * @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)
  8235. * @param string $param More param on http links
  8236. * @return string|array Output string with href link or array with all components of link
  8237. */
  8238. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8239. {
  8240. global $conf, $langs;
  8241. if (empty($conf->use_javascript_ajax)) {
  8242. return '';
  8243. }
  8244. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8245. if ($alldata == 1) {
  8246. if ($isAllowedForPreview) {
  8247. 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));
  8248. } else {
  8249. return array();
  8250. }
  8251. }
  8252. // old behavior, return a string
  8253. if ($isAllowedForPreview) {
  8254. 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')).'\')';
  8255. } else {
  8256. return '';
  8257. }
  8258. }
  8259. /**
  8260. * Make content of an input box selected when we click into input field.
  8261. *
  8262. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8263. * @param string $addlink Add a 'link to' after
  8264. * @return string
  8265. */
  8266. function ajax_autoselect($htmlname, $addlink = '')
  8267. {
  8268. global $langs;
  8269. $out = '<script>
  8270. jQuery(document).ready(function () {
  8271. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8272. });
  8273. </script>';
  8274. if ($addlink) {
  8275. $out .= ' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  8276. }
  8277. return $out;
  8278. }
  8279. /**
  8280. * Return if a file is qualified for preview
  8281. *
  8282. * @param string $file Filename we looking for information
  8283. * @return int 1 If allowed, 0 otherwise
  8284. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8285. */
  8286. function dolIsAllowedForPreview($file)
  8287. {
  8288. global $conf;
  8289. // Check .noexe extension in filename
  8290. if (preg_match('/\.noexe$/i', $file)) {
  8291. return 0;
  8292. }
  8293. // Check mime types
  8294. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8295. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8296. $mime_preview[] = 'svg+xml';
  8297. }
  8298. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8299. //$mime_preview[]='archive';
  8300. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8301. if ($num_mime !== false) {
  8302. return 1;
  8303. }
  8304. // By default, not allowed for preview
  8305. return 0;
  8306. }
  8307. /**
  8308. * Return mime type of a file
  8309. *
  8310. * @param string $file Filename we looking for MIME type
  8311. * @param string $default Default mime type if extension not found in known list
  8312. * @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
  8313. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8314. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8315. */
  8316. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8317. {
  8318. $mime = $default;
  8319. $imgmime = 'other.png';
  8320. $famime = 'file-o';
  8321. $srclang = '';
  8322. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8323. // Plain text files
  8324. if (preg_match('/\.txt$/i', $tmpfile)) {
  8325. $mime = 'text/plain';
  8326. $imgmime = 'text.png';
  8327. $famime = 'file-text-o';
  8328. }
  8329. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8330. $mime = 'text/richtext';
  8331. $imgmime = 'text.png';
  8332. $famime = 'file-text-o';
  8333. }
  8334. if (preg_match('/\.csv$/i', $tmpfile)) {
  8335. $mime = 'text/csv';
  8336. $imgmime = 'text.png';
  8337. $famime = 'file-text-o';
  8338. }
  8339. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8340. $mime = 'text/tab-separated-values';
  8341. $imgmime = 'text.png';
  8342. $famime = 'file-text-o';
  8343. }
  8344. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8345. $mime = 'text/plain';
  8346. $imgmime = 'text.png';
  8347. $famime = 'file-text-o';
  8348. }
  8349. if (preg_match('/\.ini$/i', $tmpfile)) {
  8350. $mime = 'text/plain';
  8351. $imgmime = 'text.png';
  8352. $srclang = 'ini';
  8353. $famime = 'file-text-o';
  8354. }
  8355. if (preg_match('/\.md$/i', $tmpfile)) {
  8356. $mime = 'text/plain';
  8357. $imgmime = 'text.png';
  8358. $srclang = 'md';
  8359. $famime = 'file-text-o';
  8360. }
  8361. if (preg_match('/\.css$/i', $tmpfile)) {
  8362. $mime = 'text/css';
  8363. $imgmime = 'css.png';
  8364. $srclang = 'css';
  8365. $famime = 'file-text-o';
  8366. }
  8367. if (preg_match('/\.lang$/i', $tmpfile)) {
  8368. $mime = 'text/plain';
  8369. $imgmime = 'text.png';
  8370. $srclang = 'lang';
  8371. $famime = 'file-text-o';
  8372. }
  8373. // Certificate files
  8374. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8375. $mime = 'text/plain';
  8376. $imgmime = 'text.png';
  8377. $famime = 'file-text-o';
  8378. }
  8379. // XML based (HTML/XML/XAML)
  8380. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8381. $mime = 'text/html';
  8382. $imgmime = 'html.png';
  8383. $srclang = 'html';
  8384. $famime = 'file-text-o';
  8385. }
  8386. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8387. $mime = 'text/xml';
  8388. $imgmime = 'other.png';
  8389. $srclang = 'xml';
  8390. $famime = 'file-text-o';
  8391. }
  8392. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8393. $mime = 'text/xml';
  8394. $imgmime = 'other.png';
  8395. $srclang = 'xaml';
  8396. $famime = 'file-text-o';
  8397. }
  8398. // Languages
  8399. if (preg_match('/\.bas$/i', $tmpfile)) {
  8400. $mime = 'text/plain';
  8401. $imgmime = 'text.png';
  8402. $srclang = 'bas';
  8403. $famime = 'file-code-o';
  8404. }
  8405. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8406. $mime = 'text/plain';
  8407. $imgmime = 'text.png';
  8408. $srclang = 'c';
  8409. $famime = 'file-code-o';
  8410. }
  8411. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8412. $mime = 'text/plain';
  8413. $imgmime = 'text.png';
  8414. $srclang = 'cpp';
  8415. $famime = 'file-code-o';
  8416. }
  8417. if (preg_match('/\.cs$/i', $tmpfile)) {
  8418. $mime = 'text/plain';
  8419. $imgmime = 'text.png';
  8420. $srclang = 'cs';
  8421. $famime = 'file-code-o';
  8422. }
  8423. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8424. $mime = 'text/plain';
  8425. $imgmime = 'text.png';
  8426. $srclang = 'h';
  8427. $famime = 'file-code-o';
  8428. }
  8429. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8430. $mime = 'text/plain';
  8431. $imgmime = 'text.png';
  8432. $srclang = 'java';
  8433. $famime = 'file-code-o';
  8434. }
  8435. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8436. $mime = 'text/plain';
  8437. $imgmime = 'php.png';
  8438. $srclang = 'php';
  8439. $famime = 'file-code-o';
  8440. }
  8441. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8442. $mime = 'text/plain';
  8443. $imgmime = 'php.png';
  8444. $srclang = 'php';
  8445. $famime = 'file-code-o';
  8446. }
  8447. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8448. $mime = 'text/plain';
  8449. $imgmime = 'pl.png';
  8450. $srclang = 'perl';
  8451. $famime = 'file-code-o';
  8452. }
  8453. if (preg_match('/\.sql$/i', $tmpfile)) {
  8454. $mime = 'text/plain';
  8455. $imgmime = 'text.png';
  8456. $srclang = 'sql';
  8457. $famime = 'file-code-o';
  8458. }
  8459. if (preg_match('/\.js$/i', $tmpfile)) {
  8460. $mime = 'text/x-javascript';
  8461. $imgmime = 'jscript.png';
  8462. $srclang = 'js';
  8463. $famime = 'file-code-o';
  8464. }
  8465. // Open office
  8466. if (preg_match('/\.odp$/i', $tmpfile)) {
  8467. $mime = 'application/vnd.oasis.opendocument.presentation';
  8468. $imgmime = 'ooffice.png';
  8469. $famime = 'file-powerpoint-o';
  8470. }
  8471. if (preg_match('/\.ods$/i', $tmpfile)) {
  8472. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8473. $imgmime = 'ooffice.png';
  8474. $famime = 'file-excel-o';
  8475. }
  8476. if (preg_match('/\.odt$/i', $tmpfile)) {
  8477. $mime = 'application/vnd.oasis.opendocument.text';
  8478. $imgmime = 'ooffice.png';
  8479. $famime = 'file-word-o';
  8480. }
  8481. // MS Office
  8482. if (preg_match('/\.mdb$/i', $tmpfile)) {
  8483. $mime = 'application/msaccess';
  8484. $imgmime = 'mdb.png';
  8485. $famime = 'file-o';
  8486. }
  8487. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  8488. $mime = 'application/msword';
  8489. $imgmime = 'doc.png';
  8490. $famime = 'file-word-o';
  8491. }
  8492. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  8493. $mime = 'application/msword';
  8494. $imgmime = 'doc.png';
  8495. $famime = 'file-word-o';
  8496. }
  8497. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  8498. $mime = 'application/vnd.ms-excel';
  8499. $imgmime = 'xls.png';
  8500. $famime = 'file-excel-o';
  8501. }
  8502. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  8503. $mime = 'application/vnd.ms-excel';
  8504. $imgmime = 'xls.png';
  8505. $famime = 'file-excel-o';
  8506. }
  8507. if (preg_match('/\.xls$/i', $tmpfile)) {
  8508. $mime = 'application/vnd.ms-excel';
  8509. $imgmime = 'xls.png';
  8510. $famime = 'file-excel-o';
  8511. }
  8512. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  8513. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  8514. $imgmime = 'xls.png';
  8515. $famime = 'file-excel-o';
  8516. }
  8517. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  8518. $mime = 'application/vnd.ms-powerpoint';
  8519. $imgmime = 'ppt.png';
  8520. $famime = 'file-powerpoint-o';
  8521. }
  8522. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  8523. $mime = 'application/x-mspowerpoint';
  8524. $imgmime = 'ppt.png';
  8525. $famime = 'file-powerpoint-o';
  8526. }
  8527. // Other
  8528. if (preg_match('/\.pdf$/i', $tmpfile)) {
  8529. $mime = 'application/pdf';
  8530. $imgmime = 'pdf.png';
  8531. $famime = 'file-pdf-o';
  8532. }
  8533. // Scripts
  8534. if (preg_match('/\.bat$/i', $tmpfile)) {
  8535. $mime = 'text/x-bat';
  8536. $imgmime = 'script.png';
  8537. $srclang = 'dos';
  8538. $famime = 'file-code-o';
  8539. }
  8540. if (preg_match('/\.sh$/i', $tmpfile)) {
  8541. $mime = 'text/x-sh';
  8542. $imgmime = 'script.png';
  8543. $srclang = 'bash';
  8544. $famime = 'file-code-o';
  8545. }
  8546. if (preg_match('/\.ksh$/i', $tmpfile)) {
  8547. $mime = 'text/x-ksh';
  8548. $imgmime = 'script.png';
  8549. $srclang = 'bash';
  8550. $famime = 'file-code-o';
  8551. }
  8552. if (preg_match('/\.bash$/i', $tmpfile)) {
  8553. $mime = 'text/x-bash';
  8554. $imgmime = 'script.png';
  8555. $srclang = 'bash';
  8556. $famime = 'file-code-o';
  8557. }
  8558. // Images
  8559. if (preg_match('/\.ico$/i', $tmpfile)) {
  8560. $mime = 'image/x-icon';
  8561. $imgmime = 'image.png';
  8562. $famime = 'file-image-o';
  8563. }
  8564. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  8565. $mime = 'image/jpeg';
  8566. $imgmime = 'image.png';
  8567. $famime = 'file-image-o';
  8568. }
  8569. if (preg_match('/\.png$/i', $tmpfile)) {
  8570. $mime = 'image/png';
  8571. $imgmime = 'image.png';
  8572. $famime = 'file-image-o';
  8573. }
  8574. if (preg_match('/\.gif$/i', $tmpfile)) {
  8575. $mime = 'image/gif';
  8576. $imgmime = 'image.png';
  8577. $famime = 'file-image-o';
  8578. }
  8579. if (preg_match('/\.bmp$/i', $tmpfile)) {
  8580. $mime = 'image/bmp';
  8581. $imgmime = 'image.png';
  8582. $famime = 'file-image-o';
  8583. }
  8584. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  8585. $mime = 'image/tiff';
  8586. $imgmime = 'image.png';
  8587. $famime = 'file-image-o';
  8588. }
  8589. if (preg_match('/\.svg$/i', $tmpfile)) {
  8590. $mime = 'image/svg+xml';
  8591. $imgmime = 'image.png';
  8592. $famime = 'file-image-o';
  8593. }
  8594. if (preg_match('/\.webp$/i', $tmpfile)) {
  8595. $mime = 'image/webp';
  8596. $imgmime = 'image.png';
  8597. $famime = 'file-image-o';
  8598. }
  8599. // Calendar
  8600. if (preg_match('/\.vcs$/i', $tmpfile)) {
  8601. $mime = 'text/calendar';
  8602. $imgmime = 'other.png';
  8603. $famime = 'file-text-o';
  8604. }
  8605. if (preg_match('/\.ics$/i', $tmpfile)) {
  8606. $mime = 'text/calendar';
  8607. $imgmime = 'other.png';
  8608. $famime = 'file-text-o';
  8609. }
  8610. // Other
  8611. if (preg_match('/\.torrent$/i', $tmpfile)) {
  8612. $mime = 'application/x-bittorrent';
  8613. $imgmime = 'other.png';
  8614. $famime = 'file-o';
  8615. }
  8616. // Audio
  8617. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  8618. $mime = 'audio';
  8619. $imgmime = 'audio.png';
  8620. $famime = 'file-audio-o';
  8621. }
  8622. // Video
  8623. if (preg_match('/\.mp4$/i', $tmpfile)) {
  8624. $mime = 'video/mp4';
  8625. $imgmime = 'video.png';
  8626. $famime = 'file-video-o';
  8627. }
  8628. if (preg_match('/\.ogv$/i', $tmpfile)) {
  8629. $mime = 'video/ogg';
  8630. $imgmime = 'video.png';
  8631. $famime = 'file-video-o';
  8632. }
  8633. if (preg_match('/\.webm$/i', $tmpfile)) {
  8634. $mime = 'video/webm';
  8635. $imgmime = 'video.png';
  8636. $famime = 'file-video-o';
  8637. }
  8638. if (preg_match('/\.avi$/i', $tmpfile)) {
  8639. $mime = 'video/x-msvideo';
  8640. $imgmime = 'video.png';
  8641. $famime = 'file-video-o';
  8642. }
  8643. if (preg_match('/\.divx$/i', $tmpfile)) {
  8644. $mime = 'video/divx';
  8645. $imgmime = 'video.png';
  8646. $famime = 'file-video-o';
  8647. }
  8648. if (preg_match('/\.xvid$/i', $tmpfile)) {
  8649. $mime = 'video/xvid';
  8650. $imgmime = 'video.png';
  8651. $famime = 'file-video-o';
  8652. }
  8653. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  8654. $mime = 'video';
  8655. $imgmime = 'video.png';
  8656. $famime = 'file-video-o';
  8657. }
  8658. // Archive
  8659. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  8660. $mime = 'archive';
  8661. $imgmime = 'archive.png';
  8662. $famime = 'file-archive-o';
  8663. } // application/xxx where zzz is zip, ...
  8664. // Exe
  8665. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  8666. $mime = 'application/octet-stream';
  8667. $imgmime = 'other.png';
  8668. $famime = 'file-o';
  8669. }
  8670. // Lib
  8671. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  8672. $mime = 'library';
  8673. $imgmime = 'library.png';
  8674. $famime = 'file-o';
  8675. }
  8676. // Err
  8677. if (preg_match('/\.err$/i', $tmpfile)) {
  8678. $mime = 'error';
  8679. $imgmime = 'error.png';
  8680. $famime = 'file-text-o';
  8681. }
  8682. // Return string
  8683. if ($mode == 1) {
  8684. $tmp = explode('/', $mime);
  8685. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  8686. }
  8687. if ($mode == 2) {
  8688. return $imgmime;
  8689. }
  8690. if ($mode == 3) {
  8691. return $srclang;
  8692. }
  8693. if ($mode == 4) {
  8694. return $famime;
  8695. }
  8696. return $mime;
  8697. }
  8698. /**
  8699. * Return value from dictionary
  8700. *
  8701. * @param string $tablename name of dictionary
  8702. * @param string $field the value to return
  8703. * @param int $id id of line
  8704. * @param bool $checkentity add filter on entity
  8705. * @param string $rowidfield name of the column rowid
  8706. * @return string
  8707. */
  8708. function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  8709. {
  8710. global $dictvalues, $db, $langs;
  8711. if (!isset($dictvalues[$tablename])) {
  8712. $dictvalues[$tablename] = array();
  8713. $sql = "SELECT * FROM ".$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  8714. if ($checkentity) {
  8715. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  8716. }
  8717. $resql = $db->query($sql);
  8718. if ($resql) {
  8719. while ($obj = $db->fetch_object($resql)) {
  8720. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  8721. }
  8722. } else {
  8723. dol_print_error($db);
  8724. }
  8725. }
  8726. if (!empty($dictvalues[$tablename][$id])) {
  8727. return $dictvalues[$tablename][$id]->{$field}; // Found
  8728. } else // Not found
  8729. {
  8730. if ($id > 0) {
  8731. return $id;
  8732. }
  8733. return '';
  8734. }
  8735. }
  8736. /**
  8737. * Return true if the color is light
  8738. *
  8739. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  8740. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  8741. */
  8742. function colorIsLight($stringcolor)
  8743. {
  8744. $stringcolor = str_replace('#', '', $stringcolor);
  8745. $res = -1;
  8746. if (!empty($stringcolor)) {
  8747. $res = 0;
  8748. $tmp = explode(',', $stringcolor);
  8749. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  8750. $r = $tmp[0];
  8751. $g = $tmp[1];
  8752. $b = $tmp[2];
  8753. } else {
  8754. $hexr = $stringcolor[0].$stringcolor[1];
  8755. $hexg = $stringcolor[2].$stringcolor[3];
  8756. $hexb = $stringcolor[4].$stringcolor[5];
  8757. $r = hexdec($hexr);
  8758. $g = hexdec($hexg);
  8759. $b = hexdec($hexb);
  8760. }
  8761. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  8762. if ($bright > 0.6) {
  8763. $res = 1;
  8764. }
  8765. }
  8766. return $res;
  8767. }
  8768. /**
  8769. * Function to test if an entry is enabled or not
  8770. *
  8771. * @param string $type_user 0=We test for internal user, 1=We test for external user
  8772. * @param array $menuentry Array for feature entry to test
  8773. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  8774. * @return int 0=Hide, 1=Show, 2=Show gray
  8775. */
  8776. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  8777. {
  8778. global $conf;
  8779. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  8780. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  8781. if (empty($menuentry['enabled'])) {
  8782. return 0; // Entry disabled by condition
  8783. }
  8784. if ($type_user && $menuentry['module']) {
  8785. $tmploops = explode('|', $menuentry['module']);
  8786. $found = 0;
  8787. foreach ($tmploops as $tmploop) {
  8788. if (in_array($tmploop, $listofmodulesforexternal)) {
  8789. $found++;
  8790. break;
  8791. }
  8792. }
  8793. if (!$found) {
  8794. return 0; // Entry is for menus all excluded to external users
  8795. }
  8796. }
  8797. if (!$menuentry['perms'] && $type_user) {
  8798. return 0; // No permissions and user is external
  8799. }
  8800. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  8801. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  8802. }
  8803. if (!$menuentry['perms']) {
  8804. return 2; // No permissions and user is external
  8805. }
  8806. return 1;
  8807. }
  8808. /**
  8809. * Round to next multiple.
  8810. *
  8811. * @param double $n Number to round up
  8812. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  8813. * @return integer Value rounded.
  8814. */
  8815. function roundUpToNextMultiple($n, $x = 5)
  8816. {
  8817. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  8818. }
  8819. /**
  8820. * Function dolGetBadge
  8821. *
  8822. * @param string $label label of badge no html : use in alt attribute for accessibility
  8823. * @param string $html optional : label of badge with html
  8824. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  8825. * @param string $mode default '' , 'pill', 'dot'
  8826. * @param string $url the url for link
  8827. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  8828. * @return string Html badge
  8829. */
  8830. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  8831. {
  8832. $attr = array(
  8833. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  8834. );
  8835. if (empty($html)) {
  8836. $html = $label;
  8837. }
  8838. if (!empty($url)) {
  8839. $attr['href'] = $url;
  8840. }
  8841. if ($mode === 'dot') {
  8842. $attr['class'] .= ' classfortooltip';
  8843. $attr['title'] = $html;
  8844. $attr['aria-label'] = $label;
  8845. $html = '';
  8846. }
  8847. // Override attr
  8848. if (!empty($params['attr']) && is_array($params['attr'])) {
  8849. foreach ($params['attr'] as $key => $value) {
  8850. if ($key == 'class') {
  8851. $attr['class'] .= ' '.$value;
  8852. } elseif ($key == 'classOverride') {
  8853. $attr['class'] = $value;
  8854. } else {
  8855. $attr[$key] = $value;
  8856. }
  8857. }
  8858. }
  8859. // TODO: add hook
  8860. // escape all attribute
  8861. $attr = array_map('dol_escape_htmltag', $attr);
  8862. $TCompiledAttr = array();
  8863. foreach ($attr as $key => $value) {
  8864. $TCompiledAttr[] = $key.'="'.$value.'"';
  8865. }
  8866. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  8867. $tag = !empty($url) ? 'a' : 'span';
  8868. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  8869. }
  8870. /**
  8871. * Output the badge of a status.
  8872. *
  8873. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  8874. * @param string $statusLabelShort Short label of badge no html
  8875. * @param string $html Optional : label of badge with html
  8876. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  8877. * @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
  8878. * @param string $url The url for link
  8879. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  8880. * @return string Html status string
  8881. */
  8882. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  8883. {
  8884. global $conf;
  8885. $return = '';
  8886. $dolGetBadgeParams = array();
  8887. if (!empty($params['badgeParams'])) {
  8888. $dolGetBadgeParams = $params['badgeParams'];
  8889. }
  8890. // TODO : add a hook
  8891. if ($displayMode == 0) {
  8892. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  8893. } elseif ($displayMode == 1) {
  8894. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  8895. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  8896. // Use status with images (for backward compatibility)
  8897. $return = '';
  8898. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  8899. $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>' : '');
  8900. // For small screen, we always use the short label instead of long label.
  8901. if (!empty($conf->dol_optimize_smallscreen)) {
  8902. if ($displayMode == 0) {
  8903. $displayMode = 1;
  8904. } elseif ($displayMode == 4) {
  8905. $displayMode = 2;
  8906. } elseif ($displayMode == 6) {
  8907. $displayMode = 5;
  8908. }
  8909. }
  8910. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  8911. $statusImg = array(
  8912. 'status0' => 'statut0',
  8913. 'status1' => 'statut1',
  8914. 'status2' => 'statut2',
  8915. 'status3' => 'statut3',
  8916. 'status4' => 'statut4',
  8917. 'status5' => 'statut5',
  8918. 'status6' => 'statut6',
  8919. 'status7' => 'statut7',
  8920. 'status8' => 'statut8',
  8921. 'status9' => 'statut9'
  8922. );
  8923. if (!empty($statusImg[$statusType])) {
  8924. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  8925. } else {
  8926. $htmlImg = img_picto($statusLabel, $statusType);
  8927. }
  8928. if ($displayMode === 2) {
  8929. $return = $htmlImg.' '.$htmlLabelShort;
  8930. } elseif ($displayMode === 3) {
  8931. $return = $htmlImg;
  8932. } elseif ($displayMode === 4) {
  8933. $return = $htmlImg.' '.$htmlLabel;
  8934. } elseif ($displayMode === 5) {
  8935. $return = $htmlLabelShort.' '.$htmlImg;
  8936. } else { // $displayMode >= 6
  8937. $return = $htmlLabel.' '.$htmlImg;
  8938. }
  8939. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  8940. // Use new badge
  8941. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  8942. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  8943. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  8944. if ($displayMode == 3) {
  8945. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  8946. } elseif ($displayMode === 5) {
  8947. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  8948. } else {
  8949. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  8950. }
  8951. }
  8952. return $return;
  8953. }
  8954. /**
  8955. * Function dolGetButtonAction
  8956. *
  8957. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  8958. * @param string $html optional : content with html
  8959. * @param string $actionType default, delete, danger
  8960. * @param string $url the url for link
  8961. * @param string $id attribute id of button
  8962. * @param int $userRight user action right
  8963. * // phpcs:disable
  8964. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  8965. * 'attr' => [ // to add or override button attributes
  8966. * 'xxxxx' => '', // your xxxxx attribute you want
  8967. * 'class' => '', // to add more css class to the button class attribute
  8968. * 'classOverride' => '' // to replace class attribute of the button
  8969. * ],
  8970. * 'confirm' => [
  8971. * '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.
  8972. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  8973. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  8974. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  8975. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  8976. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  8977. * ],
  8978. * ]
  8979. * // phpcs:enable
  8980. * @return string html button
  8981. */
  8982. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  8983. {
  8984. global $hookmanager, $action, $object, $langs;
  8985. $class = 'butAction';
  8986. if ($actionType == 'danger' || $actionType == 'delete') {
  8987. $class = 'butActionDelete';
  8988. if (strpos($url, 'token=') === false) $url .= '&token='.newToken();
  8989. }
  8990. $attr = array(
  8991. 'class' => $class,
  8992. 'href' => empty($url) ? '' : $url,
  8993. 'title' => $label
  8994. );
  8995. if (empty($html)) {
  8996. $html = $label;
  8997. } else {
  8998. $attr['aria-label'] = $label;
  8999. }
  9000. if (empty($userRight)) {
  9001. $attr['class'] = 'butActionRefused';
  9002. $attr['href'] = '';
  9003. }
  9004. if (!empty($id)) {
  9005. $attr['id'] = $id;
  9006. }
  9007. // Override attr
  9008. if (!empty($params['attr']) && is_array($params['attr'])) {
  9009. foreach ($params['attr'] as $key => $value) {
  9010. if ($key == 'class') {
  9011. $attr['class'] .= ' '.$value;
  9012. } elseif ($key == 'classOverride') {
  9013. $attr['class'] = $value;
  9014. } else {
  9015. $attr[$key] = $value;
  9016. }
  9017. }
  9018. }
  9019. // Js Confirm button
  9020. if ($userRight && !empty($params['confirm'])) {
  9021. if (!is_array($params['confirm'])) {
  9022. $params['confirm'] = array(
  9023. 'url' => $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes'
  9024. );
  9025. }
  9026. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9027. $attr['data-confirm-url'] = $params['confirm']['url'];
  9028. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9029. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9030. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9031. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9032. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9033. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9034. $attr['class'].= ' butActionConfirm';
  9035. }
  9036. if (isset($attr['href']) && empty($attr['href'])) {
  9037. unset($attr['href']);
  9038. }
  9039. // escape all attribute
  9040. $attr = array_map('dol_escape_htmltag', $attr);
  9041. $TCompiledAttr = array();
  9042. foreach ($attr as $key => $value) {
  9043. $TCompiledAttr[] = $key.'="'.$value.'"';
  9044. }
  9045. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9046. $tag = !empty($attr['href']) ? 'a' : 'span';
  9047. $parameters = array(
  9048. 'TCompiledAttr' => $TCompiledAttr,
  9049. 'compiledAttributes' => $compiledAttributes,
  9050. 'attr' => $attr,
  9051. 'tag' => $tag,
  9052. 'label' => $label,
  9053. 'html' => $html,
  9054. 'actionType' => $actionType,
  9055. 'url' => $url,
  9056. 'id' => $id,
  9057. 'userRight' => $userRight,
  9058. 'params' => $params
  9059. );
  9060. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9061. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9062. if (empty($reshook)) {
  9063. return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
  9064. } else {
  9065. return $hookmanager->resPrint;
  9066. }
  9067. }
  9068. /**
  9069. * Add space between dolGetButtonTitle
  9070. *
  9071. * @param string $moreClass more css class label
  9072. * @return string html of title separator
  9073. */
  9074. function dolGetButtonTitleSeparator($moreClass = "")
  9075. {
  9076. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9077. }
  9078. /**
  9079. * get field error icon
  9080. *
  9081. * @param string $fieldValidationErrorMsg message to add in tooltip
  9082. * @return string html output
  9083. */
  9084. function getFieldErrorIcon($fieldValidationErrorMsg)
  9085. {
  9086. $out = '';
  9087. if (!empty($fieldValidationErrorMsg)) {
  9088. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9089. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9090. $out.= '</span>';
  9091. }
  9092. return $out;
  9093. }
  9094. /**
  9095. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9096. *
  9097. * @param string $label label of button
  9098. * @param string $helpText optional : content for help tooltip
  9099. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9100. * @param string $url the url for link
  9101. * @param string $id attribute id of button
  9102. * @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
  9103. * @param array $params various params for future : recommended rather than adding more function arguments
  9104. * @return string html button
  9105. */
  9106. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9107. {
  9108. global $langs, $conf, $user;
  9109. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9110. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9111. return '';
  9112. }
  9113. $class = 'btnTitle';
  9114. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) {
  9115. $class .= ' btnTitlePlus';
  9116. }
  9117. $useclassfortooltip = 1;
  9118. if (!empty($params['morecss'])) {
  9119. $class .= ' '.$params['morecss'];
  9120. }
  9121. $attr = array(
  9122. 'class' => $class,
  9123. 'href' => empty($url) ? '' : $url
  9124. );
  9125. if (!empty($helpText)) {
  9126. $attr['title'] = dol_escape_htmltag($helpText);
  9127. } elseif (empty($attr['title']) && $label) {
  9128. $attr['title'] = $label;
  9129. $useclassfortooltip = 0;
  9130. }
  9131. if ($status == 2) {
  9132. $attr['class'] .= ' btnTitleSelected';
  9133. } elseif ($status <= 0) {
  9134. $attr['class'] .= ' refused';
  9135. $attr['href'] = '';
  9136. if ($status == -1) { // disable
  9137. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9138. } elseif ($status == 0) { // Not enough permissions
  9139. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9140. }
  9141. }
  9142. if (!empty($attr['title']) && $useclassfortooltip) {
  9143. $attr['class'] .= ' classfortooltip';
  9144. }
  9145. if (!empty($id)) {
  9146. $attr['id'] = $id;
  9147. }
  9148. // Override attr
  9149. if (!empty($params['attr']) && is_array($params['attr'])) {
  9150. foreach ($params['attr'] as $key => $value) {
  9151. if ($key == 'class') {
  9152. $attr['class'] .= ' '.$value;
  9153. } elseif ($key == 'classOverride') {
  9154. $attr['class'] = $value;
  9155. } else {
  9156. $attr[$key] = $value;
  9157. }
  9158. }
  9159. }
  9160. if (isset($attr['href']) && empty($attr['href'])) {
  9161. unset($attr['href']);
  9162. }
  9163. // TODO : add a hook
  9164. // escape all attribute
  9165. $attr = array_map('dol_escape_htmltag', $attr);
  9166. $TCompiledAttr = array();
  9167. foreach ($attr as $key => $value) {
  9168. $TCompiledAttr[] = $key.'="'.$value.'"';
  9169. }
  9170. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9171. $tag = (empty($attr['href']) ? 'span' : 'a');
  9172. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9173. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9174. if (!empty($params['forcenohideoftext'])) {
  9175. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9176. }
  9177. $button .= '</'.$tag.'>';
  9178. return $button;
  9179. }
  9180. /**
  9181. * Get an array with properties of an element.
  9182. * Called by fetchObjectByElement.
  9183. *
  9184. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9185. * @return array (module, classpath, element, subelement, classfile, classname)
  9186. */
  9187. function getElementProperties($element_type)
  9188. {
  9189. $regs = array();
  9190. $classfile = $classname = $classpath = '';
  9191. // Parse element/subelement (ex: project_task)
  9192. $module = $element_type;
  9193. $element = $element_type;
  9194. $subelement = $element_type;
  9195. // If we ask an resource form external module (instead of default path)
  9196. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9197. $element = $subelement = $regs[1];
  9198. $module = $regs[2];
  9199. }
  9200. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9201. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9202. $module = $element = $regs[1];
  9203. $subelement = $regs[2];
  9204. }
  9205. // For compat
  9206. if ($element_type == "action") {
  9207. $classpath = 'comm/action/class';
  9208. $subelement = 'Actioncomm';
  9209. $module = 'agenda';
  9210. }
  9211. // To work with non standard path
  9212. if ($element_type == 'facture' || $element_type == 'invoice') {
  9213. $classpath = 'compta/facture/class';
  9214. $module = 'facture';
  9215. $subelement = 'facture';
  9216. }
  9217. if ($element_type == 'commande' || $element_type == 'order') {
  9218. $classpath = 'commande/class';
  9219. $module = 'commande';
  9220. $subelement = 'commande';
  9221. }
  9222. if ($element_type == 'propal') {
  9223. $classpath = 'comm/propal/class';
  9224. }
  9225. if ($element_type == 'supplier_proposal') {
  9226. $classpath = 'supplier_proposal/class';
  9227. }
  9228. if ($element_type == 'shipping') {
  9229. $classpath = 'expedition/class';
  9230. $subelement = 'expedition';
  9231. $module = 'expedition_bon';
  9232. }
  9233. if ($element_type == 'delivery') {
  9234. $classpath = 'delivery/class';
  9235. $subelement = 'delivery';
  9236. $module = 'delivery_note';
  9237. }
  9238. if ($element_type == 'contract') {
  9239. $classpath = 'contrat/class';
  9240. $module = 'contrat';
  9241. $subelement = 'contrat';
  9242. }
  9243. if ($element_type == 'member') {
  9244. $classpath = 'adherents/class';
  9245. $module = 'adherent';
  9246. $subelement = 'adherent';
  9247. }
  9248. if ($element_type == 'cabinetmed_cons') {
  9249. $classpath = 'cabinetmed/class';
  9250. $module = 'cabinetmed';
  9251. $subelement = 'cabinetmedcons';
  9252. }
  9253. if ($element_type == 'fichinter') {
  9254. $classpath = 'fichinter/class';
  9255. $module = 'ficheinter';
  9256. $subelement = 'fichinter';
  9257. }
  9258. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9259. $classpath = 'resource/class';
  9260. $module = 'resource';
  9261. $subelement = 'dolresource';
  9262. }
  9263. if ($element_type == 'propaldet') {
  9264. $classpath = 'comm/propal/class';
  9265. $module = 'propal';
  9266. $subelement = 'propaleligne';
  9267. }
  9268. if ($element_type == 'order_supplier') {
  9269. $classpath = 'fourn/class';
  9270. $module = 'fournisseur';
  9271. $subelement = 'commandefournisseur';
  9272. $classfile = 'fournisseur.commande';
  9273. }
  9274. if ($element_type == 'invoice_supplier') {
  9275. $classpath = 'fourn/class';
  9276. $module = 'fournisseur';
  9277. $subelement = 'facturefournisseur';
  9278. $classfile = 'fournisseur.facture';
  9279. }
  9280. if ($element_type == "service") {
  9281. $classpath = 'product/class';
  9282. $subelement = 'product';
  9283. }
  9284. if (empty($classfile)) {
  9285. $classfile = strtolower($subelement);
  9286. }
  9287. if (empty($classname)) {
  9288. $classname = ucfirst($subelement);
  9289. }
  9290. if (empty($classpath)) {
  9291. $classpath = $module.'/class';
  9292. }
  9293. $element_properties = array(
  9294. 'module' => $module,
  9295. 'classpath' => $classpath,
  9296. 'element' => $element,
  9297. 'subelement' => $subelement,
  9298. 'classfile' => $classfile,
  9299. 'classname' => $classname
  9300. );
  9301. return $element_properties;
  9302. }
  9303. /**
  9304. * Fetch an object from its id and element_type
  9305. * Inclusion of classes is automatic
  9306. *
  9307. * @param int $element_id Element id
  9308. * @param string $element_type Element type
  9309. * @param string $element_ref Element ref (Use this or element_id but not both)
  9310. * @return int|object object || 0 || -1 if error
  9311. */
  9312. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9313. {
  9314. global $conf, $db;
  9315. $element_prop = getElementProperties($element_type);
  9316. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9317. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9318. $objecttmp = new $element_prop['classname']($db);
  9319. $ret = $objecttmp->fetch($element_id, $element_ref);
  9320. if ($ret >= 0) {
  9321. return $objecttmp;
  9322. }
  9323. }
  9324. return 0;
  9325. }
  9326. /**
  9327. * Return if a file can contains executable content
  9328. *
  9329. * @param string $filename File name to test
  9330. * @return boolean True if yes, False if no
  9331. */
  9332. function isAFileWithExecutableContent($filename)
  9333. {
  9334. 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)) {
  9335. return true;
  9336. }
  9337. return false;
  9338. }
  9339. /**
  9340. * Return the value of token currently saved into session with name 'newtoken'.
  9341. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9342. *
  9343. * @return string
  9344. */
  9345. function newToken()
  9346. {
  9347. return $_SESSION['newtoken'];
  9348. }
  9349. /**
  9350. * Return the value of token currently saved into session with name 'token'.
  9351. *
  9352. * @return string
  9353. */
  9354. function currentToken()
  9355. {
  9356. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  9357. }
  9358. /**
  9359. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9360. *
  9361. * @param string $header The first left header of the table (automatic translated)
  9362. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9363. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9364. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9365. * @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"
  9366. * @return void
  9367. *
  9368. * @see finishSimpleTable()
  9369. */
  9370. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9371. {
  9372. global $langs;
  9373. print '<div class="div-table-responsive-no-min">';
  9374. print '<table class="noborder centpercent">';
  9375. print '<tr class="liste_titre">';
  9376. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9377. print $langs->trans($header);
  9378. // extra space between the first header and the number
  9379. if ($number > -1) {
  9380. print ' ';
  9381. }
  9382. if (!empty($link)) {
  9383. if (!empty($arguments)) {
  9384. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9385. } else {
  9386. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9387. }
  9388. }
  9389. if ($number > -1) {
  9390. print '<span class="badge">'.$number.'</span>';
  9391. }
  9392. if (!empty($link)) {
  9393. print '</a>';
  9394. }
  9395. print '</th>';
  9396. if ($number < 0 && !empty($link)) {
  9397. print '<th class="right">';
  9398. if (!empty($arguments)) {
  9399. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9400. } else {
  9401. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9402. }
  9403. print $langs->trans("FullList");
  9404. print '</a>';
  9405. print '</th>';
  9406. }
  9407. print '</tr>';
  9408. }
  9409. /**
  9410. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9411. *
  9412. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9413. * @return void
  9414. *
  9415. * @see startSimpleTable()
  9416. */
  9417. function finishSimpleTable($addLineBreak = false)
  9418. {
  9419. print '</table>';
  9420. print '</div>';
  9421. if ($addLineBreak) {
  9422. print '<br>';
  9423. }
  9424. }
  9425. /**
  9426. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9427. *
  9428. * @param integer $tableColumnCount The complete count columns of the table
  9429. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9430. * @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)
  9431. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9432. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9433. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9434. * @return void
  9435. */
  9436. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9437. {
  9438. global $langs;
  9439. if ($num === 0) {
  9440. print '<tr class="oddeven">';
  9441. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9442. print '</tr>';
  9443. return;
  9444. }
  9445. if ($nbofloop === 0) {
  9446. // don't show a summary line
  9447. return;
  9448. }
  9449. if ($num === 0) {
  9450. $colspan = $tableColumnCount;
  9451. } elseif ($num > $nbofloop) {
  9452. $colspan = $tableColumnCount;
  9453. } else {
  9454. $colspan = $tableColumnCount - 1;
  9455. }
  9456. if ($extraRightColumn) {
  9457. $colspan--;
  9458. }
  9459. print '<tr class="liste_total">';
  9460. if ($nbofloop > 0 && $num > $nbofloop) {
  9461. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9462. } else {
  9463. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  9464. print '<td class="right" width="100">'.price($total).'</td>';
  9465. }
  9466. if ($extraRightColumn) {
  9467. print '<td></td>';
  9468. }
  9469. print '</tr>';
  9470. }
  9471. /**
  9472. * Return a file on output using a low memory. It can return very large files with no need of memory.
  9473. * WARNING: This close output buffers.
  9474. *
  9475. * @param string $fullpath_original_file_osencoded Full path of file to return.
  9476. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  9477. * @return void
  9478. */
  9479. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  9480. {
  9481. global $conf;
  9482. if ($method == -1) {
  9483. $method = 0;
  9484. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  9485. $method = 1;
  9486. }
  9487. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  9488. $method = 2;
  9489. }
  9490. }
  9491. // Be sure we don't have output buffering enabled to have readfile working correctly
  9492. while (ob_get_level()) {
  9493. ob_end_flush();
  9494. }
  9495. // Solution 0
  9496. if ($method == 0) {
  9497. readfile($fullpath_original_file_osencoded);
  9498. } elseif ($method == 1) {
  9499. // Solution 1
  9500. $handle = fopen($fullpath_original_file_osencoded, "rb");
  9501. while (!feof($handle)) {
  9502. print fread($handle, 8192);
  9503. }
  9504. fclose($handle);
  9505. } elseif ($method == 2) {
  9506. // Solution 2
  9507. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  9508. $handle2 = fopen("php://output", "wb");
  9509. stream_copy_to_stream($handle1, $handle2);
  9510. fclose($handle1);
  9511. fclose($handle2);
  9512. }
  9513. }
  9514. /**
  9515. * Create a button to copy $valuetocopy in the clipboard.
  9516. * Code that handle the click is inside lib_foot.jsp.php.
  9517. *
  9518. * @param string $valuetocopy The value to print
  9519. * @param int $showonlyonhover Show the copy-paste button only on hover
  9520. * @param string $texttoshow Replace the value to show with this text
  9521. * @return string The string to print for the button
  9522. */
  9523. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  9524. {
  9525. /*
  9526. global $conf;
  9527. if (!empty($conf->dol_no_mouse_hover)) {
  9528. $showonlyonhover = 0;
  9529. }*/
  9530. $tag = 'span'; // Using div does not work when using the js copy code.
  9531. if ($texttoshow) {
  9532. $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 opacitymedium"></span></span>';
  9533. } else {
  9534. $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 opacitymedium"></span></span>';
  9535. }
  9536. return $result;
  9537. }
  9538. /**
  9539. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  9540. *
  9541. * @param string $stringtodecode String to decode (json or serialize coded)
  9542. * @return mixed The decoded object.
  9543. */
  9544. function jsonOrUnserialize($stringtodecode)
  9545. {
  9546. $result = json_decode($stringtodecode);
  9547. if ($result === null) {
  9548. $result = unserialize($stringtodecode);
  9549. }
  9550. return $result;
  9551. }