functions.lib.php 520 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2022 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019-2023 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
  21. * Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
  22. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  23. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. * or see https://www.gnu.org/
  38. */
  39. /**
  40. * \file htdocs/core/lib/functions.lib.php
  41. * \brief A set of functions for Dolibarr
  42. * This file contains all frequently used functions.
  43. */
  44. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  45. // Function for better PHP x compatibility
  46. if (!function_exists('utf8_encode')) {
  47. /**
  48. * Implement utf8_encode for PHP that does not support it.
  49. *
  50. * @param mixed $elements PHP Object to json encode
  51. * @return string Json encoded string
  52. */
  53. function utf8_encode($elements)
  54. {
  55. return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
  56. }
  57. }
  58. if (!function_exists('utf8_decode')) {
  59. /**
  60. * Implement utf8_decode for PHP that does not support it.
  61. *
  62. * @param mixed $elements PHP Object to json encode
  63. * @return string Json encoded string
  64. */
  65. function utf8_decode($elements)
  66. {
  67. return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
  68. }
  69. }
  70. if (!function_exists('str_starts_with')) {
  71. /**
  72. * str_starts_with
  73. *
  74. * @param string $haystack haystack
  75. * @param string $needle needle
  76. * @return boolean
  77. */
  78. function str_starts_with($haystack, $needle)
  79. {
  80. return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
  81. }
  82. }
  83. if (!function_exists('str_ends_with')) {
  84. /**
  85. * str_ends_with
  86. *
  87. * @param string $haystack haystack
  88. * @param string $needle needle
  89. * @return boolean
  90. */
  91. function str_ends_with($haystack, $needle)
  92. {
  93. return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
  94. }
  95. }
  96. if (!function_exists('str_contains')) {
  97. /**
  98. * str_contains
  99. *
  100. * @param string $haystack haystack
  101. * @param string $needle needle
  102. * @return boolean
  103. */
  104. function str_contains($haystack, $needle)
  105. {
  106. return $needle !== '' && mb_strpos($haystack, $needle) !== false;
  107. }
  108. }
  109. /**
  110. * Return the full path of the directory where a module (or an object of a module) stores its files. Path may depends on the entity if a multicompany module is enabled.
  111. *
  112. * @param CommonObject $object Dolibarr common object
  113. * @param string $module Override object element, for example to use 'mycompany' instead of 'societe'
  114. * @return string|void The path of the relative directory of the module
  115. * @since Dolibarr V18
  116. */
  117. function getMultidirOutput($object, $module = '')
  118. {
  119. global $conf;
  120. if (!is_object($object) && empty($module)) {
  121. return null;
  122. }
  123. if (empty($module) && !empty($object->element)) {
  124. $module = $object->element;
  125. }
  126. return $conf->$module->multidir_output[(!empty($object->entity) ? $object->entity : $conf->entity)];
  127. }
  128. /**
  129. * Return dolibarr global constant string value
  130. *
  131. * @param string $key key to return value, return '' if not set
  132. * @param string $default value to return
  133. * @return string
  134. */
  135. function getDolGlobalString($key, $default = '')
  136. {
  137. global $conf;
  138. // return $conf->global->$key ?? $default;
  139. return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
  140. }
  141. /**
  142. * Return dolibarr global constant int value
  143. *
  144. * @param string $key key to return value, return 0 if not set
  145. * @param int $default value to return
  146. * @return int
  147. */
  148. function getDolGlobalInt($key, $default = 0)
  149. {
  150. global $conf;
  151. // return $conf->global->$key ?? $default;
  152. return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
  153. }
  154. /**
  155. * Return Dolibarr user constant string value
  156. *
  157. * @param string $key key to return value, return '' if not set
  158. * @param string $default value to return
  159. * @param User $tmpuser To get another user than current user
  160. * @return string
  161. */
  162. function getDolUserString($key, $default = '', $tmpuser = null)
  163. {
  164. if (empty($tmpuser)) {
  165. global $user;
  166. $tmpuser = $user;
  167. }
  168. // return $conf->global->$key ?? $default;
  169. return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  170. }
  171. /**
  172. * Return Dolibarr user constant int value
  173. *
  174. * @param string $key key to return value, return 0 if not set
  175. * @param int $default value to return
  176. * @param User $tmpuser To get another user than current user
  177. * @return int
  178. */
  179. function getDolUserInt($key, $default = 0, $tmpuser = null)
  180. {
  181. if (empty($tmpuser)) {
  182. global $user;
  183. $tmpuser = $user;
  184. }
  185. // return $conf->global->$key ?? $default;
  186. return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  187. }
  188. /**
  189. * Is Dolibarr module enabled
  190. *
  191. * @param string $module Module name to check
  192. * @return boolean True if module is enabled
  193. */
  194. function isModEnabled($module)
  195. {
  196. global $conf;
  197. // Fix special cases
  198. $arrayconv = array(
  199. 'project' => 'projet',
  200. 'contract' => 'contrat',
  201. 'bank' => 'banque'
  202. );
  203. if (empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) {
  204. $arrayconv['supplier_order'] = 'fournisseur';
  205. $arrayconv['supplier_invoice'] = 'fournisseur';
  206. }
  207. if (!empty($arrayconv[$module])) {
  208. $module = $arrayconv[$module];
  209. }
  210. return !empty($conf->modules[$module]);
  211. //return !empty($conf->$module->enabled);
  212. }
  213. /**
  214. * Return a DoliDB instance (database handler).
  215. *
  216. * @param string $type Type of database (mysql, pgsql...)
  217. * @param string $host Address of database server
  218. * @param string $user Authorized username
  219. * @param string $pass Password
  220. * @param string $name Name of database
  221. * @param int $port Port of database server
  222. * @return DoliDB A DoliDB instance
  223. */
  224. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  225. {
  226. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  227. $class = 'DoliDB'.ucfirst($type);
  228. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  229. return $dolidb;
  230. }
  231. /**
  232. * Get list of entity id to use.
  233. *
  234. * @param string $element Current element
  235. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  236. * 'product', 'productprice', 'stock', 'bom', 'mo',
  237. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  238. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  239. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  240. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  241. * 'email_template', 'event', 'donation'
  242. * 'c_paiement', 'c_payment_term', ...
  243. * @param int $shared 0=Return id of current entity only,
  244. * 1=Return id of current entity + shared entities (default)
  245. * @param object $currentobject Current object if needed
  246. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  247. */
  248. function getEntity($element, $shared = 1, $currentobject = null)
  249. {
  250. global $conf, $mc, $hookmanager, $object, $action, $db;
  251. if (!is_object($hookmanager)) {
  252. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  253. $hookmanager = new HookManager($db);
  254. }
  255. // fix different element names (France to English)
  256. switch ($element) {
  257. case 'contrat':
  258. $element = 'contract';
  259. break; // "/contrat/class/contrat.class.php"
  260. case 'order_supplier':
  261. $element = 'supplier_order';
  262. break; // "/fourn/class/fournisseur.commande.class.php"
  263. case 'invoice_supplier':
  264. $element = 'supplier_invoice';
  265. break; // "/fourn/class/fournisseur.facture.class.php"
  266. }
  267. if (is_object($mc)) {
  268. $out = $mc->getEntity($element, $shared, $currentobject);
  269. } else {
  270. $out = '';
  271. $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values');
  272. if (in_array($element, $addzero)) {
  273. $out .= '0,';
  274. }
  275. $out .= ((int) $conf->entity);
  276. }
  277. // Manipulate entities to query on the fly
  278. $parameters = array(
  279. 'element' => $element,
  280. 'shared' => $shared,
  281. 'object' => $object,
  282. 'currentobject' => $currentobject,
  283. 'out' => $out
  284. );
  285. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  286. if (is_numeric($reshook)) {
  287. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  288. $out .= ','.$hookmanager->resPrint; // add
  289. } elseif ($reshook == 1) {
  290. $out = $hookmanager->resPrint; // replace
  291. }
  292. }
  293. return $out;
  294. }
  295. /**
  296. * Set entity id to use when to create an object
  297. *
  298. * @param object $currentobject Current object
  299. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  300. */
  301. function setEntity($currentobject)
  302. {
  303. global $conf, $mc;
  304. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  305. return $mc->setEntity($currentobject);
  306. } else {
  307. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  308. }
  309. }
  310. /**
  311. * Return if string has a name dedicated to store a secret
  312. *
  313. * @param string $keyname Name of key to test
  314. * @return boolean True if key is used to store a secret
  315. */
  316. function isASecretKey($keyname)
  317. {
  318. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  319. }
  320. /**
  321. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  322. *
  323. * @param int|string $n Numeric value
  324. * @return string Column in Excel format
  325. */
  326. function num2Alpha($n)
  327. {
  328. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
  329. $r = chr($n % 26 + 0x41) . $r;
  330. return $r;
  331. }
  332. /**
  333. * Return information about user browser
  334. *
  335. * Returns array with the following format:
  336. * array(
  337. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  338. * 'browserversion' => Browser version. Empty if unknown
  339. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  340. * 'layout' => (tablet|phone|classic)
  341. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  342. * 'tablet' => true/false
  343. * )
  344. *
  345. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  346. * @return array Check function documentation
  347. */
  348. function getBrowserInfo($user_agent)
  349. {
  350. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  351. $name = 'unknown';
  352. $version = '';
  353. $os = 'unknown';
  354. $phone = '';
  355. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  356. $detectmobile = new Mobile_Detect(null, $user_agent);
  357. $tablet = $detectmobile->isTablet();
  358. if ($detectmobile->isMobile()) {
  359. $phone = 'unknown';
  360. // If phone/smartphone, we set phone os name.
  361. if ($detectmobile->is('AndroidOS')) {
  362. $os = $phone = 'android';
  363. } elseif ($detectmobile->is('BlackBerryOS')) {
  364. $os = $phone = 'blackberry';
  365. } elseif ($detectmobile->is('iOS')) {
  366. $os = 'ios';
  367. $phone = 'iphone';
  368. } elseif ($detectmobile->is('PalmOS')) {
  369. $os = $phone = 'palm';
  370. } elseif ($detectmobile->is('SymbianOS')) {
  371. $os = 'symbian';
  372. } elseif ($detectmobile->is('webOS')) {
  373. $os = 'webos';
  374. } elseif ($detectmobile->is('MaemoOS')) {
  375. $os = 'maemo';
  376. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  377. $os = 'windows';
  378. }
  379. }
  380. // OS
  381. if (preg_match('/linux/i', $user_agent)) {
  382. $os = 'linux';
  383. } elseif (preg_match('/macintosh/i', $user_agent)) {
  384. $os = 'macintosh';
  385. } elseif (preg_match('/windows/i', $user_agent)) {
  386. $os = 'windows';
  387. }
  388. // Name
  389. $reg = array();
  390. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  391. $name = 'firefox';
  392. $version = empty($reg[2]) ? '' : $reg[2];
  393. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  394. $name = 'edge';
  395. $version = empty($reg[2]) ? '' : $reg[2];
  396. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  397. $name = 'chrome';
  398. $version = empty($reg[2]) ? '' : $reg[2];
  399. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  400. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  401. $name = 'chrome';
  402. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  403. $name = 'iceweasel';
  404. } elseif (preg_match('/epiphany/i', $user_agent)) {
  405. $name = 'epiphany';
  406. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  407. $name = 'safari';
  408. $version = empty($reg[2]) ? '' : $reg[2];
  409. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  410. // Safari is often present in string for mobile but its not.
  411. $name = 'opera';
  412. $version = empty($reg[2]) ? '' : $reg[2];
  413. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  414. $name = 'ie';
  415. $version = end($reg);
  416. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  417. // MS products at end
  418. $name = 'ie';
  419. $version = end($reg);
  420. } elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  421. // MS products at end
  422. $name = 'lynxlinks';
  423. $version = empty($reg[3]) ? '' : $reg[3];
  424. }
  425. if ($tablet) {
  426. $layout = 'tablet';
  427. } elseif ($phone) {
  428. $layout = 'phone';
  429. } else {
  430. $layout = 'classic';
  431. }
  432. return array(
  433. 'browsername' => $name,
  434. 'browserversion' => $version,
  435. 'browseros' => $os,
  436. 'layout' => $layout,
  437. 'phone' => $phone,
  438. 'tablet' => $tablet
  439. );
  440. }
  441. /**
  442. * Function called at end of web php process
  443. *
  444. * @return void
  445. */
  446. function dol_shutdown()
  447. {
  448. global $conf, $user, $langs, $db;
  449. $disconnectdone = false;
  450. $depth = 0;
  451. if (is_object($db) && !empty($db->connected)) {
  452. $depth = $db->transaction_opened;
  453. $disconnectdone = $db->close();
  454. }
  455. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
  456. }
  457. /**
  458. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  459. * Warning:
  460. * For action=add, use: $var = GETPOST('var'); // No GETPOSTISSET, so GETPOST always called and default value is retreived if not a form POST, and value of form is retreived if it is a form POST.
  461. * For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var;
  462. *
  463. * @param string $paramname Name or parameter to test
  464. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  465. */
  466. function GETPOSTISSET($paramname)
  467. {
  468. $isset = false;
  469. $relativepathstring = $_SERVER["PHP_SELF"];
  470. // Clean $relativepathstring
  471. if (constant('DOL_URL_ROOT')) {
  472. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  473. }
  474. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  475. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  476. //var_dump($relativepathstring);
  477. //var_dump($user->default_values);
  478. // Code for search criteria persistence.
  479. // Retrieve values if restore_lastsearch_values
  480. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  481. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  482. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  483. if (is_array($tmp)) {
  484. foreach ($tmp as $key => $val) {
  485. if ($key == $paramname) { // We are on the requested parameter
  486. $isset = true;
  487. break;
  488. }
  489. }
  490. }
  491. }
  492. // If there is saved contextpage, limit, page or mode
  493. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  494. $isset = true;
  495. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  496. $isset = true;
  497. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  498. $isset = true;
  499. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  500. $isset = true;
  501. }
  502. } else {
  503. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  504. }
  505. return $isset;
  506. }
  507. /**
  508. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  509. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  510. *
  511. * @param string $paramname Name or parameter to test
  512. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  513. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  514. */
  515. function GETPOSTISARRAY($paramname, $method = 0)
  516. {
  517. // for $method test need return the same $val as GETPOST
  518. if (empty($method)) {
  519. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  520. } elseif ($method == 1) {
  521. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  522. } elseif ($method == 2) {
  523. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  524. } elseif ($method == 3) {
  525. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  526. } else {
  527. $val = 'BadFirstParameterForGETPOST';
  528. }
  529. return is_array($val);
  530. }
  531. /**
  532. * Return value of a param into GET or POST supervariable.
  533. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  534. * Note: The property $user->default_values is loaded by main.php when loading the user.
  535. *
  536. * @param string $paramname Name of parameter to found
  537. * @param string $check Type of check
  538. * ''=no check (deprecated)
  539. * 'none'=no check (only for param that should have very rich content like passwords)
  540. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  541. * 'int'=check it's numeric (integer or float)
  542. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  543. * 'alpha'=Same than alphanohtml since v13
  544. * 'alphawithlgt'=alpha with lgt
  545. * 'alphanohtml'=check there is no html content and no " and no ../
  546. * 'aZ'=check it's a-z only
  547. * 'aZ09'=check it's simple alpha string (recommended for keys)
  548. * 'aZ09arobase'=check it's a string for an element type
  549. * 'aZ09comma'=check it's a string for a sortfield or sortorder
  550. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  551. * 'nohtml'=check there is no html content
  552. * 'restricthtml'=check html content is restricted to some tags only
  553. * 'custom'= custom filter specify $filter and $options)
  554. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  555. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  556. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  557. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  558. * @return string|array Value found (string or array), or '' if check fails
  559. */
  560. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  561. {
  562. global $mysoc, $user, $conf;
  563. if (empty($paramname)) {
  564. return 'BadFirstParameterForGETPOST';
  565. }
  566. if (empty($check)) {
  567. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  568. // Enable this line to know who call the GETPOST with '' $check parameter.
  569. //var_dump(debug_backtrace()[0]);
  570. }
  571. if (empty($method)) {
  572. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  573. } elseif ($method == 1) {
  574. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  575. } elseif ($method == 2) {
  576. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  577. } elseif ($method == 3) {
  578. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  579. } else {
  580. return 'BadThirdParameterForGETPOST';
  581. }
  582. if (empty($method) || $method == 3 || $method == 4) {
  583. $relativepathstring = $_SERVER["PHP_SELF"];
  584. // Clean $relativepathstring
  585. if (constant('DOL_URL_ROOT')) {
  586. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  587. }
  588. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  589. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  590. //var_dump($relativepathstring);
  591. //var_dump($user->default_values);
  592. // Code for search criteria persistence.
  593. // Retrieve values if restore_lastsearch_values
  594. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  595. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  596. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  597. if (is_array($tmp)) {
  598. foreach ($tmp as $key => $val) {
  599. if ($key == $paramname) { // We are on the requested parameter
  600. $out = $val;
  601. break;
  602. }
  603. }
  604. }
  605. }
  606. // If there is saved contextpage, page or limit
  607. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  608. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  609. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  610. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  611. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  612. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  613. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  614. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  615. }
  616. } elseif (!isset($_GET['sortfield'])) {
  617. // Else, retrieve default values if we are not doing a sort
  618. // 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
  619. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  620. // Search default value from $object->field
  621. global $object;
  622. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  623. $out = $object->fields[$paramname]['default'];
  624. }
  625. }
  626. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  627. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  628. // Now search in setup to overwrite default values
  629. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  630. if (isset($user->default_values[$relativepathstring]['createform'])) {
  631. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  632. $qualified = 0;
  633. if ($defkey != '_noquery_') {
  634. $tmpqueryarraytohave = explode('&', $defkey);
  635. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  636. $foundintru = 0;
  637. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  638. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  639. $foundintru = 1;
  640. }
  641. }
  642. if (!$foundintru) {
  643. $qualified = 1;
  644. }
  645. //var_dump($defkey.'-'.$qualified);
  646. } else {
  647. $qualified = 1;
  648. }
  649. if ($qualified) {
  650. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  651. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  652. break;
  653. }
  654. }
  655. }
  656. }
  657. }
  658. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  659. // Management of default search_filters and sort order
  660. if (!empty($user->default_values)) {
  661. // $user->default_values defined from menu 'Setup - Default values'
  662. //var_dump($user->default_values[$relativepathstring]);
  663. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  664. // Sorted on which fields ? ASC or DESC ?
  665. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  666. // Even if paramname is sortfield, data are stored into ['sortorder...']
  667. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  668. $qualified = 0;
  669. if ($defkey != '_noquery_') {
  670. $tmpqueryarraytohave = explode('&', $defkey);
  671. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  672. $foundintru = 0;
  673. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  674. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  675. $foundintru = 1;
  676. }
  677. }
  678. if (!$foundintru) {
  679. $qualified = 1;
  680. }
  681. //var_dump($defkey.'-'.$qualified);
  682. } else {
  683. $qualified = 1;
  684. }
  685. if ($qualified) {
  686. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  687. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  688. if ($out) {
  689. $out .= ', ';
  690. }
  691. if ($paramname == 'sortfield') {
  692. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  693. }
  694. if ($paramname == 'sortorder') {
  695. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  696. }
  697. }
  698. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  699. }
  700. }
  701. }
  702. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  703. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  704. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  705. continue;
  706. }
  707. $qualified = 0;
  708. if ($defkey != '_noquery_') {
  709. $tmpqueryarraytohave = explode('&', $defkey);
  710. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  711. $foundintru = 0;
  712. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  713. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  714. $foundintru = 1;
  715. }
  716. }
  717. if (!$foundintru) {
  718. $qualified = 1;
  719. }
  720. //var_dump($defkey.'-'.$qualified);
  721. } else {
  722. $qualified = 1;
  723. }
  724. if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
  725. // We must keep $_POST and $_GET here
  726. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  727. // We made a search from quick search menu, do we still use default filter ?
  728. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  729. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  730. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  731. }
  732. } else {
  733. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  734. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  735. }
  736. break;
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. }
  744. }
  745. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  746. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  747. // 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.
  748. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  749. $reg = array();
  750. $maxloop = 20;
  751. $loopnb = 0; // Protection against infinite loop
  752. 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.
  753. $loopnb++;
  754. $newout = '';
  755. if ($reg[1] == 'DAY') {
  756. $tmp = dol_getdate(dol_now(), true);
  757. $newout = $tmp['mday'];
  758. } elseif ($reg[1] == 'MONTH') {
  759. $tmp = dol_getdate(dol_now(), true);
  760. $newout = $tmp['mon'];
  761. } elseif ($reg[1] == 'YEAR') {
  762. $tmp = dol_getdate(dol_now(), true);
  763. $newout = $tmp['year'];
  764. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  765. $tmp = dol_getdate(dol_now(), true);
  766. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  767. $newout = $tmp2['day'];
  768. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  769. $tmp = dol_getdate(dol_now(), true);
  770. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  771. $newout = $tmp2['month'];
  772. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  773. $tmp = dol_getdate(dol_now(), true);
  774. $newout = ($tmp['year'] - 1);
  775. } elseif ($reg[1] == 'NEXT_DAY') {
  776. $tmp = dol_getdate(dol_now(), true);
  777. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  778. $newout = $tmp2['day'];
  779. } elseif ($reg[1] == 'NEXT_MONTH') {
  780. $tmp = dol_getdate(dol_now(), true);
  781. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  782. $newout = $tmp2['month'];
  783. } elseif ($reg[1] == 'NEXT_YEAR') {
  784. $tmp = dol_getdate(dol_now(), true);
  785. $newout = ($tmp['year'] + 1);
  786. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  787. $newout = $mysoc->country_id;
  788. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  789. $newout = $user->id;
  790. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  791. $newout = $user->fk_user;
  792. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  793. $newout = $conf->entity;
  794. } else {
  795. $newout = ''; // Key not found, we replace with empty string
  796. }
  797. //var_dump('__'.$reg[1].'__ -> '.$newout);
  798. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  799. }
  800. }
  801. // Check rule
  802. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  803. if (!is_array($out) || empty($out)) {
  804. $out = array();
  805. } else {
  806. $tmparray = explode(':', $check);
  807. if (!empty($tmparray[1])) {
  808. $tmpcheck = $tmparray[1];
  809. } else {
  810. $tmpcheck = 'alphanohtml';
  811. }
  812. foreach ($out as $outkey => $outval) {
  813. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  814. }
  815. }
  816. } else {
  817. // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
  818. // we use the < or > to make a search on a numeric value to do higher or lower so we can add a space to break html tags
  819. if (strpos($paramname, 'search_') === 0) {
  820. $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
  821. }
  822. $out = sanitizeVal($out, $check, $filter, $options);
  823. }
  824. // Sanitizing for special parameters.
  825. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  826. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  827. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  828. $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
  829. do {
  830. $oldstringtoclean = $out;
  831. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  832. $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
  833. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  834. } while ($oldstringtoclean != $out);
  835. }
  836. // Code for search criteria persistence.
  837. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  838. if (empty($method) || $method == 3 || $method == 4) {
  839. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  840. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  841. // We save search key only if $out not empty that means:
  842. // - posted value not empty, or
  843. // - 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).
  844. if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
  845. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  846. }
  847. }
  848. }
  849. return $out;
  850. }
  851. /**
  852. * Return value of a param into GET or POST supervariable.
  853. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  854. * Note: The property $user->default_values is loaded by main.php when loading the user.
  855. *
  856. * @param string $paramname Name of parameter to found
  857. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  858. * @return int Value found (int)
  859. */
  860. function GETPOSTINT($paramname, $method = 0)
  861. {
  862. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  863. }
  864. /**
  865. * Return a sanitized or empty value after checking value against a rule.
  866. *
  867. * @deprecated
  868. * @param string|array $out Value to check/clear.
  869. * @param string $check Type of check/sanitizing
  870. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  871. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  872. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  873. */
  874. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  875. {
  876. return sanitizeVal($out, $check, $filter, $options);
  877. }
  878. /**
  879. * Return a sanitized or empty value after checking value against a rule.
  880. *
  881. * @param string|array $out Value to check/clear.
  882. * @param string $check Type of check/sanitizing
  883. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  884. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  885. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  886. */
  887. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  888. {
  889. global $conf;
  890. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  891. // Check is done after replacement
  892. switch ($check) {
  893. case 'none':
  894. break;
  895. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  896. if (!is_numeric($out)) {
  897. $out = '';
  898. }
  899. break;
  900. case 'intcomma':
  901. if (preg_match('/[^0-9,-]+/i', $out)) {
  902. $out = '';
  903. }
  904. break;
  905. case 'san_alpha':
  906. $out = filter_var($out, FILTER_SANITIZE_STRING);
  907. break;
  908. case 'email':
  909. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  910. break;
  911. case 'aZ':
  912. if (!is_array($out)) {
  913. $out = trim($out);
  914. if (preg_match('/[^a-z]+/i', $out)) {
  915. $out = '';
  916. }
  917. }
  918. break;
  919. case 'aZ09':
  920. if (!is_array($out)) {
  921. $out = trim($out);
  922. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  923. $out = '';
  924. }
  925. }
  926. break;
  927. case 'aZ09arobase': // great to sanitize $objecttype parameter
  928. if (!is_array($out)) {
  929. $out = trim($out);
  930. if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
  931. $out = '';
  932. }
  933. }
  934. break;
  935. case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
  936. if (!is_array($out)) {
  937. $out = trim($out);
  938. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  939. $out = '';
  940. }
  941. }
  942. break;
  943. case 'alpha': // No html and no ../ and "
  944. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  945. if (!is_array($out)) {
  946. $out = trim($out);
  947. do {
  948. $oldstringtoclean = $out;
  949. // Remove html tags
  950. $out = dol_string_nohtmltag($out, 0);
  951. // Remove also other dangerous string sequences
  952. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  953. // '../' or '..\' is dangerous because it allows dir transversals
  954. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  955. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  956. } while ($oldstringtoclean != $out);
  957. // keep lines feed
  958. }
  959. break;
  960. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
  961. if (!is_array($out)) {
  962. $out = trim($out);
  963. do {
  964. $oldstringtoclean = $out;
  965. // Remove html tags
  966. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  967. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  968. // '../' or '..\' is dangerous because it allows dir transversals
  969. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  970. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  971. } while ($oldstringtoclean != $out);
  972. }
  973. break;
  974. case 'nohtml': // No html
  975. $out = dol_string_nohtmltag($out, 0);
  976. break;
  977. case 'restricthtml': // Recommended for most html textarea
  978. case 'restricthtmlnolink':
  979. case 'restricthtmlallowunvalid':
  980. $out = dol_htmlwithnojs($out, 1, $check);
  981. break;
  982. case 'custom':
  983. if (!empty($out)) {
  984. if (empty($filter)) {
  985. return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
  986. }
  987. /*if (empty($options)) {
  988. return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
  989. }*/
  990. $out = filter_var($out, $filter, $options);
  991. }
  992. break;
  993. }
  994. return $out;
  995. }
  996. if (!function_exists('dol_getprefix')) {
  997. /**
  998. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  999. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  1000. * or two instances in same virtual servers.
  1001. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  1002. *
  1003. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  1004. * @return string A calculated prefix
  1005. */
  1006. function dol_getprefix($mode = '')
  1007. {
  1008. // If prefix is for email (we need to have $conf already loaded for this case)
  1009. if ($mode == 'email') {
  1010. global $conf;
  1011. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  1012. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  1013. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  1014. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  1015. return $_SERVER["SERVER_NAME"];
  1016. }
  1017. }
  1018. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  1019. if (!empty($conf->file->instance_unique_id)) {
  1020. return sha1('dolibarr'.$conf->file->instance_unique_id);
  1021. }
  1022. // For backward compatibility when instance_unique_id is not set
  1023. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1024. }
  1025. // If prefix is for session (no need to have $conf loaded)
  1026. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  1027. $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
  1028. // The recommended value (may be not defined for old versions)
  1029. if (!empty($tmp_instance_unique_id)) {
  1030. return sha1('dolibarr'.$tmp_instance_unique_id);
  1031. }
  1032. // For backward compatibility when instance_unique_id is not set
  1033. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  1034. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1035. } else {
  1036. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1037. }
  1038. }
  1039. }
  1040. /**
  1041. * Make an include_once using default root and alternate root if it fails.
  1042. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  1043. * To link to a module file from a module file, use include './mymodulefile';
  1044. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  1045. *
  1046. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  1047. * @param string $classname Class name (deprecated)
  1048. * @return bool True if load is a success, False if it fails
  1049. */
  1050. function dol_include_once($relpath, $classname = '')
  1051. {
  1052. 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']
  1053. $fullpath = dol_buildpath($relpath);
  1054. if (!file_exists($fullpath)) {
  1055. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  1056. return false;
  1057. }
  1058. if (!empty($classname) && !class_exists($classname)) {
  1059. return include $fullpath;
  1060. } else {
  1061. return include_once $fullpath;
  1062. }
  1063. }
  1064. /**
  1065. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  1066. *
  1067. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  1068. * @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)
  1069. * @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)
  1070. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  1071. * 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
  1072. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  1073. */
  1074. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  1075. {
  1076. global $conf;
  1077. $path = preg_replace('/^\//', '', $path);
  1078. if (empty($type)) { // For a filesystem path
  1079. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  1080. if (is_array($conf->file->dol_document_root)) {
  1081. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  1082. if ($key == 'main') {
  1083. continue;
  1084. }
  1085. if (file_exists($dirroot.'/'.$path)) {
  1086. $res = $dirroot.'/'.$path;
  1087. return $res;
  1088. }
  1089. }
  1090. }
  1091. if ($returnemptyifnotfound) {
  1092. // Not found into alternate dir
  1093. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  1094. return '';
  1095. }
  1096. }
  1097. } else {
  1098. // For an url path
  1099. // We try to get local path of file on filesystem from url
  1100. // Note that trying to know if a file on disk exist by forging path on disk from url
  1101. // works only for some web server and some setup. This is bugged when
  1102. // using proxy, rewriting, virtual path, etc...
  1103. $res = '';
  1104. if ($type == 1) {
  1105. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  1106. }
  1107. if ($type == 2) {
  1108. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  1109. }
  1110. if ($type == 3) {
  1111. $res = DOL_URL_ROOT.'/'.$path;
  1112. }
  1113. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  1114. if ($key == 'main') {
  1115. if ($type == 3) {
  1116. global $dolibarr_main_url_root;
  1117. // Define $urlwithroot
  1118. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1119. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1120. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1121. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  1122. }
  1123. continue;
  1124. }
  1125. $regs = array();
  1126. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  1127. if (!empty($regs[1])) {
  1128. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1129. if (file_exists($dirroot.'/'.$regs[1])) {
  1130. if ($type == 1) {
  1131. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1132. }
  1133. if ($type == 2) {
  1134. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1135. }
  1136. if ($type == 3) {
  1137. global $dolibarr_main_url_root;
  1138. // Define $urlwithroot
  1139. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1140. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1141. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1142. $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
  1143. }
  1144. break;
  1145. }
  1146. }
  1147. }
  1148. }
  1149. return $res;
  1150. }
  1151. /**
  1152. * Create a clone of instance of object (new instance with same value for each properties)
  1153. * With native = 0: Property that are reference are different memory area in the new object (full isolation clone). This means $this->db of new object may not be valid.
  1154. * 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.
  1155. * With native = 2: Property that are reference are different memory area in the new object (full isolation clone). Only scalar and array values are cloned. This means $this->db of new object is not valid.
  1156. *
  1157. * @param object $object Object to clone
  1158. * @param int $native 0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended)
  1159. * @return object Clone object
  1160. * @see https://php.net/manual/language.oop5.cloning.php
  1161. */
  1162. function dol_clone($object, $native = 0)
  1163. {
  1164. if ($native == 0) {
  1165. // deprecated method, use the method with native = 2 instead
  1166. $tmpsavdb = null;
  1167. if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
  1168. $tmpsavdb = $object->db;
  1169. unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
  1170. }
  1171. $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
  1172. if (!empty($tmpsavdb)) {
  1173. $object->db = $tmpsavdb;
  1174. }
  1175. } elseif ($native == 2) {
  1176. // recommended method to have a full isolated cloned object
  1177. $myclone = new stdClass();
  1178. $tmparray = get_object_vars($object); // return only public properties
  1179. if (is_array($tmparray)) {
  1180. foreach ($tmparray as $propertykey => $propertyval) {
  1181. if (is_scalar($propertyval) || is_array($propertyval)) {
  1182. $myclone->$propertykey = $propertyval;
  1183. }
  1184. }
  1185. }
  1186. } else {
  1187. $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)
  1188. }
  1189. return $myclone;
  1190. }
  1191. /**
  1192. * Optimize a size for some browsers (phone, smarphone, ...)
  1193. *
  1194. * @param int $size Size we want
  1195. * @param string $type Type of optimizing:
  1196. * '' = function used to define a size for truncation
  1197. * 'width' = function is used to define a width
  1198. * @return int New size after optimizing
  1199. */
  1200. function dol_size($size, $type = '')
  1201. {
  1202. global $conf;
  1203. if (empty($conf->dol_optimize_smallscreen)) {
  1204. return $size;
  1205. }
  1206. if ($type == 'width' && $size > 250) {
  1207. return 250;
  1208. } else {
  1209. return 10;
  1210. }
  1211. }
  1212. /**
  1213. * Clean a string to use it as a file name.
  1214. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1215. *
  1216. * @param string $str String to clean
  1217. * @param string $newstr String to replace bad chars with.
  1218. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1219. * @return string String cleaned (a-zA-Z_)
  1220. *
  1221. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1222. */
  1223. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1224. {
  1225. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1226. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1227. // Char '/' and '\' are file delimiters.
  1228. // 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
  1229. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1230. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1231. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1232. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1233. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1234. $tmp = str_replace('..', '', $tmp);
  1235. return $tmp;
  1236. }
  1237. /**
  1238. * Clean a string to use it as a path name.
  1239. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1240. *
  1241. * @param string $str String to clean
  1242. * @param string $newstr String to replace bad chars with
  1243. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1244. * @return string String cleaned (a-zA-Z_)
  1245. *
  1246. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1247. */
  1248. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1249. {
  1250. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1251. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1252. // 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
  1253. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1254. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1255. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1256. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1257. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1258. $tmp = str_replace('..', '', $tmp);
  1259. return $tmp;
  1260. }
  1261. /**
  1262. * Clean a string to use it as an URL (into a href or src attribute)
  1263. *
  1264. * @param string $stringtoclean String to clean
  1265. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1266. * @return string Escaped string.
  1267. */
  1268. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1269. {
  1270. // 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)
  1271. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1272. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1273. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1274. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1275. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1276. if ($type == 1) {
  1277. // removing : should disable links to external url like http:aaa)
  1278. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1279. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1280. }
  1281. do {
  1282. $oldstringtoclean = $stringtoclean;
  1283. // removing '&colon' should disable links to external url like http:aaa)
  1284. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1285. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1286. } while ($oldstringtoclean != $stringtoclean);
  1287. if ($type == 1) {
  1288. // removing '//' should disable links to external url like //aaa or http//)
  1289. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1290. }
  1291. return $stringtoclean;
  1292. }
  1293. /**
  1294. * Clean a string to use it as an Email.
  1295. *
  1296. * @param string $stringtoclean String to clean. Example 'abc@mycompany.com <My name>'
  1297. * @return string Escaped string.
  1298. */
  1299. function dol_sanitizeEmail($stringtoclean)
  1300. {
  1301. do {
  1302. $oldstringtoclean = $stringtoclean;
  1303. $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
  1304. } while ($oldstringtoclean != $stringtoclean);
  1305. return $stringtoclean;
  1306. }
  1307. /**
  1308. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1309. *
  1310. * @param string $str String to clean
  1311. * @return string Cleaned string
  1312. *
  1313. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1314. */
  1315. function dol_string_unaccent($str)
  1316. {
  1317. global $conf;
  1318. if (is_null($str)) {
  1319. return '';
  1320. }
  1321. if (utf8_check($str)) {
  1322. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1323. $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
  1324. return $transliterator->transliterate($str);
  1325. }
  1326. // See http://www.utf8-chartable.de/
  1327. $string = rawurlencode($str);
  1328. $replacements = array(
  1329. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1330. '%C3%87' => 'C',
  1331. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1332. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1333. '%C3%91' => 'N',
  1334. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1335. '%C5%A0' => 'S',
  1336. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1337. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1338. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1339. '%C3%A7' => 'c',
  1340. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1341. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1342. '%C3%B1' => 'n',
  1343. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1344. '%C5%A1' => 's',
  1345. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1346. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1347. );
  1348. $string = strtr($string, $replacements);
  1349. return rawurldecode($string);
  1350. } else {
  1351. // See http://www.ascii-code.com/
  1352. $string = strtr(
  1353. $str,
  1354. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1355. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1356. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1357. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1358. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1359. \xF9\xFA\xFB\xFC\xFD\xFF",
  1360. "AAAAAAC
  1361. EEEEIIIIDN
  1362. OOOOOUUUY
  1363. aaaaaaceeee
  1364. iiiidnooooo
  1365. uuuuyy"
  1366. );
  1367. $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"));
  1368. return $string;
  1369. }
  1370. }
  1371. /**
  1372. * Clean a string from all punctuation characters to use it as a ref or login.
  1373. * This is a more complete function than dol_sanitizeFileName().
  1374. *
  1375. * @param string $str String to clean
  1376. * @param string $newstr String to replace forbidden chars with
  1377. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1378. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1379. * @param int $keepspaces 1=Do not treat space as a special char to replace or remove
  1380. * @return string Cleaned string
  1381. *
  1382. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1383. */
  1384. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
  1385. {
  1386. $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
  1387. if (empty($keepspaces)) {
  1388. $forbidden_chars_to_replace[] = " ";
  1389. }
  1390. $forbidden_chars_to_remove = array();
  1391. //$forbidden_chars_to_remove=array("(",")");
  1392. if (is_array($badcharstoreplace)) {
  1393. $forbidden_chars_to_replace = $badcharstoreplace;
  1394. }
  1395. if (is_array($badcharstoremove)) {
  1396. $forbidden_chars_to_remove = $badcharstoremove;
  1397. }
  1398. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1399. }
  1400. /**
  1401. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1402. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1403. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1404. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1405. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1406. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1407. * @param string $str String to clean
  1408. * @param int $removetabcrlf Remove also CR-LF
  1409. * @return string Cleaned string
  1410. *
  1411. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1412. */
  1413. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1414. {
  1415. if ($removetabcrlf) {
  1416. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1417. } else {
  1418. 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
  1419. }
  1420. }
  1421. /**
  1422. * Returns text escaped for inclusion into javascript code
  1423. *
  1424. * @param string $stringtoescape String to escape
  1425. * @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 \
  1426. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1427. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1428. */
  1429. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1430. {
  1431. if (is_null($stringtoescape)) {
  1432. return '';
  1433. }
  1434. // escape quotes and backslashes, newlines, etc.
  1435. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1436. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1437. if (empty($noescapebackslashn)) {
  1438. $substitjs["\n"] = '\\n';
  1439. $substitjs['\\'] = '\\\\';
  1440. }
  1441. if (empty($mode)) {
  1442. $substitjs["'"] = "\\'";
  1443. $substitjs['"'] = "\\'";
  1444. } elseif ($mode == 1) {
  1445. $substitjs["'"] = "\\'";
  1446. } elseif ($mode == 2) {
  1447. $substitjs['"'] = '\\"';
  1448. } elseif ($mode == 3) {
  1449. $substitjs["'"] = "\\'";
  1450. $substitjs['"'] = "\\\"";
  1451. }
  1452. return strtr($stringtoescape, $substitjs);
  1453. }
  1454. /**
  1455. * Returns text escaped for inclusion into javascript code
  1456. *
  1457. * @param string $stringtoescape String to escape
  1458. * @return string Escaped string for json content.
  1459. */
  1460. function dol_escape_json($stringtoescape)
  1461. {
  1462. return str_replace('"', '\"', $stringtoescape);
  1463. }
  1464. /**
  1465. * Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields.
  1466. * When we output string on pages, we use dol_string_onlythesehtmltags(dol_htmlentitiesbr()) for notes, and use dol_escape_htmltag() for simple labels.
  1467. *
  1468. * @param string $stringtoescape String to escape
  1469. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1470. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1471. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes into tag.
  1472. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1473. * @return string Escaped string
  1474. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent(), dol_htmlentitiesbr()
  1475. */
  1476. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1477. {
  1478. if ($noescapetags == 'common') {
  1479. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1480. }
  1481. // escape quotes and backslashes, newlines, etc.
  1482. if ($escapeonlyhtmltags) {
  1483. $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
  1484. } else {
  1485. $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
  1486. }
  1487. if (!$keepb) {
  1488. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1489. }
  1490. if (!$keepn) {
  1491. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1492. }
  1493. if ($escapeonlyhtmltags) {
  1494. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1495. } else {
  1496. // Escape tags to keep
  1497. // TODO Does not works yet when there is attributes into tag
  1498. $tmparrayoftags = array();
  1499. if ($noescapetags) {
  1500. $tmparrayoftags = explode(',', $noescapetags);
  1501. }
  1502. if (count($tmparrayoftags)) {
  1503. foreach ($tmparrayoftags as $tagtoreplace) {
  1504. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1505. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1506. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1507. }
  1508. }
  1509. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1510. if (count($tmparrayoftags)) {
  1511. foreach ($tmparrayoftags as $tagtoreplace) {
  1512. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1513. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1514. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1515. }
  1516. }
  1517. return $result;
  1518. }
  1519. }
  1520. /**
  1521. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1522. *
  1523. * @param string $string String to encode
  1524. * @param string $encoding Character set encoding
  1525. * @return string String converted
  1526. */
  1527. function dol_strtolower($string, $encoding = "UTF-8")
  1528. {
  1529. if (function_exists('mb_strtolower')) {
  1530. return mb_strtolower($string, $encoding);
  1531. } else {
  1532. return strtolower($string);
  1533. }
  1534. }
  1535. /**
  1536. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1537. *
  1538. * @param string $string String to encode
  1539. * @param string $encoding Character set encoding
  1540. * @return string String converted
  1541. * @see dol_ucfirst(), dol_ucwords()
  1542. */
  1543. function dol_strtoupper($string, $encoding = "UTF-8")
  1544. {
  1545. if (function_exists('mb_strtoupper')) {
  1546. return mb_strtoupper($string, $encoding);
  1547. } else {
  1548. return strtoupper($string);
  1549. }
  1550. }
  1551. /**
  1552. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1553. *
  1554. * @param string $string String to encode
  1555. * @param string $encoding Character set encodign
  1556. * @return string String converted
  1557. * @see dol_strtoupper(), dol_ucwords()
  1558. */
  1559. function dol_ucfirst($string, $encoding = "UTF-8")
  1560. {
  1561. if (function_exists('mb_substr')) {
  1562. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1563. } else {
  1564. return ucfirst($string);
  1565. }
  1566. }
  1567. /**
  1568. * Convert first character of all the words of a string to upper.
  1569. *
  1570. * @param string $string String to encode
  1571. * @param string $encoding Character set encodign
  1572. * @return string String converted
  1573. * @see dol_strtoupper(), dol_ucfirst()
  1574. */
  1575. function dol_ucwords($string, $encoding = "UTF-8")
  1576. {
  1577. if (function_exists('mb_convert_case')) {
  1578. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1579. } else {
  1580. return ucwords($string);
  1581. }
  1582. }
  1583. /**
  1584. * Write log message into outputs. Possible outputs can be:
  1585. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1586. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1587. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1588. * this, use logging to files instead of syslog (see setup of module).
  1589. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1590. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1591. * This function works only if syslog module is enabled.
  1592. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1593. *
  1594. * @param string $message Line to log. ''=Show nothing
  1595. * @param int $level Log level
  1596. * 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
  1597. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1598. * @param int $ident 1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log)
  1599. * @param string $suffixinfilename When output is a file, append this suffix into default log filename. Example '_stripe', '_mail'
  1600. * @param string $restricttologhandler Force output of log only to this log handler
  1601. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1602. * @return void
  1603. */
  1604. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1605. {
  1606. global $conf, $user, $debugbar;
  1607. // If syslog module enabled
  1608. if (!isModEnabled('syslog')) {
  1609. return;
  1610. }
  1611. // Check if we are into execution of code of a website
  1612. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1613. global $website, $websitekey;
  1614. if (is_object($website) && !empty($website->ref)) {
  1615. $suffixinfilename .= '_website_'.$website->ref;
  1616. } elseif (!empty($websitekey)) {
  1617. $suffixinfilename .= '_website_'.$websitekey;
  1618. }
  1619. }
  1620. // Check if we have a forced suffix
  1621. if (defined('USESUFFIXINLOG')) {
  1622. $suffixinfilename .= constant('USESUFFIXINLOG');
  1623. }
  1624. if ($ident < 0) {
  1625. foreach ($conf->loghandlers as $loghandlerinstance) {
  1626. $loghandlerinstance->setIdent($ident);
  1627. }
  1628. }
  1629. if (!empty($message)) {
  1630. // Test log level
  1631. $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');
  1632. if (!array_key_exists($level, $logLevels)) {
  1633. throw new Exception('Incorrect log level');
  1634. }
  1635. if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
  1636. return;
  1637. }
  1638. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1639. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1640. }
  1641. // If adding log inside HTML page is required
  1642. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1643. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1644. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1645. }
  1646. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1647. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1648. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1649. print "\n\n<!-- Log start\n";
  1650. print dol_escape_htmltag($message)."\n";
  1651. print "Log end -->\n";
  1652. }
  1653. $data = array(
  1654. 'message' => $message,
  1655. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1656. 'level' => $level,
  1657. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1658. 'ip' => false
  1659. );
  1660. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1661. if (!empty($remoteip)) {
  1662. $data['ip'] = $remoteip;
  1663. // This is when server run behind a reverse proxy
  1664. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1665. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1666. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1667. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1668. }
  1669. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1670. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1671. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1672. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1673. // 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).
  1674. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1675. } elseif (!empty($_SERVER['LOGNAME'])) {
  1676. // 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).
  1677. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1678. }
  1679. // Loop on each log handler and send output
  1680. foreach ($conf->loghandlers as $loghandlerinstance) {
  1681. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1682. continue;
  1683. }
  1684. $loghandlerinstance->export($data, $suffixinfilename);
  1685. }
  1686. unset($data);
  1687. }
  1688. if ($ident > 0) {
  1689. foreach ($conf->loghandlers as $loghandlerinstance) {
  1690. $loghandlerinstance->setIdent($ident);
  1691. }
  1692. }
  1693. }
  1694. /**
  1695. * Return HTML code to output a button to open a dialog popup box.
  1696. * Such buttons must be included inside a HTML form.
  1697. *
  1698. * @param string $name A name for the html component
  1699. * @param string $label Label shown in Popup title top bar
  1700. * @param string $buttonstring button string (HTML text we can click on)
  1701. * @param string $url Relative Url to open. For example '/project/card.php'
  1702. * @param string $disabled Disabled text
  1703. * @param string $morecss More CSS
  1704. * @param string $jsonopen Some JS code to execute on click/open of popup
  1705. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1706. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1707. * @param string $accesskey A key to use shortcut
  1708. * @return string HTML component with button
  1709. */
  1710. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
  1711. {
  1712. global $conf;
  1713. if (strpos($url, '?') > 0) {
  1714. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1715. } else {
  1716. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1717. }
  1718. $out = '';
  1719. $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
  1720. if ($backtopagejsfields) {
  1721. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1722. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1723. $backtopagejsfields = $name.":".$backtopagejsfields;
  1724. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1725. } else {
  1726. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1727. }
  1728. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1729. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1730. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1731. }
  1732. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1733. $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
  1734. $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
  1735. if (empty($conf->use_javascript_ajax)) {
  1736. $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
  1737. } elseif ($jsonopen) {
  1738. $out .= ' href="#" onclick="'.$jsonopen.'"';
  1739. } else {
  1740. $out .= ' href="#"';
  1741. }
  1742. $out .= '>'.$buttonstring.'</a>';
  1743. if (!empty($conf->use_javascript_ajax)) {
  1744. // Add code to open url using the popup. Add also hidden field to retreive the returned variables
  1745. $out .= '<!-- code to open popup and variables to retreive returned variables -->';
  1746. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1747. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1748. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1749. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1750. $out .= '<script nonce="'.getNonce().'" type="text/javascript">
  1751. jQuery(document).ready(function () {
  1752. jQuery(".button_'.$name.'").click(function () {
  1753. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1754. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1755. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1756. $tmpdialog.dialog({
  1757. autoOpen: false,
  1758. modal: true,
  1759. height: (window.innerHeight - 150),
  1760. width: \'80%\',
  1761. title: \''.dol_escape_js($label).'\',
  1762. open: function (event, ui) {
  1763. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1764. },
  1765. close: function (event, ui) {
  1766. var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1767. var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1768. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1769. if (returnedid != "" && returnedid != "div for returned id") {
  1770. jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
  1771. }
  1772. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1773. jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
  1774. }
  1775. }
  1776. });
  1777. $tmpdialog.dialog(\'open\');
  1778. return false;
  1779. });
  1780. });
  1781. </script>';
  1782. }
  1783. return $out;
  1784. }
  1785. /**
  1786. * Show tab header of a card
  1787. *
  1788. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1789. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1790. * @param string $title Title
  1791. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no sepaaration under tab (to start a tab just after), -3=Add tab header but no footer separation
  1792. * @param string $picto Add a picto on tab title
  1793. * @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.
  1794. * @param string $morehtmlright Add more html content on right of tabs title
  1795. * @param string $morecss More Css
  1796. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1797. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1798. * @return void
  1799. * @deprecated Use print dol_get_fiche_head() instead
  1800. */
  1801. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1802. {
  1803. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1804. }
  1805. /**
  1806. * Show tabs of a record
  1807. *
  1808. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1809. * @param string $active Active tab name
  1810. * @param string $title Title
  1811. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after), -3=-2+'noborderbottom'
  1812. * @param string $picto Add a picto on tab title
  1813. * @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.
  1814. * @param string $morehtmlright Add more html content on right of tabs title
  1815. * @param string $morecss More CSS on the link <a>
  1816. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1817. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1818. * @param int $dragdropfile 0 (default) or 1. 1 enable a drop zone for file to be upload, 0 disable it
  1819. * @return string
  1820. */
  1821. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
  1822. {
  1823. global $conf, $langs, $hookmanager;
  1824. // Show title
  1825. $showtitle = 1;
  1826. if (!empty($conf->dol_optimize_smallscreen)) {
  1827. $showtitle = 0;
  1828. }
  1829. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1830. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1831. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1832. }
  1833. // Show right part
  1834. if ($morehtmlright) {
  1835. $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.
  1836. }
  1837. // Show title
  1838. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1839. $limittitle = 30;
  1840. $out .= '<a class="tabTitle">';
  1841. if ($picto) {
  1842. $noprefix = $pictoisfullpath;
  1843. if (strpos($picto, 'fontawesome_') !== false) {
  1844. $noprefix = 1;
  1845. }
  1846. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1847. }
  1848. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1849. $out .= '</a>';
  1850. }
  1851. // Show tabs
  1852. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1853. $maxkey = -1;
  1854. if (is_array($links) && !empty($links)) {
  1855. $keys = array_keys($links);
  1856. if (count($keys)) {
  1857. $maxkey = max($keys);
  1858. }
  1859. }
  1860. // Show tabs
  1861. // if =0 we don't use the feature
  1862. if (empty($limittoshow)) {
  1863. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1864. }
  1865. if (!empty($conf->dol_optimize_smallscreen)) {
  1866. $limittoshow = 2;
  1867. }
  1868. $displaytab = 0;
  1869. $nbintab = 0;
  1870. $popuptab = 0;
  1871. $outmore = '';
  1872. for ($i = 0; $i <= $maxkey; $i++) {
  1873. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1874. // If active tab is already present
  1875. if ($i >= $limittoshow) {
  1876. $limittoshow--;
  1877. }
  1878. }
  1879. }
  1880. for ($i = 0; $i <= $maxkey; $i++) {
  1881. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1882. $isactive = true;
  1883. } else {
  1884. $isactive = false;
  1885. }
  1886. if ($i < $limittoshow || $isactive) {
  1887. // Output entry with a visible tab
  1888. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
  1889. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1890. if (!empty($links[$i][0])) {
  1891. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1892. } else {
  1893. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1894. }
  1895. } elseif (!empty($links[$i][1])) {
  1896. //print "x $i $active ".$links[$i][2]." z";
  1897. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1898. if (!empty($links[$i][0])) {
  1899. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1900. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').(!empty($links[$i][5]) ? ' '.$links[$i][5] : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  1901. }
  1902. $out .= $links[$i][1];
  1903. if (!empty($links[$i][0])) {
  1904. $out .= '</a>'."\n";
  1905. }
  1906. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1907. $out .= '</div>';
  1908. }
  1909. $out .= '</div>';
  1910. } else {
  1911. // Add entry into the combo popup with the other tabs
  1912. if (!$popuptab) {
  1913. $popuptab = 1;
  1914. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1915. }
  1916. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1917. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1918. if (!empty($links[$i][0])) {
  1919. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1920. } else {
  1921. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1922. }
  1923. } elseif (!empty($links[$i][1])) {
  1924. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1925. $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.
  1926. $outmore .= '</a>'."\n";
  1927. }
  1928. $outmore .= '</div>';
  1929. $nbintab++;
  1930. }
  1931. $displaytab = $i;
  1932. }
  1933. if ($popuptab) {
  1934. $outmore .= '</div>';
  1935. }
  1936. if ($popuptab) { // If there is some tabs not shown
  1937. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1938. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1939. $widthofpopup = 200;
  1940. $tabsname = $moretabssuffix;
  1941. if (empty($tabsname)) {
  1942. $tabsname = str_replace("@", "", $picto);
  1943. }
  1944. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  1945. $out .= '<div class="tab"><a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
  1946. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1947. $out .= $outmore;
  1948. $out .= '</div>';
  1949. $out .= '<div></div>';
  1950. $out .= "</div>\n";
  1951. $out .= '<script nonce="'.getNonce().'">';
  1952. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1953. var x = this.offsetLeft, y = this.offsetTop;
  1954. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1955. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1956. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1957. }
  1958. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1959. });
  1960. ";
  1961. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1962. $out .= "</script>";
  1963. }
  1964. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1965. $out .= "</div>\n";
  1966. }
  1967. if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
  1968. $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
  1969. }
  1970. if (!empty($dragdropfile)) {
  1971. $out .= dragAndDropFileUpload("dragDropAreaTabBar");
  1972. }
  1973. $parameters = array('tabname' => $active, 'out' => $out);
  1974. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1975. if ($reshook > 0) {
  1976. $out = $hookmanager->resPrint;
  1977. }
  1978. return $out;
  1979. }
  1980. /**
  1981. * Show tab footer of a card
  1982. *
  1983. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1984. * @return void
  1985. * @deprecated Use print dol_get_fiche_end() instead
  1986. */
  1987. function dol_fiche_end($notab = 0)
  1988. {
  1989. print dol_get_fiche_end($notab);
  1990. }
  1991. /**
  1992. * Return tab footer of a card
  1993. *
  1994. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1995. * @return string
  1996. */
  1997. function dol_get_fiche_end($notab = 0)
  1998. {
  1999. if (!$notab || $notab == -1) {
  2000. return "\n</div>\n";
  2001. } else {
  2002. return '';
  2003. }
  2004. }
  2005. /**
  2006. * Show tab footer of a card.
  2007. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  2008. *
  2009. * @param Object $object Object to show
  2010. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  2011. * @param string $morehtml More html content to output just before the nav bar
  2012. * @param int $shownav Show Condition (navigation is shown if value is 1)
  2013. * @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.
  2014. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  2015. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  2016. * @param string $moreparam More param to add in nav link url.
  2017. * @param int $nodbprefix Do not include DB prefix to forge table name
  2018. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  2019. * @param string $morehtmlstatus More html code to show under navigation arrows
  2020. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  2021. * @param string $morehtmlright More html code to show before navigation arrows
  2022. * @return void
  2023. */
  2024. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  2025. {
  2026. global $conf, $form, $user, $langs, $hookmanager, $action;
  2027. $error = 0;
  2028. $maxvisiblephotos = 1;
  2029. $showimage = 1;
  2030. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  2031. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  2032. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  2033. $showbarcode = 0;
  2034. }
  2035. $modulepart = 'unknown';
  2036. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  2037. $modulepart = $object->element;
  2038. } elseif ($object->element == 'member') {
  2039. $modulepart = 'memberphoto';
  2040. } elseif ($object->element == 'user') {
  2041. $modulepart = 'userphoto';
  2042. }
  2043. if (class_exists("Imagick")) {
  2044. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  2045. $modulepart = $object->element;
  2046. } elseif ($object->element == 'fichinter') {
  2047. $modulepart = 'ficheinter';
  2048. } elseif ($object->element == 'contrat') {
  2049. $modulepart = 'contract';
  2050. } elseif ($object->element == 'order_supplier') {
  2051. $modulepart = 'supplier_order';
  2052. } elseif ($object->element == 'invoice_supplier') {
  2053. $modulepart = 'supplier_invoice';
  2054. }
  2055. }
  2056. if ($object->element == 'product') {
  2057. $width = 80;
  2058. $cssclass = 'photowithmargin photoref';
  2059. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  2060. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  2061. if ($conf->browser->layout == 'phone') {
  2062. $maxvisiblephotos = 1;
  2063. }
  2064. if ($showimage) {
  2065. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
  2066. } else {
  2067. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  2068. $nophoto = '';
  2069. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2070. } else { // Show no photo link
  2071. $nophoto = '/public/theme/common/nophoto.png';
  2072. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" title="'.dol_escape_htmltag($langs->trans("UploadAnImageToSeeAPhotoHere", $langs->transnoentitiesnoconv("Documents"))).'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  2073. }
  2074. }
  2075. } elseif ($object->element == 'ticket') {
  2076. $width = 80;
  2077. $cssclass = 'photoref';
  2078. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  2079. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  2080. if ($conf->browser->layout == 'phone') {
  2081. $maxvisiblephotos = 1;
  2082. }
  2083. if ($showimage) {
  2084. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  2085. if ($object->nbphoto > 0) {
  2086. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  2087. } else {
  2088. $showimage = 0;
  2089. }
  2090. }
  2091. if (!$showimage) {
  2092. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  2093. $nophoto = '';
  2094. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2095. } else { // Show no photo link
  2096. $nophoto = img_picto('No photo', 'object_ticket');
  2097. $morehtmlleft .= '<!-- No photo to show -->';
  2098. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2099. $morehtmlleft .= $nophoto;
  2100. $morehtmlleft .= '</div></div>';
  2101. }
  2102. }
  2103. } else {
  2104. if ($showimage) {
  2105. if ($modulepart != 'unknown') {
  2106. $phototoshow = '';
  2107. // Check if a preview file is available
  2108. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  2109. $objectref = dol_sanitizeFileName($object->ref);
  2110. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  2111. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  2112. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  2113. $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
  2114. } else {
  2115. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  2116. }
  2117. if (empty($subdir)) {
  2118. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  2119. }
  2120. $filepath = $dir_output.$subdir."/";
  2121. $filepdf = $filepath.$objectref.".pdf";
  2122. $relativepath = $subdir.'/'.$objectref.'.pdf';
  2123. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  2124. $fileimage = $filepdf.'_preview.png';
  2125. $relativepathimage = $relativepath.'_preview.png';
  2126. $pdfexists = file_exists($filepdf);
  2127. // If PDF file exists
  2128. if ($pdfexists) {
  2129. // Conversion du PDF en image png si fichier png non existant
  2130. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  2131. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  2132. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2133. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  2134. if ($ret < 0) {
  2135. $error++;
  2136. }
  2137. }
  2138. }
  2139. }
  2140. if ($pdfexists && !$error) {
  2141. $heightforphotref = 80;
  2142. if (!empty($conf->dol_optimize_smallscreen)) {
  2143. $heightforphotref = 60;
  2144. }
  2145. // If the preview file is found
  2146. if (file_exists($fileimage)) {
  2147. $phototoshow = '<div class="photoref">';
  2148. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  2149. $phototoshow .= '</div>';
  2150. }
  2151. }
  2152. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  2153. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  2154. }
  2155. if ($phototoshow) {
  2156. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  2157. $morehtmlleft .= $phototoshow;
  2158. $morehtmlleft .= '</div>';
  2159. }
  2160. }
  2161. if (empty($phototoshow)) { // Show No photo link (picto of object)
  2162. if ($object->element == 'action') {
  2163. $width = 80;
  2164. $cssclass = 'photorefcenter';
  2165. $nophoto = img_picto('No photo', 'title_agenda');
  2166. } else {
  2167. $width = 14;
  2168. $cssclass = 'photorefcenter';
  2169. $picto = $object->picto;
  2170. $prefix = 'object_';
  2171. if ($object->element == 'project' && !$object->public) {
  2172. $picto = 'project'; // instead of projectpub
  2173. }
  2174. if (strpos($picto, 'fontawesome_') !== false) {
  2175. $prefix = '';
  2176. }
  2177. $nophoto = img_picto('No photo', $prefix.$picto);
  2178. }
  2179. $morehtmlleft .= '<!-- No photo to show -->';
  2180. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2181. $morehtmlleft .= $nophoto;
  2182. $morehtmlleft .= '</div></div>';
  2183. }
  2184. }
  2185. }
  2186. // Show barcode
  2187. if ($showbarcode) {
  2188. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
  2189. }
  2190. if ($object->element == 'societe') {
  2191. if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2192. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  2193. } else {
  2194. $morehtmlstatus .= $object->getLibStatut(6);
  2195. }
  2196. } elseif ($object->element == 'product') {
  2197. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  2198. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2199. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  2200. } else {
  2201. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  2202. }
  2203. $morehtmlstatus .= ' &nbsp; ';
  2204. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2205. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2206. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2207. } else {
  2208. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2209. }
  2210. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  2211. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2212. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2213. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2214. }
  2215. $morehtmlstatus .= $tmptxt;
  2216. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2217. if ($object->statut == 0) {
  2218. $morehtmlstatus .= $object->getLibStatut(5);
  2219. } else {
  2220. $morehtmlstatus .= $object->getLibStatut(4);
  2221. }
  2222. } elseif ($object->element == 'facturerec') {
  2223. if ($object->frequency == 0) {
  2224. $morehtmlstatus .= $object->getLibStatut(2);
  2225. } else {
  2226. $morehtmlstatus .= $object->getLibStatut(5);
  2227. }
  2228. } elseif ($object->element == 'project_task') {
  2229. $object->fk_statut = 1;
  2230. if ($object->progress > 0) {
  2231. $object->fk_statut = 2;
  2232. }
  2233. if ($object->progress >= 100) {
  2234. $object->fk_statut = 3;
  2235. }
  2236. $tmptxt = $object->getLibStatut(5);
  2237. $morehtmlstatus .= $tmptxt; // No status on task
  2238. } elseif (method_exists($object, 'getLibStatut')) { // Generic case
  2239. $tmptxt = $object->getLibStatut(6);
  2240. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2241. $tmptxt = $object->getLibStatut(5);
  2242. }
  2243. $morehtmlstatus .= $tmptxt;
  2244. }
  2245. // Add if object was dispatched "into accountancy"
  2246. if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2247. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2248. if (method_exists($object, 'getVentilExportCompta')) {
  2249. $accounted = $object->getVentilExportCompta();
  2250. $langs->load("accountancy");
  2251. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2252. }
  2253. }
  2254. // Add alias for thirdparty
  2255. if (!empty($object->name_alias)) {
  2256. $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
  2257. }
  2258. // Add label
  2259. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2260. if (!empty($object->label)) {
  2261. $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
  2262. }
  2263. }
  2264. // Show address and email
  2265. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2266. $moreaddress = $object->getBannerAddress('refaddress', $object);
  2267. if ($moreaddress) {
  2268. $morehtmlref .= '<div class="refidno refaddress">';
  2269. $morehtmlref .= $moreaddress;
  2270. $morehtmlref .= '</div>';
  2271. }
  2272. }
  2273. 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)) {
  2274. $morehtmlref .= '<div style="clear: both;"></div>';
  2275. $morehtmlref .= '<div class="refidno opacitymedium">';
  2276. $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
  2277. $morehtmlref .= '</div>';
  2278. }
  2279. $parameters=array('morehtmlref'=>$morehtmlref);
  2280. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2281. if ($reshook < 0) {
  2282. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2283. } elseif (empty($reshook)) {
  2284. $morehtmlref .= $hookmanager->resPrint;
  2285. } elseif ($reshook > 0) {
  2286. $morehtmlref = $hookmanager->resPrint;
  2287. }
  2288. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2289. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2290. print '</div>';
  2291. print '<div class="underrefbanner clearboth"></div>';
  2292. }
  2293. /**
  2294. * Show a string with the label tag dedicated to the HTML edit field.
  2295. *
  2296. * @param string $langkey Translation key
  2297. * @param string $fieldkey Key of the html select field the text refers to
  2298. * @param int $fieldrequired 1=Field is mandatory
  2299. * @return string
  2300. * @deprecated Form::editfieldkey
  2301. */
  2302. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2303. {
  2304. global $langs;
  2305. $ret = '';
  2306. if ($fieldrequired) {
  2307. $ret .= '<span class="fieldrequired">';
  2308. }
  2309. $ret .= '<label for="'.$fieldkey.'">';
  2310. $ret .= $langs->trans($langkey);
  2311. $ret .= '</label>';
  2312. if ($fieldrequired) {
  2313. $ret .= '</span>';
  2314. }
  2315. return $ret;
  2316. }
  2317. /**
  2318. * Return string to add class property on html element with pair/impair.
  2319. *
  2320. * @param string $var 0 or 1
  2321. * @param string $moreclass More class to add
  2322. * @return string String to add class onto HTML element
  2323. */
  2324. function dol_bc($var, $moreclass = '')
  2325. {
  2326. global $bc;
  2327. $ret = ' '.$bc[$var];
  2328. if ($moreclass) {
  2329. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2330. }
  2331. return $ret;
  2332. }
  2333. /**
  2334. * Return a formated address (part address/zip/town/state) according to country rules.
  2335. * See https://en.wikipedia.org/wiki/Address
  2336. *
  2337. * @param Object $object A company or contact object
  2338. * @param int $withcountry 1=Add country into address string
  2339. * @param string $sep Separator to use to build string
  2340. * @param Translate $outputlangs Object lang that contains language for text translation.
  2341. * @param int $mode 0=Standard output, 1=Remove address
  2342. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2343. * @return string Formated string
  2344. * @see dol_print_address()
  2345. */
  2346. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2347. {
  2348. global $conf, $langs, $hookmanager;
  2349. $ret = '';
  2350. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2351. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2352. // Address
  2353. if (empty($mode)) {
  2354. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2355. }
  2356. // Zip/Town/State
  2357. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2358. // US: title firstname name \n address lines \n town, state, zip \n country
  2359. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2360. $ret .= (($ret && $town) ? $sep : '').$town;
  2361. if (!empty($object->state)) {
  2362. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2363. }
  2364. if (!empty($object->zip)) {
  2365. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2366. }
  2367. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2368. // UK: title firstname name \n address lines \n town state \n zip \n country
  2369. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2370. $ret .= ($ret ? $sep : '').$town;
  2371. if (!empty($object->state)) {
  2372. $ret .= ($ret ? ", " : '').$object->state;
  2373. }
  2374. if (!empty($object->zip)) {
  2375. $ret .= ($ret ? $sep : '').$object->zip;
  2376. }
  2377. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2378. // ES: title firstname name \n address lines \n zip town \n state \n country
  2379. $ret .= ($ret ? $sep : '').$object->zip;
  2380. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2381. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2382. if (!empty($object->state)) {
  2383. $ret .= "\n".$object->state;
  2384. }
  2385. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2386. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2387. // See https://www.sljfaq.org/afaq/addresses.html
  2388. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2389. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2390. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2391. // IT: title firstname name\n address lines \n zip town state_code \n country
  2392. $ret .= ($ret ? $sep : '').$object->zip;
  2393. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2394. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2395. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2396. } else {
  2397. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2398. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2399. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2400. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2401. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2402. $ret .= ($ret ? ", " : '').$object->state;
  2403. }
  2404. }
  2405. if (!is_object($outputlangs)) {
  2406. $outputlangs = $langs;
  2407. }
  2408. if ($withcountry) {
  2409. $langs->load("dict");
  2410. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2411. }
  2412. if ($hookmanager) {
  2413. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2414. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2415. if ($reshook > 0) {
  2416. $ret = '';
  2417. }
  2418. $ret .= $hookmanager->resPrint;
  2419. }
  2420. return $ret;
  2421. }
  2422. /**
  2423. * Format a string.
  2424. *
  2425. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2426. * @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)
  2427. * @param int $is_gmt See comment of timestamp parameter
  2428. * @return string A formatted string
  2429. */
  2430. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2431. {
  2432. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2433. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2434. } else {
  2435. return 'Error date into a not supported range';
  2436. }
  2437. }
  2438. /**
  2439. * Output date in a string format according to outputlangs (or langs if not defined).
  2440. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2441. *
  2442. * @param int $time GM Timestamps date
  2443. * @param string $format Output date format (tag of strftime function)
  2444. * "%d %b %Y",
  2445. * "%d/%m/%Y %H:%M",
  2446. * "%d/%m/%Y %H:%M:%S",
  2447. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2448. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2449. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2450. * false or 'tzserver' => output string is for local PHP server TZ usage
  2451. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2452. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2453. * @param Translate $outputlangs Object lang that contains language for text translation.
  2454. * @param boolean $encodetooutput false=no convert into output pagecode
  2455. * @return string Formated date or '' if time is null
  2456. *
  2457. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2458. */
  2459. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2460. {
  2461. global $conf, $langs;
  2462. // If date undefined or "", we return ""
  2463. if (dol_strlen($time) == 0) {
  2464. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2465. }
  2466. if ($tzoutput === 'auto') {
  2467. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2468. }
  2469. // Clean parameters
  2470. $to_gmt = false;
  2471. $offsettz = $offsetdst = 0;
  2472. if ($tzoutput) {
  2473. $to_gmt = true; // For backward compatibility
  2474. if (is_string($tzoutput)) {
  2475. if ($tzoutput == 'tzserver') {
  2476. $to_gmt = false;
  2477. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2478. $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
  2479. $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
  2480. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2481. $to_gmt = true;
  2482. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2483. if (class_exists('DateTimeZone')) {
  2484. $user_date_tz = new DateTimeZone($offsettzstring);
  2485. $user_dt = new DateTime();
  2486. $user_dt->setTimezone($user_date_tz);
  2487. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2488. $offsettz = $user_dt->getOffset(); // should include dst ?
  2489. } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
  2490. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2491. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2492. }
  2493. }
  2494. }
  2495. }
  2496. if (!is_object($outputlangs)) {
  2497. $outputlangs = $langs;
  2498. }
  2499. if (!$format) {
  2500. $format = 'daytextshort';
  2501. }
  2502. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2503. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2504. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2505. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2506. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2507. if ($formatwithoutreduce != $format) {
  2508. $format = $formatwithoutreduce;
  2509. $reduceformat = 1;
  2510. } // so format 'dayreduceformat' is processed like day
  2511. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2512. // TODO Add format daysmallyear and dayhoursmallyear
  2513. if ($format == 'day') {
  2514. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2515. } elseif ($format == 'hour') {
  2516. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2517. } elseif ($format == 'hourduration') {
  2518. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2519. } elseif ($format == 'daytext') {
  2520. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2521. } elseif ($format == 'daytextshort') {
  2522. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2523. } elseif ($format == 'dayhour') {
  2524. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2525. } elseif ($format == 'dayhoursec') {
  2526. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2527. } elseif ($format == 'dayhourtext') {
  2528. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2529. } elseif ($format == 'dayhourtextshort') {
  2530. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2531. } elseif ($format == 'dayhourlog') {
  2532. // Format not sensitive to language
  2533. $format = '%Y%m%d%H%M%S';
  2534. } elseif ($format == 'dayhourlogsmall') {
  2535. // Format not sensitive to language
  2536. $format = '%y%m%d%H%M';
  2537. } elseif ($format == 'dayhourldap') {
  2538. $format = '%Y%m%d%H%M%SZ';
  2539. } elseif ($format == 'dayhourxcard') {
  2540. $format = '%Y%m%dT%H%M%SZ';
  2541. } elseif ($format == 'dayxcard') {
  2542. $format = '%Y%m%d';
  2543. } elseif ($format == 'dayrfc') {
  2544. $format = '%Y-%m-%d'; // DATE_RFC3339
  2545. } elseif ($format == 'dayhourrfc') {
  2546. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2547. } elseif ($format == 'standard') {
  2548. $format = '%Y-%m-%d %H:%M:%S';
  2549. }
  2550. if ($reduceformat) {
  2551. $format = str_replace('%Y', '%y', $format);
  2552. $format = str_replace('yyyy', 'yy', $format);
  2553. }
  2554. // Clean format
  2555. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2556. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2557. $format = str_replace('%b', '__b__', $format);
  2558. $format = str_replace('%B', '__B__', $format);
  2559. }
  2560. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2561. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2562. $format = str_replace('%a', '__a__', $format);
  2563. $format = str_replace('%A', '__A__', $format);
  2564. }
  2565. // Analyze date
  2566. $reg = array();
  2567. 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
  2568. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2569. return '';
  2570. } 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
  2571. // This part of code should not be used anymore.
  2572. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2573. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2574. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2575. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2576. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2577. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2578. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2579. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2580. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2581. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2582. if ($to_gmt) {
  2583. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2584. } else {
  2585. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2586. }
  2587. $dtts = new DateTime();
  2588. $dtts->setTimestamp($time);
  2589. $dtts->setTimezone($tzo);
  2590. $newformat = str_replace(
  2591. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2592. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2593. $format);
  2594. $ret = $dtts->format($newformat);
  2595. $ret = str_replace(
  2596. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2597. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2598. $ret
  2599. );
  2600. } else {
  2601. // Date is a timestamps
  2602. if ($time < 100000000000) { // Protection against bad date values
  2603. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2604. if ($to_gmt) {
  2605. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2606. } else {
  2607. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2608. }
  2609. $dtts = new DateTime();
  2610. $dtts->setTimestamp($timetouse);
  2611. $dtts->setTimezone($tzo);
  2612. $newformat = str_replace(
  2613. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2614. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2615. $format);
  2616. $ret = $dtts->format($newformat);
  2617. $ret = str_replace(
  2618. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2619. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2620. $ret
  2621. );
  2622. //var_dump($ret);exit;
  2623. } else {
  2624. $ret = 'Bad value '.$time.' for date';
  2625. }
  2626. }
  2627. if (preg_match('/__b__/i', $format)) {
  2628. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2629. if ($to_gmt) {
  2630. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2631. } else {
  2632. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2633. }
  2634. $dtts = new DateTime();
  2635. $dtts->setTimestamp($timetouse);
  2636. $dtts->setTimezone($tzo);
  2637. $month = $dtts->format("m");
  2638. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2639. if ($encodetooutput) {
  2640. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2641. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2642. } else {
  2643. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2644. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2645. }
  2646. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2647. $ret = str_replace('__b__', $monthtextshort, $ret);
  2648. $ret = str_replace('__B__', $monthtext, $ret);
  2649. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2650. //return $ret;
  2651. }
  2652. if (preg_match('/__a__/i', $format)) {
  2653. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2654. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2655. if ($to_gmt) {
  2656. $tzo = new DateTimeZone('UTC');
  2657. } else {
  2658. $tzo = new DateTimeZone(date_default_timezone_get());
  2659. }
  2660. $dtts = new DateTime();
  2661. $dtts->setTimestamp($timetouse);
  2662. $dtts->setTimezone($tzo);
  2663. $w = $dtts->format("w");
  2664. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2665. $ret = str_replace('__A__', $dayweek, $ret);
  2666. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2667. }
  2668. return $ret;
  2669. }
  2670. /**
  2671. * Return an array with locale date info.
  2672. * WARNING: This function use PHP server timezone by default to return locale informations.
  2673. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2674. *
  2675. * @param int $timestamp Timestamp
  2676. * @param boolean $fast Fast mode. deprecated.
  2677. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2678. * @return array Array of informations
  2679. * 'seconds' => $secs,
  2680. * 'minutes' => $min,
  2681. * 'hours' => $hour,
  2682. * 'mday' => $day,
  2683. * 'wday' => $dow, 0=sunday, 6=saturday
  2684. * 'mon' => $month,
  2685. * 'year' => $year,
  2686. * 'yday' => floor($secsInYear/$_day_power)
  2687. * '0' => original timestamp
  2688. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2689. */
  2690. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2691. {
  2692. $datetimeobj = new DateTime();
  2693. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2694. if ($forcetimezone) {
  2695. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2696. }
  2697. $arrayinfo = array(
  2698. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2699. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2700. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2701. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2702. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2703. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2704. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2705. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2706. '0'=>$timestamp
  2707. );
  2708. return $arrayinfo;
  2709. }
  2710. /**
  2711. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2712. * Replace function mktime not available under Windows if year < 1970
  2713. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2714. *
  2715. * @param int $hour Hour (can be -1 for undefined)
  2716. * @param int $minute Minute (can be -1 for undefined)
  2717. * @param int $second Second (can be -1 for undefined)
  2718. * @param int $month Month (1 to 12)
  2719. * @param int $day Day (1 to 31)
  2720. * @param int $year Year
  2721. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2722. * False or 0 or 'tzserver' = local to server TZ
  2723. * 'auto'
  2724. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2725. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user into a GMT date.
  2726. * 'tz,TimeZone' = use specified timezone
  2727. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2728. * @return int|string Date as a timestamp, '' or false if error
  2729. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2730. */
  2731. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2732. {
  2733. global $conf;
  2734. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2735. if ($gm === 'auto') {
  2736. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2737. }
  2738. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2739. // Clean parameters
  2740. if ($hour == -1 || empty($hour)) {
  2741. $hour = 0;
  2742. }
  2743. if ($minute == -1 || empty($minute)) {
  2744. $minute = 0;
  2745. }
  2746. if ($second == -1 || empty($second)) {
  2747. $second = 0;
  2748. }
  2749. // Check parameters
  2750. if ($check) {
  2751. if (!$month || !$day) {
  2752. return '';
  2753. }
  2754. if ($day > 31) {
  2755. return '';
  2756. }
  2757. if ($month > 12) {
  2758. return '';
  2759. }
  2760. if ($hour < 0 || $hour > 24) {
  2761. return '';
  2762. }
  2763. if ($minute < 0 || $minute > 60) {
  2764. return '';
  2765. }
  2766. if ($second < 0 || $second > 60) {
  2767. return '';
  2768. }
  2769. }
  2770. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2771. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2772. $localtz = new DateTimeZone($default_timezone);
  2773. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2774. // We use dol_tz_string first because it is more reliable.
  2775. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2776. try {
  2777. $localtz = new DateTimeZone($default_timezone);
  2778. } catch (Exception $e) {
  2779. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2780. $default_timezone = @date_default_timezone_get();
  2781. }
  2782. } elseif (strrpos($gm, "tz,") !== false) {
  2783. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2784. try {
  2785. $localtz = new DateTimeZone($timezone);
  2786. } catch (Exception $e) {
  2787. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2788. }
  2789. }
  2790. if (empty($localtz)) {
  2791. $localtz = new DateTimeZone('UTC');
  2792. }
  2793. //var_dump($localtz);
  2794. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2795. $dt = new DateTime('now', $localtz);
  2796. $dt->setDate((int) $year, (int) $month, (int) $day);
  2797. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2798. $date = $dt->getTimestamp(); // should include daylight saving time
  2799. //var_dump($date);
  2800. return $date;
  2801. }
  2802. /**
  2803. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2804. *
  2805. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2806. * 'gmt' => we return GMT timestamp,
  2807. * 'tzserver' => we add the PHP server timezone
  2808. * 'tzref' => we add the company timezone. Not implemented.
  2809. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2810. * @return int $date Timestamp
  2811. */
  2812. function dol_now($mode = 'auto')
  2813. {
  2814. $ret = 0;
  2815. if ($mode === 'auto') {
  2816. $mode = 'gmt';
  2817. }
  2818. if ($mode == 'gmt') {
  2819. $ret = time(); // Time for now at greenwich.
  2820. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2821. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2822. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2823. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2824. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2825. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2826. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2827. // $ret=dol_now('gmt')+($tzsecond*3600);
  2828. //}
  2829. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2830. // Time for now with user timezone added
  2831. //print 'time: '.time();
  2832. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2833. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2834. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2835. }
  2836. return $ret;
  2837. }
  2838. /**
  2839. * Return string with formated size
  2840. *
  2841. * @param int $size Size to print
  2842. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2843. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2844. * @return string Link
  2845. */
  2846. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2847. {
  2848. global $conf, $langs;
  2849. $level = 1024;
  2850. if (!empty($conf->dol_optimize_smallscreen)) {
  2851. $shortunit = 1;
  2852. }
  2853. // Set value text
  2854. if (empty($shortvalue) || $size < ($level * 10)) {
  2855. $ret = $size;
  2856. $textunitshort = $langs->trans("b");
  2857. $textunitlong = $langs->trans("Bytes");
  2858. } else {
  2859. $ret = round($size / $level, 0);
  2860. $textunitshort = $langs->trans("Kb");
  2861. $textunitlong = $langs->trans("KiloBytes");
  2862. }
  2863. // Use long or short text unit
  2864. if (empty($shortunit)) {
  2865. $ret .= ' '.$textunitlong;
  2866. } else {
  2867. $ret .= ' '.$textunitshort;
  2868. }
  2869. return $ret;
  2870. }
  2871. /**
  2872. * Show Url link
  2873. *
  2874. * @param string $url Url to show
  2875. * @param string $target Target for link
  2876. * @param int $max Max number of characters to show
  2877. * @param int $withpicto With picto
  2878. * @param string $morecss More CSS
  2879. * @return string HTML Link
  2880. */
  2881. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = 'float')
  2882. {
  2883. global $langs;
  2884. if (empty($url)) {
  2885. return '';
  2886. }
  2887. $link = '<a href="';
  2888. if (!preg_match('/^http/i', $url)) {
  2889. $link .= 'http://';
  2890. }
  2891. $link .= $url;
  2892. $link .= '"';
  2893. if ($target) {
  2894. $link .= ' target="'.$target.'"';
  2895. }
  2896. $link .= '>';
  2897. if (!preg_match('/^http/i', $url)) {
  2898. $link .= 'http://';
  2899. }
  2900. $link .= dol_trunc($url, $max);
  2901. $link .= '</a>';
  2902. if ($morecss == 'float') {
  2903. return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2904. } else {
  2905. return '<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</span>';
  2906. }
  2907. }
  2908. /**
  2909. * Show EMail link formatted for HTML output.
  2910. *
  2911. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2912. * @param int $cid Id of contact if known
  2913. * @param int $socid Id of third party if known
  2914. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2915. * @param int $max Max number of characters to show
  2916. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2917. * @param int|string $withpicto Show picto
  2918. * @return string HTML Link
  2919. */
  2920. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2921. {
  2922. global $conf, $user, $langs, $hookmanager;
  2923. $newemail = dol_escape_htmltag($email);
  2924. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2925. $withpicto = 0;
  2926. }
  2927. if (empty($email)) {
  2928. return '&nbsp;';
  2929. }
  2930. if (!empty($addlink)) {
  2931. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2932. if (!preg_match('/^mailto:/i', $email)) {
  2933. $newemail .= 'mailto:';
  2934. }
  2935. $newemail .= $email;
  2936. $newemail .= '">';
  2937. $newemail .= dol_trunc($email, $max);
  2938. $newemail .= '</a>';
  2939. if ($showinvalid && !isValidEmail($email)) {
  2940. $langs->load("errors");
  2941. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2942. }
  2943. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  2944. $type = 'AC_EMAIL';
  2945. $link = '';
  2946. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2947. $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>';
  2948. }
  2949. if ($link) {
  2950. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2951. }
  2952. }
  2953. } else {
  2954. if ($showinvalid && !isValidEmail($email)) {
  2955. $langs->load("errors");
  2956. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2957. }
  2958. }
  2959. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2960. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  2961. //$rep .= '</div>';
  2962. if ($hookmanager) {
  2963. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2964. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2965. if ($reshook > 0) {
  2966. $rep = '';
  2967. }
  2968. $rep .= $hookmanager->resPrint;
  2969. }
  2970. return $rep;
  2971. }
  2972. /**
  2973. * Get array of social network dictionary
  2974. *
  2975. * @return array Array of Social Networks Dictionary
  2976. */
  2977. function getArrayOfSocialNetworks()
  2978. {
  2979. global $conf, $db;
  2980. $socialnetworks = array();
  2981. // Enable caching of array
  2982. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2983. $cachekey = 'socialnetworks_' . $conf->entity;
  2984. $dataretrieved = dol_getcache($cachekey);
  2985. if (!is_null($dataretrieved)) {
  2986. $socialnetworks = $dataretrieved;
  2987. } else {
  2988. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2989. $sql .= " WHERE entity=".$conf->entity;
  2990. $resql = $db->query($sql);
  2991. if ($resql) {
  2992. while ($obj = $db->fetch_object($resql)) {
  2993. $socialnetworks[$obj->code] = array(
  2994. 'rowid' => $obj->rowid,
  2995. 'label' => $obj->label,
  2996. 'url' => $obj->url,
  2997. 'icon' => $obj->icon,
  2998. 'active' => $obj->active,
  2999. );
  3000. }
  3001. }
  3002. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  3003. }
  3004. return $socialnetworks;
  3005. }
  3006. /**
  3007. * Show social network link
  3008. *
  3009. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  3010. * @param int $cid Id of contact if known
  3011. * @param int $socid Id of third party if known
  3012. * @param string $type 'skype','facebook',...
  3013. * @param array $dictsocialnetworks socialnetworks availables
  3014. * @return string HTML Link
  3015. */
  3016. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  3017. {
  3018. global $conf, $user, $langs;
  3019. $htmllink = $value;
  3020. if (empty($value)) {
  3021. return '&nbsp;';
  3022. }
  3023. if (!empty($type)) {
  3024. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  3025. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  3026. $htmllink .= '<span class="fa pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  3027. if ($type == 'skype') {
  3028. $htmllink .= dol_escape_htmltag($value);
  3029. $htmllink .= '&nbsp; <a href="skype:';
  3030. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3031. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  3032. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  3033. $htmllink .= '</a><a href="skype:';
  3034. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3035. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  3036. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  3037. $htmllink .= '</a>';
  3038. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
  3039. $addlink = 'AC_SKYPE';
  3040. $link = '';
  3041. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  3042. $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>';
  3043. }
  3044. $htmllink .= ($link ? ' '.$link : '');
  3045. }
  3046. } else {
  3047. if (!empty($dictsocialnetworks[$type]['url'])) {
  3048. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  3049. if ($tmpvirginurl) {
  3050. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3051. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3052. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  3053. if ($tmpvirginurl3) {
  3054. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3055. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3056. }
  3057. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  3058. if ($tmpvirginurl2) {
  3059. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3060. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3061. }
  3062. }
  3063. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  3064. if (preg_match('/^https?:\/\//i', $link)) {
  3065. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3066. } else {
  3067. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3068. }
  3069. } else {
  3070. $htmllink .= dol_escape_htmltag($value);
  3071. }
  3072. }
  3073. $htmllink .= '</div>';
  3074. } else {
  3075. $langs->load("errors");
  3076. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  3077. }
  3078. return $htmllink;
  3079. }
  3080. /**
  3081. * Format profIDs according to country
  3082. *
  3083. * @param string $profID Value of profID to format
  3084. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  3085. * @param string $countrycode Country code to use for formatting
  3086. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  3087. * @param string $separ Separation between numbers for a better visibility example : xxx xxx xxx xxxxx
  3088. * @return string Formated profID
  3089. */
  3090. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
  3091. {
  3092. global $mysoc;
  3093. if (empty($profID) || empty($profIDtype)) {
  3094. return '';
  3095. }
  3096. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  3097. $newProfID = $profID;
  3098. $id = substr($profIDtype, -1);
  3099. $ret = '';
  3100. if (strtoupper($countrycode) == 'FR') {
  3101. // France
  3102. if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
  3103. if ($id == 2 && dol_strlen($newProfID) == 14) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3).$separ.substr($newProfID, 9, 5);
  3104. if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) $newProfID = substr($newProfID, 0, 4).$separ.substr($newProfID, 4, 3).$separ.substr($newProfID, 7, 3).$separ.substr($newProfID, 10, 3);
  3105. }
  3106. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  3107. else $ret = $newProfID;
  3108. return $ret;
  3109. }
  3110. /**
  3111. * Format phone numbers according to country
  3112. *
  3113. * @param string $phone Phone number to format
  3114. * @param string $countrycode Country code to use for formatting
  3115. * @param int $cid Id of contact if known
  3116. * @param int $socid Id of third party if known
  3117. * @param string $addlink ''=no link to create action, 'AC_TEL'=add link to clicktodial (if module enabled) and add link to create event (if conf->global->AGENDA_ADDACTIONFORPHONE set), 'tel'=Force "tel:..." link
  3118. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  3119. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  3120. * @param string $titlealt Text to show on alt
  3121. * @param int $adddivfloat Add div float around phone.
  3122. * @return string Formated phone number
  3123. */
  3124. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  3125. {
  3126. global $conf, $user, $langs, $mysoc, $hookmanager;
  3127. // Clean phone parameter
  3128. $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
  3129. if (empty($phone)) {
  3130. return '';
  3131. }
  3132. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  3133. $separ = $conf->global->MAIN_PHONE_SEPAR;
  3134. }
  3135. if (empty($countrycode) && is_object($mysoc)) {
  3136. $countrycode = $mysoc->country_code;
  3137. }
  3138. // Short format for small screens
  3139. if ($conf->dol_optimize_smallscreen) {
  3140. $separ = '';
  3141. }
  3142. $newphone = $phone;
  3143. if (strtoupper($countrycode) == "FR") {
  3144. // France
  3145. if (dol_strlen($phone) == 10) {
  3146. $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);
  3147. } elseif (dol_strlen($phone) == 7) {
  3148. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  3149. } elseif (dol_strlen($phone) == 9) {
  3150. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  3151. } elseif (dol_strlen($phone) == 11) {
  3152. $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);
  3153. } elseif (dol_strlen($phone) == 12) {
  3154. $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);
  3155. } elseif (dol_strlen($phone) == 13) {
  3156. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  3157. }
  3158. } elseif (strtoupper($countrycode) == "CA") {
  3159. if (dol_strlen($phone) == 10) {
  3160. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  3161. }
  3162. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  3163. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  3164. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3165. }
  3166. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  3167. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  3168. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  3169. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  3170. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  3171. }
  3172. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  3173. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  3174. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  3175. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  3176. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  3177. }
  3178. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  3179. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  3180. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3181. }
  3182. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  3183. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  3184. $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);
  3185. }
  3186. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  3187. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  3188. $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);
  3189. }
  3190. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  3191. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  3192. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3193. }
  3194. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  3195. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  3196. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3197. }
  3198. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  3199. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  3200. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3201. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  3202. $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);
  3203. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  3204. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3205. }
  3206. } elseif (strtoupper($countrycode) == "ML") {//Mali
  3207. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  3208. $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);
  3209. }
  3210. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  3211. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  3212. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3213. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  3214. $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);
  3215. }
  3216. } elseif (strtoupper($countrycode) == "MU") {
  3217. //Maurice
  3218. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  3219. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  3220. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  3221. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  3222. }
  3223. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  3224. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  3225. $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);
  3226. }
  3227. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  3228. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  3229. $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);
  3230. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  3231. $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);
  3232. }
  3233. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  3234. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  3235. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3236. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  3237. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3238. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  3239. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  3240. }
  3241. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  3242. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  3243. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3244. }
  3245. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  3246. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  3247. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3248. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  3249. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3250. }
  3251. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  3252. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  3253. $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);
  3254. }
  3255. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  3256. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  3257. $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);
  3258. }
  3259. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3260. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3261. $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);
  3262. }
  3263. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3264. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3265. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3266. }
  3267. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3268. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
  3269. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  3270. }
  3271. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3272. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3273. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3274. }
  3275. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3276. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3277. $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);
  3278. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3279. $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);
  3280. }
  3281. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3282. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3283. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3284. }
  3285. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3286. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3287. $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);
  3288. }
  3289. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3290. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3291. $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);
  3292. }
  3293. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3294. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3295. $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);
  3296. }
  3297. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3298. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3299. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3300. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3301. $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);
  3302. }
  3303. } elseif (strtoupper($countrycode) == "AU") {
  3304. //Australie
  3305. if (dol_strlen($phone) == 12) {
  3306. //ex: +61_A_BCDE_FGHI
  3307. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3308. }
  3309. } elseif (strtoupper($countrycode) == "LU") {
  3310. // Luxembourg
  3311. if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
  3312. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
  3313. } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
  3314. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 1);
  3315. } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
  3316. $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);
  3317. } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
  3318. $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);
  3319. }
  3320. }
  3321. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3322. if ($addlink == 'tel' || $conf->browser->layout == 'phone' || (isModEnabled('clicktodial') && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) { // If phone or option for, we use link of phone
  3323. $newphoneform = $newphone;
  3324. $newphone = '<a href="tel:'.$phone.'"';
  3325. $newphone .= '>'.$newphoneform.'</a>';
  3326. } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3327. if (empty($user->clicktodial_loaded)) {
  3328. $user->fetch_clicktodial();
  3329. }
  3330. // Define urlmask
  3331. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  3332. if (!empty($conf->global->CLICKTODIAL_URL)) {
  3333. $urlmask = $conf->global->CLICKTODIAL_URL;
  3334. }
  3335. if (!empty($user->clicktodial_url)) {
  3336. $urlmask = $user->clicktodial_url;
  3337. }
  3338. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  3339. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  3340. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  3341. // This line is for backward compatibility
  3342. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3343. // Thoose lines are for substitution
  3344. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3345. '__PHONETO__'=>urlencode($phone),
  3346. '__LOGIN__'=>$clicktodial_login,
  3347. '__PASS__'=>$clicktodial_password);
  3348. $url = make_substitutions($url, $substitarray);
  3349. $newphonesav = $newphone;
  3350. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  3351. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3352. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3353. $newphone .= '>'.$newphonesav.'</a>';
  3354. } else {
  3355. // Old method
  3356. $newphone = '<a href="'.$url.'"';
  3357. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  3358. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  3359. }
  3360. $newphone .= '>'.$newphonesav.'</a>';
  3361. }
  3362. }
  3363. //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
  3364. if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3365. $type = 'AC_TEL';
  3366. $link = '';
  3367. if ($addlink == 'AC_FAX') {
  3368. $type = 'AC_FAX';
  3369. }
  3370. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  3371. $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage='. urlencode($_SERVER['REQUEST_URI']) .'&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  3372. }
  3373. if ($link) {
  3374. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  3375. }
  3376. }
  3377. }
  3378. if (empty($titlealt)) {
  3379. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3380. }
  3381. $rep = '';
  3382. if ($hookmanager) {
  3383. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3384. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3385. $rep .= $hookmanager->resPrint;
  3386. }
  3387. if (empty($reshook)) {
  3388. $picto = '';
  3389. if ($withpicto) {
  3390. if ($withpicto == 'fax') {
  3391. $picto = 'phoning_fax';
  3392. } elseif ($withpicto == 'phone') {
  3393. $picto = 'phoning';
  3394. } elseif ($withpicto == 'mobile') {
  3395. $picto = 'phoning_mobile';
  3396. } else {
  3397. $picto = '';
  3398. }
  3399. }
  3400. if ($adddivfloat == 1) {
  3401. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3402. } elseif (empty($adddivfloat)) {
  3403. $rep .= '<span style="margin-right: 10px;">';
  3404. }
  3405. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  3406. if ($adddivfloat == 1) {
  3407. $rep .= '</div>';
  3408. } elseif (empty($adddivfloat)) {
  3409. $rep .= '</span>';
  3410. }
  3411. }
  3412. return $rep;
  3413. }
  3414. /**
  3415. * Return an IP formated to be shown on screen
  3416. *
  3417. * @param string $ip IP
  3418. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3419. * @return string Formated IP, with country if GeoIP module is enabled
  3420. */
  3421. function dol_print_ip($ip, $mode = 0)
  3422. {
  3423. global $conf, $langs;
  3424. $ret = '';
  3425. if (empty($mode)) {
  3426. $ret .= $ip;
  3427. }
  3428. if ($mode != 2) {
  3429. $countrycode = dolGetCountryCodeFromIp($ip);
  3430. if ($countrycode) { // If success, countrycode is us, fr, ...
  3431. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3432. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3433. } else {
  3434. $ret .= ' ('.$countrycode.')';
  3435. }
  3436. } else {
  3437. // Nothing
  3438. }
  3439. }
  3440. return $ret;
  3441. }
  3442. /**
  3443. * Return the IP of remote user.
  3444. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3445. * Then HTTP_CLIENT_IP if defined (rare)
  3446. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3447. *
  3448. * @return string Ip of remote user.
  3449. */
  3450. function getUserRemoteIP()
  3451. {
  3452. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3453. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3454. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3455. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3456. } else {
  3457. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3458. }
  3459. } else {
  3460. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3461. }
  3462. } else {
  3463. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3464. }
  3465. return $ip;
  3466. }
  3467. /**
  3468. * Return if we are using a HTTPS connexion
  3469. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3470. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3471. * Then HTTP_X_FORWARDED_SSL
  3472. *
  3473. * @return boolean True if user is using HTTPS
  3474. */
  3475. function isHTTPS()
  3476. {
  3477. $isSecure = false;
  3478. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3479. $isSecure = true;
  3480. } 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') {
  3481. $isSecure = true;
  3482. }
  3483. return $isSecure;
  3484. }
  3485. /**
  3486. * Return a country code from IP. Empty string if not found.
  3487. *
  3488. * @param string $ip IP
  3489. * @return string Country code ('us', 'fr', ...)
  3490. */
  3491. function dolGetCountryCodeFromIp($ip)
  3492. {
  3493. global $conf;
  3494. $countrycode = '';
  3495. if (!empty($conf->geoipmaxmind->enabled)) {
  3496. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3497. //$ip='24.24.24.24';
  3498. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3499. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3500. $geoip = new DolGeoIP('country', $datafile);
  3501. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3502. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3503. }
  3504. return $countrycode;
  3505. }
  3506. /**
  3507. * Return country code for current user.
  3508. * If software is used inside a local network, detection may fails (we need a public ip)
  3509. *
  3510. * @return string Country code (fr, es, it, us, ...)
  3511. */
  3512. function dol_user_country()
  3513. {
  3514. global $conf, $langs, $user;
  3515. //$ret=$user->xxx;
  3516. $ret = '';
  3517. if (!empty($conf->geoipmaxmind->enabled)) {
  3518. $ip = getUserRemoteIP();
  3519. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3520. //$ip='24.24.24.24';
  3521. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3522. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3523. $geoip = new DolGeoIP('country', $datafile);
  3524. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3525. $ret = $countrycode;
  3526. }
  3527. return $ret;
  3528. }
  3529. /**
  3530. * Format address string
  3531. *
  3532. * @param string $address Address string, already formatted with dol_format_address()
  3533. * @param int $htmlid Html ID (for example 'gmap')
  3534. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3535. * @param int $id Id of object
  3536. * @param int $noprint No output. Result is the function return
  3537. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3538. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3539. * @see dol_format_address()
  3540. */
  3541. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3542. {
  3543. global $conf, $user, $langs, $hookmanager;
  3544. $out = '';
  3545. if ($address) {
  3546. if ($hookmanager) {
  3547. $parameters = array('element' => $element, 'id' => $id);
  3548. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3549. $out .= $hookmanager->resPrint;
  3550. }
  3551. if (empty($reshook)) {
  3552. if (empty($charfornl)) {
  3553. $out .= nl2br($address);
  3554. } else {
  3555. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3556. }
  3557. // TODO Remove this block, we can add this using the hook now
  3558. $showgmap = $showomap = 0;
  3559. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3560. $showgmap = 1;
  3561. }
  3562. if ($element == 'contact' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3563. $showgmap = 1;
  3564. }
  3565. if ($element == 'member' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3566. $showgmap = 1;
  3567. }
  3568. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3569. $showomap = 1;
  3570. }
  3571. if ($element == 'contact' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3572. $showomap = 1;
  3573. }
  3574. if ($element == 'member' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3575. $showomap = 1;
  3576. }
  3577. if ($showgmap) {
  3578. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3579. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3580. }
  3581. if ($showomap) {
  3582. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3583. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3584. }
  3585. }
  3586. }
  3587. if ($noprint) {
  3588. return $out;
  3589. } else {
  3590. print $out;
  3591. }
  3592. }
  3593. /**
  3594. * Return true if email syntax is ok.
  3595. *
  3596. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3597. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3598. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3599. * @return boolean true if email syntax is OK, false if KO or empty string
  3600. * @see isValidMXRecord()
  3601. */
  3602. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3603. {
  3604. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3605. return true;
  3606. }
  3607. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3608. return true;
  3609. }
  3610. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3611. return true;
  3612. }
  3613. return false;
  3614. }
  3615. /**
  3616. * Return if the domain name has a valid MX record.
  3617. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3618. *
  3619. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3620. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3621. * @see isValidEmail()
  3622. */
  3623. function isValidMXRecord($domain)
  3624. {
  3625. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3626. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3627. return 0;
  3628. }
  3629. if (function_exists('getmxrr')) {
  3630. $mxhosts = array();
  3631. $weight = array();
  3632. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3633. if (count($mxhosts) > 1) {
  3634. return 1;
  3635. }
  3636. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3637. return 1;
  3638. }
  3639. return 0;
  3640. }
  3641. }
  3642. // function idn_to_ascii or checkdnsrr or getmxrr does not exists
  3643. return -1;
  3644. }
  3645. /**
  3646. * Return true if phone number syntax is ok
  3647. * TODO Decide what to do with this
  3648. *
  3649. * @param string $phone phone (Ex: "0601010101")
  3650. * @return boolean true if phone syntax is OK, false if KO or empty string
  3651. */
  3652. function isValidPhone($phone)
  3653. {
  3654. return true;
  3655. }
  3656. /**
  3657. * Return first letters of a strings.
  3658. * Example with nbofchar=1: 'ghi' will return 'g' but 'abc def' will return 'ad'
  3659. * Example with nbofchar=2: 'ghi' will return 'gh' but 'abc def' will return 'abde'
  3660. *
  3661. * @param string $s String to truncate
  3662. * @param int $nbofchar Nb of characters to keep
  3663. * @return string Return first chars.
  3664. */
  3665. function dolGetFirstLetters($s, $nbofchar = 1)
  3666. {
  3667. $ret = '';
  3668. $tmparray = explode(' ', $s);
  3669. foreach ($tmparray as $tmps) {
  3670. $ret .= dol_substr($tmps, 0, $nbofchar);
  3671. }
  3672. return $ret;
  3673. }
  3674. /**
  3675. * Make a strlen call. Works even if mbstring module not enabled
  3676. *
  3677. * @param string $string String to calculate length
  3678. * @param string $stringencoding Encoding of string
  3679. * @return int Length of string
  3680. */
  3681. function dol_strlen($string, $stringencoding = 'UTF-8')
  3682. {
  3683. if (is_null($string)) {
  3684. return 0;
  3685. }
  3686. if (function_exists('mb_strlen')) {
  3687. return mb_strlen($string, $stringencoding);
  3688. } else {
  3689. return strlen($string);
  3690. }
  3691. }
  3692. /**
  3693. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3694. *
  3695. * @param string $string String to scan
  3696. * @param string $start Start position
  3697. * @param int|null $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3698. * @param string $stringencoding Page code used for input string encoding
  3699. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3700. * @return string substring
  3701. */
  3702. function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
  3703. {
  3704. global $langs;
  3705. if (empty($stringencoding)) {
  3706. $stringencoding = $langs->charset_output;
  3707. }
  3708. $ret = '';
  3709. if (empty($trunconbytes)) {
  3710. if (function_exists('mb_substr')) {
  3711. $ret = mb_substr($string, $start, $length, $stringencoding);
  3712. } else {
  3713. $ret = substr($string, $start, $length);
  3714. }
  3715. } else {
  3716. if (function_exists('mb_strcut')) {
  3717. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3718. } else {
  3719. $ret = substr($string, $start, $length);
  3720. }
  3721. }
  3722. return $ret;
  3723. }
  3724. /**
  3725. * Truncate a string to a particular length adding '…' if string larger than length.
  3726. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3727. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3728. *
  3729. * @param string $string String to truncate
  3730. * @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 ...)
  3731. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3732. * @param string $stringencoding Tell what is source string encoding
  3733. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3734. * @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)
  3735. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3736. */
  3737. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3738. {
  3739. global $conf;
  3740. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3741. return $string;
  3742. }
  3743. if (empty($stringencoding)) {
  3744. $stringencoding = 'UTF-8';
  3745. }
  3746. // reduce for small screen
  3747. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3748. $size = round($size / 3);
  3749. }
  3750. // We go always here
  3751. if ($trunc == 'right') {
  3752. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3753. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3754. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3755. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3756. } else {
  3757. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3758. return $string;
  3759. }
  3760. } elseif ($trunc == 'middle') {
  3761. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3762. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3763. $size1 = round($size / 2);
  3764. $size2 = round($size / 2);
  3765. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3766. } else {
  3767. return $string;
  3768. }
  3769. } elseif ($trunc == 'left') {
  3770. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3771. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3772. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3773. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3774. } else {
  3775. return $string;
  3776. }
  3777. } elseif ($trunc == 'wrap') {
  3778. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3779. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3780. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3781. } else {
  3782. return $string;
  3783. }
  3784. } else {
  3785. return 'BadParam3CallingDolTrunc';
  3786. }
  3787. }
  3788. /**
  3789. * Show picto whatever it's its name (generic function)
  3790. *
  3791. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3792. * @param string $picto Name of image file to show ('filenew', ...).
  3793. * For font awesome icon (example 'user'), you can use picto_nocolor to not have the color of picto forced.
  3794. * If no extension provided and it is not a font awesome icon, we use '.png'. Image must be stored into theme/xxx/img directory.
  3795. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3796. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3797. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3798. * Example: fontawesome_envelope-open-text_fas_red_1em if you want to use fontaweseome icons: fontawesome_<icon-name>_<style>_<color>_<size> (only icon-name is mandatory)
  3799. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3800. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3801. * @param int $srconly Return only content of the src attribute of img.
  3802. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3803. * @param string $alt Force alt for bind people
  3804. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3805. * @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.
  3806. * @return string Return img tag
  3807. * @see img_object(), img_picto_common()
  3808. */
  3809. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3810. {
  3811. global $conf, $langs;
  3812. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3813. $url = DOL_URL_ROOT;
  3814. $theme = isset($conf->theme) ? $conf->theme : null;
  3815. $path = 'theme/'.$theme;
  3816. // Define fullpathpicto to use into src
  3817. if ($pictoisfullpath) {
  3818. // Clean parameters
  3819. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3820. $picto .= '.png';
  3821. }
  3822. $fullpathpicto = $picto;
  3823. $reg = array();
  3824. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3825. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3826. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3827. }
  3828. } else {
  3829. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3830. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3831. $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
  3832. if (strpos($pictowithouttext, 'fontawesome_') !== false || preg_match('/^fa-/', $pictowithouttext)) {
  3833. // This is a font awesome image 'fonwtawesome_xxx' or 'fa-xxx'
  3834. $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
  3835. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  3836. $pictowithouttextarray = explode('_', $pictowithouttext);
  3837. $marginleftonlyshort = 0;
  3838. if (!empty($pictowithouttextarray[1])) {
  3839. // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
  3840. $fakey = 'fa-'.$pictowithouttextarray[0];
  3841. $fa = empty($pictowithouttextarray[1]) ? 'fa' : $pictowithouttextarray[1];
  3842. $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
  3843. $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  3844. } else {
  3845. $fakey = 'fa-'.$pictowithouttext;
  3846. $fa = 'fa';
  3847. $facolor = '';
  3848. $fasize = '';
  3849. }
  3850. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3851. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3852. $morestyle = '';
  3853. $reg = array();
  3854. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3855. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3856. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3857. }
  3858. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3859. $morestyle = $reg[1];
  3860. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3861. }
  3862. $moreatt = trim($moreatt);
  3863. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3864. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3865. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3866. $enabledisablehtml .= $titlealt;
  3867. }*/
  3868. $enabledisablehtml .= '</span>';
  3869. return $enabledisablehtml;
  3870. }
  3871. if (empty($srconly) && in_array($pictowithouttext, array(
  3872. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3873. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3874. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  3875. 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3876. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
  3877. 'currency', 'multicurrency',
  3878. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3879. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
  3880. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3881. 'gears', 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3882. 'hands-helping', 'help', 'holiday',
  3883. 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
  3884. 'knowledgemanagement',
  3885. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
  3886. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3887. 'off', 'on', 'order',
  3888. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
  3889. 'stock', 'resize', 'service', 'stats', 'trip',
  3890. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_warning', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
  3891. 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3892. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3893. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3894. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3895. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3896. 'technic', 'ticket',
  3897. 'error', 'warning',
  3898. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
  3899. 'shapes', 'skill', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3900. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3901. 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
  3902. 'conferenceorbooth', 'eventorganization',
  3903. 'stamp', 'signature'
  3904. ))) {
  3905. $fakey = $pictowithouttext;
  3906. $facolor = '';
  3907. $fasize = '';
  3908. $fa = 'fas';
  3909. if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3910. $fa = 'far';
  3911. }
  3912. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3913. $fa = 'fab';
  3914. }
  3915. $arrayconvpictotofa = array(
  3916. 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  3917. 'bank_account'=>'university',
  3918. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3919. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3920. 'bom'=>'shapes',
  3921. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time', 'cross'=>'times',
  3922. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3923. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3924. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3925. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3926. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3927. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3928. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3929. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3930. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'jobprofile'=>'cogs',
  3931. 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  3932. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3933. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3934. 'sign-out'=>'sign-out-alt',
  3935. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_warning'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3936. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3937. 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3938. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'currency'=>'dollar-sign', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3939. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3940. 'other'=>'square',
  3941. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'proposal'=>'file-signature',
  3942. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'pictoconfirm'=>'check-square', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
  3943. 'recent' => 'check-square', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3944. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3945. 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
  3946. 'service'=>'concierge-bell',
  3947. 'skill'=>'shapes', 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3948. 'supplier'=>'building', 'technic'=>'cogs',
  3949. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3950. 'title_agenda'=>'calendar-alt',
  3951. 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'arrow-alt-circle-down',
  3952. 'jabber'=>'comment-o',
  3953. 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
  3954. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3955. );
  3956. if ($pictowithouttext == 'off') {
  3957. $fakey = 'fa-square';
  3958. $fasize = '1.3em';
  3959. } elseif ($pictowithouttext == 'on') {
  3960. $fakey = 'fa-check-square';
  3961. $fasize = '1.3em';
  3962. } elseif ($pictowithouttext == 'listlight') {
  3963. $fakey = 'fa-download';
  3964. $marginleftonlyshort = 1;
  3965. } elseif ($pictowithouttext == 'printer') {
  3966. $fakey = 'fa-print';
  3967. $fasize = '1.2em';
  3968. } elseif ($pictowithouttext == 'note') {
  3969. $fakey = 'fa-sticky-note';
  3970. $marginleftonlyshort = 1;
  3971. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3972. $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');
  3973. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3974. if (preg_match('/selected/', $pictowithouttext)) {
  3975. $facolor = '#888';
  3976. }
  3977. $marginleftonlyshort = 1;
  3978. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3979. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3980. } else {
  3981. $fakey = 'fa-'.$pictowithouttext;
  3982. }
  3983. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3984. $morecss .= ' em092';
  3985. }
  3986. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3987. $morecss .= ' em088';
  3988. }
  3989. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3990. $morecss .= ' em080';
  3991. }
  3992. // Define $marginleftonlyshort
  3993. $arrayconvpictotomarginleftonly = array(
  3994. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3995. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3996. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3997. );
  3998. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3999. $marginleftonlyshort = 0;
  4000. }
  4001. // Add CSS
  4002. $arrayconvpictotomorcess = array(
  4003. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  4004. 'bank_account'=>'infobox-bank_account',
  4005. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  4006. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  4007. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  4008. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  4009. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  4010. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  4011. 'incoterm'=>'infobox-supplier_proposal',
  4012. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  4013. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  4014. 'order'=>'infobox-commande',
  4015. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  4016. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_warning'=>'font-status4 warning', 'switch_on_red'=>'font-status8',
  4017. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  4018. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  4019. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  4020. 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
  4021. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  4022. 'resource'=>'infobox-action',
  4023. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  4024. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  4025. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  4026. 'vat'=>'infobox-bank_account',
  4027. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  4028. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  4029. );
  4030. if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4031. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  4032. }
  4033. // Define $color
  4034. $arrayconvpictotocolor = array(
  4035. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  4036. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  4037. 'dynamicprice'=>'#a69944',
  4038. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  4039. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  4040. 'lock'=>'#ddd', 'lot'=>'#a69944',
  4041. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  4042. 'other'=>'#ddd', 'world'=>'#986c6a',
  4043. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  4044. //'shipment'=>'#a69944',
  4045. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  4046. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  4047. 'website'=>'#304', 'workstation'=>'#a69944'
  4048. );
  4049. if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4050. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  4051. }
  4052. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  4053. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  4054. $morestyle = '';
  4055. $reg = array();
  4056. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4057. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4058. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4059. }
  4060. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  4061. $morestyle = $reg[1];
  4062. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  4063. }
  4064. $moreatt = trim($moreatt);
  4065. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  4066. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  4067. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4068. $enabledisablehtml .= $titlealt;
  4069. }*/
  4070. $enabledisablehtml .= '</span>';
  4071. return $enabledisablehtml;
  4072. }
  4073. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  4074. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  4075. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  4076. $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
  4077. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  4078. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  4079. }
  4080. // If we ask an image into $url/$mymodule/img (instead of default path)
  4081. $regs = array();
  4082. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  4083. $picto = $regs[1];
  4084. $path = $regs[2]; // $path is $mymodule
  4085. }
  4086. // Clean parameters
  4087. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  4088. $picto .= '.png';
  4089. }
  4090. // If alt path are defined, define url where img file is, according to physical path
  4091. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  4092. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  4093. if ($type == 'main') {
  4094. continue;
  4095. }
  4096. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  4097. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  4098. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  4099. break;
  4100. }
  4101. }
  4102. // $url is '' or '/custom', $path is current theme or
  4103. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  4104. }
  4105. if ($srconly) {
  4106. return $fullpathpicto;
  4107. }
  4108. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  4109. 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
  4110. }
  4111. /**
  4112. * Show a picto called object_picto (generic function)
  4113. *
  4114. * @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.
  4115. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  4116. * For external modules use imagename@mymodule to search into directory "img" of module.
  4117. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  4118. * @param int $pictoisfullpath If 1, image path is a full path
  4119. * @param int $srconly Return only content of the src attribute of img.
  4120. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4121. * @return string Return img tag
  4122. * @see img_picto(), img_picto_common()
  4123. */
  4124. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  4125. {
  4126. if (strpos($picto, '^') === 0) {
  4127. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  4128. } else {
  4129. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  4130. }
  4131. }
  4132. /**
  4133. * Show weather picto
  4134. *
  4135. * @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.
  4136. * @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).
  4137. * @param string $moreatt Add more attribute on img tag
  4138. * @param int $pictoisfullpath If 1, image path is a full path
  4139. * @param string $morecss More CSS
  4140. * @return string Return img tag
  4141. * @see img_object(), img_picto()
  4142. */
  4143. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  4144. {
  4145. global $conf;
  4146. if (is_numeric($picto)) {
  4147. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  4148. //$picto = $leveltopicto[$picto];
  4149. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  4150. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4151. $picto .= '.png';
  4152. }
  4153. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  4154. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  4155. }
  4156. /**
  4157. * Show picto (generic function)
  4158. *
  4159. * @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.
  4160. * @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.
  4161. * @param string $moreatt Add more attribute on img tag
  4162. * @param int $pictoisfullpath If 1, image path is a full path
  4163. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4164. * @return string Return img tag
  4165. * @see img_object(), img_picto()
  4166. */
  4167. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  4168. {
  4169. global $conf;
  4170. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4171. $picto .= '.png';
  4172. }
  4173. if ($pictoisfullpath) {
  4174. $path = $picto;
  4175. } else {
  4176. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  4177. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  4178. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  4179. if (file_exists($themepath)) {
  4180. $path = $themepath;
  4181. }
  4182. }
  4183. }
  4184. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  4185. }
  4186. /**
  4187. * Show logo action
  4188. *
  4189. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  4190. * @param string $numaction Action id or code to show
  4191. * @param string $picto Name of image file to show ('filenew', ...)
  4192. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  4193. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4194. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4195. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4196. * @param string $moreatt More attributes
  4197. * @return string Return an img tag
  4198. */
  4199. function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
  4200. {
  4201. global $langs;
  4202. if (empty($titlealt) || $titlealt == 'default') {
  4203. if ($numaction == '-1' || $numaction == 'ST_NO') {
  4204. $numaction = -1;
  4205. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  4206. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  4207. $numaction = 0;
  4208. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  4209. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  4210. $numaction = 1;
  4211. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  4212. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  4213. $numaction = 2;
  4214. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  4215. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  4216. $numaction = 3;
  4217. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  4218. } else {
  4219. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  4220. $numaction = 0;
  4221. }
  4222. }
  4223. if (!is_numeric($numaction)) {
  4224. $numaction = 0;
  4225. }
  4226. return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
  4227. }
  4228. /**
  4229. * Show pdf logo
  4230. *
  4231. * @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.
  4232. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  4233. * @return string Retourne tag img
  4234. */
  4235. function img_pdf($titlealt = 'default', $size = 3)
  4236. {
  4237. global $langs;
  4238. if ($titlealt == 'default') {
  4239. $titlealt = $langs->trans('Show');
  4240. }
  4241. return img_picto($titlealt, 'pdf'.$size.'.png');
  4242. }
  4243. /**
  4244. * Show logo +
  4245. *
  4246. * @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.
  4247. * @param string $other Add more attributes on img
  4248. * @return string Return tag img
  4249. */
  4250. function img_edit_add($titlealt = 'default', $other = '')
  4251. {
  4252. global $langs;
  4253. if ($titlealt == 'default') {
  4254. $titlealt = $langs->trans('Add');
  4255. }
  4256. return img_picto($titlealt, 'edit_add.png', $other);
  4257. }
  4258. /**
  4259. * Show logo -
  4260. *
  4261. * @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.
  4262. * @param string $other Add more attributes on img
  4263. * @return string Return tag img
  4264. */
  4265. function img_edit_remove($titlealt = 'default', $other = '')
  4266. {
  4267. global $langs;
  4268. if ($titlealt == 'default') {
  4269. $titlealt = $langs->trans('Remove');
  4270. }
  4271. return img_picto($titlealt, 'edit_remove.png', $other);
  4272. }
  4273. /**
  4274. * Show logo editer/modifier fiche
  4275. *
  4276. * @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.
  4277. * @param integer $float If you have to put the style "float: right"
  4278. * @param string $other Add more attributes on img
  4279. * @return string Return tag img
  4280. */
  4281. function img_edit($titlealt = 'default', $float = 0, $other = '')
  4282. {
  4283. global $langs;
  4284. if ($titlealt == 'default') {
  4285. $titlealt = $langs->trans('Modify');
  4286. }
  4287. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  4288. }
  4289. /**
  4290. * Show logo view card
  4291. *
  4292. * @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.
  4293. * @param integer $float If you have to put the style "float: right"
  4294. * @param string $other Add more attributes on img
  4295. * @return string Return tag img
  4296. */
  4297. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  4298. {
  4299. global $langs;
  4300. if ($titlealt == 'default') {
  4301. $titlealt = $langs->trans('View');
  4302. }
  4303. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4304. return img_picto($titlealt, 'eye', $moreatt);
  4305. }
  4306. /**
  4307. * Show delete logo
  4308. *
  4309. * @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.
  4310. * @param string $other Add more attributes on img
  4311. * @param string $morecss More CSS
  4312. * @return string Retourne tag img
  4313. */
  4314. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4315. {
  4316. global $langs;
  4317. if ($titlealt == 'default') {
  4318. $titlealt = $langs->trans('Delete');
  4319. }
  4320. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4321. }
  4322. /**
  4323. * Show printer logo
  4324. *
  4325. * @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.
  4326. * @param string $other Add more attributes on img
  4327. * @return string Retourne tag img
  4328. */
  4329. function img_printer($titlealt = "default", $other = '')
  4330. {
  4331. global $langs;
  4332. if ($titlealt == "default") {
  4333. $titlealt = $langs->trans("Print");
  4334. }
  4335. return img_picto($titlealt, 'printer.png', $other);
  4336. }
  4337. /**
  4338. * Show split logo
  4339. *
  4340. * @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.
  4341. * @param string $other Add more attributes on img
  4342. * @return string Retourne tag img
  4343. */
  4344. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4345. {
  4346. global $langs;
  4347. if ($titlealt == 'default') {
  4348. $titlealt = $langs->trans('Split');
  4349. }
  4350. return img_picto($titlealt, 'split.png', $other);
  4351. }
  4352. /**
  4353. * Show help logo with cursor "?"
  4354. *
  4355. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4356. * @param int|string $usealttitle Text to use as alt title
  4357. * @return string Return tag img
  4358. */
  4359. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4360. {
  4361. global $langs;
  4362. if ($usealttitle) {
  4363. if (is_string($usealttitle)) {
  4364. $usealttitle = dol_escape_htmltag($usealttitle);
  4365. } else {
  4366. $usealttitle = $langs->trans('Info');
  4367. }
  4368. }
  4369. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4370. }
  4371. /**
  4372. * Show info logo
  4373. *
  4374. * @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.
  4375. * @return string Return img tag
  4376. */
  4377. function img_info($titlealt = 'default')
  4378. {
  4379. global $langs;
  4380. if ($titlealt == 'default') {
  4381. $titlealt = $langs->trans('Informations');
  4382. }
  4383. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4384. }
  4385. /**
  4386. * Show warning logo
  4387. *
  4388. * @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.
  4389. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4390. * @param string $morecss Add more CSS
  4391. * @return string Return img tag
  4392. */
  4393. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4394. {
  4395. global $langs;
  4396. if ($titlealt == 'default') {
  4397. $titlealt = $langs->trans('Warning');
  4398. }
  4399. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4400. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4401. }
  4402. /**
  4403. * Show error logo
  4404. *
  4405. * @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.
  4406. * @return string Return img tag
  4407. */
  4408. function img_error($titlealt = 'default')
  4409. {
  4410. global $langs;
  4411. if ($titlealt == 'default') {
  4412. $titlealt = $langs->trans('Error');
  4413. }
  4414. return img_picto($titlealt, 'error.png');
  4415. }
  4416. /**
  4417. * Show next logo
  4418. *
  4419. * @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.
  4420. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4421. * @return string Return img tag
  4422. */
  4423. function img_next($titlealt = 'default', $moreatt = '')
  4424. {
  4425. global $langs;
  4426. if ($titlealt == 'default') {
  4427. $titlealt = $langs->trans('Next');
  4428. }
  4429. //return img_picto($titlealt, 'next.png', $moreatt);
  4430. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4431. }
  4432. /**
  4433. * Show previous logo
  4434. *
  4435. * @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.
  4436. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4437. * @return string Return img tag
  4438. */
  4439. function img_previous($titlealt = 'default', $moreatt = '')
  4440. {
  4441. global $langs;
  4442. if ($titlealt == 'default') {
  4443. $titlealt = $langs->trans('Previous');
  4444. }
  4445. //return img_picto($titlealt, 'previous.png', $moreatt);
  4446. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4447. }
  4448. /**
  4449. * Show down arrow logo
  4450. *
  4451. * @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.
  4452. * @param int $selected Selected
  4453. * @param string $moreclass Add more CSS classes
  4454. * @return string Return img tag
  4455. */
  4456. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4457. {
  4458. global $langs;
  4459. if ($titlealt == 'default') {
  4460. $titlealt = $langs->trans('Down');
  4461. }
  4462. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4463. }
  4464. /**
  4465. * Show top arrow logo
  4466. *
  4467. * @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.
  4468. * @param int $selected Selected
  4469. * @param string $moreclass Add more CSS classes
  4470. * @return string Return img tag
  4471. */
  4472. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4473. {
  4474. global $langs;
  4475. if ($titlealt == 'default') {
  4476. $titlealt = $langs->trans('Up');
  4477. }
  4478. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4479. }
  4480. /**
  4481. * Show left arrow logo
  4482. *
  4483. * @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.
  4484. * @param int $selected Selected
  4485. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4486. * @return string Return img tag
  4487. */
  4488. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4489. {
  4490. global $langs;
  4491. if ($titlealt == 'default') {
  4492. $titlealt = $langs->trans('Left');
  4493. }
  4494. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4495. }
  4496. /**
  4497. * Show right arrow logo
  4498. *
  4499. * @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.
  4500. * @param int $selected Selected
  4501. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4502. * @return string Return img tag
  4503. */
  4504. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4505. {
  4506. global $langs;
  4507. if ($titlealt == 'default') {
  4508. $titlealt = $langs->trans('Right');
  4509. }
  4510. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4511. }
  4512. /**
  4513. * Show tick logo if allowed
  4514. *
  4515. * @param string $allow Allow
  4516. * @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.
  4517. * @return string Return img tag
  4518. */
  4519. function img_allow($allow, $titlealt = 'default')
  4520. {
  4521. global $langs;
  4522. if ($titlealt == 'default') {
  4523. $titlealt = $langs->trans('Active');
  4524. }
  4525. if ($allow == 1) {
  4526. return img_picto($titlealt, 'tick.png');
  4527. }
  4528. return '-';
  4529. }
  4530. /**
  4531. * Return image of a credit card according to its brand name
  4532. *
  4533. * @param string $brand Brand name of credit card
  4534. * @param string $morecss More CSS
  4535. * @return string Return img tag
  4536. */
  4537. function img_credit_card($brand, $morecss = null)
  4538. {
  4539. if (is_null($morecss)) {
  4540. $morecss = 'fa-2x';
  4541. }
  4542. if ($brand == 'visa' || $brand == 'Visa') {
  4543. $brand = 'cc-visa';
  4544. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4545. $brand = 'cc-mastercard';
  4546. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4547. $brand = 'cc-amex';
  4548. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4549. $brand = 'cc-discover';
  4550. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4551. $brand = 'cc-jcb';
  4552. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4553. $brand = 'cc-diners-club';
  4554. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4555. $brand = 'credit-card';
  4556. }
  4557. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4558. }
  4559. /**
  4560. * Show MIME img of a file
  4561. *
  4562. * @param string $file Filename
  4563. * @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.
  4564. * @param string $morecss More css
  4565. * @return string Return img tag
  4566. */
  4567. function img_mime($file, $titlealt = '', $morecss = '')
  4568. {
  4569. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4570. $mimetype = dol_mimetype($file, '', 1);
  4571. $mimeimg = dol_mimetype($file, '', 2);
  4572. $mimefa = dol_mimetype($file, '', 4);
  4573. if (empty($titlealt)) {
  4574. $titlealt = 'Mime type: '.$mimetype;
  4575. }
  4576. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4577. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4578. }
  4579. /**
  4580. * Show search logo
  4581. *
  4582. * @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.
  4583. * @param string $other Add more attributes on img
  4584. * @return string Retourne tag img
  4585. */
  4586. function img_search($titlealt = 'default', $other = '')
  4587. {
  4588. global $conf, $langs;
  4589. if ($titlealt == 'default') {
  4590. $titlealt = $langs->trans('Search');
  4591. }
  4592. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4593. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4594. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4595. return $input;
  4596. }
  4597. /**
  4598. * Show search logo
  4599. *
  4600. * @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.
  4601. * @param string $other Add more attributes on img
  4602. * @return string Retourne tag img
  4603. */
  4604. function img_searchclear($titlealt = 'default', $other = '')
  4605. {
  4606. global $conf, $langs;
  4607. if ($titlealt == 'default') {
  4608. $titlealt = $langs->trans('Search');
  4609. }
  4610. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4611. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4612. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4613. return $input;
  4614. }
  4615. /**
  4616. * Show information for admin users or standard users
  4617. *
  4618. * @param string $text Text info
  4619. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4620. * @param int $nodiv No div
  4621. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4622. * @param string $morecss More CSS ('', 'warning', 'error')
  4623. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4624. * @return string String with info text
  4625. */
  4626. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4627. {
  4628. global $conf, $langs;
  4629. if ($infoonimgalt) {
  4630. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4631. } else {
  4632. if (empty($conf->use_javascript_ajax)) {
  4633. $textfordropdown = '';
  4634. }
  4635. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4636. $result = ($nodiv ? '' : '<div class="'.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  4637. if ($textfordropdown) {
  4638. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4639. $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
  4640. jQuery(document).ready(function() {
  4641. jQuery(".'.$class.'text").click(function() {
  4642. console.log("toggle text");
  4643. jQuery(".'.$class.'").toggle();
  4644. });
  4645. });
  4646. </script>';
  4647. $result = $tmpresult.$result;
  4648. }
  4649. }
  4650. return $result;
  4651. }
  4652. /**
  4653. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4654. * This function must be called when a blocking technical error is encountered.
  4655. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4656. *
  4657. * @param DoliDB|string $db Database handler
  4658. * @param string|string[] $error String or array of errors strings to show
  4659. * @param array $errors Array of errors
  4660. * @return void
  4661. * @see dol_htmloutput_errors()
  4662. */
  4663. function dol_print_error($db = '', $error = '', $errors = null)
  4664. {
  4665. global $conf, $langs, $argv;
  4666. global $dolibarr_main_prod;
  4667. $out = '';
  4668. $syslog = '';
  4669. // If error occurs before the $lang object was loaded
  4670. if (!$langs) {
  4671. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4672. $langs = new Translate('', $conf);
  4673. $langs->load("main");
  4674. }
  4675. // Load translation files required by the error messages
  4676. $langs->loadLangs(array('main', 'errors'));
  4677. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4678. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4679. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4680. $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";
  4681. }
  4682. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4683. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4684. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4685. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4686. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4687. }
  4688. if (function_exists("phpversion")) {
  4689. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4690. }
  4691. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4692. if (function_exists("php_uname")) {
  4693. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4694. }
  4695. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4696. $out .= "<br>\n";
  4697. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4698. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4699. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4700. $out .= "<br>\n";
  4701. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4702. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4703. } else { // Mode CLI
  4704. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4705. $syslog .= "pid=".dol_getmypid();
  4706. }
  4707. if (!empty($conf->modules)) {
  4708. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4709. }
  4710. if (is_object($db)) {
  4711. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4712. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4713. $lastqueryerror = $db->lastqueryerror();
  4714. if (!utf8_check($lastqueryerror)) {
  4715. $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
  4716. }
  4717. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4718. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4719. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4720. $out .= "<br>\n";
  4721. } else { // Mode CLI
  4722. // No dol_escape_htmltag for output, we are in CLI mode
  4723. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4724. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4725. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4726. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4727. }
  4728. $syslog .= ", sql=".$db->lastquery();
  4729. $syslog .= ", db_error=".$db->lasterror();
  4730. }
  4731. if ($error || $errors) {
  4732. $langs->load("errors");
  4733. // Merge all into $errors array
  4734. if (is_array($error) && is_array($errors)) {
  4735. $errors = array_merge($error, $errors);
  4736. } elseif (is_array($error)) {
  4737. $errors = $error;
  4738. } elseif (is_array($errors)) {
  4739. $errors = array_merge(array($error), $errors);
  4740. } else {
  4741. $errors = array_merge(array($error), array($errors));
  4742. }
  4743. foreach ($errors as $msg) {
  4744. if (empty($msg)) {
  4745. continue;
  4746. }
  4747. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4748. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4749. } else // Mode CLI
  4750. {
  4751. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4752. }
  4753. $syslog .= ", msg=".$msg;
  4754. }
  4755. }
  4756. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4757. xdebug_print_function_stack();
  4758. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4759. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4760. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4761. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4762. $out .= "<br>\n";
  4763. }
  4764. // Return a http header with error code if possible
  4765. if (!headers_sent()) {
  4766. if (function_exists('top_httphead')) { // In CLI context, the method does not exists
  4767. top_httphead();
  4768. }
  4769. http_response_code(500);
  4770. }
  4771. if (empty($dolibarr_main_prod)) {
  4772. print $out;
  4773. } else {
  4774. if (empty($langs->defaultlang)) {
  4775. $langs->setDefaultLang();
  4776. }
  4777. $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.
  4778. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4779. 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";
  4780. print $langs->trans("DolibarrHasDetectedError").'. ';
  4781. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4782. define("MAIN_CORE_ERROR", 1);
  4783. }
  4784. dol_syslog("Error ".$syslog, LOG_ERR);
  4785. }
  4786. /**
  4787. * Show a public email and error code to contact if technical error
  4788. *
  4789. * @param string $prefixcode Prefix of public error code
  4790. * @param string $errormessage Complete error message
  4791. * @param array $errormessages Array of error messages
  4792. * @param string $morecss More css
  4793. * @param string $email Email
  4794. * @return void
  4795. */
  4796. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4797. {
  4798. global $langs, $conf;
  4799. if (empty($email)) {
  4800. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4801. }
  4802. $langs->load("errors");
  4803. $now = dol_now();
  4804. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4805. print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
  4806. if ($errormessage) {
  4807. print '<br><br>'.$errormessage;
  4808. }
  4809. if (is_array($errormessages) && count($errormessages)) {
  4810. foreach ($errormessages as $mesgtoshow) {
  4811. print '<br><br>'.$mesgtoshow;
  4812. }
  4813. }
  4814. print '</div></div>';
  4815. }
  4816. /**
  4817. * Show title line of an array
  4818. *
  4819. * @param string $name Label of field
  4820. * @param string $file Url used when we click on sort picto
  4821. * @param string $field Field to use for new sorting
  4822. * @param string $begin ("" by defaut)
  4823. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4824. * @param string $moreattrib Options of attribute td ("" by defaut)
  4825. * @param string $sortfield Current field used to sort
  4826. * @param string $sortorder Current sort order
  4827. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4828. * @param string $tooltip Tooltip
  4829. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4830. * @return void
  4831. */
  4832. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4833. {
  4834. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4835. }
  4836. /**
  4837. * Get title line of an array
  4838. *
  4839. * @param string $name Translation key of field to show or complete HTML string to show
  4840. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4841. * @param string $file Url used when we click on sort picto
  4842. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4843. * @param string $begin ("" by defaut)
  4844. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4845. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  4846. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4847. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4848. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4849. * @param string $disablesortlink 1=Disable sort link
  4850. * @param string $tooltip Tooltip
  4851. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4852. * @return string
  4853. */
  4854. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4855. {
  4856. global $conf, $langs, $form;
  4857. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4858. if ($moreattrib == 'class="right"') {
  4859. $prefix .= 'right '; // For backward compatibility
  4860. }
  4861. $sortorder = strtoupper($sortorder);
  4862. $out = '';
  4863. $sortimg = '';
  4864. $tag = 'th';
  4865. if ($thead == 2) {
  4866. $tag = 'div';
  4867. }
  4868. $tmpsortfield = explode(',', $sortfield);
  4869. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4870. $tmpfield = explode(',', $field);
  4871. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4872. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4873. $prefix = 'wrapcolumntitle '.$prefix;
  4874. }
  4875. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4876. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4877. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4878. $liste_titre = 'liste_titre';
  4879. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4880. $liste_titre = 'liste_titre_sel';
  4881. }
  4882. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4883. //$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)).'"' : '');
  4884. $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4885. $tagstart .= '>';
  4886. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4887. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4888. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4889. $options = preg_replace('/&+/i', '&', $options);
  4890. if (!preg_match('/^&/', $options)) {
  4891. $options = '&'.$options;
  4892. }
  4893. $sortordertouseinlink = '';
  4894. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4895. if (preg_match('/^DESC/i', $sortorder)) {
  4896. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4897. } else { // We reverse the var $sortordertouseinlink
  4898. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4899. }
  4900. } else { // We are on field that is the first current sorting criteria
  4901. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4902. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4903. } else {
  4904. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4905. }
  4906. }
  4907. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4908. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4909. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4910. $out .= '>';
  4911. }
  4912. if ($tooltip) {
  4913. // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
  4914. if (preg_match('/:\w+$/', $tooltip)) {
  4915. $tmptooltip = explode(':', $tooltip);
  4916. } else {
  4917. $tmptooltip = array($tooltip);
  4918. }
  4919. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4920. } else {
  4921. $out .= $langs->trans($name);
  4922. }
  4923. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4924. $out .= '</a>';
  4925. }
  4926. if (empty($thead) && $field) { // If this is a sort field
  4927. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4928. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4929. $options = preg_replace('/&+/i', '&', $options);
  4930. if (!preg_match('/^&/', $options)) {
  4931. $options = '&'.$options;
  4932. }
  4933. if (!$sortorder || ($field1 != $sortfield1)) {
  4934. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4935. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4936. } else {
  4937. if (preg_match('/^DESC/', $sortorder)) {
  4938. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4939. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4940. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  4941. }
  4942. if (preg_match('/^ASC/', $sortorder)) {
  4943. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4944. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4945. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  4946. }
  4947. }
  4948. }
  4949. $tagend = '</'.$tag.'>';
  4950. $out = $tagstart.$sortimg.$out.$tagend;
  4951. return $out;
  4952. }
  4953. /**
  4954. * Show a title.
  4955. *
  4956. * @param string $title Title to show
  4957. * @return void
  4958. * @deprecated Use load_fiche_titre instead
  4959. * @see load_fiche_titre()
  4960. */
  4961. function print_titre($title)
  4962. {
  4963. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4964. print '<div class="titre">'.$title.'</div>';
  4965. }
  4966. /**
  4967. * Show a title with picto
  4968. *
  4969. * @param string $title Title to show
  4970. * @param string $mesg Added message to show on right
  4971. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4972. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4973. * @param int $id To force an id on html objects
  4974. * @return void
  4975. * @deprecated Use print load_fiche_titre instead
  4976. */
  4977. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4978. {
  4979. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4980. }
  4981. /**
  4982. * Load a title with picto
  4983. *
  4984. * @param string $titre Title to show
  4985. * @param string $morehtmlright Added message to show on right
  4986. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4987. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4988. * @param string $id To force an id on html objects
  4989. * @param string $morecssontable More css on table
  4990. * @param string $morehtmlcenter Added message to show on center
  4991. * @return string
  4992. * @see print_barre_liste()
  4993. */
  4994. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4995. {
  4996. global $conf;
  4997. $return = '';
  4998. if ($picto == 'setup') {
  4999. $picto = 'generic';
  5000. }
  5001. $return .= "\n";
  5002. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  5003. $return .= '<tr class="titre">';
  5004. if ($picto) {
  5005. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  5006. }
  5007. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  5008. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  5009. $return .= '</td>';
  5010. if (dol_strlen($morehtmlcenter)) {
  5011. $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5012. }
  5013. if (dol_strlen($morehtmlright)) {
  5014. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
  5015. }
  5016. $return .= '</tr></table>'."\n";
  5017. return $return;
  5018. }
  5019. /**
  5020. * Print a title with navigation controls for pagination
  5021. *
  5022. * @param string $titre Title to show (required)
  5023. * @param int|null $page Numero of page to show in navigation links (required)
  5024. * @param string $file Url of page (required)
  5025. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  5026. * @param string $sortfield Field to sort on ('' by default)
  5027. * @param string $sortorder Order to sort ('' by default)
  5028. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  5029. * @param int $num Number of records found by select with limit+1
  5030. * @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.
  5031. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5032. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5033. * @param string $morehtmlright More html to show (after arrows)
  5034. * @param string $morecss More css to the table
  5035. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  5036. * @param int $hideselectlimit Force to hide select limit
  5037. * @param int $hidenavigation Force to hide the arrows and page for navigation
  5038. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  5039. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  5040. * @return void
  5041. */
  5042. 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 = '')
  5043. {
  5044. global $conf, $langs;
  5045. $savlimit = $limit;
  5046. $savtotalnboflines = $totalnboflines;
  5047. $totalnboflines = abs((int) $totalnboflines);
  5048. $page = (int) $page;
  5049. if ($picto == 'setup') {
  5050. $picto = 'title_setup.png';
  5051. }
  5052. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  5053. $picto = 'title.gif';
  5054. }
  5055. if ($limit < 0) {
  5056. $limit = $conf->liste_limit;
  5057. }
  5058. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  5059. $nextpage = 1;
  5060. } else {
  5061. $nextpage = 0;
  5062. }
  5063. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
  5064. print "\n";
  5065. print "<!-- Begin title -->\n";
  5066. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  5067. // Left
  5068. if ($picto && $titre) {
  5069. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  5070. }
  5071. print '<td class="nobordernopadding valignmiddle col-title">';
  5072. print '<div class="titre inline-block">'.$titre;
  5073. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  5074. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  5075. }
  5076. print '</div></td>';
  5077. // Center
  5078. if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
  5079. print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5080. }
  5081. // Right
  5082. print '<td class="nobordernopadding valignmiddle right col-right">';
  5083. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  5084. if ($sortfield) {
  5085. $options .= "&sortfield=".urlencode($sortfield);
  5086. }
  5087. if ($sortorder) {
  5088. $options .= "&sortorder=".urlencode($sortorder);
  5089. }
  5090. // Show navigation bar
  5091. $pagelist = '';
  5092. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  5093. if ($totalnboflines) { // If we know total nb of lines
  5094. // Define nb of extra page links before and after selected page + ... + first or last
  5095. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  5096. if ($limit > 0) {
  5097. $nbpages = ceil($totalnboflines / $limit);
  5098. } else {
  5099. $nbpages = 1;
  5100. }
  5101. $cpt = ($page - $maxnbofpage);
  5102. if ($cpt < 0) {
  5103. $cpt = 0;
  5104. }
  5105. if ($cpt >= 1) {
  5106. if (empty($pagenavastextinput)) {
  5107. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  5108. if ($cpt > 2) {
  5109. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5110. } elseif ($cpt == 2) {
  5111. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  5112. }
  5113. }
  5114. }
  5115. do {
  5116. if ($pagenavastextinput) {
  5117. if ($cpt == $page) {
  5118. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  5119. $pagelist .= '/';
  5120. }
  5121. } else {
  5122. if ($cpt == $page) {
  5123. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  5124. } else {
  5125. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  5126. }
  5127. }
  5128. $cpt++;
  5129. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  5130. if (empty($pagenavastextinput)) {
  5131. if ($cpt < $nbpages) {
  5132. if ($cpt < $nbpages - 2) {
  5133. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5134. } elseif ($cpt == $nbpages - 2) {
  5135. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  5136. }
  5137. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5138. }
  5139. } else {
  5140. //var_dump($page.' '.$cpt.' '.$nbpages);
  5141. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5142. }
  5143. } else {
  5144. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  5145. }
  5146. }
  5147. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  5148. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow, $hidenavigation); // output the div and ul for previous/last completed with page numbers into $pagelist
  5149. }
  5150. // js to autoselect page field on focus
  5151. if ($pagenavastextinput) {
  5152. print ajax_autoselect('.pageplusone');
  5153. }
  5154. print '</td>';
  5155. print '</tr>';
  5156. print '</table>'."\n";
  5157. // Center
  5158. if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
  5159. print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
  5160. }
  5161. print "<!-- End title -->\n\n";
  5162. }
  5163. /**
  5164. * Function to show navigation arrows into lists
  5165. *
  5166. * @param int $page Number of page
  5167. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  5168. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  5169. * @param integer $nextpage Do we show a next page button
  5170. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  5171. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  5172. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  5173. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  5174. * @param int $hideselectlimit Force to hide select limit
  5175. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  5176. * @param int $hidenavigation Force to hide the switch mode view and the navigation tool (select limit, arrows $betweenarrows and $afterarrows but not $beforearrows)
  5177. * @return void
  5178. */
  5179. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '', $hidenavigation = 0)
  5180. {
  5181. global $conf, $langs;
  5182. print '<div class="pagination"><ul>';
  5183. if ($beforearrows) {
  5184. print '<li class="paginationbeforearrows">';
  5185. print $beforearrows;
  5186. print '</li>';
  5187. }
  5188. if (empty($hidenavigation)) {
  5189. if ((int) $limit > 0 && empty($hideselectlimit)) {
  5190. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
  5191. $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
  5192. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  5193. //$pagesizechoices.=',2:2';
  5194. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  5195. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  5196. }
  5197. print '<li class="pagination">';
  5198. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  5199. $tmpchoice = explode(',', $pagesizechoices);
  5200. $tmpkey = $limit.':'.$limit;
  5201. if (!in_array($tmpkey, $tmpchoice)) {
  5202. $tmpchoice[] = $tmpkey;
  5203. }
  5204. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  5205. if (!in_array($tmpkey, $tmpchoice)) {
  5206. $tmpchoice[] = $tmpkey;
  5207. }
  5208. asort($tmpchoice, SORT_NUMERIC);
  5209. foreach ($tmpchoice as $val) {
  5210. $selected = '';
  5211. $tmp = explode(':', $val);
  5212. $key = $tmp[0];
  5213. $val = $tmp[1];
  5214. if ($key != '' && $val != '') {
  5215. if ((int) $key == (int) $limit) {
  5216. $selected = ' selected="selected"';
  5217. }
  5218. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  5219. }
  5220. }
  5221. print '</select>';
  5222. if ($conf->use_javascript_ajax) {
  5223. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  5224. <script>
  5225. jQuery(document).ready(function () {
  5226. jQuery(".selectlimit").change(function() {
  5227. console.log("Change limit. Send submit");
  5228. $(this).parents(\'form:first\').submit();
  5229. });
  5230. });
  5231. </script>
  5232. ';
  5233. }
  5234. print '</li>';
  5235. }
  5236. if ($page > 0) {
  5237. 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>';
  5238. }
  5239. if ($betweenarrows) {
  5240. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  5241. print $betweenarrows;
  5242. print '<!--</div>-->';
  5243. }
  5244. if ($nextpage > 0) {
  5245. 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>';
  5246. }
  5247. if ($afterarrows) {
  5248. print '<li class="paginationafterarrows">';
  5249. print $afterarrows;
  5250. print '</li>';
  5251. }
  5252. }
  5253. print '</ul></div>'."\n";
  5254. }
  5255. /**
  5256. * Return a string with VAT rate label formated for view output
  5257. * Used into pdf and HTML pages
  5258. *
  5259. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  5260. * @param boolean $addpercent Add a percent % sign in output
  5261. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  5262. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  5263. * @param int $html Used for html output
  5264. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  5265. */
  5266. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
  5267. {
  5268. $morelabel = '';
  5269. if (preg_match('/%/', $rate)) {
  5270. $rate = str_replace('%', '', $rate);
  5271. $addpercent = true;
  5272. }
  5273. $reg = array();
  5274. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  5275. $morelabel = ' ('.$reg[1].')';
  5276. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  5277. $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
  5278. }
  5279. if (preg_match('/\*/', $rate)) {
  5280. $rate = str_replace('*', '', $rate);
  5281. $info_bits |= 1;
  5282. }
  5283. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  5284. if (!preg_match('/\//', $rate)) {
  5285. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  5286. } else {
  5287. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  5288. $ret = $rate.($addpercent ? '%' : '');
  5289. }
  5290. if (($info_bits & 1) && $usestarfornpr >= 0) {
  5291. $ret .= ' *';
  5292. }
  5293. $ret .= $morelabel;
  5294. return $ret;
  5295. }
  5296. /**
  5297. * Function to format a value into an amount for visual output
  5298. * Function used into PDF and HTML pages
  5299. *
  5300. * @param float $amount Amount to format
  5301. * @param integer $form Type of format, HTML or not (not by default)
  5302. * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators.
  5303. * @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.
  5304. * @param int $rounding MINIMUM number of decimal to show: 0=no change, -1=we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  5305. * @param int|string $forcerounding MAXIMUM number of decimal to forcerounding decimal: -1=no change, 'MU' or 'MT' or numeric to round to MU or MT or to a given number of decimal
  5306. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  5307. * @return string String with formated amount
  5308. *
  5309. * @see price2num() Revert function of price
  5310. */
  5311. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  5312. {
  5313. global $langs, $conf;
  5314. // Clean parameters
  5315. if (empty($amount)) {
  5316. $amount = 0; // To have a numeric value if amount not defined or = ''
  5317. }
  5318. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  5319. if ($rounding == -1) {
  5320. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  5321. }
  5322. $nbdecimal = $rounding;
  5323. if ($outlangs === 'none') {
  5324. // Use international separators
  5325. $dec = '.';
  5326. $thousand = '';
  5327. } else {
  5328. // Output separators by default (french)
  5329. $dec = ',';
  5330. $thousand = ' ';
  5331. // If $outlangs not forced, we use use language
  5332. if (!is_object($outlangs)) {
  5333. $outlangs = $langs;
  5334. }
  5335. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5336. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5337. }
  5338. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5339. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5340. }
  5341. if ($thousand == 'None') {
  5342. $thousand = '';
  5343. } elseif ($thousand == 'Space') {
  5344. $thousand = ' ';
  5345. }
  5346. }
  5347. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5348. //print "amount=".$amount."-";
  5349. $amount = str_replace(',', '.', $amount); // should be useless
  5350. //print $amount."-";
  5351. $datas = explode('.', $amount);
  5352. $decpart = isset($datas[1]) ? $datas[1] : '';
  5353. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5354. //print "decpart=".$decpart."<br>";
  5355. $end = '';
  5356. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5357. if (dol_strlen($decpart) > $nbdecimal) {
  5358. $nbdecimal = dol_strlen($decpart);
  5359. }
  5360. // Si on depasse max
  5361. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5362. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5363. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5364. // Si un affichage est tronque, on montre des ...
  5365. $end = '...';
  5366. }
  5367. }
  5368. // If force rounding
  5369. if ((string) $forcerounding != '-1') {
  5370. if ($forcerounding === 'MU') {
  5371. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5372. } elseif ($forcerounding === 'MT') {
  5373. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5374. } elseif ($forcerounding >= 0) {
  5375. $nbdecimal = $forcerounding;
  5376. }
  5377. }
  5378. // Format number
  5379. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5380. if ($form) {
  5381. $output = preg_replace('/\s/', '&nbsp;', $output);
  5382. $output = preg_replace('/\'/', '&#039;', $output);
  5383. }
  5384. // Add symbol of currency if requested
  5385. $cursymbolbefore = $cursymbolafter = '';
  5386. if ($currency_code && is_object($outlangs)) {
  5387. if ($currency_code == 'auto') {
  5388. $currency_code = $conf->currency;
  5389. }
  5390. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC');
  5391. $listoflanguagesbefore = array('nl_NL');
  5392. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5393. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5394. } else {
  5395. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5396. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5397. }
  5398. }
  5399. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5400. return $output;
  5401. }
  5402. /**
  5403. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5404. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5405. * should be roundtext2num().
  5406. *
  5407. * @param string|float $amount Amount to convert/clean or round
  5408. * @param string|int $rounding ''=No rounding
  5409. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5410. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5411. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5412. * 'CU'=Round to Max unit price of foreign currency accuracy
  5413. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5414. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5415. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5416. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5417. * @return string Amount with universal numeric format (Example: '99.99999').
  5418. * If conversion fails to return a numeric, it returns:
  5419. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5420. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5421. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5422. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  5423. *
  5424. * @see price() Opposite function of price2num
  5425. */
  5426. function price2num($amount, $rounding = '', $option = 0)
  5427. {
  5428. global $langs, $conf;
  5429. // Clean parameters
  5430. if (is_null($amount)) {
  5431. $amount = '';
  5432. }
  5433. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5434. // Numbers must be '1234.56'
  5435. // Decimal delimiter for PHP and database SQL requests must be '.'
  5436. $dec = ',';
  5437. $thousand = ' ';
  5438. if (is_null($langs)) { // $langs is not defined, we use english values.
  5439. $dec = '.';
  5440. $thousand = ',';
  5441. } else {
  5442. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5443. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5444. }
  5445. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5446. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5447. }
  5448. }
  5449. if ($thousand == 'None') {
  5450. $thousand = '';
  5451. } elseif ($thousand == 'Space') {
  5452. $thousand = ' ';
  5453. }
  5454. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5455. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5456. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5457. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5458. if (!is_numeric($amount)) {
  5459. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5460. }
  5461. 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
  5462. $amount = str_replace($thousand, '', $amount);
  5463. }
  5464. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5465. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5466. // So if number was already a good number, it is converted into local Dolibarr setup.
  5467. if (is_numeric($amount)) {
  5468. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5469. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5470. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5471. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5472. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5473. }
  5474. //print "QQ".$amount."<br>\n";
  5475. // Now make replace (the main goal of function)
  5476. if ($thousand != ',' && $thousand != '.') {
  5477. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5478. }
  5479. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5480. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5481. $amount = str_replace($dec, '.', $amount);
  5482. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5483. }
  5484. //print ' XX'.$amount.' '.$rounding;
  5485. // Now, $amount is a real PHP float number. We make a rounding if required.
  5486. if ($rounding) {
  5487. $nbofdectoround = '';
  5488. if ($rounding == 'MU') {
  5489. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5490. } elseif ($rounding == 'MT') {
  5491. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5492. } elseif ($rounding == 'MS') {
  5493. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5494. } elseif ($rounding == 'CU') {
  5495. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5496. } elseif ($rounding == 'CT') {
  5497. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5498. } elseif (is_numeric($rounding)) {
  5499. $nbofdectoround = (int) $rounding;
  5500. }
  5501. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5502. if (dol_strlen($nbofdectoround)) {
  5503. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5504. } else {
  5505. return 'ErrorBadParameterProvidedToFunction';
  5506. }
  5507. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5508. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5509. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5510. if (is_numeric($amount)) {
  5511. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5512. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5513. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5514. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5515. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5516. }
  5517. //print "TT".$amount.'<br>';
  5518. // Always make replace because each math function (like round) replace
  5519. // with local values and we want a number that has a SQL string format x.y
  5520. if ($thousand != ',' && $thousand != '.') {
  5521. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5522. }
  5523. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5524. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5525. $amount = str_replace($dec, '.', $amount);
  5526. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5527. }
  5528. return $amount;
  5529. }
  5530. /**
  5531. * Output a dimension with best unit
  5532. *
  5533. * @param float $dimension Dimension
  5534. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5535. * @param string $type 'weight', 'volume', ...
  5536. * @param Translate $outputlangs Translate language object
  5537. * @param int $round -1 = non rounding, x = number of decimal
  5538. * @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)
  5539. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5540. * @return string String to show dimensions
  5541. */
  5542. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5543. {
  5544. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5545. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5546. $dimension = $dimension * 1000000;
  5547. $unit = $unit - 6;
  5548. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5549. $dimension = $dimension * 1000;
  5550. $unit = $unit - 3;
  5551. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5552. $dimension = $dimension / 1000000;
  5553. $unit = $unit + 6;
  5554. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5555. $dimension = $dimension / 1000;
  5556. $unit = $unit + 3;
  5557. }
  5558. // Special case when we want output unit into pound or ounce
  5559. /* TODO
  5560. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5561. {
  5562. $dimension = // convert dimension from standard unit into ounce or pound
  5563. $unit = $forceunitoutput;
  5564. }
  5565. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5566. {
  5567. $dimension = // convert dimension from standard unit into ounce or pound
  5568. $unit = $forceunitoutput;
  5569. }*/
  5570. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5571. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5572. return $ret;
  5573. }
  5574. /**
  5575. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5576. * Note: This function applies same rules than get_default_tva
  5577. *
  5578. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5579. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5580. * @param Societe $thirdparty_buyer Object of buying third party
  5581. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5582. * @param int $vatnpr If vat rate is NPR or not
  5583. * @return mixed 0 if not found, localtax rate if found
  5584. * @see get_default_tva()
  5585. */
  5586. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5587. {
  5588. global $db, $conf, $mysoc;
  5589. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5590. $thirdparty_seller = $mysoc;
  5591. }
  5592. 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);
  5593. $vatratecleaned = $vatrate;
  5594. $reg = array();
  5595. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5596. $vatratecleaned = trim($reg[1]);
  5597. $vatratecode = $reg[2];
  5598. }
  5599. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5600. {
  5601. return 0;
  5602. }*/
  5603. // Some test to guess with no need to make database access
  5604. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5605. if ($local == 1) {
  5606. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5607. return 0;
  5608. }
  5609. if ($thirdparty_seller->id == $mysoc->id) {
  5610. if (!$thirdparty_buyer->localtax1_assuj) {
  5611. return 0;
  5612. }
  5613. } else {
  5614. if (!$thirdparty_seller->localtax1_assuj) {
  5615. return 0;
  5616. }
  5617. }
  5618. }
  5619. if ($local == 2) {
  5620. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5621. if (!$mysoc->localtax2_assuj) {
  5622. return 0; // If main vat is 0, IRPF may be different than 0.
  5623. }
  5624. if ($thirdparty_seller->id == $mysoc->id) {
  5625. if (!$thirdparty_buyer->localtax2_assuj) {
  5626. return 0;
  5627. }
  5628. } else {
  5629. if (!$thirdparty_seller->localtax2_assuj) {
  5630. return 0;
  5631. }
  5632. }
  5633. }
  5634. } else {
  5635. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5636. return 0;
  5637. }
  5638. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5639. return 0;
  5640. }
  5641. }
  5642. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5643. if (in_array($mysoc->country_code, array('ES'))) {
  5644. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5645. }
  5646. // Search local taxes
  5647. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5648. if ($local == 1) {
  5649. if ($thirdparty_seller != $mysoc) {
  5650. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5651. return $thirdparty_seller->localtax1_value;
  5652. }
  5653. } else { // i am the seller
  5654. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5655. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5656. }
  5657. }
  5658. }
  5659. if ($local == 2) {
  5660. if ($thirdparty_seller != $mysoc) {
  5661. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5662. // TODO We should also return value defined on thirdparty only if defined
  5663. return $thirdparty_seller->localtax2_value;
  5664. }
  5665. } else { // i am the seller
  5666. if (in_array($mysoc->country_code, array('ES'))) {
  5667. return $thirdparty_buyer->localtax2_value;
  5668. } else {
  5669. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5670. }
  5671. }
  5672. }
  5673. }
  5674. // By default, search value of local tax on line of common tax
  5675. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5676. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5677. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5678. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5679. if (!empty($vatratecode)) {
  5680. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5681. } else {
  5682. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5683. }
  5684. $resql = $db->query($sql);
  5685. if ($resql) {
  5686. $obj = $db->fetch_object($resql);
  5687. if ($obj) {
  5688. if ($local == 1) {
  5689. return $obj->localtax1;
  5690. } elseif ($local == 2) {
  5691. return $obj->localtax2;
  5692. }
  5693. }
  5694. }
  5695. return 0;
  5696. }
  5697. /**
  5698. * Return true if LocalTax (1 or 2) is unique.
  5699. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5700. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5701. *
  5702. * @param int $local Local tax to test (1 or 2)
  5703. * @return boolean True if LocalTax have multiple values, False if not
  5704. */
  5705. function isOnlyOneLocalTax($local)
  5706. {
  5707. $tax = get_localtax_by_third($local);
  5708. $valors = explode(":", $tax);
  5709. if (count($valors) > 1) {
  5710. return false;
  5711. } else {
  5712. return true;
  5713. }
  5714. }
  5715. /**
  5716. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5717. *
  5718. * @param int $local LocalTax to get
  5719. * @return string Values of localtax (Can be '20', '-19:-15:-9') or 'Error'
  5720. */
  5721. function get_localtax_by_third($local)
  5722. {
  5723. global $db, $mysoc;
  5724. $sql = " SELECT t.localtax".$local." as localtax";
  5725. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
  5726. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux = (";
  5727. $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";
  5728. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1)";
  5729. $sql .= " AND t.localtax".$local."_type <> '0'";
  5730. $sql .= " ORDER BY t.rowid DESC";
  5731. $resql = $db->query($sql);
  5732. if ($resql) {
  5733. $obj = $db->fetch_object($resql);
  5734. if ($obj) {
  5735. return $obj->localtax;
  5736. } else {
  5737. return '0';
  5738. }
  5739. }
  5740. return 'Error';
  5741. }
  5742. /**
  5743. * Get tax (VAT) main information from Id.
  5744. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5745. *
  5746. * @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.
  5747. * @param Societe $buyer Company object
  5748. * @param Societe $seller Company object
  5749. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5750. * @return array array('rowid'=> , 'code'=> ...)
  5751. * @see getLocalTaxesFromRate()
  5752. */
  5753. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5754. {
  5755. global $db, $mysoc;
  5756. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5757. // Search local taxes
  5758. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5759. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5760. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5761. if ($firstparamisid) {
  5762. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5763. } else {
  5764. $vatratecleaned = $vatrate;
  5765. $vatratecode = '';
  5766. $reg = array();
  5767. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5768. $vatratecleaned = $reg[1];
  5769. $vatratecode = $reg[2];
  5770. }
  5771. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5772. /*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 ??
  5773. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5774. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5775. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5776. if ($vatratecode) {
  5777. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5778. }
  5779. }
  5780. $resql = $db->query($sql);
  5781. if ($resql) {
  5782. $obj = $db->fetch_object($resql);
  5783. if ($obj) {
  5784. return array(
  5785. 'rowid'=>$obj->rowid,
  5786. 'code'=>$obj->code,
  5787. 'rate'=>$obj->rate,
  5788. 'localtax1'=>$obj->localtax1,
  5789. 'localtax1_type'=>$obj->localtax1_type,
  5790. 'localtax2'=>$obj->localtax2,
  5791. 'localtax2_type'=>$obj->localtax2_type,
  5792. 'npr'=>$obj->npr,
  5793. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5794. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5795. );
  5796. } else {
  5797. return array();
  5798. }
  5799. } else {
  5800. dol_print_error($db);
  5801. }
  5802. return array();
  5803. }
  5804. /**
  5805. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5806. * This does not take into account the seller setup if subject to vat or not, only country.
  5807. *
  5808. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5809. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5810. * provide the selected value to the function calcul_price_total.
  5811. *
  5812. * @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.
  5813. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5814. * @param Societe $buyer Company object
  5815. * @param Societe $seller Company object
  5816. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5817. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5818. * @see getTaxesFromId()
  5819. */
  5820. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5821. {
  5822. global $db, $mysoc;
  5823. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5824. // Search local taxes
  5825. $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";
  5826. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5827. if ($firstparamisid) {
  5828. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5829. } else {
  5830. $vatratecleaned = $vatrate;
  5831. $vatratecode = '';
  5832. $reg = array();
  5833. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5834. $vatratecleaned = $reg[1];
  5835. $vatratecode = $reg[2];
  5836. }
  5837. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5838. if (!empty($mysoc) && $mysoc->country_code == 'ES') {
  5839. $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
  5840. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'"; // local tax in spain use the buyer country ??
  5841. } else {
  5842. $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
  5843. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'";
  5844. }
  5845. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5846. if ($vatratecode) {
  5847. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5848. }
  5849. }
  5850. $resql = $db->query($sql);
  5851. if ($resql) {
  5852. $obj = $db->fetch_object($resql);
  5853. if ($obj) {
  5854. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5855. if ($local == 1) {
  5856. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5857. } elseif ($local == 2) {
  5858. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5859. } else {
  5860. 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);
  5861. }
  5862. }
  5863. }
  5864. return array();
  5865. }
  5866. /**
  5867. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5868. * Function called by get_default_tva().
  5869. *
  5870. * @param int $idprod Id of product or 0 if not a predefined product
  5871. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5872. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5873. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5874. * @see get_product_localtax_for_country()
  5875. */
  5876. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5877. {
  5878. global $db, $conf, $mysoc;
  5879. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5880. $ret = 0;
  5881. $found = 0;
  5882. if ($idprod > 0) {
  5883. // Load product
  5884. $product = new Product($db);
  5885. $product->fetch($idprod);
  5886. if ($mysoc->country_code == $thirdpartytouse->country_code) {
  5887. // If country to consider is ours
  5888. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5889. $result = $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5890. if ($result > 0) {
  5891. $ret = $product->vatrate_supplier;
  5892. if ($product->default_vat_code_supplier) {
  5893. $ret .= ' ('.$product->default_vat_code_supplier.')';
  5894. }
  5895. $found = 1;
  5896. }
  5897. }
  5898. if (!$found) {
  5899. $ret = $product->tva_tx; // Default sales vat of product
  5900. if ($product->default_vat_code) {
  5901. $ret .= ' ('.$product->default_vat_code.')';
  5902. }
  5903. $found = 1;
  5904. }
  5905. } else {
  5906. // TODO Read default product vat according to product and another countrycode.
  5907. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5908. }
  5909. }
  5910. if (!$found) {
  5911. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5912. // If vat of product for the country not found or not defined, we return the first rate found (sorting on use_default, then on higher vat of country).
  5913. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5914. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5915. $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
  5916. $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5917. $sql .= $db->plimit(1);
  5918. $resql = $db->query($sql);
  5919. if ($resql) {
  5920. $obj = $db->fetch_object($resql);
  5921. if ($obj) {
  5922. $ret = $obj->vat_rate;
  5923. if ($obj->default_vat_code) {
  5924. $ret .= ' ('.$obj->default_vat_code.')';
  5925. }
  5926. }
  5927. $db->free($resql);
  5928. } else {
  5929. dol_print_error($db);
  5930. }
  5931. } else {
  5932. // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
  5933. // '1.23'
  5934. // or '1.23 (CODE)'
  5935. $defaulttx = '';
  5936. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5937. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5938. }
  5939. /*if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5940. $defaultcode = $reg[1];
  5941. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5942. }*/
  5943. $ret = $defaulttx;
  5944. }
  5945. }
  5946. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5947. return $ret;
  5948. }
  5949. /**
  5950. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5951. *
  5952. * @param int $idprod Id of product
  5953. * @param int $local 1 for localtax1, 2 for localtax 2
  5954. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5955. * @return int <0 if KO, Vat rate if OK
  5956. * @see get_product_vat_for_country()
  5957. */
  5958. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5959. {
  5960. global $db, $mysoc;
  5961. if (!class_exists('Product')) {
  5962. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5963. }
  5964. $ret = 0;
  5965. $found = 0;
  5966. if ($idprod > 0) {
  5967. // Load product
  5968. $product = new Product($db);
  5969. $result = $product->fetch($idprod);
  5970. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5971. /* Not defined yet, so we don't use this
  5972. if ($local==1) $ret=$product->localtax1_tx;
  5973. elseif ($local==2) $ret=$product->localtax2_tx;
  5974. $found=1;
  5975. */
  5976. } else {
  5977. // TODO Read default product vat according to product and another countrycode.
  5978. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5979. }
  5980. }
  5981. if (!$found) {
  5982. // If vat of product for the country not found or not defined, we return higher vat of country.
  5983. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5984. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5985. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5986. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5987. $sql .= $db->plimit(1);
  5988. $resql = $db->query($sql);
  5989. if ($resql) {
  5990. $obj = $db->fetch_object($resql);
  5991. if ($obj) {
  5992. if ($local == 1) {
  5993. $ret = $obj->localtax1;
  5994. } elseif ($local == 2) {
  5995. $ret = $obj->localtax2;
  5996. }
  5997. }
  5998. } else {
  5999. dol_print_error($db);
  6000. }
  6001. }
  6002. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  6003. return $ret;
  6004. }
  6005. /**
  6006. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  6007. * VATRULE 1: If seller does not use VAT, default VAT is 0. End of rule.
  6008. * VATRULE 2: If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6009. * VATRULE 3: If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  6010. * VATRULE 4: If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6011. * VATRULE 5: If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6012. * VATRULE 6: Otherwise the VAT proposed by default=0. End of rule.
  6013. *
  6014. * @param Societe $thirdparty_seller Objet societe vendeuse
  6015. * @param Societe $thirdparty_buyer Objet societe acheteuse
  6016. * @param int $idprod Id product
  6017. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  6018. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  6019. * @see get_default_npr(), get_default_localtax()
  6020. */
  6021. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6022. {
  6023. global $conf;
  6024. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  6025. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  6026. $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;
  6027. $seller_country_code = $thirdparty_seller->country_code;
  6028. $seller_in_cee = isInEEC($thirdparty_seller);
  6029. $buyer_country_code = $thirdparty_buyer->country_code;
  6030. $buyer_in_cee = isInEEC($thirdparty_buyer);
  6031. 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 : ''));
  6032. // 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)
  6033. // we use the buyer VAT.
  6034. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  6035. if ($seller_in_cee && $buyer_in_cee) {
  6036. $isacompany = $thirdparty_buyer->isACompany();
  6037. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6038. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6039. if (!isValidVATID($thirdparty_buyer)) {
  6040. $isacompany = 0;
  6041. }
  6042. }
  6043. if (!$isacompany) {
  6044. //print 'VATRULE 0';
  6045. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  6046. }
  6047. }
  6048. }
  6049. // If seller does not use VAT, default VAT is 0. End of rule.
  6050. if (!$seller_use_vat) {
  6051. //print 'VATRULE 1';
  6052. return 0;
  6053. }
  6054. // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6055. if (($seller_country_code == $buyer_country_code)
  6056. || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  6057. //print 'VATRULE 2';
  6058. $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6059. if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
  6060. // Special case for india.
  6061. //print 'VATRULE 2b';
  6062. $reg = array();
  6063. if (preg_match('/C+S-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
  6064. // we must revert the C+S into I
  6065. $tmpvat = str_replace("C+S", "I", $tmpvat);
  6066. } elseif (preg_match('/I-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
  6067. // we must revert the I into C+S
  6068. $tmpvat = str_replace("I", "C+S", $tmpvat);
  6069. }
  6070. }
  6071. return $tmpvat;
  6072. }
  6073. // If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  6074. // 'VATRULE 3' - Not supported
  6075. // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6076. // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6077. if (($seller_in_cee && $buyer_in_cee)) {
  6078. $isacompany = $thirdparty_buyer->isACompany();
  6079. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6080. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6081. if (!isValidVATID($thirdparty_buyer)) {
  6082. $isacompany = 0;
  6083. }
  6084. }
  6085. if (!$isacompany) {
  6086. //print 'VATRULE 4';
  6087. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6088. } else {
  6089. //print 'VATRULE 5';
  6090. return 0;
  6091. }
  6092. }
  6093. // If (seller in the European Community and buyer outside the European Community and private buyer) then VAT by default = VAT of the product sold. End of rule
  6094. // I don't see any use case that need this rule.
  6095. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  6096. $isacompany = $thirdparty_buyer->isACompany();
  6097. if (!$isacompany) {
  6098. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6099. //print 'VATRULE extra';
  6100. }
  6101. }
  6102. // Otherwise the VAT proposed by default=0. End of rule.
  6103. // Rem: This means that at least one of the 2 is outside the European Community and the country differs
  6104. //print 'VATRULE 6';
  6105. return 0;
  6106. }
  6107. /**
  6108. * Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
  6109. *
  6110. * @param Societe $thirdparty_seller Thirdparty seller
  6111. * @param Societe $thirdparty_buyer Thirdparty buyer
  6112. * @param int $idprod Id product
  6113. * @param int $idprodfournprice Id supplier price for product
  6114. * @return float 0 or 1
  6115. * @see get_default_tva(), get_default_localtax()
  6116. */
  6117. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6118. {
  6119. global $db;
  6120. if ($idprodfournprice > 0) {
  6121. if (!class_exists('ProductFournisseur')) {
  6122. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6123. }
  6124. $prodprice = new ProductFournisseur($db);
  6125. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  6126. return $prodprice->fourn_tva_npr;
  6127. } elseif ($idprod > 0) {
  6128. if (!class_exists('Product')) {
  6129. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6130. }
  6131. $prod = new Product($db);
  6132. $prod->fetch($idprod);
  6133. return $prod->tva_npr;
  6134. }
  6135. return 0;
  6136. }
  6137. /**
  6138. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  6139. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  6140. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  6141. * Sinon TVA proposee par defaut=0. Fin de regle.
  6142. *
  6143. * @param Societe $thirdparty_seller Thirdparty seller
  6144. * @param Societe $thirdparty_buyer Thirdparty buyer
  6145. * @param int $local Localtax to process (1 or 2)
  6146. * @param int $idprod Id product
  6147. * @return integer localtax, -1 si ne peut etre determine
  6148. * @see get_default_tva(), get_default_npr()
  6149. */
  6150. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  6151. {
  6152. global $mysoc;
  6153. if (!is_object($thirdparty_seller)) {
  6154. return -1;
  6155. }
  6156. if (!is_object($thirdparty_buyer)) {
  6157. return -1;
  6158. }
  6159. if ($local == 1) { // Localtax 1
  6160. if ($mysoc->country_code == 'ES') {
  6161. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  6162. return 0;
  6163. }
  6164. } else {
  6165. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  6166. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  6167. return 0;
  6168. }
  6169. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  6170. return 0;
  6171. }
  6172. }
  6173. } elseif ($local == 2) { //I Localtax 2
  6174. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  6175. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  6176. return 0;
  6177. }
  6178. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  6179. return 0;
  6180. }
  6181. }
  6182. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  6183. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  6184. }
  6185. return 0;
  6186. }
  6187. /**
  6188. * Return yes or no in current language
  6189. *
  6190. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  6191. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  6192. * @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.
  6193. * @return string HTML string
  6194. */
  6195. function yn($yesno, $case = 1, $color = 0)
  6196. {
  6197. global $langs;
  6198. $result = 'unknown';
  6199. $classname = '';
  6200. if ($yesno == 1 || (isset($yesno) && (strtolower($yesno) == 'yes' || strtolower($yesno) == 'true'))) { // A mettre avant test sur no a cause du == 0
  6201. $result = $langs->trans('yes');
  6202. if ($case == 1 || $case == 3) {
  6203. $result = $langs->trans("Yes");
  6204. }
  6205. if ($case == 2) {
  6206. $result = '<input type="checkbox" value="1" checked disabled>';
  6207. }
  6208. if ($case == 3) {
  6209. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  6210. }
  6211. $classname = 'ok';
  6212. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  6213. $result = $langs->trans("no");
  6214. if ($case == 1 || $case == 3) {
  6215. $result = $langs->trans("No");
  6216. }
  6217. if ($case == 2) {
  6218. $result = '<input type="checkbox" value="0" disabled>';
  6219. }
  6220. if ($case == 3) {
  6221. $result = '<input type="checkbox" value="0" disabled> '.$result;
  6222. }
  6223. if ($color == 2) {
  6224. $classname = 'ok';
  6225. } else {
  6226. $classname = 'error';
  6227. }
  6228. }
  6229. if ($color) {
  6230. return '<span class="'.$classname.'">'.$result.'</span>';
  6231. }
  6232. return $result;
  6233. }
  6234. /**
  6235. * Return a path to have a the directory according to object where files are stored.
  6236. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  6237. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  6238. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  6239. * 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/"
  6240. *
  6241. * @param string|int $num Id of object (deprecated, $object will be used in future)
  6242. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  6243. * @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)
  6244. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  6245. * @param Object $object Object to use to get ref to forge the path.
  6246. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  6247. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  6248. */
  6249. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  6250. {
  6251. global $conf;
  6252. if (empty($modulepart) && !empty($object->module)) {
  6253. $modulepart = $object->module;
  6254. }
  6255. $path = '';
  6256. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  6257. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  6258. $arrayforoldpath[] = 'product';
  6259. }
  6260. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  6261. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  6262. if (empty($alpha)) {
  6263. $num = preg_replace('/([^0-9])/i', '', $num);
  6264. } else {
  6265. $num = preg_replace('/^.*\-/i', '', $num);
  6266. }
  6267. $num = substr("000".$num, -$level);
  6268. if ($level == 1) {
  6269. $path = substr($num, 0, 1);
  6270. }
  6271. if ($level == 2) {
  6272. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  6273. }
  6274. if ($level == 3) {
  6275. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  6276. }
  6277. } else {
  6278. // We will enhance here a common way of forging path for document storage.
  6279. // In a future, we may distribute directories on several levels depending on setup and object.
  6280. // Here, $object->id, $object->ref and $modulepart are required.
  6281. //var_dump($modulepart);
  6282. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  6283. }
  6284. if (empty($withoutslash) && !empty($path)) {
  6285. $path .= '/';
  6286. }
  6287. return $path;
  6288. }
  6289. /**
  6290. * Creation of a directory (this can create recursive subdir)
  6291. *
  6292. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  6293. * @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)
  6294. * @param string $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  6295. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  6296. */
  6297. function dol_mkdir($dir, $dataroot = '', $newmask = '')
  6298. {
  6299. global $conf;
  6300. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  6301. $dir_osencoded = dol_osencode($dir);
  6302. if (@is_dir($dir_osencoded)) {
  6303. return 0;
  6304. }
  6305. $nberr = 0;
  6306. $nbcreated = 0;
  6307. $ccdir = '';
  6308. if (!empty($dataroot)) {
  6309. // Remove data root from loop
  6310. $dir = str_replace($dataroot.'/', '', $dir);
  6311. $ccdir = $dataroot.'/';
  6312. }
  6313. $cdir = explode("/", $dir);
  6314. $num = count($cdir);
  6315. for ($i = 0; $i < $num; $i++) {
  6316. if ($i > 0) {
  6317. $ccdir .= '/'.$cdir[$i];
  6318. } else {
  6319. $ccdir .= $cdir[$i];
  6320. }
  6321. if (preg_match("/^.:$/", $ccdir, $regs)) {
  6322. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  6323. }
  6324. // Attention, le is_dir() peut echouer bien que le rep existe.
  6325. // (ex selon config de open_basedir)
  6326. if ($ccdir) {
  6327. $ccdir_osencoded = dol_osencode($ccdir);
  6328. if (!@is_dir($ccdir_osencoded)) {
  6329. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  6330. umask(0);
  6331. $dirmaskdec = octdec((string) $newmask);
  6332. if (empty($newmask)) {
  6333. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  6334. }
  6335. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  6336. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  6337. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  6338. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  6339. $nberr++;
  6340. } else {
  6341. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  6342. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  6343. $nbcreated++;
  6344. }
  6345. } else {
  6346. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  6347. }
  6348. }
  6349. }
  6350. return ($nberr ? -$nberr : $nbcreated);
  6351. }
  6352. /**
  6353. * Change mod of a file
  6354. *
  6355. * @param string $filepath Full file path
  6356. * @param string $newmask Force new mask. For example '0644'
  6357. * @return void
  6358. */
  6359. function dolChmod($filepath, $newmask = '')
  6360. {
  6361. global $conf;
  6362. if (!empty($newmask)) {
  6363. @chmod($filepath, octdec($newmask));
  6364. } elseif (!empty($conf->global->MAIN_UMASK)) {
  6365. @chmod($filepath, octdec($conf->global->MAIN_UMASK));
  6366. }
  6367. }
  6368. /**
  6369. * Return picto saying a field is required
  6370. *
  6371. * @return string Chaine avec picto obligatoire
  6372. */
  6373. function picto_required()
  6374. {
  6375. return '<span class="fieldrequired">*</span>';
  6376. }
  6377. /**
  6378. * Clean a string from all HTML tags and entities.
  6379. * This function differs from strip_tags because:
  6380. * - <br> are replaced with \n if removelinefeed=0 or 1
  6381. * - if entities are found, they are decoded BEFORE the strip
  6382. * - you can decide to convert line feed into a space
  6383. *
  6384. * @param string $stringtoclean String to clean
  6385. * @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..."
  6386. * @param string $pagecodeto Encoding of input/output string
  6387. * @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')
  6388. * @param integer $removedoublespaces Replace double space into one space
  6389. * @return string String cleaned
  6390. *
  6391. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6392. */
  6393. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6394. {
  6395. if (is_null($stringtoclean)) {
  6396. return '';
  6397. }
  6398. if ($removelinefeed == 2) {
  6399. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6400. }
  6401. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6402. // 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)
  6403. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6404. $temp = str_replace('< ', '__ltspace__', $temp);
  6405. if ($strip_tags) {
  6406. $temp = strip_tags($temp);
  6407. } else {
  6408. // 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).
  6409. $pattern = "/<[^<>]+>/";
  6410. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6411. // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6412. // pass 2 - $temp after pass 2: 0000-021
  6413. $tempbis = $temp;
  6414. do {
  6415. $temp = $tempbis;
  6416. $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6417. $tempbis = preg_replace($pattern, '', $tempbis);
  6418. //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
  6419. } while ($tempbis != $temp);
  6420. $temp = $tempbis;
  6421. // Remove '<' into remaining, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
  6422. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6423. }
  6424. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6425. // Remove also carriage returns
  6426. if ($removelinefeed == 1) {
  6427. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6428. }
  6429. // And double quotes
  6430. if ($removedoublespaces) {
  6431. while (strpos($temp, " ")) {
  6432. $temp = str_replace(" ", " ", $temp);
  6433. }
  6434. }
  6435. $temp = str_replace('__ltspace__', '< ', $temp);
  6436. return trim($temp);
  6437. }
  6438. /**
  6439. * Clean a string to keep only desirable HTML tags.
  6440. * WARNING: This also clean HTML comments (because they can be used to obfuscate tag name).
  6441. *
  6442. * @param string $stringtoclean String to clean
  6443. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6444. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6445. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6446. * @param int $allowiframe Allow iframe tags.
  6447. * @param array $allowed_tags List of allowed tags to replace the default list
  6448. * @param int $allowlink Allow link tags.
  6449. * @return string String cleaned
  6450. *
  6451. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6452. */
  6453. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0)
  6454. {
  6455. if (empty($allowed_tags)) {
  6456. $allowed_tags = array(
  6457. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li",
  6458. "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"
  6459. );
  6460. }
  6461. $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6462. if ($allowiframe) {
  6463. if (!in_array('iframe', $allowed_tags)) {
  6464. $allowed_tags[] = "iframe";
  6465. }
  6466. }
  6467. if ($allowlink) {
  6468. if (!in_array('link', $allowed_tags)) {
  6469. $allowed_tags[] = "link";
  6470. }
  6471. }
  6472. $allowed_tags_string = join("><", $allowed_tags);
  6473. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6474. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6475. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6476. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6477. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6478. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6479. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6480. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </>, so may changes string obfuscated with </> that pass the injection detection into a harmfull string
  6481. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6482. $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
  6483. }
  6484. if ($removeclassattribute) { // Clean for remaining html tags
  6485. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6486. }
  6487. // Remove 'javascript:' that we should not find into a text with
  6488. // 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)).
  6489. if ($cleanalsojavascript) {
  6490. $temp = preg_replace('/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t\s*:/i', '', $temp);
  6491. }
  6492. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6493. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6494. return $temp;
  6495. }
  6496. /**
  6497. * Clean a string from some undesirable HTML tags.
  6498. * Note: Complementary to dol_string_onlythesehtmltags().
  6499. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6500. *
  6501. * @param string $stringtoclean String to clean
  6502. * @param array $allowed_attributes Array of tags not allowed
  6503. * @return string String cleaned
  6504. *
  6505. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6506. */
  6507. 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"))
  6508. {
  6509. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6510. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6511. $dom = new DOMDocument(null, 'UTF-8');
  6512. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6513. if (is_object($dom)) {
  6514. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6515. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6516. //var_dump($attrs->item($ii));
  6517. if (!empty($attrs->item($ii)->name)) {
  6518. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6519. // Delete attribute if not into allowed_attributes
  6520. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6521. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6522. // If attribute is 'style'
  6523. $valuetoclean = $attrs->item($ii)->value;
  6524. if (isset($valuetoclean)) {
  6525. do {
  6526. $oldvaluetoclean = $valuetoclean;
  6527. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6528. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6529. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6530. $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
  6531. $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
  6532. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
  6533. }
  6534. // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
  6535. $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
  6536. $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
  6537. } while ($oldvaluetoclean != $valuetoclean);
  6538. }
  6539. $attrs->item($ii)->value = $valuetoclean;
  6540. }
  6541. }
  6542. }
  6543. }
  6544. }
  6545. $return = $dom->saveHTML();
  6546. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6547. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6548. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6549. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6550. return trim($return);
  6551. } else {
  6552. return $stringtoclean;
  6553. }
  6554. }
  6555. /**
  6556. * Clean a string from some undesirable HTML tags.
  6557. * Note. Not as secured as dol_string_onlythesehtmltags().
  6558. *
  6559. * @param string $stringtoclean String to clean
  6560. * @param array $disallowed_tags Array of tags not allowed
  6561. * @param string $cleanalsosomestyles Clean also some tags
  6562. * @return string String cleaned
  6563. *
  6564. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6565. */
  6566. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6567. {
  6568. $temp = $stringtoclean;
  6569. foreach ($disallowed_tags as $tagtoremove) {
  6570. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6571. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6572. }
  6573. if ($cleanalsosomestyles) {
  6574. $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
  6575. }
  6576. return $temp;
  6577. }
  6578. /**
  6579. * Return first line of text. Cut will depends if content is HTML or not.
  6580. *
  6581. * @param string $text Input text
  6582. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6583. * @param string $charset Charset of $text string (UTF-8 by default)
  6584. * @return string Output text
  6585. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6586. */
  6587. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6588. {
  6589. if ($nboflines == 1) {
  6590. if (dol_textishtml($text)) {
  6591. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6592. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6593. } else {
  6594. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6595. }
  6596. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  6597. } else {
  6598. $ishtml = 0;
  6599. if (dol_textishtml($text)) {
  6600. $text = preg_replace('/\n/', '', $text);
  6601. $ishtml = 1;
  6602. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6603. } else {
  6604. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6605. }
  6606. $text = strtr($text, $repTable);
  6607. if ($charset == 'UTF-8') {
  6608. $pattern = '/(<br[^>]*>)/Uu';
  6609. } else {
  6610. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6611. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6612. }
  6613. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6614. $firstline = '';
  6615. $i = 0;
  6616. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  6617. while (($i < $nba) && ($i < ($nboflines * 2))) {
  6618. if ($i % 2 == 0) {
  6619. $firstline .= $a[$i];
  6620. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  6621. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6622. }
  6623. $i++;
  6624. }
  6625. unset($a);
  6626. return $firstline.(($i < $nba) ? '...' : '');
  6627. }
  6628. }
  6629. /**
  6630. * Replace CRLF in string with a HTML BR tag.
  6631. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have
  6632. * encoded the special chars of stringtoencode into HTML before with dol_htmlentitiesbr().
  6633. *
  6634. * @param string $stringtoencode String to encode
  6635. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6636. * @param bool $forxml false=Use <br>, true=Use <br />
  6637. * @return string String encoded
  6638. * @see dol_nboflines(), dolGetFirstLineOfText()
  6639. */
  6640. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6641. {
  6642. if (is_null($stringtoencode)) {
  6643. return '';
  6644. }
  6645. if (!$nl2brmode) {
  6646. return nl2br($stringtoencode, $forxml);
  6647. } else {
  6648. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6649. return $ret;
  6650. }
  6651. }
  6652. /**
  6653. * Sanitize a HTML to remove js and dangerous content
  6654. *
  6655. * @param string $stringtoencode String to encode
  6656. * @param int $nouseofiframesandbox Allow use of option MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS for html sanitizing
  6657. * @param string $check 'restricthtmlnolink' or 'restricthtml' or 'restricthtmlallowunvalid'
  6658. * @return string HTML sanitized
  6659. */
  6660. function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
  6661. {
  6662. global $conf;
  6663. if (empty($nouseofiframesandbox) && !empty($conf->global->MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS)) {
  6664. // TODO using sandbox on inline html content is not possible yet with current browsers
  6665. //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
  6666. //$s .= $stringtoencode;
  6667. //$s .= '</body></html></iframe>';
  6668. return $stringtoencode;
  6669. } else {
  6670. $out = $stringtoencode;
  6671. do {
  6672. $oldstringtoclean = $out;
  6673. libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
  6674. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  6675. try {
  6676. $dom = new DOMDocument;
  6677. // Add a trick to solve pb with text without parent tag
  6678. // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
  6679. // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
  6680. $out = '<div class="tricktoremove">'.$out.'</div>';
  6681. $dom->loadHTML($out, LIBXML_HTML_NODEFDTD|LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6682. $out = trim($dom->saveHTML());
  6683. // Remove the trick added to solve pb with text without parent tag
  6684. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  6685. $out = preg_replace('/<\/div>$/', '', $out);
  6686. } catch (Exception $e) {
  6687. // If error, invalid HTML string with no way to clean it
  6688. //print $e->getMessage();
  6689. $out = 'InvalidHTMLString';
  6690. }
  6691. }
  6692. // Clean some html entities that are useless so text is cleaner
  6693. $out = preg_replace('/&(tab|newline);/i', ' ', $out);
  6694. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  6695. // encoded using text entities) so we can then exclude all numeric entities.
  6696. $out = preg_replace('/&#39;/i', '&apos;', $out);
  6697. // 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).
  6698. // 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
  6699. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  6700. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  6701. return realCharForNumericEntities($m); }, $out);
  6702. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  6703. $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'.
  6704. // Keep only some html tags and remove also some 'javascript:' strings
  6705. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  6706. // We should also exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
  6707. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  6708. // 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.
  6709. $out = dol_string_onlythesehtmlattributes($out);
  6710. }
  6711. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  6712. $out = preg_replace('/&apos;/i', "&#39;", $out);
  6713. } while ($oldstringtoclean != $out);
  6714. // Check the limit of external links that are automatically executed in a Rich text content. We count:
  6715. // '<img' to avoid <img src="http...">
  6716. // 'url(' to avoid inline style like background: url(http...
  6717. // '<link' to avoid <link href="http...">
  6718. $reg = array();
  6719. preg_match_all('/(<img|url\(|<link)/i', $out, $reg);
  6720. $nbextlink = count($reg[0]);
  6721. if ($nbextlink > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
  6722. $out = 'TooManyLinksIntoHTMLString';
  6723. }
  6724. //
  6725. if (!empty($conf->global->MAIN_DISALLOW_EXT_URL_INTO_DESCRIPTIONS) || $check == 'restricthtmlnolink') {
  6726. if ($nbextlink > 0) {
  6727. $out = 'ExternalLinksNotAllowed';
  6728. }
  6729. }
  6730. return $out;
  6731. }
  6732. }
  6733. /**
  6734. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6735. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6736. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6737. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6738. * For PDF usage, you can show text by 2 ways:
  6739. * - writeHTMLCell -> param must be encoded into HTML.
  6740. * - MultiCell -> param must not be encoded into HTML.
  6741. * Because writeHTMLCell convert also \n into <br>, if function
  6742. * is used to build PDF, nl2brmode must be 1.
  6743. * When we output string on pages, we use dol_string_onlythesehtmltags(dol_htmlentitiesbr()) for notes, and use dol_escape_htmltag() for simple labels.
  6744. *
  6745. * @param string $stringtoencode String to encode
  6746. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6747. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6748. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6749. * @return string String encoded
  6750. * @see dol_escape_htmltag(), dolGetFirstLineOfText()
  6751. */
  6752. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6753. {
  6754. if (is_null($stringtoencode)) {
  6755. return '';
  6756. }
  6757. $newstring = $stringtoencode;
  6758. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6759. $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.
  6760. if ($removelasteolbr) {
  6761. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6762. }
  6763. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6764. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6765. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6766. } else {
  6767. if ($removelasteolbr) {
  6768. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6769. }
  6770. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6771. }
  6772. // Other substitutions that htmlentities does not do
  6773. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6774. return $newstring;
  6775. }
  6776. /**
  6777. * This function is called to decode a HTML string (it decodes entities and br tags)
  6778. *
  6779. * @param string $stringtodecode String to decode
  6780. * @param string $pagecodeto Page code for result
  6781. * @return string String decoded
  6782. */
  6783. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6784. {
  6785. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6786. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6787. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6788. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6789. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6790. return $ret;
  6791. }
  6792. /**
  6793. * This function remove all ending \n and br at end
  6794. *
  6795. * @param string $stringtodecode String to decode
  6796. * @return string String decoded
  6797. */
  6798. function dol_htmlcleanlastbr($stringtodecode)
  6799. {
  6800. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6801. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6802. return $ret;
  6803. }
  6804. /**
  6805. * Replace html_entity_decode functions to manage errors
  6806. *
  6807. * @param string $a Operand a
  6808. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6809. * @param string $c Operand c
  6810. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6811. * @return string String decoded
  6812. */
  6813. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6814. {
  6815. $newstring = $a;
  6816. if ($keepsomeentities) {
  6817. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6818. }
  6819. $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
  6820. if ($keepsomeentities) {
  6821. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6822. }
  6823. return $newstring;
  6824. }
  6825. /**
  6826. * Replace htmlentities functions.
  6827. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6828. *
  6829. * @param string $string The input string to encode
  6830. * @param int $flags Flags (see PHP doc above)
  6831. * @param string $encoding Encoding page code
  6832. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6833. * @return string $ret Encoded string
  6834. */
  6835. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6836. {
  6837. return htmlentities($string, $flags, $encoding, $double_encode);
  6838. }
  6839. /**
  6840. * Check if a string is a correct iso string
  6841. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6842. * Example, if string contains euro symbol that has ascii code 128
  6843. *
  6844. * @param string $s String to check
  6845. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6846. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6847. */
  6848. function dol_string_is_good_iso($s, $clean = 0)
  6849. {
  6850. $len = dol_strlen($s);
  6851. $out = '';
  6852. $ok = 1;
  6853. for ($scursor = 0; $scursor < $len; $scursor++) {
  6854. $ordchar = ord($s[$scursor]);
  6855. //print $scursor.'-'.$ordchar.'<br>';
  6856. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6857. $ok = 0;
  6858. break;
  6859. } elseif ($ordchar > 126 && $ordchar < 160) {
  6860. $ok = 0;
  6861. break;
  6862. } elseif ($clean) {
  6863. $out .= $s[$scursor];
  6864. }
  6865. }
  6866. if ($clean) {
  6867. return $out;
  6868. }
  6869. return $ok;
  6870. }
  6871. /**
  6872. * Return nb of lines of a clear text
  6873. *
  6874. * @param string $s String to check
  6875. * @param int $maxchar Not yet used
  6876. * @return int Number of lines
  6877. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6878. */
  6879. function dol_nboflines($s, $maxchar = 0)
  6880. {
  6881. if ($s == '') {
  6882. return 0;
  6883. }
  6884. $arraystring = explode("\n", $s);
  6885. $nb = count($arraystring);
  6886. return $nb;
  6887. }
  6888. /**
  6889. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6890. *
  6891. * @param string $text Text
  6892. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6893. * @param string $charset Give the charset used to encode the $text variable in memory.
  6894. * @return int Number of lines
  6895. * @see dol_nboflines(), dolGetFirstLineOfText()
  6896. */
  6897. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6898. {
  6899. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6900. if (dol_textishtml($text)) {
  6901. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6902. }
  6903. $text = strtr($text, $repTable);
  6904. if ($charset == 'UTF-8') {
  6905. $pattern = '/(<br[^>]*>)/Uu';
  6906. } else {
  6907. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6908. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6909. }
  6910. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6911. $nblines = (int) floor((count($a) + 1) / 2);
  6912. // count possible auto line breaks
  6913. if ($maxlinesize) {
  6914. foreach ($a as $line) {
  6915. if (dol_strlen($line) > $maxlinesize) {
  6916. //$line_dec = html_entity_decode(strip_tags($line));
  6917. $line_dec = html_entity_decode($line);
  6918. if (dol_strlen($line_dec) > $maxlinesize) {
  6919. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6920. $nblines += substr_count($line_dec, '\n');
  6921. }
  6922. }
  6923. }
  6924. }
  6925. unset($a);
  6926. return $nblines;
  6927. }
  6928. /**
  6929. * Return if a text is a html content
  6930. *
  6931. * @param string $msg Content to check
  6932. * @param int $option 0=Full detection, 1=Fast check
  6933. * @return boolean true/false
  6934. * @see dol_concatdesc()
  6935. */
  6936. function dol_textishtml($msg, $option = 0)
  6937. {
  6938. if (is_null($msg)) {
  6939. return false;
  6940. }
  6941. if ($option == 1) {
  6942. if (preg_match('/<html/i', $msg)) {
  6943. return true;
  6944. } elseif (preg_match('/<body/i', $msg)) {
  6945. return true;
  6946. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6947. return true;
  6948. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  6949. return true;
  6950. } elseif (preg_match('/<br/i', $msg)) {
  6951. return true;
  6952. }
  6953. return false;
  6954. } else {
  6955. // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
  6956. $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
  6957. if (preg_match('/<html/i', $msg)) {
  6958. return true;
  6959. } elseif (preg_match('/<body/i', $msg)) {
  6960. return true;
  6961. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6962. return true;
  6963. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  6964. return true;
  6965. } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
  6966. return true;
  6967. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
  6968. return true;
  6969. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6970. return true;
  6971. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6972. return true; // must accept <img src="http://example.com/aaa.png" />
  6973. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6974. return true; // must accept <a href="http://example.com/aaa.png" />
  6975. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6976. return true;
  6977. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6978. // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
  6979. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6980. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6981. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6982. }
  6983. return false;
  6984. }
  6985. }
  6986. /**
  6987. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6988. * text1 html + text2 html => text1 + '<br>' + text2
  6989. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6990. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6991. * text1 txt + text2 txt => text1 + '\n' + text2
  6992. *
  6993. * @param string $text1 Text 1
  6994. * @param string $text2 Text 2
  6995. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6996. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6997. * @return string Text 1 + new line + Text2
  6998. * @see dol_textishtml()
  6999. */
  7000. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  7001. {
  7002. if (!empty($invert)) {
  7003. $tmp = $text1;
  7004. $text1 = $text2;
  7005. $text2 = $tmp;
  7006. }
  7007. $ret = '';
  7008. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  7009. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  7010. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  7011. return $ret;
  7012. }
  7013. /**
  7014. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  7015. *
  7016. * @param Translate $outputlangs Output language
  7017. * @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)
  7018. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7019. * @param Object $object Object for keys on object
  7020. * @param array $include Array of family keys we want to include. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7021. * @return array Array of substitutions
  7022. * @see setSubstitFromObject()
  7023. */
  7024. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
  7025. {
  7026. global $db, $conf, $mysoc, $user, $extrafields;
  7027. $substitutionarray = array();
  7028. if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include))) {
  7029. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  7030. // this will include signature content first and then replace var found into content of signature
  7031. //var_dump($onlykey);
  7032. $emailsendersignature = $user->signature; // dy default, we use the signature of current user. We must complete substitution with signature in c_email_senderprofile of array after calling getCommonSubstitutionArray()
  7033. $usersignature = $user->signature;
  7034. $substitutionarray = array_merge($substitutionarray, array(
  7035. '__SENDEREMAIL_SIGNATURE__' => (string) ((empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
  7036. '__USER_SIGNATURE__' => (string) (($usersignature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
  7037. ));
  7038. if (is_object($user)) {
  7039. $substitutionarray = array_merge($substitutionarray, array(
  7040. '__USER_ID__' => (string) $user->id,
  7041. '__USER_LOGIN__' => (string) $user->login,
  7042. '__USER_EMAIL__' => (string) $user->email,
  7043. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
  7044. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
  7045. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
  7046. '__USER_FAX__' => (string) $user->office_fax,
  7047. '__USER_LASTNAME__' => (string) $user->lastname,
  7048. '__USER_FIRSTNAME__' => (string) $user->firstname,
  7049. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  7050. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  7051. '__USER_JOB__' => (string) $user->job,
  7052. '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
  7053. '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
  7054. ));
  7055. }
  7056. }
  7057. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
  7058. $substitutionarray = array_merge($substitutionarray, array(
  7059. '__MYCOMPANY_NAME__' => $mysoc->name,
  7060. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  7061. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone, '', 0, 0, '', " ", '', '', -1),
  7062. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax, '', 0, 0, '', " ", '', '', -1),
  7063. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  7064. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  7065. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  7066. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  7067. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  7068. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  7069. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  7070. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  7071. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  7072. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  7073. '__MYCOMPANY_TOWN__' => $mysoc->town,
  7074. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  7075. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  7076. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  7077. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  7078. ));
  7079. }
  7080. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
  7081. if ($onlykey) {
  7082. $substitutionarray['__ID__'] = '__ID__';
  7083. $substitutionarray['__REF__'] = '__REF__';
  7084. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  7085. $substitutionarray['__LABEL__'] = '__LABEL__';
  7086. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  7087. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  7088. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  7089. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  7090. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  7091. if (isModEnabled("societe")) { // Most objects are concerned
  7092. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  7093. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  7094. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  7095. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  7096. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  7097. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  7098. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  7099. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  7100. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  7101. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  7102. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  7103. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  7104. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  7105. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  7106. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  7107. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  7108. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  7109. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  7110. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  7111. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  7112. }
  7113. if (isModEnabled('adherent') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
  7114. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  7115. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  7116. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  7117. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  7118. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  7119. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  7120. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  7121. }
  7122. // add variables subtitutions ticket
  7123. if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
  7124. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  7125. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  7126. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  7127. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  7128. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  7129. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  7130. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  7131. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  7132. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  7133. }
  7134. if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
  7135. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  7136. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  7137. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  7138. }
  7139. if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
  7140. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  7141. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  7142. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  7143. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  7144. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  7145. }
  7146. if (isModEnabled('contrat') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
  7147. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  7148. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  7149. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  7150. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  7151. }
  7152. if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
  7153. $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
  7154. }
  7155. if (isModEnabled("ficheinter") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
  7156. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
  7157. }
  7158. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  7159. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  7160. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  7161. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  7162. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  7163. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  7164. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  7165. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  7166. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  7167. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  7168. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  7169. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  7170. if (isModEnabled("expedition") && (!is_object($object) || $object->element == 'shipping')) {
  7171. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  7172. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  7173. }
  7174. if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
  7175. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  7176. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  7177. }
  7178. } else {
  7179. $substitutionarray['__ID__'] = $object->id;
  7180. $substitutionarray['__REF__'] = $object->ref;
  7181. $substitutionarray['__NEWREF__'] = $object->newref;
  7182. $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
  7183. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7184. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7185. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  7186. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  7187. if ($object->element == "shipping") {
  7188. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, 'day', 0, $outputlangs) : '');
  7189. } else {
  7190. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  7191. }
  7192. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  7193. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  7194. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  7195. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  7196. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  7197. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  7198. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  7199. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  7200. // For backward compatibility (deprecated)
  7201. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7202. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7203. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  7204. $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 : '')) : '');
  7205. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  7206. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  7207. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  7208. if (method_exists($object, 'getCivilityLabel')) {
  7209. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  7210. }
  7211. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  7212. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  7213. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  7214. if (method_exists($object, 'getFullName')) {
  7215. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  7216. }
  7217. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  7218. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  7219. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  7220. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  7221. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  7222. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  7223. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  7224. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  7225. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  7226. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  7227. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  7228. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  7229. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  7230. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  7231. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  7232. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
  7233. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
  7234. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  7235. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  7236. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  7237. }
  7238. if (is_object($object) && $object->element == 'societe') {
  7239. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  7240. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  7241. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  7242. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  7243. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  7244. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  7245. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  7246. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  7247. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  7248. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  7249. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  7250. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  7251. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  7252. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  7253. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  7254. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  7255. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  7256. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  7257. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  7258. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  7259. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  7260. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  7261. } elseif (is_object($object->thirdparty)) {
  7262. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  7263. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  7264. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  7265. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  7266. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  7267. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  7268. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  7269. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  7270. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  7271. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  7272. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  7273. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  7274. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  7275. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  7276. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  7277. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  7278. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  7279. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  7280. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  7281. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  7282. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  7283. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  7284. }
  7285. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  7286. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  7287. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7288. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7289. }
  7290. if (is_object($object) && $object->element == 'conferenceorboothattendee') {
  7291. $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
  7292. $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7293. $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7294. }
  7295. if (is_object($object->project)) {
  7296. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  7297. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  7298. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  7299. }
  7300. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  7301. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  7302. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  7303. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  7304. }
  7305. if (is_object($object) && $object->element == 'project') {
  7306. $substitutionarray['__PROJECT_NAME__'] = $object->title;
  7307. }
  7308. if (is_object($object) && $object->element == 'shipping') {
  7309. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  7310. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  7311. }
  7312. if (is_object($object) && $object->element == 'reception') {
  7313. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  7314. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  7315. }
  7316. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  7317. $dateplannedstart = '';
  7318. $datenextexpiration = '';
  7319. foreach ($object->lines as $line) {
  7320. if ($line->date_start > $dateplannedstart) {
  7321. $dateplannedstart = $line->date_start;
  7322. }
  7323. if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
  7324. $datenextexpiration = $line->date_end;
  7325. }
  7326. }
  7327. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  7328. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  7329. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  7330. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  7331. }
  7332. // add substition variable for ticket
  7333. if (is_object($object) && $object->element == 'ticket') {
  7334. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  7335. $substitutionarray['__REF__'] = $object->ref;
  7336. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  7337. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  7338. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  7339. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  7340. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  7341. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  7342. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  7343. $userstat = new User($db);
  7344. if ($object->fk_user_assign > 0) {
  7345. $userstat->fetch($object->fk_user_assign);
  7346. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7347. }
  7348. if ($object->fk_user_create > 0) {
  7349. $userstat->fetch($object->fk_user_create);
  7350. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7351. }
  7352. }
  7353. // Create dynamic tags for __EXTRAFIELD_FIELD__
  7354. if ($object->table_element && $object->id > 0) {
  7355. if (!is_object($extrafields)) {
  7356. $extrafields = new ExtraFields($db);
  7357. }
  7358. $extrafields->fetch_name_optionals_label($object->table_element, true);
  7359. if ($object->fetch_optionals() > 0) {
  7360. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  7361. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  7362. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  7363. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  7364. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  7365. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  7366. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  7367. $datetime = $object->array_options['options_'.$key];
  7368. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  7369. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  7370. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  7371. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  7372. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  7373. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  7374. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  7375. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7376. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  7377. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
  7378. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7379. }
  7380. }
  7381. }
  7382. }
  7383. }
  7384. // Complete substitution array with the url to make online payment
  7385. $paymenturl = '';
  7386. if (empty($substitutionarray['__REF__'])) {
  7387. $paymenturl = '';
  7388. } else {
  7389. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  7390. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  7391. $outputlangs->loadLangs(array('paypal', 'other'));
  7392. $amounttouse = 0;
  7393. $typeforonlinepayment = 'free';
  7394. if (is_object($object) && $object->element == 'commande') {
  7395. $typeforonlinepayment = 'order';
  7396. }
  7397. if (is_object($object) && $object->element == 'facture') {
  7398. $typeforonlinepayment = 'invoice';
  7399. }
  7400. if (is_object($object) && $object->element == 'member') {
  7401. $typeforonlinepayment = 'member';
  7402. if (!empty($object->last_subscription_amount)) {
  7403. $amounttouse = $object->last_subscription_amount;
  7404. }
  7405. }
  7406. if (is_object($object) && $object->element == 'contrat') {
  7407. $typeforonlinepayment = 'contract';
  7408. }
  7409. if (is_object($object) && $object->element == 'fichinter') {
  7410. $typeforonlinepayment = 'ficheinter';
  7411. }
  7412. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], $amounttouse);
  7413. $paymenturl = $url;
  7414. }
  7415. if ($object->id > 0) {
  7416. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  7417. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  7418. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  7419. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7420. } else {
  7421. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  7422. }
  7423. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  7424. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  7425. } else {
  7426. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  7427. }
  7428. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  7429. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  7430. } else {
  7431. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  7432. }
  7433. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  7434. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  7435. } else {
  7436. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  7437. }
  7438. if (!empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'fichinter') {
  7439. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
  7440. } else {
  7441. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
  7442. }
  7443. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  7444. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7445. } else {
  7446. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  7447. }
  7448. if (is_object($object) && $object->element == 'propal') {
  7449. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  7450. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7451. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  7452. }
  7453. if (is_object($object) && $object->element == 'commande') {
  7454. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  7455. }
  7456. if (is_object($object) && $object->element == 'facture') {
  7457. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  7458. }
  7459. if (is_object($object) && $object->element == 'contrat') {
  7460. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  7461. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7462. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', $object->ref);
  7463. }
  7464. if (is_object($object) && $object->element == 'fichinter') {
  7465. $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT."/fichinter/card.php?id=".$object->id;
  7466. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7467. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', $object->ref);
  7468. }
  7469. if (is_object($object) && $object->element == 'supplier_proposal') {
  7470. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  7471. }
  7472. if (is_object($object) && $object->element == 'shipping') {
  7473. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  7474. }
  7475. }
  7476. if (is_object($object) && $object->element == 'action') {
  7477. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  7478. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  7479. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  7480. }
  7481. }
  7482. }
  7483. if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
  7484. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  7485. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  7486. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  7487. $already_payed_all = 0;
  7488. if (is_object($object) && ($object instanceof Facture)) {
  7489. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  7490. }
  7491. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  7492. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  7493. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  7494. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  7495. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
  7496. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7497. $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)) : '';
  7498. $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)) : '';
  7499. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7500. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  7501. }
  7502. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7503. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  7504. }
  7505. // Amount keys formated in a currency
  7506. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7507. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7508. $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc - $already_payed_all, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7509. $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)) : '';
  7510. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7511. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7512. }
  7513. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7514. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7515. }
  7516. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  7517. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  7518. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  7519. // TODO Add other keys for foreign multicurrency
  7520. // For backward compatibility
  7521. if ($onlykey != 2) {
  7522. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  7523. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  7524. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7525. }
  7526. }
  7527. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  7528. if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
  7529. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  7530. $now = dol_now();
  7531. $tmp = dol_getdate($now, true);
  7532. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7533. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  7534. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7535. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  7536. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  7537. $substitutionarray = array_merge($substitutionarray, array(
  7538. '__NOW_TMS__' => (int) $now,
  7539. '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 0, $outputlangs),
  7540. '__DAY__' => (string) $tmp['mday'],
  7541. '__DAY_TEXT__' => $daytext, // Monday
  7542. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  7543. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  7544. '__MONTH__' => (string) $tmp['mon'],
  7545. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  7546. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  7547. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  7548. '__YEAR__' => (string) $tmp['year'],
  7549. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  7550. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  7551. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  7552. '__NEXT_DAY__' => (string) $tmp4['day'],
  7553. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7554. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7555. ));
  7556. }
  7557. if (isModEnabled('multicompany')) {
  7558. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7559. }
  7560. if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
  7561. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7562. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7563. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7564. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7565. }
  7566. return $substitutionarray;
  7567. }
  7568. /**
  7569. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7570. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7571. * Example of usage:
  7572. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7573. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7574. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7575. *
  7576. * @param string $text Source string in which we must do substitution
  7577. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7578. * @param Translate $outputlangs Output language
  7579. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7580. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7581. * @return string Output string after substitutions
  7582. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7583. */
  7584. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7585. {
  7586. global $conf, $langs;
  7587. if (!is_array($substitutionarray)) {
  7588. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7589. }
  7590. if (empty($outputlangs)) {
  7591. $outputlangs = $langs;
  7592. }
  7593. // Is initial text HTML or simple text ?
  7594. $msgishtml = 0;
  7595. if (dol_textishtml($text, 1)) {
  7596. $msgishtml = 1;
  7597. }
  7598. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7599. if (is_object($outputlangs)) {
  7600. $reg = array();
  7601. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7602. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7603. $tmp = explode('|', $reg[1]);
  7604. if (!empty($tmp[1])) {
  7605. $outputlangs->load($tmp[1]);
  7606. }
  7607. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7608. if (empty($converttextinhtmlifnecessary)) {
  7609. // convert $newval into HTML is necessary
  7610. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7611. } else {
  7612. if (! $msgishtml) {
  7613. $valueishtml = dol_textishtml($value, 1);
  7614. //var_dump("valueishtml=".$valueishtml);
  7615. if ($valueishtml) {
  7616. $text = dol_htmlentitiesbr($text);
  7617. $msgishtml = 1;
  7618. }
  7619. } else {
  7620. $value = dol_nl2br("$value");
  7621. }
  7622. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7623. }
  7624. }
  7625. }
  7626. // Make substitution for constant keys.
  7627. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7628. $reg = array();
  7629. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7630. $keyfound = $reg[1];
  7631. if (isASecretKey($keyfound)) {
  7632. $value = '*****forbidden*****';
  7633. } else {
  7634. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7635. }
  7636. if (empty($converttextinhtmlifnecessary)) {
  7637. // convert $newval into HTML is necessary
  7638. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7639. } else {
  7640. if (! $msgishtml) {
  7641. $valueishtml = dol_textishtml($value, 1);
  7642. if ($valueishtml) {
  7643. $text = dol_htmlentitiesbr($text);
  7644. $msgishtml = 1;
  7645. }
  7646. } else {
  7647. $value = dol_nl2br("$value");
  7648. }
  7649. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7650. }
  7651. }
  7652. // Make substitution for array $substitutionarray
  7653. foreach ($substitutionarray as $key => $value) {
  7654. if (!isset($value)) {
  7655. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7656. }
  7657. if (($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__') && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  7658. $value = ''; // Protection
  7659. }
  7660. if (empty($converttextinhtmlifnecessary)) {
  7661. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7662. } else {
  7663. if (! $msgishtml) {
  7664. $valueishtml = dol_textishtml($value, 1);
  7665. if ($valueishtml) {
  7666. $text = dol_htmlentitiesbr($text);
  7667. $msgishtml = 1;
  7668. }
  7669. } else {
  7670. $value = dol_nl2br("$value");
  7671. }
  7672. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7673. }
  7674. }
  7675. return $text;
  7676. }
  7677. /**
  7678. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  7679. * In this case, method completesubstitutionarray provided by module is called.
  7680. *
  7681. * @param array $substitutionarray Array substitution old value => new value value
  7682. * @param Translate $outputlangs Output language
  7683. * @param Object $object Source object
  7684. * @param mixed $parameters Add more parameters (useful to pass product lines)
  7685. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  7686. * @return void
  7687. * @see make_substitutions()
  7688. */
  7689. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  7690. {
  7691. global $conf, $user;
  7692. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7693. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7694. // Check if there is external substitution to do, requested by plugins
  7695. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7696. foreach ($dirsubstitutions as $reldir) {
  7697. $dir = dol_buildpath($reldir, 0);
  7698. // Check if directory exists
  7699. if (!dol_is_dir($dir)) {
  7700. continue;
  7701. }
  7702. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7703. foreach ($substitfiles as $substitfile) {
  7704. $reg = array();
  7705. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7706. $module = $reg[1];
  7707. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7708. // Include the user's functions file
  7709. require_once $dir.$substitfile['name'];
  7710. // Call the user's function, and only if it is defined
  7711. $function_name = $module."_".$callfunc;
  7712. if (function_exists($function_name)) {
  7713. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7714. }
  7715. }
  7716. }
  7717. }
  7718. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7719. // to list all tags in odt template
  7720. $tags = '';
  7721. foreach ($substitutionarray as $key => $value) {
  7722. $tags .= '{'.$key.'} => '.$value."\n";
  7723. }
  7724. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7725. }
  7726. }
  7727. /**
  7728. * Format output for start and end date
  7729. *
  7730. * @param int $date_start Start date
  7731. * @param int $date_end End date
  7732. * @param string $format Output format
  7733. * @param Translate $outputlangs Output language
  7734. * @return void
  7735. */
  7736. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7737. {
  7738. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7739. }
  7740. /**
  7741. * Format output for start and end date
  7742. *
  7743. * @param int $date_start Start date
  7744. * @param int $date_end End date
  7745. * @param string $format Output date format ('day', 'dayhour', ...)
  7746. * @param Translate $outputlangs Output language
  7747. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7748. * @return string String
  7749. */
  7750. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7751. {
  7752. global $langs;
  7753. $out = '';
  7754. if (!is_object($outputlangs)) {
  7755. $outputlangs = $langs;
  7756. }
  7757. if ($date_start && $date_end) {
  7758. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7759. }
  7760. if ($date_start && !$date_end) {
  7761. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7762. }
  7763. if (!$date_start && $date_end) {
  7764. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7765. }
  7766. return $out;
  7767. }
  7768. /**
  7769. * Return firstname and lastname in correct order
  7770. *
  7771. * @param string $firstname Firstname
  7772. * @param string $lastname Lastname
  7773. * @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
  7774. * @return string Firstname + lastname or Lastname + firstname
  7775. */
  7776. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7777. {
  7778. global $conf;
  7779. $ret = '';
  7780. // If order not defined, we use the setup
  7781. if ($nameorder < 0) {
  7782. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7783. }
  7784. if ($nameorder == 1) {
  7785. $ret .= $firstname;
  7786. if ($firstname && $lastname) {
  7787. $ret .= ' ';
  7788. }
  7789. $ret .= $lastname;
  7790. } elseif ($nameorder == 2 || $nameorder == 3) {
  7791. $ret .= $firstname;
  7792. if (empty($ret) && $nameorder == 3) {
  7793. $ret .= $lastname;
  7794. }
  7795. } else { // 0, 4 or 5
  7796. $ret .= $lastname;
  7797. if (empty($ret) && $nameorder == 5) {
  7798. $ret .= $firstname;
  7799. }
  7800. if ($nameorder == 0) {
  7801. if ($firstname && $lastname) {
  7802. $ret .= ' ';
  7803. }
  7804. $ret .= $firstname;
  7805. }
  7806. }
  7807. return $ret;
  7808. }
  7809. /**
  7810. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  7811. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7812. * Note: Prefer to use setEventMessages instead.
  7813. *
  7814. * @param string|string[] $mesgs Message string or array
  7815. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7816. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  7817. * @return void
  7818. * @see dol_htmloutput_events()
  7819. */
  7820. function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0)
  7821. {
  7822. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  7823. if (!is_array($mesgs)) {
  7824. // If mesgs is a string
  7825. if ($mesgs) {
  7826. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
  7827. return;
  7828. }
  7829. $_SESSION['dol_events'][$style][] = $mesgs;
  7830. }
  7831. } else {
  7832. // If mesgs is an array
  7833. foreach ($mesgs as $mesg) {
  7834. if ($mesg) {
  7835. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
  7836. return;
  7837. }
  7838. $_SESSION['dol_events'][$style][] = $mesg;
  7839. }
  7840. }
  7841. }
  7842. }
  7843. /**
  7844. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7845. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7846. *
  7847. * @param string $mesg Message string
  7848. * @param array|null $mesgs Message array
  7849. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7850. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7851. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  7852. * @return void
  7853. * @see dol_htmloutput_events()
  7854. */
  7855. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0)
  7856. {
  7857. if (empty($mesg) && empty($mesgs)) {
  7858. dol_syslog("Try to add a message in stack, but value to add is empty message", LOG_WARNING);
  7859. } else {
  7860. if ($messagekey) {
  7861. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7862. // TODO
  7863. $mesg .= '';
  7864. }
  7865. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7866. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7867. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7868. }
  7869. if (empty($mesgs)) {
  7870. setEventMessage($mesg, $style, $noduplicate);
  7871. } else {
  7872. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7873. setEventMessage($mesg, $style, $noduplicate); // Add message string if not already into array
  7874. }
  7875. setEventMessage($mesgs, $style, $noduplicate);
  7876. }
  7877. }
  7878. }
  7879. }
  7880. /**
  7881. * Print formated messages to output (Used to show messages on html output).
  7882. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7883. * no need to call it explicitely.
  7884. *
  7885. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7886. * @return void
  7887. * @see dol_htmloutput_mesg()
  7888. */
  7889. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7890. {
  7891. // Show mesgs
  7892. if (isset($_SESSION['dol_events']['mesgs'])) {
  7893. if (empty($disabledoutputofmessages)) {
  7894. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7895. }
  7896. unset($_SESSION['dol_events']['mesgs']);
  7897. }
  7898. // Show errors
  7899. if (isset($_SESSION['dol_events']['errors'])) {
  7900. if (empty($disabledoutputofmessages)) {
  7901. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7902. }
  7903. unset($_SESSION['dol_events']['errors']);
  7904. }
  7905. // Show warnings
  7906. if (isset($_SESSION['dol_events']['warnings'])) {
  7907. if (empty($disabledoutputofmessages)) {
  7908. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7909. }
  7910. unset($_SESSION['dol_events']['warnings']);
  7911. }
  7912. }
  7913. /**
  7914. * Get formated messages to output (Used to show messages on html output).
  7915. * This include also the translation of the message key.
  7916. *
  7917. * @param string $mesgstring Message string or message key
  7918. * @param string[] $mesgarray Array of message strings or message keys
  7919. * @param string $style Style of message output ('ok' or 'error')
  7920. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7921. * @return string Return html output
  7922. *
  7923. * @see dol_print_error()
  7924. * @see dol_htmloutput_errors()
  7925. * @see setEventMessages()
  7926. */
  7927. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7928. {
  7929. global $conf, $langs;
  7930. $ret = 0;
  7931. $return = '';
  7932. $out = '';
  7933. $divstart = $divend = '';
  7934. // If inline message with no format, we add it.
  7935. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7936. $divstart = '<div class="'.$style.' clearboth">';
  7937. $divend = '</div>';
  7938. }
  7939. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7940. $langs->load("errors");
  7941. $out .= $divstart;
  7942. if (is_array($mesgarray) && count($mesgarray)) {
  7943. foreach ($mesgarray as $message) {
  7944. $ret++;
  7945. $out .= $langs->trans($message);
  7946. if ($ret < count($mesgarray)) {
  7947. $out .= "<br>\n";
  7948. }
  7949. }
  7950. }
  7951. if ($mesgstring) {
  7952. $ret++;
  7953. $out .= $langs->trans($mesgstring);
  7954. }
  7955. $out .= $divend;
  7956. }
  7957. if ($out) {
  7958. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7959. $return = '<script nonce="'.getNonce().'">
  7960. $(document).ready(function() {
  7961. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7962. if (block) {
  7963. $.dolEventValid("","'.dol_escape_js($out).'");
  7964. } else {
  7965. /* jnotify(message, preset of message type, keepmessage) */
  7966. $.jnotify("'.dol_escape_js($out).'",
  7967. "'.($style == "ok" ? 3000 : $style).'",
  7968. '.($style == "ok" ? "false" : "true").',
  7969. { remove: function (){} } );
  7970. }
  7971. });
  7972. </script>';
  7973. } else {
  7974. $return = $out;
  7975. }
  7976. }
  7977. return $return;
  7978. }
  7979. /**
  7980. * Get formated error messages to output (Used to show messages on html output).
  7981. *
  7982. * @param string $mesgstring Error message
  7983. * @param array $mesgarray Error messages array
  7984. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7985. * @return string Return html output
  7986. *
  7987. * @see dol_print_error()
  7988. * @see dol_htmloutput_mesg()
  7989. */
  7990. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7991. {
  7992. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7993. }
  7994. /**
  7995. * Print formated messages to output (Used to show messages on html output).
  7996. *
  7997. * @param string $mesgstring Message string or message key
  7998. * @param string[] $mesgarray Array of message strings or message keys
  7999. * @param string $style Which style to use ('ok', 'warning', 'error')
  8000. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  8001. * @return void
  8002. *
  8003. * @see dol_print_error()
  8004. * @see dol_htmloutput_errors()
  8005. * @see setEventMessages()
  8006. */
  8007. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  8008. {
  8009. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  8010. return;
  8011. }
  8012. $iserror = 0;
  8013. $iswarning = 0;
  8014. if (is_array($mesgarray)) {
  8015. foreach ($mesgarray as $val) {
  8016. if ($val && preg_match('/class="error"/i', $val)) {
  8017. $iserror++;
  8018. break;
  8019. }
  8020. if ($val && preg_match('/class="warning"/i', $val)) {
  8021. $iswarning++;
  8022. break;
  8023. }
  8024. }
  8025. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  8026. $iserror++;
  8027. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  8028. $iswarning++;
  8029. }
  8030. if ($style == 'error') {
  8031. $iserror++;
  8032. }
  8033. if ($style == 'warning') {
  8034. $iswarning++;
  8035. }
  8036. if ($iserror || $iswarning) {
  8037. // Remove div from texts
  8038. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  8039. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  8040. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  8041. // Remove div from texts array
  8042. if (is_array($mesgarray)) {
  8043. $newmesgarray = array();
  8044. foreach ($mesgarray as $val) {
  8045. if (is_string($val)) {
  8046. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  8047. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  8048. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  8049. $newmesgarray[] = $tmpmesgstring;
  8050. } else {
  8051. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  8052. }
  8053. }
  8054. $mesgarray = $newmesgarray;
  8055. }
  8056. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  8057. } else {
  8058. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  8059. }
  8060. }
  8061. /**
  8062. * Print formated error messages to output (Used to show messages on html output).
  8063. *
  8064. * @param string $mesgstring Error message
  8065. * @param array $mesgarray Error messages array
  8066. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8067. * @return void
  8068. *
  8069. * @see dol_print_error()
  8070. * @see dol_htmloutput_mesg()
  8071. */
  8072. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8073. {
  8074. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8075. }
  8076. /**
  8077. * Advanced sort array by second index function, which produces ascending (default)
  8078. * or descending output and uses optionally natural case insensitive sorting (which
  8079. * can be optionally case sensitive as well).
  8080. *
  8081. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  8082. * @param string $index Key in array to use for sorting criteria
  8083. * @param int $order Sort order ('asc' or 'desc')
  8084. * @param int $natsort If values are strings (I said value not type): 0=Use alphabetical order, 1=use "natural" sort (natsort)
  8085. * If values are numeric (I said value not type): 0=Use numeric order (even if type is string) so use a "natural" sort, 1=use "natural" sort too (same than 0), -1=Force alphabetical order
  8086. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  8087. * @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.
  8088. * @return array Sorted array
  8089. */
  8090. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  8091. {
  8092. // Clean parameters
  8093. $order = strtolower($order);
  8094. if (is_array($array)) {
  8095. $sizearray = count($array);
  8096. if ($sizearray > 0) {
  8097. $temp = array();
  8098. foreach (array_keys($array) as $key) {
  8099. if (is_object($array[$key])) {
  8100. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  8101. } else {
  8102. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  8103. }
  8104. if ($natsort == -1) {
  8105. $temp[$key] = '___'.$temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
  8106. }
  8107. }
  8108. if (empty($natsort) || $natsort == -1) {
  8109. if ($order == 'asc') {
  8110. asort($temp);
  8111. } else {
  8112. arsort($temp);
  8113. }
  8114. } else {
  8115. if ($case_sensitive) {
  8116. natsort($temp);
  8117. } else {
  8118. natcasesort($temp); // natecasesort is not sensible to case
  8119. }
  8120. if ($order != 'asc') {
  8121. $temp = array_reverse($temp, true);
  8122. }
  8123. }
  8124. $sorted = array();
  8125. foreach (array_keys($temp) as $key) {
  8126. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  8127. }
  8128. return $sorted;
  8129. }
  8130. }
  8131. return $array;
  8132. }
  8133. /**
  8134. * Check if a string is in UTF8
  8135. *
  8136. * @param string $str String to check
  8137. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  8138. */
  8139. function utf8_check($str)
  8140. {
  8141. $str = (string) $str; // Sometimes string is an int.
  8142. // We must use here a binary strlen function (so not dol_strlen)
  8143. $strLength = dol_strlen($str);
  8144. for ($i = 0; $i < $strLength; $i++) {
  8145. if (ord($str[$i]) < 0x80) {
  8146. continue; // 0bbbbbbb
  8147. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  8148. $n = 1; // 110bbbbb
  8149. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  8150. $n = 2; // 1110bbbb
  8151. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  8152. $n = 3; // 11110bbb
  8153. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  8154. $n = 4; // 111110bb
  8155. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  8156. $n = 5; // 1111110b
  8157. } else {
  8158. return false; // Does not match any model
  8159. }
  8160. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  8161. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  8162. return false;
  8163. }
  8164. }
  8165. }
  8166. return true;
  8167. }
  8168. /**
  8169. * Check if a string is in UTF8
  8170. *
  8171. * @param string $str String to check
  8172. * @return boolean True if string is valid UTF8 string, false if corrupted
  8173. */
  8174. function utf8_valid($str)
  8175. {
  8176. /* 2 other methods to test if string is utf8
  8177. $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
  8178. $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
  8179. */
  8180. return preg_match('//u', $str) ? true : false;
  8181. }
  8182. /**
  8183. * Check if a string is in ASCII
  8184. *
  8185. * @param string $str String to check
  8186. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  8187. */
  8188. function ascii_check($str)
  8189. {
  8190. if (function_exists('mb_check_encoding')) {
  8191. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  8192. if (!mb_check_encoding($str, 'ASCII')) {
  8193. return false;
  8194. }
  8195. } else {
  8196. if (preg_match('/[^\x00-\x7f]/', $str)) {
  8197. return false; // Contains a byte > 7f
  8198. }
  8199. }
  8200. return true;
  8201. }
  8202. /**
  8203. * Return a string encoded into OS filesystem encoding. This function is used to define
  8204. * value to pass to filesystem PHP functions.
  8205. *
  8206. * @param string $str String to encode (UTF-8)
  8207. * @return string Encoded string (UTF-8, ISO-8859-1)
  8208. */
  8209. function dol_osencode($str)
  8210. {
  8211. global $conf;
  8212. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  8213. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  8214. $tmp = 'iso-8859-1'; // By default for windows
  8215. }
  8216. if (empty($tmp)) {
  8217. $tmp = 'utf-8'; // By default for other
  8218. }
  8219. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  8220. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  8221. }
  8222. if ($tmp == 'iso-8859-1') {
  8223. return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
  8224. }
  8225. return $str;
  8226. }
  8227. /**
  8228. * Return an id or code from a code or id.
  8229. * Store also Code-Id into a cache to speed up next request on same key.
  8230. *
  8231. * @param DoliDB $db Database handler
  8232. * @param string $key Code or Id to get Id or Code
  8233. * @param string $tablename Table name without prefix
  8234. * @param string $fieldkey Field to search the key into
  8235. * @param string $fieldid Field to get
  8236. * @param int $entityfilter Filter by entity
  8237. * @param string $filters Filters to add. WARNING: string must be escaped for SQL and not coming from user input.
  8238. * @return int <0 if KO, Id of code if OK
  8239. * @see $langs->getLabelFromKey
  8240. */
  8241. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '')
  8242. {
  8243. global $cache_codes;
  8244. // If key empty
  8245. if ($key == '') {
  8246. return '';
  8247. }
  8248. // Check in cache
  8249. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  8250. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  8251. }
  8252. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  8253. $sql = "SELECT ".$fieldid." as valuetoget";
  8254. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  8255. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  8256. if (!empty($entityfilter)) {
  8257. $sql .= " AND entity IN (".getEntity($tablename).")";
  8258. }
  8259. if ($filters) {
  8260. $sql .= $filters;
  8261. }
  8262. $resql = $db->query($sql);
  8263. if ($resql) {
  8264. $obj = $db->fetch_object($resql);
  8265. if ($obj) {
  8266. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  8267. } else {
  8268. $cache_codes[$tablename][$key][$fieldid] = '';
  8269. }
  8270. $db->free($resql);
  8271. return $cache_codes[$tablename][$key][$fieldid];
  8272. } else {
  8273. return -1;
  8274. }
  8275. }
  8276. /**
  8277. * Verify if condition in string is ok or not
  8278. *
  8279. * @param string $strToEvaluate String with condition to check
  8280. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  8281. */
  8282. function verifCond($strToEvaluate)
  8283. {
  8284. global $user, $conf, $langs;
  8285. global $leftmenu;
  8286. global $rights; // To export to dol_eval function
  8287. //print $strToEvaluate."<br>\n";
  8288. $rights = true;
  8289. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  8290. //var_dump($strToEvaluate);
  8291. $rep = dol_eval($strToEvaluate, 1, 1, '1'); // The dol_eval must contains all the global $xxx for all variables $xxx found into the string condition
  8292. $rights = $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
  8293. //var_dump($rights);
  8294. }
  8295. return $rights;
  8296. }
  8297. /**
  8298. * Replace eval function to add more security.
  8299. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  8300. *
  8301. * @param string $s String to evaluate
  8302. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  8303. * @param int $hideerrors 1=Hide errors
  8304. * @param string $onlysimplestring '0' (used for computed property of extrafields)=Accept all chars, '1' (most common use)=Accept only simple string with char 'a-z0-9\s^$_+-.*>&|=!?():"\',/@';', '2' (rarely used)=Accept also '[]'
  8305. * @return mixed Nothing or return result of eval
  8306. */
  8307. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  8308. {
  8309. // Only global variables can be changed by eval function and returned to caller
  8310. global $db, $langs, $user, $conf, $website, $websitepage;
  8311. global $action, $mainmenu, $leftmenu;
  8312. global $mysoc;
  8313. global $objectoffield;
  8314. // Old variables used
  8315. global $rights;
  8316. global $object;
  8317. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  8318. global $soc; // For backward compatibility
  8319. try {
  8320. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  8321. if ($onlysimplestring == '1') {
  8322. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL'
  8323. // We must accept: '$conf->barcode->enabled || preg_match(\'/^AAA/\',$leftmenu)'
  8324. // We must accept: '$user->rights->cabinetmed->read && !$object->canvas=="patient@cabinetmed"'
  8325. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@', '/').']/i', $s)) {
  8326. if ($returnvalue) {
  8327. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8328. } else {
  8329. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8330. return '';
  8331. }
  8332. // TODO
  8333. // We can exclude all parenthesis ( that are not '($db' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match(' and 'isModEnabled('
  8334. // ...
  8335. }
  8336. } elseif ($onlysimplestring == '2') {
  8337. // We must accept: (($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"
  8338. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@[]', '/').']/i', $s)) {
  8339. if ($returnvalue) {
  8340. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8341. } else {
  8342. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8343. return '';
  8344. }
  8345. // TODO
  8346. // We can exclude all parenthesis ( that are not '($db' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match(' and 'isModEnabled('
  8347. // ...
  8348. }
  8349. }
  8350. if (is_array($s) || $s === 'Array') {
  8351. return 'Bad string syntax to evaluate (value is Array) '.var_export($s, true);
  8352. }
  8353. if (strpos($s, '::') !== false) {
  8354. if ($returnvalue) {
  8355. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  8356. } else {
  8357. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  8358. return '';
  8359. }
  8360. }
  8361. if (strpos($s, '`') !== false) {
  8362. if ($returnvalue) {
  8363. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  8364. } else {
  8365. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  8366. return '';
  8367. }
  8368. }
  8369. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  8370. if ($returnvalue) {
  8371. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  8372. } else {
  8373. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  8374. return '';
  8375. }
  8376. }
  8377. // We block use of php exec or php file functions
  8378. $forbiddenphpstrings = array('$$');
  8379. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  8380. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI", "verifCond", "base64_decode");
  8381. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  8382. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  8383. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  8384. do {
  8385. $oldstringtoclean = $s;
  8386. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  8387. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  8388. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  8389. } while ($oldstringtoclean != $s);
  8390. if (strpos($s, '__forbiddenstring__') !== false) {
  8391. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  8392. if ($returnvalue) {
  8393. return 'Bad string syntax to evaluate: '.$s;
  8394. } else {
  8395. dol_syslog('Bad string syntax to evaluate: '.$s);
  8396. return '';
  8397. }
  8398. }
  8399. //print $s."<br>\n";
  8400. if ($returnvalue) {
  8401. if ($hideerrors) {
  8402. return @eval('return '.$s.';');
  8403. } else {
  8404. return eval('return '.$s.';');
  8405. }
  8406. } else {
  8407. if ($hideerrors) {
  8408. @eval($s);
  8409. } else {
  8410. eval($s);
  8411. }
  8412. }
  8413. } catch (Error $e) {
  8414. $error = 'dol_eval try/catch error : ';
  8415. $error .= $e->getMessage();
  8416. dol_syslog($error);
  8417. }
  8418. }
  8419. /**
  8420. * Return if var element is ok
  8421. *
  8422. * @param string $element Variable to check
  8423. * @return boolean Return true of variable is not empty
  8424. */
  8425. function dol_validElement($element)
  8426. {
  8427. return (trim($element) != '');
  8428. }
  8429. /**
  8430. * Return img flag of country for a language code or country code.
  8431. *
  8432. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  8433. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  8434. * @param int $notitlealt No title alt
  8435. * @return string HTML img string with flag.
  8436. */
  8437. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  8438. {
  8439. if (empty($codelang)) {
  8440. return '';
  8441. }
  8442. if ($codelang == 'auto') {
  8443. return '<span class="fa fa-language"></span>';
  8444. }
  8445. $langtocountryflag = array(
  8446. 'ar_AR' => '',
  8447. 'ca_ES' => 'catalonia',
  8448. 'da_DA' => 'dk',
  8449. 'fr_CA' => 'mq',
  8450. 'sv_SV' => 'se',
  8451. 'sw_SW' => 'unknown',
  8452. 'AQ' => 'unknown',
  8453. 'CW' => 'unknown',
  8454. 'IM' => 'unknown',
  8455. 'JE' => 'unknown',
  8456. 'MF' => 'unknown',
  8457. 'BL' => 'unknown',
  8458. 'SX' => 'unknown'
  8459. );
  8460. if (isset($langtocountryflag[$codelang])) {
  8461. $flagImage = $langtocountryflag[$codelang];
  8462. } else {
  8463. $tmparray = explode('_', $codelang);
  8464. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  8465. }
  8466. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  8467. }
  8468. /**
  8469. * Return default language from country code.
  8470. * Return null if not found.
  8471. *
  8472. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  8473. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  8474. */
  8475. function getLanguageCodeFromCountryCode($countrycode)
  8476. {
  8477. global $mysoc;
  8478. if (empty($countrycode)) {
  8479. return null;
  8480. }
  8481. if (strtoupper($countrycode) == 'MQ') {
  8482. return 'fr_CA';
  8483. }
  8484. if (strtoupper($countrycode) == 'SE') {
  8485. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  8486. }
  8487. if (strtoupper($countrycode) == 'CH') {
  8488. if ($mysoc->country_code == 'FR') {
  8489. return 'fr_CH';
  8490. }
  8491. if ($mysoc->country_code == 'DE') {
  8492. return 'de_CH';
  8493. }
  8494. if ($mysoc->country_code == 'IT') {
  8495. return 'it_CH';
  8496. }
  8497. }
  8498. // Locale list taken from:
  8499. // http://stackoverflow.com/questions/3191664/
  8500. // list-of-all-locales-and-their-short-codes
  8501. $locales = array(
  8502. 'af-ZA',
  8503. 'am-ET',
  8504. 'ar-AE',
  8505. 'ar-BH',
  8506. 'ar-DZ',
  8507. 'ar-EG',
  8508. 'ar-IQ',
  8509. 'ar-JO',
  8510. 'ar-KW',
  8511. 'ar-LB',
  8512. 'ar-LY',
  8513. 'ar-MA',
  8514. 'ar-OM',
  8515. 'ar-QA',
  8516. 'ar-SA',
  8517. 'ar-SY',
  8518. 'ar-TN',
  8519. 'ar-YE',
  8520. //'as-IN', // Moved after en-IN
  8521. 'ba-RU',
  8522. 'be-BY',
  8523. 'bg-BG',
  8524. 'bn-BD',
  8525. //'bn-IN', // Moved after en-IN
  8526. 'bo-CN',
  8527. 'br-FR',
  8528. 'ca-ES',
  8529. 'co-FR',
  8530. 'cs-CZ',
  8531. 'cy-GB',
  8532. 'da-DK',
  8533. 'de-AT',
  8534. 'de-CH',
  8535. 'de-DE',
  8536. 'de-LI',
  8537. 'de-LU',
  8538. 'dv-MV',
  8539. 'el-GR',
  8540. 'en-AU',
  8541. 'en-BZ',
  8542. 'en-CA',
  8543. 'en-GB',
  8544. 'en-IE',
  8545. 'en-IN',
  8546. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  8547. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  8548. 'en-JM',
  8549. 'en-MY',
  8550. 'en-NZ',
  8551. 'en-PH',
  8552. 'en-SG',
  8553. 'en-TT',
  8554. 'en-US',
  8555. 'en-ZA',
  8556. 'en-ZW',
  8557. 'es-AR',
  8558. 'es-BO',
  8559. 'es-CL',
  8560. 'es-CO',
  8561. 'es-CR',
  8562. 'es-DO',
  8563. 'es-EC',
  8564. 'es-ES',
  8565. 'es-GT',
  8566. 'es-HN',
  8567. 'es-MX',
  8568. 'es-NI',
  8569. 'es-PA',
  8570. 'es-PE',
  8571. 'es-PR',
  8572. 'es-PY',
  8573. 'es-SV',
  8574. 'es-US',
  8575. 'es-UY',
  8576. 'es-VE',
  8577. 'et-EE',
  8578. 'eu-ES',
  8579. 'fa-IR',
  8580. 'fi-FI',
  8581. 'fo-FO',
  8582. 'fr-BE',
  8583. 'fr-CA',
  8584. 'fr-CH',
  8585. 'fr-FR',
  8586. 'fr-LU',
  8587. 'fr-MC',
  8588. 'fy-NL',
  8589. 'ga-IE',
  8590. 'gd-GB',
  8591. 'gl-ES',
  8592. 'gu-IN',
  8593. 'he-IL',
  8594. 'hi-IN',
  8595. 'hr-BA',
  8596. 'hr-HR',
  8597. 'hu-HU',
  8598. 'hy-AM',
  8599. 'id-ID',
  8600. 'ig-NG',
  8601. 'ii-CN',
  8602. 'is-IS',
  8603. 'it-CH',
  8604. 'it-IT',
  8605. 'ja-JP',
  8606. 'ka-GE',
  8607. 'kk-KZ',
  8608. 'kl-GL',
  8609. 'km-KH',
  8610. 'kn-IN',
  8611. 'ko-KR',
  8612. 'ky-KG',
  8613. 'lb-LU',
  8614. 'lo-LA',
  8615. 'lt-LT',
  8616. 'lv-LV',
  8617. 'mi-NZ',
  8618. 'mk-MK',
  8619. 'ml-IN',
  8620. 'mn-MN',
  8621. 'mr-IN',
  8622. 'ms-BN',
  8623. 'ms-MY',
  8624. 'mt-MT',
  8625. 'nb-NO',
  8626. 'ne-NP',
  8627. 'nl-BE',
  8628. 'nl-NL',
  8629. 'nn-NO',
  8630. 'oc-FR',
  8631. 'or-IN',
  8632. 'pa-IN',
  8633. 'pl-PL',
  8634. 'ps-AF',
  8635. 'pt-BR',
  8636. 'pt-PT',
  8637. 'rm-CH',
  8638. 'ro-MD',
  8639. 'ro-RO',
  8640. 'ru-RU',
  8641. 'rw-RW',
  8642. 'sa-IN',
  8643. 'se-FI',
  8644. 'se-NO',
  8645. 'se-SE',
  8646. 'si-LK',
  8647. 'sk-SK',
  8648. 'sl-SI',
  8649. 'sq-AL',
  8650. 'sv-FI',
  8651. 'sv-SE',
  8652. 'sw-KE',
  8653. 'ta-IN',
  8654. 'te-IN',
  8655. 'th-TH',
  8656. 'tk-TM',
  8657. 'tn-ZA',
  8658. 'tr-TR',
  8659. 'tt-RU',
  8660. 'ug-CN',
  8661. 'uk-UA',
  8662. 'ur-PK',
  8663. 'vi-VN',
  8664. 'wo-SN',
  8665. 'xh-ZA',
  8666. 'yo-NG',
  8667. 'zh-CN',
  8668. 'zh-HK',
  8669. 'zh-MO',
  8670. 'zh-SG',
  8671. 'zh-TW',
  8672. 'zu-ZA',
  8673. );
  8674. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  8675. if (in_array($buildprimarykeytotest, $locales)) {
  8676. return strtolower($countrycode).'_'.strtoupper($countrycode);
  8677. }
  8678. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  8679. foreach ($locales as $locale) {
  8680. $locale_language = locale_get_primary_language($locale);
  8681. $locale_region = locale_get_region($locale);
  8682. if (strtoupper($countrycode) == $locale_region) {
  8683. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  8684. return strtolower($locale_language).'_'.strtoupper($locale_region);
  8685. }
  8686. }
  8687. } else {
  8688. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  8689. }
  8690. return null;
  8691. }
  8692. /**
  8693. * Complete or removed entries into a head array (used to build tabs).
  8694. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  8695. * Or by change using hook completeTabsHead
  8696. *
  8697. * @param Conf $conf Object conf
  8698. * @param Translate $langs Object langs
  8699. * @param object|null $object Object object
  8700. * @param array $head Object head
  8701. * @param int $h New position to fill
  8702. * @param string $type Value for object where objectvalue can be
  8703. * 'thirdparty' to add a tab in third party view
  8704. * 'intervention' to add a tab in intervention view
  8705. * 'supplier_order' to add a tab in purchase order view
  8706. * 'supplier_invoice' to add a tab in purchase invoice view
  8707. * 'invoice' to add a tab in sales invoice view
  8708. * 'order' to add a tab in sales order view
  8709. * 'contract' to add a tabl in contract view
  8710. * 'product' to add a tab in product view
  8711. * 'propal' to add a tab in propal view
  8712. * 'user' to add a tab in user view
  8713. * 'group' to add a tab in group view
  8714. * 'member' to add a tab in fundation member view
  8715. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  8716. * 'ecm' to add a tab for another ecm view
  8717. * 'stock' to add a tab for warehouse view
  8718. * @param string $mode 'add' to complete head, 'remove' to remove entries
  8719. * @param string $filterorigmodule Filter on module origin: 'external' will show only external modules. 'core' only core modules. No filter (default) will add both.
  8720. * @return void
  8721. */
  8722. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
  8723. {
  8724. global $hookmanager, $db;
  8725. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  8726. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  8727. $values = explode(':', $value);
  8728. $reg = array();
  8729. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  8730. if (count($values) == 6) {
  8731. // new declaration with permissions:
  8732. // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8733. // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8734. if ($values[0] != $type) {
  8735. continue;
  8736. }
  8737. if (verifCond($values[4])) {
  8738. if ($values[3]) {
  8739. if ($filterorigmodule) { // If a filter of module origin has been requested
  8740. if (strpos($values[3], '@')) { // This is an external module
  8741. if ($filterorigmodule != 'external') {
  8742. continue;
  8743. }
  8744. } else { // This looks a core module
  8745. if ($filterorigmodule != 'core') {
  8746. continue;
  8747. }
  8748. }
  8749. }
  8750. $langs->load($values[3]);
  8751. }
  8752. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8753. // If label is "SUBSTITUION_..."
  8754. $substitutionarray = array();
  8755. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8756. $label = make_substitutions($reg[1], $substitutionarray);
  8757. } else {
  8758. // If label is "Label,Class,File,Method", we call the method to show content inside the badge
  8759. $labeltemp = explode(',', $values[2]);
  8760. $label = $langs->trans($labeltemp[0]);
  8761. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  8762. dol_include_once($labeltemp[2]);
  8763. $classtoload = $labeltemp[1];
  8764. if (class_exists($classtoload)) {
  8765. $obj = new $classtoload($db);
  8766. $function = $labeltemp[3];
  8767. if ($obj && $function && method_exists($obj, $function)) {
  8768. $nbrec = $obj->$function($object->id, $obj);
  8769. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  8770. }
  8771. }
  8772. }
  8773. }
  8774. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  8775. $head[$h][1] = $label;
  8776. $head[$h][2] = str_replace('+', '', $values[1]);
  8777. $h++;
  8778. }
  8779. } elseif (count($values) == 5) { // case deprecated
  8780. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  8781. if ($values[0] != $type) {
  8782. continue;
  8783. }
  8784. if ($values[3]) {
  8785. if ($filterorigmodule) { // If a filter of module origin has been requested
  8786. if (strpos($values[3], '@')) { // This is an external module
  8787. if ($filterorigmodule != 'external') {
  8788. continue;
  8789. }
  8790. } else { // This looks a core module
  8791. if ($filterorigmodule != 'core') {
  8792. continue;
  8793. }
  8794. }
  8795. }
  8796. $langs->load($values[3]);
  8797. }
  8798. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8799. $substitutionarray = array();
  8800. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8801. $label = make_substitutions($reg[1], $substitutionarray);
  8802. } else {
  8803. $label = $langs->trans($values[2]);
  8804. }
  8805. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  8806. $head[$h][1] = $label;
  8807. $head[$h][2] = str_replace('+', '', $values[1]);
  8808. $h++;
  8809. }
  8810. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  8811. if ($values[0] != $type) {
  8812. continue;
  8813. }
  8814. $tabname = str_replace('-', '', $values[1]);
  8815. foreach ($head as $key => $val) {
  8816. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  8817. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  8818. if ($head[$key][2] == $tabname && $condition) {
  8819. unset($head[$key]);
  8820. break;
  8821. }
  8822. }
  8823. }
  8824. }
  8825. }
  8826. // No need to make a return $head. Var is modified as a reference
  8827. if (!empty($hookmanager)) {
  8828. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
  8829. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  8830. if ($reshook > 0) { // Hook ask to replace completely the array
  8831. $head = $hookmanager->resArray;
  8832. } else { // Hook
  8833. $head = array_merge($head, $hookmanager->resArray);
  8834. }
  8835. $h = count($head);
  8836. }
  8837. }
  8838. /**
  8839. * Print common footer :
  8840. * conf->global->MAIN_HTML_FOOTER
  8841. * js for switch of menu hider
  8842. * js for conf->global->MAIN_GOOGLE_AN_ID
  8843. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  8844. * js for conf->logbuffer
  8845. *
  8846. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  8847. * @return void
  8848. */
  8849. function printCommonFooter($zone = 'private')
  8850. {
  8851. global $conf, $hookmanager, $user, $debugbar;
  8852. global $action;
  8853. global $micro_start_time;
  8854. if ($zone == 'private') {
  8855. print "\n".'<!-- Common footer for private page -->'."\n";
  8856. } else {
  8857. print "\n".'<!-- Common footer for public page -->'."\n";
  8858. }
  8859. // A div to store page_y POST parameter so we can read it using javascript
  8860. print "\n<!-- A div to store page_y POST parameter -->\n";
  8861. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  8862. $parameters = array();
  8863. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  8864. if (empty($reshook)) {
  8865. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  8866. print $conf->global->MAIN_HTML_FOOTER."\n";
  8867. }
  8868. print "\n";
  8869. if (!empty($conf->use_javascript_ajax)) {
  8870. print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and madatory fields, tuning info, ... -->\n";
  8871. print '<script>'."\n";
  8872. print 'jQuery(document).ready(function() {'."\n";
  8873. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  8874. print "\n";
  8875. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  8876. print 'jQuery("li.menuhider").click(function(event) {';
  8877. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  8878. print ' console.log("We click on .menuhider");'."\n";
  8879. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  8880. print '});'."\n";
  8881. }
  8882. // Management of focus and mandatory for fields
  8883. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))) || ((empty($action) || $action == 'addline') && (preg_match('/card\.php/', $_SERVER["PHP_SELF"])))) {
  8884. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  8885. $relativepathstring = $_SERVER["PHP_SELF"];
  8886. // Clean $relativepathstring
  8887. if (constant('DOL_URL_ROOT')) {
  8888. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  8889. }
  8890. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  8891. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  8892. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  8893. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  8894. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  8895. $qualified = 0;
  8896. if ($defkey != '_noquery_') {
  8897. $tmpqueryarraytohave = explode('&', $defkey);
  8898. $foundintru = 0;
  8899. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8900. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8901. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8902. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8903. $foundintru = 1;
  8904. }
  8905. }
  8906. if (!$foundintru) {
  8907. $qualified = 1;
  8908. }
  8909. //var_dump($defkey.'-'.$qualified);
  8910. } else {
  8911. $qualified = 1;
  8912. }
  8913. if ($qualified) {
  8914. foreach ($defval as $paramkey => $paramval) {
  8915. // Set focus on field
  8916. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  8917. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  8918. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  8919. }
  8920. }
  8921. }
  8922. }
  8923. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  8924. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  8925. $qualified = 0;
  8926. if ($defkey != '_noquery_') {
  8927. $tmpqueryarraytohave = explode('&', $defkey);
  8928. $foundintru = 0;
  8929. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8930. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8931. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8932. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8933. $foundintru = 1;
  8934. }
  8935. }
  8936. if (!$foundintru) {
  8937. $qualified = 1;
  8938. }
  8939. //var_dump($defkey.'-'.$qualified);
  8940. } else {
  8941. $qualified = 1;
  8942. }
  8943. if ($qualified) {
  8944. foreach ($defval as $paramkey => $paramval) {
  8945. // Add property 'required' on input
  8946. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8947. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8948. 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";
  8949. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8950. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  8951. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  8952. // Add 'field required' class on closest td for all input elements : input, textarea and select
  8953. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  8954. }
  8955. }
  8956. }
  8957. }
  8958. }
  8959. print '});'."\n";
  8960. // End of tuning
  8961. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  8962. print "\n";
  8963. print "/* JS CODE TO ENABLE to add memory info */\n";
  8964. print 'window.console && console.log("';
  8965. if (!empty($conf->global->MEMCACHED_SERVER)) {
  8966. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  8967. }
  8968. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  8969. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  8970. $micro_end_time = microtime(true);
  8971. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  8972. }
  8973. if (function_exists("memory_get_usage")) {
  8974. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  8975. }
  8976. if (function_exists("memory_get_peak_usage")) {
  8977. print ' - Real mem peak: '.memory_get_peak_usage(true);
  8978. }
  8979. if (function_exists("zend_loader_file_encoded")) {
  8980. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8981. }
  8982. print '");'."\n";
  8983. }
  8984. print "\n".'</script>'."\n";
  8985. // Google Analytics
  8986. // TODO Add a hook here
  8987. if (isModEnabled('google') && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8988. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8989. foreach ($tmptagarray as $tmptag) {
  8990. print "\n";
  8991. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8992. print '
  8993. <!-- Global site tag (gtag.js) - Google Analytics -->
  8994. <script nonce="'.getNonce().'" async src="https://www.googletagmanager.com/gtag/js?id='.trim($tmptag).'"></script>
  8995. <script>
  8996. window.dataLayer = window.dataLayer || [];
  8997. function gtag(){dataLayer.push(arguments);}
  8998. gtag(\'js\', new Date());
  8999. gtag(\'config\', \''.trim($tmptag).'\');
  9000. </script>';
  9001. print "\n";
  9002. }
  9003. }
  9004. }
  9005. // Add Xdebug coverage of code
  9006. if (defined('XDEBUGCOVERAGE')) {
  9007. print_r(xdebug_get_code_coverage());
  9008. }
  9009. // Add DebugBar data
  9010. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  9011. $debugbar['time']->stopMeasure('pageaftermaster');
  9012. print '<!-- Output debugbar data -->'."\n";
  9013. $renderer = $debugbar->getRenderer();
  9014. print $debugbar->getRenderer()->render();
  9015. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  9016. print "\n";
  9017. print "<!-- Start of log output\n";
  9018. //print '<div class="hidden">'."\n";
  9019. foreach ($conf->logbuffer as $logline) {
  9020. print $logline."<br>\n";
  9021. }
  9022. //print '</div>'."\n";
  9023. print "End of log output -->\n";
  9024. }
  9025. }
  9026. }
  9027. /**
  9028. * Split a string with 2 keys into key array.
  9029. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  9030. *
  9031. * @param string $string String to explode
  9032. * @param string $delimiter Delimiter between each couple of data. Example: ';' or '[\n;]+' or '(\n\r|\r|\n|;)'
  9033. * @param string $kv Delimiter between key and value
  9034. * @return array Array of data exploded
  9035. */
  9036. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  9037. {
  9038. if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\(.*\)$/sm', $delimiter)) {
  9039. // This is a regex string
  9040. $newdelimiter = $delimiter;
  9041. } else {
  9042. // This is a simple string
  9043. $newdelimiter = preg_quote($delimiter, '/');
  9044. }
  9045. if ($a = preg_split('/'.$newdelimiter.'/', $string)) {
  9046. $ka = array();
  9047. foreach ($a as $s) { // each part
  9048. if ($s) {
  9049. if ($pos = strpos($s, $kv)) { // key/value delimiter
  9050. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  9051. } else { // key delimiter not found
  9052. $ka[] = trim($s);
  9053. }
  9054. }
  9055. }
  9056. return $ka;
  9057. }
  9058. return array();
  9059. }
  9060. /**
  9061. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  9062. *
  9063. * @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.
  9064. * @return void
  9065. */
  9066. function dol_set_focus($selector)
  9067. {
  9068. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  9069. print '<script nonce="'.getNonce().'">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  9070. }
  9071. /**
  9072. * Return getmypid() or random PID when function is disabled
  9073. * Some web hosts disable this php function for security reasons
  9074. * and sometimes we can't redeclare function.
  9075. *
  9076. * @return int
  9077. */
  9078. function dol_getmypid()
  9079. {
  9080. if (!function_exists('getmypid')) {
  9081. return mt_rand(99900000, 99965535);
  9082. } else {
  9083. return getmypid(); // May be a number on 64 bits (depending on OS)
  9084. }
  9085. }
  9086. /**
  9087. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  9088. *
  9089. * @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")
  9090. * @param string $value The value to look for.
  9091. * If param $mode is 0, can contains several keywords separated with a space or |
  9092. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  9093. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  9094. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < -1000"
  9095. * If param $mode is 2 or -2, can contains a list of int id separated by comma like "1,3,4"
  9096. * If param $mode is 3 or -3, can contains a list of string separated by comma like "a,b,c".
  9097. * @param integer $mode 0=value is list of keyword strings, 1=value is a numeric test (Example ">5.5 <10"), 2=value is a list of ID separated with comma (Example '1,3,4'), -2 is for exclude list,
  9098. * 3=value is list of string separated with comma (Example 'text 1,text 2'), -3 if for exclude list, 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
  9099. * @param integer $nofirstand 1=Do not output the first 'AND'
  9100. * @return string $res The statement to append to the SQL query
  9101. * @see dolSqlDateFilter()
  9102. */
  9103. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  9104. {
  9105. global $db, $langs;
  9106. $value = trim($value);
  9107. if ($mode == 0) {
  9108. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  9109. }
  9110. if ($mode == 1) {
  9111. $value = preg_replace('/([!<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can then explode on space to get all tests to do
  9112. }
  9113. $value = preg_replace('/\s*\|\s*/', '|', $value);
  9114. $crits = explode(' ', $value);
  9115. $res = '';
  9116. if (!is_array($fields)) {
  9117. $fields = array($fields);
  9118. }
  9119. $i1 = 0; // count the nb of and criteria added (all fields / criterias)
  9120. foreach ($crits as $crit) { // Loop on each AND criteria
  9121. $crit = trim($crit);
  9122. $i2 = 0; // count the nb of valid criteria added for this this first criteria
  9123. $newres = '';
  9124. foreach ($fields as $field) {
  9125. if ($mode == 1) {
  9126. $tmpcrits = explode('|', $crit);
  9127. $i3 = 0; // count the nb of valid criteria added for this current field
  9128. foreach ($tmpcrits as $tmpcrit) {
  9129. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9130. continue;
  9131. }
  9132. $tmpcrit = trim($tmpcrit);
  9133. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9134. $operator = '=';
  9135. $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
  9136. $reg = array();
  9137. preg_match('/([!<>=]+)/', $tmpcrit, $reg);
  9138. if (!empty($reg[1])) {
  9139. $operator = $reg[1];
  9140. }
  9141. if ($newcrit != '') {
  9142. $numnewcrit = price2num($newcrit);
  9143. if (is_numeric($numnewcrit)) {
  9144. $newres .= $field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  9145. } else {
  9146. $newres .= '1 = 2'; // force false, we received a corrupted data
  9147. }
  9148. $i3++; // a criteria was added to string
  9149. }
  9150. }
  9151. $i2++; // a criteria for 1 more field was added to string
  9152. } elseif ($mode == 2 || $mode == -2) {
  9153. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  9154. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  9155. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  9156. if ($mode == -2) {
  9157. $newres .= ' OR '.$field.' IS NULL';
  9158. }
  9159. $i2++; // a criteria for 1 more field was added to string
  9160. } elseif ($mode == 3 || $mode == -3) {
  9161. $tmparray = explode(',', $crit);
  9162. if (count($tmparray)) {
  9163. $listofcodes = '';
  9164. foreach ($tmparray as $val) {
  9165. $val = trim($val);
  9166. if ($val) {
  9167. $listofcodes .= ($listofcodes ? ',' : '');
  9168. $listofcodes .= "'".$db->escape($val)."'";
  9169. }
  9170. }
  9171. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  9172. $i2++; // a criteria for 1 more field was added to string
  9173. }
  9174. if ($mode == -3) {
  9175. $newres .= ' OR '.$field.' IS NULL';
  9176. }
  9177. } elseif ($mode == 4) {
  9178. $tmparray = explode(',', $crit);
  9179. if (count($tmparray)) {
  9180. $listofcodes = '';
  9181. foreach ($tmparray as $val) {
  9182. $val = trim($val);
  9183. if ($val) {
  9184. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  9185. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  9186. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  9187. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  9188. $newres .= ')';
  9189. $i2++; // a criteria for 1 more field was added to string (we can add several citeria for the same field as it is a multiselect search criteria)
  9190. }
  9191. }
  9192. }
  9193. } else { // $mode=0
  9194. $tmpcrits = explode('|', $crit);
  9195. $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
  9196. foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
  9197. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9198. continue;
  9199. }
  9200. $tmpcrit = trim($tmpcrit);
  9201. if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
  9202. $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
  9203. } else {
  9204. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9205. }
  9206. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  9207. $newres .= $field." = ".(is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
  9208. } else {
  9209. $tmpcrit2 = $tmpcrit;
  9210. $tmpbefore = '%';
  9211. $tmpafter = '%';
  9212. $tmps = '';
  9213. if (preg_match('/^!/', $tmpcrit)) {
  9214. $tmps .= $field." NOT LIKE "; // ! as exclude character
  9215. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  9216. } else {
  9217. $tmps .= $field." LIKE ";
  9218. }
  9219. $tmps .= "'";
  9220. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  9221. $tmpbefore = '';
  9222. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  9223. }
  9224. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  9225. $tmpafter = '';
  9226. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  9227. }
  9228. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9229. $tmps = "(".$tmps;
  9230. }
  9231. $newres .= $tmps;
  9232. $newres .= $tmpbefore;
  9233. $newres .= $db->escape($tmpcrit2);
  9234. $newres .= $tmpafter;
  9235. $newres .= "'";
  9236. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9237. $newres .= " OR ".$field." IS NULL)";
  9238. }
  9239. }
  9240. $i3++;
  9241. }
  9242. $i2++; // a criteria for 1 more field was added to string
  9243. }
  9244. }
  9245. if ($newres) {
  9246. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  9247. }
  9248. $i1++;
  9249. }
  9250. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  9251. return $res;
  9252. }
  9253. /**
  9254. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  9255. *
  9256. * @param Object $object Object
  9257. * @return string Url string
  9258. */
  9259. function showDirectDownloadLink($object)
  9260. {
  9261. global $conf, $langs;
  9262. $out = '';
  9263. $url = $object->getLastMainDocLink($object->element);
  9264. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  9265. if ($url) {
  9266. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  9267. $out .= ajax_autoselect("directdownloadlink", 0);
  9268. } else {
  9269. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  9270. }
  9271. return $out;
  9272. }
  9273. /**
  9274. * Return the filename of file to get the thumbs
  9275. *
  9276. * @param string $file Original filename (full or relative path)
  9277. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  9278. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  9279. * @return string New file name (full or relative path, including the thumbs/). May be the original path if no thumb can exists.
  9280. */
  9281. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  9282. {
  9283. $dirName = dirname($file);
  9284. if ($dirName == '.') {
  9285. $dirName = '';
  9286. }
  9287. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  9288. $fileName = basename($fileName);
  9289. if (empty($extImgTarget)) {
  9290. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  9291. }
  9292. if (empty($extImgTarget)) {
  9293. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  9294. }
  9295. if (empty($extImgTarget)) {
  9296. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  9297. }
  9298. if (empty($extImgTarget)) {
  9299. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  9300. }
  9301. if (empty($extImgTarget)) {
  9302. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  9303. }
  9304. if (empty($extImgTarget)) {
  9305. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  9306. }
  9307. if (!$extImgTarget) {
  9308. return $file;
  9309. }
  9310. $subdir = '';
  9311. if ($extName) {
  9312. $subdir = 'thumbs/';
  9313. }
  9314. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  9315. }
  9316. /**
  9317. * Return URL we can use for advanced preview links
  9318. *
  9319. * @param string $modulepart propal, facture, facture_fourn, ...
  9320. * @param string $relativepath Relative path of docs.
  9321. * @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)
  9322. * @param string $param More param on http links
  9323. * @return string|array Output string with href link or array with all components of link
  9324. */
  9325. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  9326. {
  9327. global $conf, $langs;
  9328. if (empty($conf->use_javascript_ajax)) {
  9329. return '';
  9330. }
  9331. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  9332. if ($alldata == 1) {
  9333. if ($isAllowedForPreview) {
  9334. 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));
  9335. } else {
  9336. return array();
  9337. }
  9338. }
  9339. // old behavior, return a string
  9340. if ($isAllowedForPreview) {
  9341. 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')).'\')';
  9342. } else {
  9343. return '';
  9344. }
  9345. }
  9346. /**
  9347. * Make content of an input box selected when we click into input field.
  9348. *
  9349. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  9350. * @param string $addlink Add a 'link to' after
  9351. * @param string $textonlink Text to show on link or 'image'
  9352. * @return string
  9353. */
  9354. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  9355. {
  9356. global $langs;
  9357. $out = '<script nonce="'.getNonce().'">
  9358. jQuery(document).ready(function () {
  9359. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  9360. });
  9361. </script>';
  9362. if ($addlink) {
  9363. if ($textonlink === 'image') {
  9364. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  9365. } else {
  9366. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  9367. }
  9368. }
  9369. return $out;
  9370. }
  9371. /**
  9372. * Return if a file is qualified for preview
  9373. *
  9374. * @param string $file Filename we looking for information
  9375. * @return int 1 If allowed, 0 otherwise
  9376. * @see dol_mimetype(), image_format_supported() from images.lib.php
  9377. */
  9378. function dolIsAllowedForPreview($file)
  9379. {
  9380. global $conf;
  9381. // Check .noexe extension in filename
  9382. if (preg_match('/\.noexe$/i', $file)) {
  9383. return 0;
  9384. }
  9385. // Check mime types
  9386. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  9387. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  9388. $mime_preview[] = 'svg+xml';
  9389. }
  9390. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  9391. //$mime_preview[]='archive';
  9392. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  9393. if ($num_mime !== false) {
  9394. return 1;
  9395. }
  9396. // By default, not allowed for preview
  9397. return 0;
  9398. }
  9399. /**
  9400. * Return MIME type of a file from its name with extension.
  9401. *
  9402. * @param string $file Filename we looking for MIME type
  9403. * @param string $default Default mime type if extension not found in known list
  9404. * @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
  9405. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  9406. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  9407. */
  9408. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  9409. {
  9410. $mime = $default;
  9411. $imgmime = 'other.png';
  9412. $famime = 'file-o';
  9413. $srclang = '';
  9414. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  9415. // Plain text files
  9416. if (preg_match('/\.txt$/i', $tmpfile)) {
  9417. $mime = 'text/plain';
  9418. $imgmime = 'text.png';
  9419. $famime = 'file-text-o';
  9420. }
  9421. if (preg_match('/\.rtx$/i', $tmpfile)) {
  9422. $mime = 'text/richtext';
  9423. $imgmime = 'text.png';
  9424. $famime = 'file-text-o';
  9425. }
  9426. if (preg_match('/\.csv$/i', $tmpfile)) {
  9427. $mime = 'text/csv';
  9428. $imgmime = 'text.png';
  9429. $famime = 'file-text-o';
  9430. }
  9431. if (preg_match('/\.tsv$/i', $tmpfile)) {
  9432. $mime = 'text/tab-separated-values';
  9433. $imgmime = 'text.png';
  9434. $famime = 'file-text-o';
  9435. }
  9436. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  9437. $mime = 'text/plain';
  9438. $imgmime = 'text.png';
  9439. $famime = 'file-text-o';
  9440. }
  9441. if (preg_match('/\.ini$/i', $tmpfile)) {
  9442. $mime = 'text/plain';
  9443. $imgmime = 'text.png';
  9444. $srclang = 'ini';
  9445. $famime = 'file-text-o';
  9446. }
  9447. if (preg_match('/\.md$/i', $tmpfile)) {
  9448. $mime = 'text/plain';
  9449. $imgmime = 'text.png';
  9450. $srclang = 'md';
  9451. $famime = 'file-text-o';
  9452. }
  9453. if (preg_match('/\.css$/i', $tmpfile)) {
  9454. $mime = 'text/css';
  9455. $imgmime = 'css.png';
  9456. $srclang = 'css';
  9457. $famime = 'file-text-o';
  9458. }
  9459. if (preg_match('/\.lang$/i', $tmpfile)) {
  9460. $mime = 'text/plain';
  9461. $imgmime = 'text.png';
  9462. $srclang = 'lang';
  9463. $famime = 'file-text-o';
  9464. }
  9465. // Certificate files
  9466. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  9467. $mime = 'text/plain';
  9468. $imgmime = 'text.png';
  9469. $famime = 'file-text-o';
  9470. }
  9471. // XML based (HTML/XML/XAML)
  9472. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  9473. $mime = 'text/html';
  9474. $imgmime = 'html.png';
  9475. $srclang = 'html';
  9476. $famime = 'file-text-o';
  9477. }
  9478. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  9479. $mime = 'text/xml';
  9480. $imgmime = 'other.png';
  9481. $srclang = 'xml';
  9482. $famime = 'file-text-o';
  9483. }
  9484. if (preg_match('/\.xaml$/i', $tmpfile)) {
  9485. $mime = 'text/xml';
  9486. $imgmime = 'other.png';
  9487. $srclang = 'xaml';
  9488. $famime = 'file-text-o';
  9489. }
  9490. // Languages
  9491. if (preg_match('/\.bas$/i', $tmpfile)) {
  9492. $mime = 'text/plain';
  9493. $imgmime = 'text.png';
  9494. $srclang = 'bas';
  9495. $famime = 'file-code-o';
  9496. }
  9497. if (preg_match('/\.(c)$/i', $tmpfile)) {
  9498. $mime = 'text/plain';
  9499. $imgmime = 'text.png';
  9500. $srclang = 'c';
  9501. $famime = 'file-code-o';
  9502. }
  9503. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  9504. $mime = 'text/plain';
  9505. $imgmime = 'text.png';
  9506. $srclang = 'cpp';
  9507. $famime = 'file-code-o';
  9508. }
  9509. if (preg_match('/\.cs$/i', $tmpfile)) {
  9510. $mime = 'text/plain';
  9511. $imgmime = 'text.png';
  9512. $srclang = 'cs';
  9513. $famime = 'file-code-o';
  9514. }
  9515. if (preg_match('/\.(h)$/i', $tmpfile)) {
  9516. $mime = 'text/plain';
  9517. $imgmime = 'text.png';
  9518. $srclang = 'h';
  9519. $famime = 'file-code-o';
  9520. }
  9521. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  9522. $mime = 'text/plain';
  9523. $imgmime = 'text.png';
  9524. $srclang = 'java';
  9525. $famime = 'file-code-o';
  9526. }
  9527. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  9528. $mime = 'text/plain';
  9529. $imgmime = 'php.png';
  9530. $srclang = 'php';
  9531. $famime = 'file-code-o';
  9532. }
  9533. if (preg_match('/\.phtml$/i', $tmpfile)) {
  9534. $mime = 'text/plain';
  9535. $imgmime = 'php.png';
  9536. $srclang = 'php';
  9537. $famime = 'file-code-o';
  9538. }
  9539. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  9540. $mime = 'text/plain';
  9541. $imgmime = 'pl.png';
  9542. $srclang = 'perl';
  9543. $famime = 'file-code-o';
  9544. }
  9545. if (preg_match('/\.sql$/i', $tmpfile)) {
  9546. $mime = 'text/plain';
  9547. $imgmime = 'text.png';
  9548. $srclang = 'sql';
  9549. $famime = 'file-code-o';
  9550. }
  9551. if (preg_match('/\.js$/i', $tmpfile)) {
  9552. $mime = 'text/x-javascript';
  9553. $imgmime = 'jscript.png';
  9554. $srclang = 'js';
  9555. $famime = 'file-code-o';
  9556. }
  9557. // Open office
  9558. if (preg_match('/\.odp$/i', $tmpfile)) {
  9559. $mime = 'application/vnd.oasis.opendocument.presentation';
  9560. $imgmime = 'ooffice.png';
  9561. $famime = 'file-powerpoint-o';
  9562. }
  9563. if (preg_match('/\.ods$/i', $tmpfile)) {
  9564. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  9565. $imgmime = 'ooffice.png';
  9566. $famime = 'file-excel-o';
  9567. }
  9568. if (preg_match('/\.odt$/i', $tmpfile)) {
  9569. $mime = 'application/vnd.oasis.opendocument.text';
  9570. $imgmime = 'ooffice.png';
  9571. $famime = 'file-word-o';
  9572. }
  9573. // MS Office
  9574. if (preg_match('/\.mdb$/i', $tmpfile)) {
  9575. $mime = 'application/msaccess';
  9576. $imgmime = 'mdb.png';
  9577. $famime = 'file-o';
  9578. }
  9579. if (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
  9580. $mime = 'application/msword';
  9581. $imgmime = 'doc.png';
  9582. $famime = 'file-word-o';
  9583. }
  9584. if (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
  9585. $mime = 'application/msword';
  9586. $imgmime = 'doc.png';
  9587. $famime = 'file-word-o';
  9588. }
  9589. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  9590. $mime = 'application/vnd.ms-excel';
  9591. $imgmime = 'xls.png';
  9592. $famime = 'file-excel-o';
  9593. }
  9594. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  9595. $mime = 'application/vnd.ms-excel';
  9596. $imgmime = 'xls.png';
  9597. $famime = 'file-excel-o';
  9598. }
  9599. if (preg_match('/\.xls$/i', $tmpfile)) {
  9600. $mime = 'application/vnd.ms-excel';
  9601. $imgmime = 'xls.png';
  9602. $famime = 'file-excel-o';
  9603. }
  9604. if (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
  9605. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  9606. $imgmime = 'xls.png';
  9607. $famime = 'file-excel-o';
  9608. }
  9609. if (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
  9610. $mime = 'application/vnd.ms-powerpoint';
  9611. $imgmime = 'ppt.png';
  9612. $famime = 'file-powerpoint-o';
  9613. }
  9614. if (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
  9615. $mime = 'application/x-mspowerpoint';
  9616. $imgmime = 'ppt.png';
  9617. $famime = 'file-powerpoint-o';
  9618. }
  9619. // Other
  9620. if (preg_match('/\.pdf$/i', $tmpfile)) {
  9621. $mime = 'application/pdf';
  9622. $imgmime = 'pdf.png';
  9623. $famime = 'file-pdf-o';
  9624. }
  9625. // Scripts
  9626. if (preg_match('/\.bat$/i', $tmpfile)) {
  9627. $mime = 'text/x-bat';
  9628. $imgmime = 'script.png';
  9629. $srclang = 'dos';
  9630. $famime = 'file-code-o';
  9631. }
  9632. if (preg_match('/\.sh$/i', $tmpfile)) {
  9633. $mime = 'text/x-sh';
  9634. $imgmime = 'script.png';
  9635. $srclang = 'bash';
  9636. $famime = 'file-code-o';
  9637. }
  9638. if (preg_match('/\.ksh$/i', $tmpfile)) {
  9639. $mime = 'text/x-ksh';
  9640. $imgmime = 'script.png';
  9641. $srclang = 'bash';
  9642. $famime = 'file-code-o';
  9643. }
  9644. if (preg_match('/\.bash$/i', $tmpfile)) {
  9645. $mime = 'text/x-bash';
  9646. $imgmime = 'script.png';
  9647. $srclang = 'bash';
  9648. $famime = 'file-code-o';
  9649. }
  9650. // Images
  9651. if (preg_match('/\.ico$/i', $tmpfile)) {
  9652. $mime = 'image/x-icon';
  9653. $imgmime = 'image.png';
  9654. $famime = 'file-image-o';
  9655. }
  9656. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  9657. $mime = 'image/jpeg';
  9658. $imgmime = 'image.png';
  9659. $famime = 'file-image-o';
  9660. }
  9661. if (preg_match('/\.png$/i', $tmpfile)) {
  9662. $mime = 'image/png';
  9663. $imgmime = 'image.png';
  9664. $famime = 'file-image-o';
  9665. }
  9666. if (preg_match('/\.gif$/i', $tmpfile)) {
  9667. $mime = 'image/gif';
  9668. $imgmime = 'image.png';
  9669. $famime = 'file-image-o';
  9670. }
  9671. if (preg_match('/\.bmp$/i', $tmpfile)) {
  9672. $mime = 'image/bmp';
  9673. $imgmime = 'image.png';
  9674. $famime = 'file-image-o';
  9675. }
  9676. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  9677. $mime = 'image/tiff';
  9678. $imgmime = 'image.png';
  9679. $famime = 'file-image-o';
  9680. }
  9681. if (preg_match('/\.svg$/i', $tmpfile)) {
  9682. $mime = 'image/svg+xml';
  9683. $imgmime = 'image.png';
  9684. $famime = 'file-image-o';
  9685. }
  9686. if (preg_match('/\.webp$/i', $tmpfile)) {
  9687. $mime = 'image/webp';
  9688. $imgmime = 'image.png';
  9689. $famime = 'file-image-o';
  9690. }
  9691. // Calendar
  9692. if (preg_match('/\.vcs$/i', $tmpfile)) {
  9693. $mime = 'text/calendar';
  9694. $imgmime = 'other.png';
  9695. $famime = 'file-text-o';
  9696. }
  9697. if (preg_match('/\.ics$/i', $tmpfile)) {
  9698. $mime = 'text/calendar';
  9699. $imgmime = 'other.png';
  9700. $famime = 'file-text-o';
  9701. }
  9702. // Other
  9703. if (preg_match('/\.torrent$/i', $tmpfile)) {
  9704. $mime = 'application/x-bittorrent';
  9705. $imgmime = 'other.png';
  9706. $famime = 'file-o';
  9707. }
  9708. // Audio
  9709. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  9710. $mime = 'audio';
  9711. $imgmime = 'audio.png';
  9712. $famime = 'file-audio-o';
  9713. }
  9714. // Video
  9715. if (preg_match('/\.mp4$/i', $tmpfile)) {
  9716. $mime = 'video/mp4';
  9717. $imgmime = 'video.png';
  9718. $famime = 'file-video-o';
  9719. }
  9720. if (preg_match('/\.ogv$/i', $tmpfile)) {
  9721. $mime = 'video/ogg';
  9722. $imgmime = 'video.png';
  9723. $famime = 'file-video-o';
  9724. }
  9725. if (preg_match('/\.webm$/i', $tmpfile)) {
  9726. $mime = 'video/webm';
  9727. $imgmime = 'video.png';
  9728. $famime = 'file-video-o';
  9729. }
  9730. if (preg_match('/\.avi$/i', $tmpfile)) {
  9731. $mime = 'video/x-msvideo';
  9732. $imgmime = 'video.png';
  9733. $famime = 'file-video-o';
  9734. }
  9735. if (preg_match('/\.divx$/i', $tmpfile)) {
  9736. $mime = 'video/divx';
  9737. $imgmime = 'video.png';
  9738. $famime = 'file-video-o';
  9739. }
  9740. if (preg_match('/\.xvid$/i', $tmpfile)) {
  9741. $mime = 'video/xvid';
  9742. $imgmime = 'video.png';
  9743. $famime = 'file-video-o';
  9744. }
  9745. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  9746. $mime = 'video';
  9747. $imgmime = 'video.png';
  9748. $famime = 'file-video-o';
  9749. }
  9750. // Archive
  9751. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  9752. $mime = 'archive';
  9753. $imgmime = 'archive.png';
  9754. $famime = 'file-archive-o';
  9755. } // application/xxx where zzz is zip, ...
  9756. // Exe
  9757. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  9758. $mime = 'application/octet-stream';
  9759. $imgmime = 'other.png';
  9760. $famime = 'file-o';
  9761. }
  9762. // Lib
  9763. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  9764. $mime = 'library';
  9765. $imgmime = 'library.png';
  9766. $famime = 'file-o';
  9767. }
  9768. // Err
  9769. if (preg_match('/\.err$/i', $tmpfile)) {
  9770. $mime = 'error';
  9771. $imgmime = 'error.png';
  9772. $famime = 'file-text-o';
  9773. }
  9774. // Return string
  9775. if ($mode == 1) {
  9776. $tmp = explode('/', $mime);
  9777. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  9778. }
  9779. if ($mode == 2) {
  9780. return $imgmime;
  9781. }
  9782. if ($mode == 3) {
  9783. return $srclang;
  9784. }
  9785. if ($mode == 4) {
  9786. return $famime;
  9787. }
  9788. return $mime;
  9789. }
  9790. /**
  9791. * Return the value of a filed into a dictionary for the record $id.
  9792. * This also set all the values into a cache for a next search.
  9793. *
  9794. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  9795. * @param string $field The name of field where to find the value to return
  9796. * @param int $id Id of line record
  9797. * @param bool $checkentity Add filter on entity
  9798. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  9799. * @return string The value of field $field. This also set $dictvalues cache.
  9800. */
  9801. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  9802. {
  9803. global $conf, $db;
  9804. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  9805. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  9806. if (is_null($dictvalues)) {
  9807. $dictvalues = array();
  9808. $sql = "SELECT * FROM ".MAIN_DB_PREFIX.$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  9809. if ($checkentity) {
  9810. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  9811. }
  9812. $resql = $db->query($sql);
  9813. if ($resql) {
  9814. while ($obj = $db->fetch_object($resql)) {
  9815. $dictvalues[$obj->{$rowidfield}] = $obj; // $obj is stdClass
  9816. }
  9817. } else {
  9818. dol_print_error($db);
  9819. }
  9820. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  9821. }
  9822. if (!empty($dictvalues[$id])) {
  9823. // Found
  9824. $tmp = $dictvalues[$id];
  9825. return (property_exists($tmp, $field) ? $tmp->$field : '');
  9826. } else {
  9827. // Not found
  9828. return '';
  9829. }
  9830. }
  9831. /**
  9832. * Return true if the color is light
  9833. *
  9834. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  9835. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  9836. */
  9837. function colorIsLight($stringcolor)
  9838. {
  9839. $stringcolor = str_replace('#', '', $stringcolor);
  9840. $res = -1;
  9841. if (!empty($stringcolor)) {
  9842. $res = 0;
  9843. $tmp = explode(',', $stringcolor);
  9844. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  9845. $r = $tmp[0];
  9846. $g = $tmp[1];
  9847. $b = $tmp[2];
  9848. } else {
  9849. $hexr = $stringcolor[0].$stringcolor[1];
  9850. $hexg = $stringcolor[2].$stringcolor[3];
  9851. $hexb = $stringcolor[4].$stringcolor[5];
  9852. $r = hexdec($hexr);
  9853. $g = hexdec($hexg);
  9854. $b = hexdec($hexb);
  9855. }
  9856. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  9857. if ($bright > 0.6) {
  9858. $res = 1;
  9859. }
  9860. }
  9861. return $res;
  9862. }
  9863. /**
  9864. * Function to test if an entry is enabled or not
  9865. *
  9866. * @param string $type_user 0=We test for internal user, 1=We test for external user
  9867. * @param array $menuentry Array for feature entry to test
  9868. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  9869. * @return int 0=Hide, 1=Show, 2=Show gray
  9870. */
  9871. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  9872. {
  9873. global $conf;
  9874. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  9875. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  9876. if (empty($menuentry['enabled'])) {
  9877. return 0; // Entry disabled by condition
  9878. }
  9879. if ($type_user && $menuentry['module']) {
  9880. $tmploops = explode('|', $menuentry['module']);
  9881. $found = 0;
  9882. foreach ($tmploops as $tmploop) {
  9883. if (in_array($tmploop, $listofmodulesforexternal)) {
  9884. $found++;
  9885. break;
  9886. }
  9887. }
  9888. if (!$found) {
  9889. return 0; // Entry is for menus all excluded to external users
  9890. }
  9891. }
  9892. if (!$menuentry['perms'] && $type_user) {
  9893. return 0; // No permissions and user is external
  9894. }
  9895. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  9896. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  9897. }
  9898. if (!$menuentry['perms']) {
  9899. return 2; // No permissions and user is external
  9900. }
  9901. return 1;
  9902. }
  9903. /**
  9904. * Round to next multiple.
  9905. *
  9906. * @param double $n Number to round up
  9907. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  9908. * @return integer Value rounded.
  9909. */
  9910. function roundUpToNextMultiple($n, $x = 5)
  9911. {
  9912. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  9913. }
  9914. /**
  9915. * Function dolGetBadge
  9916. *
  9917. * @param string $label label of badge no html : use in alt attribute for accessibility
  9918. * @param string $html optional : label of badge with html
  9919. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  9920. * @param string $mode default '' , 'pill', 'dot'
  9921. * @param string $url the url for link
  9922. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  9923. * @return string Html badge
  9924. */
  9925. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  9926. {
  9927. $attr = array(
  9928. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  9929. );
  9930. if (empty($html)) {
  9931. $html = $label;
  9932. }
  9933. if (!empty($url)) {
  9934. $attr['href'] = $url;
  9935. }
  9936. if ($mode === 'dot') {
  9937. $attr['class'] .= ' classfortooltip';
  9938. $attr['title'] = $html;
  9939. $attr['aria-label'] = $label;
  9940. $html = '';
  9941. }
  9942. // Override attr
  9943. if (!empty($params['attr']) && is_array($params['attr'])) {
  9944. foreach ($params['attr'] as $key => $value) {
  9945. if ($key == 'class') {
  9946. $attr['class'] .= ' '.$value;
  9947. } elseif ($key == 'classOverride') {
  9948. $attr['class'] = $value;
  9949. } else {
  9950. $attr[$key] = $value;
  9951. }
  9952. }
  9953. }
  9954. // TODO: add hook
  9955. // escape all attribute
  9956. $attr = array_map('dol_escape_htmltag', $attr);
  9957. $TCompiledAttr = array();
  9958. foreach ($attr as $key => $value) {
  9959. $TCompiledAttr[] = $key.'="'.$value.'"';
  9960. }
  9961. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9962. $tag = !empty($url) ? 'a' : 'span';
  9963. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  9964. }
  9965. /**
  9966. * Output the badge of a status.
  9967. *
  9968. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  9969. * @param string $statusLabelShort Short label of badge no html
  9970. * @param string $html Optional : label of badge with html
  9971. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  9972. * @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
  9973. * @param string $url The url for link
  9974. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  9975. * @return string Html status string
  9976. */
  9977. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  9978. {
  9979. global $conf;
  9980. $return = '';
  9981. $dolGetBadgeParams = array();
  9982. if (!empty($params['badgeParams'])) {
  9983. $dolGetBadgeParams = $params['badgeParams'];
  9984. }
  9985. // TODO : add a hook
  9986. if ($displayMode == 0) {
  9987. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  9988. } elseif ($displayMode == 1) {
  9989. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9990. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  9991. // Use status with images (for backward compatibility)
  9992. $return = '';
  9993. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  9994. $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>' : '');
  9995. // For small screen, we always use the short label instead of long label.
  9996. if (!empty($conf->dol_optimize_smallscreen)) {
  9997. if ($displayMode == 0) {
  9998. $displayMode = 1;
  9999. } elseif ($displayMode == 4) {
  10000. $displayMode = 2;
  10001. } elseif ($displayMode == 6) {
  10002. $displayMode = 5;
  10003. }
  10004. }
  10005. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  10006. $statusImg = array(
  10007. 'status0' => 'statut0',
  10008. 'status1' => 'statut1',
  10009. 'status2' => 'statut2',
  10010. 'status3' => 'statut3',
  10011. 'status4' => 'statut4',
  10012. 'status5' => 'statut5',
  10013. 'status6' => 'statut6',
  10014. 'status7' => 'statut7',
  10015. 'status8' => 'statut8',
  10016. 'status9' => 'statut9'
  10017. );
  10018. if (!empty($statusImg[$statusType])) {
  10019. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  10020. } else {
  10021. $htmlImg = img_picto($statusLabel, $statusType);
  10022. }
  10023. if ($displayMode === 2) {
  10024. $return = $htmlImg.' '.$htmlLabelShort;
  10025. } elseif ($displayMode === 3) {
  10026. $return = $htmlImg;
  10027. } elseif ($displayMode === 4) {
  10028. $return = $htmlImg.' '.$htmlLabel;
  10029. } elseif ($displayMode === 5) {
  10030. $return = $htmlLabelShort.' '.$htmlImg;
  10031. } else { // $displayMode >= 6
  10032. $return = $htmlLabel.' '.$htmlImg;
  10033. }
  10034. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  10035. // Use new badge
  10036. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  10037. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  10038. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  10039. if ($displayMode == 3) {
  10040. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  10041. } elseif ($displayMode === 5) {
  10042. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  10043. } else {
  10044. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  10045. }
  10046. }
  10047. return $return;
  10048. }
  10049. /**
  10050. * Function dolGetButtonAction
  10051. *
  10052. * @param string $label Label or tooltip of button. Also used as tooltip in title attribute. Can be escaped HTML content or full simple text.
  10053. * @param string $text Optional : short label on button. Can be escaped HTML content or full simple text.
  10054. * @param string $actionType 'default', 'delete', 'danger', 'email', ...
  10055. * @param string|array $url Url for link or array of subbutton description
  10056. * @param string $id Attribute id of button
  10057. * @param int|boolean $userRight User action right
  10058. * // phpcs:disable
  10059. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  10060. * 'attr' => [ // to add or override button attributes
  10061. * 'xxxxx' => '', // your xxxxx attribute you want
  10062. * 'class' => 'reposition', // to add more css class to the button class attribute
  10063. * 'classOverride' => '' // to replace class attribute of the button
  10064. * ],
  10065. * 'confirm' => [
  10066. * '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.
  10067. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  10068. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  10069. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  10070. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  10071. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  10072. * 'isDropDrown' => false, // true|false to display dialog as a dropdown (with dark background)
  10073. * ],
  10074. * ]
  10075. * // phpcs:enable
  10076. * @return string html button
  10077. */
  10078. function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  10079. {
  10080. global $hookmanager, $action, $object, $langs;
  10081. // If $url is an array, we must build a dropdown button
  10082. if (is_array($url)) {
  10083. $out = '<div class="dropdown inline-block dropdown-holder">';
  10084. $out .= '<a style="margin-right: auto;" class="dropdown-toggle butAction" data-toggle="dropdown">'.$label.'</a>';
  10085. $out .= '<div class="dropdown-content">';
  10086. foreach ($url as $subbutton) {
  10087. if ($subbutton['enabled'] && $subbutton['perm']) {
  10088. if (!empty($subbutton['lang'])) {
  10089. $langs->load($subbutton['lang']);
  10090. }
  10091. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage'])), '', 1, array('isDropDown' => true));
  10092. }
  10093. }
  10094. $out .= "</div>";
  10095. $out .= "</div>";
  10096. return $out;
  10097. }
  10098. // If $url is a simple link
  10099. if (!empty($params['isDropdown']))
  10100. $class = "dropdown-item";
  10101. else {
  10102. $class = 'butAction';
  10103. if ($actionType == 'danger' || $actionType == 'delete') {
  10104. $class = 'butActionDelete';
  10105. if (!empty($url) && strpos($url, 'token=') === false) $url .= '&token='.newToken();
  10106. }
  10107. }
  10108. $attr = array(
  10109. 'class' => $class,
  10110. 'href' => empty($url) ? '' : $url,
  10111. 'title' => $label
  10112. );
  10113. if (empty($text)) {
  10114. $text = $label;
  10115. $attr['title'] = ''; // if html not set, leave label on title is redundant
  10116. } else {
  10117. $attr['title'] = $label;
  10118. $attr['aria-label'] = $label;
  10119. }
  10120. if (empty($userRight)) {
  10121. $attr['class'] = 'butActionRefused';
  10122. $attr['href'] = '';
  10123. $attr['title'] = (($label && $text && $label != $text) ? $label : $langs->trans('NotEnoughPermissions'));
  10124. }
  10125. if (!empty($id)) {
  10126. $attr['id'] = $id;
  10127. }
  10128. // Override attr
  10129. if (!empty($params['attr']) && is_array($params['attr'])) {
  10130. foreach ($params['attr'] as $key => $value) {
  10131. if ($key == 'class') {
  10132. $attr['class'] .= ' '.$value;
  10133. } elseif ($key == 'classOverride') {
  10134. $attr['class'] = $value;
  10135. } else {
  10136. $attr[$key] = $value;
  10137. }
  10138. }
  10139. }
  10140. // automatic add tooltip when title is detected
  10141. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  10142. $attr['class'].= ' classfortooltip';
  10143. }
  10144. // Js Confirm button
  10145. if ($userRight && !empty($params['confirm'])) {
  10146. if (!is_array($params['confirm'])) {
  10147. $params['confirm'] = array();
  10148. }
  10149. if (empty($params['confirm']['url'])) {
  10150. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  10151. }
  10152. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  10153. $attr['data-confirm-url'] = $params['confirm']['url'];
  10154. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  10155. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  10156. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  10157. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  10158. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  10159. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  10160. $attr['class'].= ' butActionConfirm';
  10161. }
  10162. if (isset($attr['href']) && empty($attr['href'])) {
  10163. unset($attr['href']);
  10164. }
  10165. // escape all attribute
  10166. $attr = array_map('dol_escape_htmltag', $attr);
  10167. $TCompiledAttr = array();
  10168. foreach ($attr as $key => $value) {
  10169. $TCompiledAttr[] = $key.'= "'.$value.'"';
  10170. }
  10171. $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
  10172. $tag = !empty($attr['href']) ? 'a' : 'span';
  10173. $parameters = array(
  10174. 'TCompiledAttr' => $TCompiledAttr, // array
  10175. 'compiledAttributes' => $compiledAttributes, // string
  10176. 'attr' => $attr,
  10177. 'tag' => $tag,
  10178. 'label' => $label,
  10179. 'html' => $text,
  10180. 'actionType' => $actionType,
  10181. 'url' => $url,
  10182. 'id' => $id,
  10183. 'userRight' => $userRight,
  10184. 'params' => $params
  10185. );
  10186. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  10187. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  10188. if (empty($reshook)) {
  10189. if (dol_textishtml($text)) { // If content already HTML encoded
  10190. return '<' . $tag . ' ' . $compiledAttributes . '>' . $text . '</' . $tag . '>';
  10191. } else {
  10192. return '<' . $tag . ' ' . $compiledAttributes . '>' . dol_escape_htmltag($text) . '</' . $tag . '>';
  10193. }
  10194. } else {
  10195. return $hookmanager->resPrint;
  10196. }
  10197. }
  10198. /**
  10199. * Add space between dolGetButtonTitle
  10200. *
  10201. * @param string $moreClass more css class label
  10202. * @return string html of title separator
  10203. */
  10204. function dolGetButtonTitleSeparator($moreClass = "")
  10205. {
  10206. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  10207. }
  10208. /**
  10209. * get field error icon
  10210. *
  10211. * @param string $fieldValidationErrorMsg message to add in tooltip
  10212. * @return string html output
  10213. */
  10214. function getFieldErrorIcon($fieldValidationErrorMsg)
  10215. {
  10216. $out = '';
  10217. if (!empty($fieldValidationErrorMsg)) {
  10218. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  10219. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  10220. $out.= '</span>';
  10221. }
  10222. return $out;
  10223. }
  10224. /**
  10225. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  10226. *
  10227. * @param string $label label of button
  10228. * @param string $helpText optional : content for help tooltip
  10229. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  10230. * @param string $url the url for link
  10231. * @param string $id attribute id of button
  10232. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use param $helpText as tooltip help
  10233. * @param array $params various params for future : recommended rather than adding more function arguments
  10234. * @return string html button
  10235. */
  10236. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  10237. {
  10238. global $langs, $conf, $user;
  10239. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  10240. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  10241. return '';
  10242. }
  10243. $class = 'btnTitle';
  10244. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
  10245. $class .= ' btnTitlePlus';
  10246. }
  10247. $useclassfortooltip = 1;
  10248. if (!empty($params['morecss'])) {
  10249. $class .= ' '.$params['morecss'];
  10250. }
  10251. $attr = array(
  10252. 'class' => $class,
  10253. 'href' => empty($url) ? '' : $url
  10254. );
  10255. if (!empty($helpText)) {
  10256. $attr['title'] = dol_escape_htmltag($helpText);
  10257. } elseif (empty($attr['title']) && $label) {
  10258. $attr['title'] = $label;
  10259. $useclassfortooltip = 0;
  10260. }
  10261. if ($status == 2) {
  10262. $attr['class'] .= ' btnTitleSelected';
  10263. } elseif ($status <= 0) {
  10264. $attr['class'] .= ' refused';
  10265. $attr['href'] = '';
  10266. if ($status == -1) { // disable
  10267. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  10268. } elseif ($status == 0) { // Not enough permissions
  10269. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  10270. }
  10271. }
  10272. if (!empty($attr['title']) && $useclassfortooltip) {
  10273. $attr['class'] .= ' classfortooltip';
  10274. }
  10275. if (!empty($id)) {
  10276. $attr['id'] = $id;
  10277. }
  10278. // Override attr
  10279. if (!empty($params['attr']) && is_array($params['attr'])) {
  10280. foreach ($params['attr'] as $key => $value) {
  10281. if ($key == 'class') {
  10282. $attr['class'] .= ' '.$value;
  10283. } elseif ($key == 'classOverride') {
  10284. $attr['class'] = $value;
  10285. } else {
  10286. $attr[$key] = $value;
  10287. }
  10288. }
  10289. }
  10290. if (isset($attr['href']) && empty($attr['href'])) {
  10291. unset($attr['href']);
  10292. }
  10293. // TODO : add a hook
  10294. // escape all attribute
  10295. $attr = array_map('dol_escape_htmltag', $attr);
  10296. $TCompiledAttr = array();
  10297. foreach ($attr as $key => $value) {
  10298. $TCompiledAttr[] = $key.'="'.$value.'"';
  10299. }
  10300. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  10301. $tag = (empty($attr['href']) ? 'span' : 'a');
  10302. $button = '<'.$tag.' '.$compiledAttributes.'>';
  10303. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  10304. if (!empty($params['forcenohideoftext'])) {
  10305. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  10306. }
  10307. $button .= '</'.$tag.'>';
  10308. return $button;
  10309. }
  10310. /**
  10311. * Get an array with properties of an element.
  10312. *
  10313. * @param string $element_type Element type (Value of $object->element). Example:
  10314. * 'action', 'facture', 'project', 'project_task' or
  10315. * 'myobject@mymodule' or
  10316. * 'myobject_mysubobject' (where mymodule = myobject, like 'project_task')
  10317. * @return array array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>)
  10318. * @see fetchObjectByElement()
  10319. */
  10320. function getElementProperties($element_type)
  10321. {
  10322. global $conf;
  10323. $regs = array();
  10324. $classfile = $classname = $classpath = $subdir = $dir_output = '';
  10325. // Parse element/subelement
  10326. $module = $element_type;
  10327. $element = $element_type;
  10328. $subelement = $element_type;
  10329. // If we ask a resource form external module (instead of default path)
  10330. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) { // 'myobject@mymodule'
  10331. $element = $subelement = $regs[1];
  10332. $module = $regs[2];
  10333. }
  10334. // If we ask a resource for a string with an element and a subelement
  10335. // Example 'project_task'
  10336. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
  10337. $module = $element = $regs[1];
  10338. $subelement = $regs[2];
  10339. }
  10340. // For compat and To work with non standard path
  10341. if ($element_type == "action") {
  10342. $classpath = 'comm/action/class';
  10343. $subelement = 'Actioncomm';
  10344. $module = 'agenda';
  10345. } elseif ($element_type == 'cronjob') {
  10346. $classpath = 'cron/class';
  10347. $module = 'cron';
  10348. } elseif ($element_type == 'adherent_type') {
  10349. $classpath = 'adherents/class';
  10350. $classfile = 'adherent_type';
  10351. $module = 'adherent';
  10352. $subelement = 'adherent_type';
  10353. $classname = 'AdherentType';
  10354. } elseif ($element_type == 'bank_account') {
  10355. $classpath = 'compta/bank/class';
  10356. $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
  10357. $classfile = 'account';
  10358. $classname = 'Account';
  10359. } elseif ($element_type == 'category') {
  10360. $classpath = 'categories/class';
  10361. $module = 'categorie';
  10362. $subelement = 'categorie';
  10363. } elseif ($element_type == 'contact') {
  10364. $classpath = 'contact/class';
  10365. $classfile = 'contact';
  10366. $module = 'societe';
  10367. $subelement = 'contact';
  10368. } elseif ($element_type == 'stock') {
  10369. $classpath = 'product/stock/class';
  10370. $classfile = 'entrepot';
  10371. $classname = 'Entrepot';
  10372. } elseif ($element_type == 'project') {
  10373. $classpath = 'projet/class';
  10374. $module = 'projet';
  10375. } elseif ($element_type == 'project_task') {
  10376. $classpath = 'projet/class';
  10377. $module = 'projet';
  10378. $subelement = 'task';
  10379. } elseif ($element_type == 'facture' || $element_type == 'invoice') {
  10380. $classpath = 'compta/facture/class';
  10381. $module = 'facture';
  10382. $subelement = 'facture';
  10383. } elseif ($element_type == 'commande' || $element_type == 'order') {
  10384. $classpath = 'commande/class';
  10385. $module = 'commande';
  10386. $subelement = 'commande';
  10387. } elseif ($element_type == 'propal') {
  10388. $classpath = 'comm/propal/class';
  10389. } elseif ($element_type == 'shipping') {
  10390. $classpath = 'expedition/class';
  10391. $classfile = 'expedition';
  10392. $classname = 'Expedition';
  10393. $module = 'expedition';
  10394. } elseif ($element_type == 'supplier_proposal') {
  10395. $classpath = 'supplier_proposal/class';
  10396. $module = 'supplier_proposal';
  10397. $element = 'supplierproposal';
  10398. $classfile = 'supplier_proposal';
  10399. $subelement = 'supplierproposal';
  10400. } elseif ($element_type == 'shipping') {
  10401. $classpath = 'expedition/class';
  10402. $subelement = 'expedition';
  10403. $module = 'expedition_bon';
  10404. } elseif ($element_type == 'delivery') {
  10405. $classpath = 'delivery/class';
  10406. $subelement = 'delivery';
  10407. $module = 'delivery_note';
  10408. } elseif ($element_type == 'contract') {
  10409. $classpath = 'contrat/class';
  10410. $module = 'contrat';
  10411. $subelement = 'contrat';
  10412. } elseif ($element_type == 'mailing') {
  10413. $classpath = 'comm/mailing/class';
  10414. $module = 'mailing';
  10415. $classfile = 'mailing';
  10416. $classname = 'Mailing';
  10417. $subelement = '';
  10418. } elseif ($element_type == 'member') {
  10419. $classpath = 'adherents/class';
  10420. $module = 'adherent';
  10421. $subelement = 'adherent';
  10422. } elseif ($element_type == 'usergroup') {
  10423. $classpath = 'user/class';
  10424. $module = 'user';
  10425. } elseif ($element_type == 'mo') {
  10426. $classpath = 'mrp/class';
  10427. $classfile = 'mo';
  10428. $classname = 'Mo';
  10429. $module = 'mrp';
  10430. $subelement = '';
  10431. } elseif ($element_type == 'cabinetmed_cons') {
  10432. $classpath = 'cabinetmed/class';
  10433. $module = 'cabinetmed';
  10434. $subelement = 'cabinetmedcons';
  10435. } elseif ($element_type == 'fichinter') {
  10436. $classpath = 'fichinter/class';
  10437. $module = 'ficheinter';
  10438. $subelement = 'fichinter';
  10439. } elseif ($element_type == 'dolresource' || $element_type == 'resource') {
  10440. $classpath = 'resource/class';
  10441. $module = 'resource';
  10442. $subelement = 'dolresource';
  10443. } elseif ($element_type == 'propaldet') {
  10444. $classpath = 'comm/propal/class';
  10445. $module = 'propal';
  10446. $subelement = 'propaleligne';
  10447. } elseif ($element_type == 'opensurvey_sondage') {
  10448. $classpath = 'opensurvey/class';
  10449. $module = 'opensurvey';
  10450. $subelement = 'opensurveysondage';
  10451. } elseif ($element_type == 'order_supplier') {
  10452. $classpath = 'fourn/class';
  10453. $module = 'fournisseur';
  10454. $classfile = 'fournisseur.commande';
  10455. $element = 'order_supplier';
  10456. $subelement = '';
  10457. $classname = 'CommandeFournisseur';
  10458. } elseif ($element_type == 'invoice_supplier') {
  10459. $classpath = 'fourn/class';
  10460. $module = 'fournisseur';
  10461. $classfile = 'fournisseur.facture';
  10462. $element = 'invoice_supplier';
  10463. $subelement = '';
  10464. $classname = 'FactureFournisseur';
  10465. } elseif ($element_type == "service") {
  10466. $classpath = 'product/class';
  10467. $subelement = 'product';
  10468. } elseif ($element_type == 'salary') {
  10469. $classpath = 'salaries/class';
  10470. $module = 'salaries';
  10471. } elseif ($element_type == 'productlot') {
  10472. $module = 'productbatch';
  10473. $classpath = 'product/stock/class';
  10474. $classfile = 'productlot';
  10475. $classname = 'Productlot';
  10476. $element = 'productlot';
  10477. $subelement = '';
  10478. } elseif ($element_type == 'websitepage') {
  10479. $classpath = 'website/class';
  10480. $classfile = 'websitepage';
  10481. $classname = 'Websitepage';
  10482. $module = 'website';
  10483. $subelement = 'websitepage';
  10484. } elseif ($element_type == 'fiscalyear') {
  10485. $classpath = 'core/class';
  10486. $module = 'accounting';
  10487. $subelement = 'fiscalyear';
  10488. } elseif ($element_type == 'chargesociales') {
  10489. $classpath = 'compta/sociales/class';
  10490. $module = 'tax';
  10491. } elseif ($element_type == 'tva') {
  10492. $classpath = 'compta/tva/class';
  10493. $module = 'tax';
  10494. $subdir = '/vat';
  10495. }
  10496. if (empty($classfile)) {
  10497. $classfile = strtolower($subelement);
  10498. }
  10499. if (empty($classname)) {
  10500. $classname = ucfirst($subelement);
  10501. }
  10502. if (empty($classpath)) {
  10503. $classpath = $module.'/class';
  10504. }
  10505. //print 'getElementProperties subdir='.$subdir;
  10506. // Set dir_output
  10507. if ($module && isset($conf->$module)) { // The generic case
  10508. if (!empty($conf->$module->multidir_output[$conf->entity])) {
  10509. $dir_output = $conf->$module->multidir_output[$conf->entity];
  10510. } elseif (!empty($conf->$module->output[$conf->entity])) {
  10511. $dir_output = $conf->$module->output[$conf->entity];
  10512. } elseif (!empty($conf->$module->dir_output)) {
  10513. $dir_output = $conf->$module->dir_output;
  10514. }
  10515. }
  10516. // Overwrite value for special cases
  10517. if ($element == 'order_supplier') {
  10518. $dir_output = $conf->fournisseur->commande->dir_output;
  10519. } elseif ($element == 'invoice_supplier') {
  10520. $dir_output = $conf->fournisseur->facture->dir_output;
  10521. }
  10522. $dir_output .= $subdir;
  10523. $element_properties = array(
  10524. 'module' => $module,
  10525. 'element' => $element,
  10526. 'subelement' => $subelement,
  10527. 'classpath' => $classpath,
  10528. 'classfile' => $classfile,
  10529. 'classname' => $classname,
  10530. 'dir_output' => $dir_output
  10531. );
  10532. return $element_properties;
  10533. }
  10534. /**
  10535. * Fetch an object from its id and element_type
  10536. * Inclusion of classes is automatic
  10537. *
  10538. * @param int $element_id Element id
  10539. * @param string $element_type Element type ('module' or 'myobject@mymodule' or 'mymodule_myobject')
  10540. * @param string $element_ref Element ref (Use this or element_id but not both)
  10541. * @return int|object object || 0 || <0 if error
  10542. */
  10543. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  10544. {
  10545. global $db;
  10546. $ret = 0;
  10547. $element_prop = getElementProperties($element_type);
  10548. if (is_array($element_prop) && isModEnabled($element_prop['module'])) {
  10549. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  10550. if (class_exists($element_prop['classname'])) {
  10551. $classname = $element_prop['classname'];
  10552. $objecttmp = new $classname($db);
  10553. $ret = $objecttmp->fetch($element_id, $element_ref);
  10554. if ($ret >= 0) {
  10555. if (empty($objecttmp->module)) {
  10556. $objecttmp->module = $element_prop['module'];
  10557. }
  10558. return $objecttmp;
  10559. }
  10560. } else {
  10561. return -1;
  10562. }
  10563. }
  10564. return $ret;
  10565. }
  10566. /**
  10567. * Return if a file can contains executable content
  10568. *
  10569. * @param string $filename File name to test
  10570. * @return boolean True if yes, False if no
  10571. */
  10572. function isAFileWithExecutableContent($filename)
  10573. {
  10574. 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)) {
  10575. return true;
  10576. }
  10577. return false;
  10578. }
  10579. /**
  10580. * Return the value of token currently saved into session with name 'newtoken'.
  10581. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  10582. *
  10583. * @since Dolibarr v10.0.7
  10584. * @return string
  10585. */
  10586. function newToken()
  10587. {
  10588. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  10589. }
  10590. /**
  10591. * Return the value of token currently saved into session with name 'token'.
  10592. * For ajax call, you must use this token as a parameter of the call into the js calling script (the called ajax php page must also set constant NOTOKENRENEWAL).
  10593. *
  10594. * @since Dolibarr v10.0.7
  10595. * @return string
  10596. */
  10597. function currentToken()
  10598. {
  10599. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  10600. }
  10601. /**
  10602. * Return a random string to be used as a nonce value for js
  10603. *
  10604. * @return string
  10605. */
  10606. function getNonce()
  10607. {
  10608. global $conf;
  10609. if (empty($conf->cache['nonce'])) {
  10610. $conf->cache['nonce'] = dolGetRandomBytes(8);
  10611. }
  10612. return $conf->cache['nonce'];
  10613. }
  10614. /**
  10615. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  10616. *
  10617. * @param string $header The first left header of the table (automatic translated)
  10618. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  10619. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  10620. * @param integer $emptyRows (optional) The count of empty rows after the first header
  10621. * @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"
  10622. * @return void
  10623. *
  10624. * @see finishSimpleTable()
  10625. */
  10626. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  10627. {
  10628. global $langs;
  10629. print '<div class="div-table-responsive-no-min">';
  10630. print '<table class="noborder centpercent">';
  10631. print '<tr class="liste_titre">';
  10632. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  10633. print $langs->trans($header);
  10634. // extra space between the first header and the number
  10635. if ($number > -1) {
  10636. print ' ';
  10637. }
  10638. if (!empty($link)) {
  10639. if (!empty($arguments)) {
  10640. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10641. } else {
  10642. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  10643. }
  10644. }
  10645. if ($number > -1) {
  10646. print '<span class="badge">'.$number.'</span>';
  10647. }
  10648. if (!empty($link)) {
  10649. print '</a>';
  10650. }
  10651. print '</th>';
  10652. if ($number < 0 && !empty($link)) {
  10653. print '<th class="right">';
  10654. if (!empty($arguments)) {
  10655. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10656. } else {
  10657. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  10658. }
  10659. print $langs->trans("FullList");
  10660. print '</a>';
  10661. print '</th>';
  10662. }
  10663. print '</tr>';
  10664. }
  10665. /**
  10666. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  10667. *
  10668. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  10669. * @return void
  10670. *
  10671. * @see startSimpleTable()
  10672. */
  10673. function finishSimpleTable($addLineBreak = false)
  10674. {
  10675. print '</table>';
  10676. print '</div>';
  10677. if ($addLineBreak) {
  10678. print '<br>';
  10679. }
  10680. }
  10681. /**
  10682. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  10683. *
  10684. * @param integer $tableColumnCount The complete count columns of the table
  10685. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  10686. * @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)
  10687. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  10688. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  10689. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  10690. * @return void
  10691. */
  10692. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  10693. {
  10694. global $langs;
  10695. if ($num === 0) {
  10696. print '<tr class="oddeven">';
  10697. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  10698. print '</tr>';
  10699. return;
  10700. }
  10701. if ($nbofloop === 0) {
  10702. // don't show a summary line
  10703. return;
  10704. }
  10705. if ($num === 0) {
  10706. $colspan = $tableColumnCount;
  10707. } elseif ($num > $nbofloop) {
  10708. $colspan = $tableColumnCount;
  10709. } else {
  10710. $colspan = $tableColumnCount - 1;
  10711. }
  10712. if ($extraRightColumn) {
  10713. $colspan--;
  10714. }
  10715. print '<tr class="liste_total">';
  10716. if ($nbofloop > 0 && $num > $nbofloop) {
  10717. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  10718. } else {
  10719. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  10720. print '<td class="right" width="100">'.price($total).'</td>';
  10721. }
  10722. if ($extraRightColumn) {
  10723. print '<td></td>';
  10724. }
  10725. print '</tr>';
  10726. }
  10727. /**
  10728. * Return a file on output using a low memory. It can return very large files with no need of memory.
  10729. * WARNING: This close output buffers.
  10730. *
  10731. * @param string $fullpath_original_file_osencoded Full path of file to return.
  10732. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  10733. * @return void
  10734. */
  10735. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  10736. {
  10737. global $conf;
  10738. if ($method == -1) {
  10739. $method = 0;
  10740. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  10741. $method = 1;
  10742. }
  10743. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  10744. $method = 2;
  10745. }
  10746. }
  10747. // Be sure we don't have output buffering enabled to have readfile working correctly
  10748. while (ob_get_level()) {
  10749. ob_end_flush();
  10750. }
  10751. // Solution 0
  10752. if ($method == 0) {
  10753. readfile($fullpath_original_file_osencoded);
  10754. } elseif ($method == 1) {
  10755. // Solution 1
  10756. $handle = fopen($fullpath_original_file_osencoded, "rb");
  10757. while (!feof($handle)) {
  10758. print fread($handle, 8192);
  10759. }
  10760. fclose($handle);
  10761. } elseif ($method == 2) {
  10762. // Solution 2
  10763. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  10764. $handle2 = fopen("php://output", "wb");
  10765. stream_copy_to_stream($handle1, $handle2);
  10766. fclose($handle1);
  10767. fclose($handle2);
  10768. }
  10769. }
  10770. /**
  10771. * Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
  10772. * Code that handle the click is inside core/js/lib_foot.js.php.
  10773. *
  10774. * @param string $valuetocopy The value to print
  10775. * @param int $showonlyonhover Show the copy-paste button only on hover
  10776. * @param string $texttoshow Replace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
  10777. * @return string The string to print for the button
  10778. */
  10779. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  10780. {
  10781. /*
  10782. global $conf;
  10783. if (!empty($conf->dol_no_mouse_hover)) {
  10784. $showonlyonhover = 0;
  10785. }*/
  10786. $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
  10787. if ($texttoshow === 'none') {
  10788. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint"></span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  10789. } elseif ($texttoshow) {
  10790. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint">'.dol_escape_htmltag($texttoshow, 1, 1).'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  10791. } else {
  10792. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  10793. }
  10794. return $result;
  10795. }
  10796. /**
  10797. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  10798. *
  10799. * @param string $stringtodecode String to decode (json or serialize coded)
  10800. * @return mixed The decoded object.
  10801. */
  10802. function jsonOrUnserialize($stringtodecode)
  10803. {
  10804. $result = json_decode($stringtodecode);
  10805. if ($result === null) {
  10806. $result = unserialize($stringtodecode);
  10807. }
  10808. return $result;
  10809. }
  10810. /**
  10811. * forgeSQLFromUniversalSearchCriteria
  10812. *
  10813. * @param string $filter String with universal search string. Must be '(aaa:bbb:...) OR (ccc:ddd:...) ...' with
  10814. * aaa is a field name (with alias or not) and
  10815. * bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'.
  10816. * Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
  10817. * @param string $errorstr Error message string
  10818. * @param int $noand 1=Do not add the AND before the condition string.
  10819. * @param int $nopar 1=Do not add the perenthesis around the condition string.
  10820. * @param int $noerror 1=If search criteria is not valid, does not return an error string but invalidate the SQL
  10821. * @return string Return forged SQL string
  10822. */
  10823. function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0)
  10824. {
  10825. if (!preg_match('/^\(.*\)$/', $filter)) { // If $filter does not start and end with ()
  10826. $filter = '(' . $filter . ')';
  10827. }
  10828. $regexstring = '\(([a-zA-Z0-9_\.]+:[<>!=insotlke]+:[^\(\)]+)\)'; // Must be (aaa:bbb:...) with aaa is a field name (with alias or not) and bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'
  10829. if (!dolCheckFilters($filter, $errorstr)) {
  10830. if ($noerror) {
  10831. return '1 = 2';
  10832. } else {
  10833. return 'Filter syntax error - '.$errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
  10834. }
  10835. }
  10836. // Test the filter syntax
  10837. $t = preg_replace_callback('/'.$regexstring.'/i', 'dolForgeDummyCriteriaCallback', $filter);
  10838. $t = str_replace(array('and','or','AND','OR',' '), '', $t); // Remove the only strings allowed between each () criteria
  10839. // If the string result contains something else than '()', the syntax was wrong
  10840. if (preg_match('/[^\(\)]/', $t)) {
  10841. $errorstr = 'Bad syntax of the search string';
  10842. if ($noerror) {
  10843. return '1 = 2';
  10844. } else {
  10845. return 'Filter syntax error - '.$errorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
  10846. }
  10847. }
  10848. return ($noand ? "" : " AND ").($nopar ? "" : '(').preg_replace_callback('/'.$regexstring.'/i', 'dolForgeCriteriaCallback', $filter).($nopar ? "" : ')');
  10849. }
  10850. /**
  10851. * Return if a $sqlfilters parameter has a valid balance of parenthesis
  10852. *
  10853. * @param string $sqlfilters sqlfilter string
  10854. * @param string $error Error message
  10855. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  10856. */
  10857. function dolCheckFilters($sqlfilters, &$error = '')
  10858. {
  10859. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  10860. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  10861. $tmp = $sqlfilters;
  10862. $i = 0; $nb = strlen($tmp);
  10863. $counter = 0;
  10864. while ($i < $nb) {
  10865. if ($tmp[$i] == '(') {
  10866. $counter++;
  10867. }
  10868. if ($tmp[$i] == ')') {
  10869. $counter--;
  10870. }
  10871. if ($counter < 0) {
  10872. $error = "Wrond balance of parenthesis in sqlfilters=".$sqlfilters;
  10873. dol_syslog($error, LOG_WARNING);
  10874. return false;
  10875. }
  10876. $i++;
  10877. }
  10878. return true;
  10879. }
  10880. /**
  10881. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  10882. * This method is called by forgeSQLFromUniversalSearchCriteria()
  10883. *
  10884. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  10885. * @return string Forged criteria. Example: "" or "()"
  10886. */
  10887. function dolForgeDummyCriteriaCallback($matches)
  10888. {
  10889. //dol_syslog("Convert matches ".$matches[1]);
  10890. if (empty($matches[1])) {
  10891. return '';
  10892. }
  10893. $tmp = explode(':', $matches[1]);
  10894. if (count($tmp) < 3) {
  10895. return '';
  10896. }
  10897. return '()'; // An empty criteria
  10898. }
  10899. /**
  10900. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  10901. * This method is called by forgeSQLFromUniversalSearchCriteria()
  10902. *
  10903. * @param array $matches Array of found string by regex search.
  10904. * Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL"
  10905. * @return string Forged criteria. Example: "t.field LIKE 'abc%'"
  10906. */
  10907. function dolForgeCriteriaCallback($matches)
  10908. {
  10909. global $db;
  10910. //dol_syslog("Convert matches ".$matches[1]);
  10911. if (empty($matches[1])) {
  10912. return '';
  10913. }
  10914. $tmp = explode(':', $matches[1]);
  10915. if (count($tmp) < 3) {
  10916. return '';
  10917. }
  10918. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  10919. $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
  10920. if ($operator == 'NOTLIKE') {
  10921. $operator = 'NOT LIKE';
  10922. }
  10923. if ($operator == 'ISNOT') {
  10924. $operator = 'IS NOT';
  10925. }
  10926. if ($operator == '!=') {
  10927. $operator = '<>';
  10928. }
  10929. $tmpescaped = $tmp[2];
  10930. $regbis = array();
  10931. if ($operator == 'IN') { // IN is allowed for list of ID or code only
  10932. //if (!preg_match('/^\(.*\)$/', $tmpescaped)) {
  10933. $tmpescaped = '('.$db->escape($db->sanitize($tmpescaped, 1, 0)).')';
  10934. //} else {
  10935. // $tmpescaped = $db->escape($db->sanitize($tmpescaped, 1));
  10936. //}
  10937. } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
  10938. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  10939. $tmpescaped = $regbis[1];
  10940. }
  10941. //$tmpescaped = "'".$db->escapeforlike($db->escape($regbis[1]))."'";
  10942. $tmpescaped = "'".$db->escape($tmpescaped)."'"; // We do not escape the _ and % so the like will works
  10943. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  10944. $tmpescaped = "'".$db->escape($regbis[1])."'";
  10945. } else {
  10946. if (strtoupper($tmpescaped) == 'NULL') {
  10947. $tmpescaped = 'NULL';
  10948. } elseif (is_int($tmpescaped)) {
  10949. $tmpescaped = (int) $tmpescaped;
  10950. } else {
  10951. $tmpescaped = (float) $tmpescaped;
  10952. }
  10953. }
  10954. return '('.$db->escape($operand).' '.strtoupper($operator).' '.$tmpescaped.')';
  10955. }
  10956. /**
  10957. * Get timeline icon
  10958. *
  10959. * @param ActionComm $actionstatic actioncomm
  10960. * @param array $histo histo
  10961. * @param int $key key
  10962. * @return string
  10963. */
  10964. function getTimelineIcon($actionstatic, &$histo, $key)
  10965. {
  10966. global $conf, $langs;
  10967. $out = '<!-- timeline icon -->'."\n";
  10968. $iconClass = 'fa fa-comments';
  10969. $img_picto = '';
  10970. $colorClass = '';
  10971. $pictoTitle = '';
  10972. if ($histo[$key]['percent'] == -1) {
  10973. $colorClass = 'timeline-icon-not-applicble';
  10974. $pictoTitle = $langs->trans('StatusNotApplicable');
  10975. } elseif ($histo[$key]['percent'] == 0) {
  10976. $colorClass = 'timeline-icon-todo';
  10977. $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
  10978. } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
  10979. $colorClass = 'timeline-icon-in-progress';
  10980. $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
  10981. } elseif ($histo[$key]['percent'] >= 100) {
  10982. $colorClass = 'timeline-icon-done';
  10983. $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
  10984. }
  10985. if ($actionstatic->code == 'AC_TICKET_CREATE') {
  10986. $iconClass = 'fa fa-ticket';
  10987. } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
  10988. $iconClass = 'fa fa-pencilxxx';
  10989. } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  10990. $iconClass = 'fa fa-comments';
  10991. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  10992. $iconClass = 'fa fa-mask';
  10993. } elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  10994. if ($actionstatic->type_picto) {
  10995. $img_picto = img_picto('', $actionstatic->type_picto);
  10996. } else {
  10997. if ($actionstatic->type_code == 'AC_RDV') {
  10998. $iconClass = 'fa fa-handshake';
  10999. } elseif ($actionstatic->type_code == 'AC_TEL') {
  11000. $iconClass = 'fa fa-phone';
  11001. } elseif ($actionstatic->type_code == 'AC_FAX') {
  11002. $iconClass = 'fa fa-fax';
  11003. } elseif ($actionstatic->type_code == 'AC_EMAIL') {
  11004. $iconClass = 'fa fa-envelope';
  11005. } elseif ($actionstatic->type_code == 'AC_INT') {
  11006. $iconClass = 'fa fa-shipping-fast';
  11007. } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
  11008. $iconClass = 'fa fa-robot';
  11009. } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
  11010. $iconClass = 'fa fa-robot';
  11011. }
  11012. }
  11013. }
  11014. $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
  11015. return $out;
  11016. }
  11017. /**
  11018. * getActionCommEcmList
  11019. *
  11020. * @param ActionComm $object Object ActionComm
  11021. * @return array Array of documents in index table
  11022. */
  11023. function getActionCommEcmList($object)
  11024. {
  11025. global $conf, $db;
  11026. $documents = array();
  11027. $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename';
  11028. $sql .= ' FROM '.MAIN_DB_PREFIX.'ecm_files ecm';
  11029. $sql .= " WHERE ecm.filepath = 'agenda/".((int) $object->id)."'";
  11030. //$sql.= " ecm.src_object_type = '".$db->escape($object->element)."' AND ecm.src_object_id = ".((int) $object->id); // Old version didn't add object_type during upload
  11031. $sql .= ' ORDER BY ecm.position ASC';
  11032. $resql = $db->query($sql);
  11033. if ($resql) {
  11034. if ($db->num_rows($resql)) {
  11035. while ($obj = $db->fetch_object($resql)) {
  11036. $documents[$obj->id] = $obj;
  11037. }
  11038. }
  11039. }
  11040. return $documents;
  11041. }
  11042. /**
  11043. * Show html area with actions in messaging format.
  11044. * Note: Global parameter $param must be defined.
  11045. *
  11046. * @param Conf $conf Object conf
  11047. * @param Translate $langs Object langs
  11048. * @param DoliDB $db Object db
  11049. * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object
  11050. * @param Contact $objcon Filter on object contact to filter events on a contact
  11051. * @param int $noprint Return string but does not output it
  11052. * @param string $actioncode Filter on actioncode
  11053. * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all).
  11054. * @param array $filters Filter on other fields
  11055. * @param string $sortfield Sort field
  11056. * @param string $sortorder Sort order
  11057. * @return string|void Return html part or void if noprint is 1
  11058. */
  11059. function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
  11060. {
  11061. global $user, $conf;
  11062. global $form;
  11063. global $param, $massactionbutton;
  11064. dol_include_once('/comm/action/class/actioncomm.class.php');
  11065. // Check parameters
  11066. if (!is_object($filterobj) && !is_object($objcon)) {
  11067. dol_print_error('', 'BadParameter');
  11068. }
  11069. $histo = array();
  11070. $numaction = 0;
  11071. $now = dol_now();
  11072. $sortfield_list = explode(',', $sortfield);
  11073. $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
  11074. $sortfield_new_list = array();
  11075. foreach ($sortfield_list as $sortfield_value) {
  11076. $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
  11077. }
  11078. $sortfield_new = implode(',', $sortfield_new_list);
  11079. if (isModEnabled('agenda')) {
  11080. // Search histo on actioncomm
  11081. if (is_object($objcon) && $objcon->id > 0) {
  11082. $sql = "SELECT DISTINCT a.id, a.label as label,";
  11083. } else {
  11084. $sql = "SELECT a.id, a.label as label,";
  11085. }
  11086. $sql .= " a.datep as dp,";
  11087. $sql .= " a.note as message,";
  11088. $sql .= " a.datep2 as dp2,";
  11089. $sql .= " a.percent as percent, 'action' as type,";
  11090. $sql .= " a.fk_element, a.elementtype,";
  11091. $sql .= " a.fk_contact,";
  11092. $sql .= " a.email_from as msg_from,";
  11093. $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
  11094. $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
  11095. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11096. $sql .= ", sp.lastname, sp.firstname";
  11097. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11098. $sql .= ", m.lastname, m.firstname";
  11099. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11100. $sql .= ", o.ref";
  11101. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11102. $sql .= ", o.ref";
  11103. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11104. $sql .= ", o.ref";
  11105. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11106. $sql .= ", o.ref";
  11107. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11108. $sql .= ", o.ref";
  11109. }
  11110. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  11111. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
  11112. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
  11113. $force_filter_contact = false;
  11114. if (is_object($objcon) && $objcon->id > 0) {
  11115. $force_filter_contact = true;
  11116. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
  11117. $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
  11118. }
  11119. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11120. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
  11121. } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
  11122. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
  11123. $sql .= " ON er.resource_type = 'dolresource'";
  11124. $sql .= " AND er.element_id = a.id";
  11125. $sql .= " AND er.resource_id = ".((int) $filterobj->id);
  11126. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11127. $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
  11128. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11129. $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
  11130. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11131. $sql .= ", ".MAIN_DB_PREFIX."product as o";
  11132. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11133. $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
  11134. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11135. $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
  11136. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11137. $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
  11138. }
  11139. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  11140. if ($force_filter_contact === false) {
  11141. if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
  11142. $sql .= " AND a.fk_soc = ".((int) $filterobj->id);
  11143. } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
  11144. $sql .= " AND a.fk_project = ".((int) $filterobj->id);
  11145. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11146. $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
  11147. if ($filterobj->id) {
  11148. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11149. }
  11150. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11151. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
  11152. if ($filterobj->id) {
  11153. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11154. }
  11155. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11156. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
  11157. if ($filterobj->id) {
  11158. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11159. }
  11160. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11161. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
  11162. if ($filterobj->id) {
  11163. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11164. }
  11165. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11166. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
  11167. if ($filterobj->id) {
  11168. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11169. }
  11170. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11171. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
  11172. if ($filterobj->id) {
  11173. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11174. }
  11175. }
  11176. }
  11177. // Condition on actioncode
  11178. if (!empty($actioncode)) {
  11179. if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  11180. if ($actioncode == 'AC_NON_AUTO') {
  11181. $sql .= " AND c.type != 'systemauto'";
  11182. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11183. $sql .= " AND c.type = 'systemauto'";
  11184. } else {
  11185. if ($actioncode == 'AC_OTH') {
  11186. $sql .= " AND c.type != 'systemauto'";
  11187. } elseif ($actioncode == 'AC_OTH_AUTO') {
  11188. $sql .= " AND c.type = 'systemauto'";
  11189. }
  11190. }
  11191. } else {
  11192. if ($actioncode == 'AC_NON_AUTO') {
  11193. $sql .= " AND c.type != 'systemauto'";
  11194. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11195. $sql .= " AND c.type = 'systemauto'";
  11196. } else {
  11197. $sql .= " AND c.code = '".$db->escape($actioncode)."'";
  11198. }
  11199. }
  11200. }
  11201. if ($donetodo == 'todo') {
  11202. $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11203. } elseif ($donetodo == 'done') {
  11204. $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11205. }
  11206. if (is_array($filters) && $filters['search_agenda_label']) {
  11207. $sql .= natural_search('a.label', $filters['search_agenda_label']);
  11208. }
  11209. }
  11210. // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
  11211. if (isModEnabled('mailing') && !empty($objcon->email)
  11212. && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
  11213. $langs->load("mails");
  11214. $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type";
  11215. $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
  11216. $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
  11217. $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
  11218. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11219. $sql2 .= ", '' as lastname, '' as firstname";
  11220. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11221. $sql2 .= ", '' as lastname, '' as firstname";
  11222. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11223. $sql2 .= ", '' as ref";
  11224. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11225. $sql2 .= ", '' as ref";
  11226. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11227. $sql2 .= ", '' as ref";
  11228. }
  11229. $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
  11230. $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
  11231. $sql2 .= " AND mc.statut = 1";
  11232. $sql2 .= " AND u.rowid = m.fk_user_valid";
  11233. $sql2 .= " AND mc.fk_mailing=m.rowid";
  11234. }
  11235. if (!empty($sql) && !empty($sql2)) {
  11236. $sql = $sql." UNION ".$sql2;
  11237. } elseif (empty($sql) && !empty($sql2)) {
  11238. $sql = $sql2;
  11239. }
  11240. // TODO Add limit in nb of results
  11241. if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too
  11242. $sql .= $db->order($sortfield_new, $sortorder);
  11243. dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
  11244. $resql = $db->query($sql);
  11245. if ($resql) {
  11246. $i = 0;
  11247. $num = $db->num_rows($resql);
  11248. while ($i < $num) {
  11249. $obj = $db->fetch_object($resql);
  11250. if ($obj->type == 'action') {
  11251. $contactaction = new ActionComm($db);
  11252. $contactaction->id = $obj->id;
  11253. $result = $contactaction->fetchResources();
  11254. if ($result < 0) {
  11255. dol_print_error($db);
  11256. setEventMessage("actions.lib::show_actions_messaging Error fetch ressource", 'errors');
  11257. }
  11258. //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11259. //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11260. $tododone = '';
  11261. if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
  11262. $tododone = 'todo';
  11263. }
  11264. $histo[$numaction] = array(
  11265. 'type'=>$obj->type,
  11266. 'tododone'=>$tododone,
  11267. 'id'=>$obj->id,
  11268. 'datestart'=>$db->jdate($obj->dp),
  11269. 'dateend'=>$db->jdate($obj->dp2),
  11270. 'note'=>$obj->label,
  11271. 'message'=>$obj->message,
  11272. 'percent'=>$obj->percent,
  11273. 'userid'=>$obj->user_id,
  11274. 'login'=>$obj->user_login,
  11275. 'userfirstname'=>$obj->user_firstname,
  11276. 'userlastname'=>$obj->user_lastname,
  11277. 'userphoto'=>$obj->user_photo,
  11278. 'msg_from'=>$obj->msg_from,
  11279. 'contact_id'=>$obj->fk_contact,
  11280. 'socpeopleassigned' => $contactaction->socpeopleassigned,
  11281. 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
  11282. 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
  11283. 'fk_element'=>$obj->fk_element,
  11284. 'elementtype'=>$obj->elementtype,
  11285. // Type of event
  11286. 'acode'=>$obj->acode,
  11287. 'alabel'=>$obj->alabel,
  11288. 'libelle'=>$obj->alabel, // deprecated
  11289. 'apicto'=>$obj->apicto
  11290. );
  11291. } else {
  11292. $histo[$numaction] = array(
  11293. 'type'=>$obj->type,
  11294. 'tododone'=>'done',
  11295. 'id'=>$obj->id,
  11296. 'datestart'=>$db->jdate($obj->dp),
  11297. 'dateend'=>$db->jdate($obj->dp2),
  11298. 'note'=>$obj->label,
  11299. 'message'=>$obj->message,
  11300. 'percent'=>$obj->percent,
  11301. 'acode'=>$obj->acode,
  11302. 'userid'=>$obj->user_id,
  11303. 'login'=>$obj->user_login,
  11304. 'userfirstname'=>$obj->user_firstname,
  11305. 'userlastname'=>$obj->user_lastname,
  11306. 'userphoto'=>$obj->user_photo
  11307. );
  11308. }
  11309. $numaction++;
  11310. $i++;
  11311. }
  11312. } else {
  11313. dol_print_error($db);
  11314. }
  11315. }
  11316. // Set $out to show events
  11317. $out = '';
  11318. if (!isModEnabled('agenda')) {
  11319. $langs->loadLangs(array("admin", "errors"));
  11320. $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
  11321. }
  11322. if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
  11323. $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
  11324. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  11325. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  11326. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  11327. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  11328. $formactions = new FormActions($db);
  11329. $actionstatic = new ActionComm($db);
  11330. $userstatic = new User($db);
  11331. $contactstatic = new Contact($db);
  11332. $userGetNomUrlCache = array();
  11333. $contactGetNomUrlCache = array();
  11334. $out .= '<div class="filters-container" >';
  11335. $out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  11336. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  11337. if ($objcon && get_class($objcon) == 'Contact' &&
  11338. (is_null($filterobj) || get_class($filterobj) == 'Societe')) {
  11339. $out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
  11340. } else {
  11341. $out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
  11342. }
  11343. if ($filterobj && get_class($filterobj) == 'Societe') {
  11344. $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
  11345. }
  11346. $out .= "\n";
  11347. $out .= '<div class="div-table-responsive-no-min">';
  11348. $out .= '<table class="noborder borderbottom centpercent">';
  11349. $out .= '<tr class="liste_titre">';
  11350. $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n";
  11351. $out .= '<th class="liste_titre"><strong class="hideonsmartphone">'.$langs->trans("Search").' : </strong></th>';
  11352. if ($donetodo) {
  11353. $out .= '<th class="liste_titre"></th>';
  11354. }
  11355. $out .= '<th class="liste_titre">';
  11356. $out .= '<span class="fas fa-square inline-block fawidth30" style=" color: #ddd;" title="'.$langs->trans("ActionType").'"></span>';
  11357. //$out .= img_picto($langs->trans("Type"), 'type');
  11358. $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1, 'minwidth200imp');
  11359. $out .= '</th>';
  11360. $out .= '<th class="liste_titre maxwidth100onsmartphone">';
  11361. $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'" placeholder="'.$langs->trans("Label").'">';
  11362. $out .= '</th>';
  11363. $out .= '<th class="liste_titre width50 middle">';
  11364. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11365. $out .= $searchpicto;
  11366. $out .= '</th>';
  11367. $out .= '</tr>';
  11368. $out .= '</table>';
  11369. $out .= '</form>';
  11370. $out .= '</div>';
  11371. $out .= "\n";
  11372. $out .= '<ul class="timeline">';
  11373. if ($donetodo) {
  11374. $tmp = '';
  11375. if (get_class($filterobj) == 'Societe') {
  11376. $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
  11377. }
  11378. $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
  11379. $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
  11380. $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
  11381. //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
  11382. if (get_class($filterobj) == 'Societe') {
  11383. $tmp .= '</a>';
  11384. }
  11385. $out .= getTitleFieldOfList($tmp);
  11386. }
  11387. //require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
  11388. //$caction=new CActionComm($db);
  11389. //$arraylist=$caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:0), '', 1);
  11390. $actualCycleDate = false;
  11391. // Loop on each event to show it
  11392. foreach ($histo as $key => $value) {
  11393. $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
  11394. $actionstatic->type_picto = $histo[$key]['apicto'];
  11395. $actionstatic->type_code = $histo[$key]['acode'];
  11396. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
  11397. $tmpa = dol_getdate($histo[$key]['datestart'], false);
  11398. if ($actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
  11399. $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
  11400. $out .= '<!-- timeline time label -->';
  11401. $out .= '<li class="time-label">';
  11402. $out .= '<span class="timeline-badge-date">';
  11403. $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
  11404. $out .= '</span>';
  11405. $out .= '</li>';
  11406. $out .= '<!-- /.timeline-label -->';
  11407. }
  11408. $out .= '<!-- timeline item -->'."\n";
  11409. $out .= '<li class="timeline-code-'.strtolower($actionstatic->code).'">';
  11410. $out .= getTimelineIcon($actionstatic, $histo, $key);
  11411. $out .= '<div class="timeline-item">'."\n";
  11412. $out .= '<span class="timeline-header-action">';
  11413. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
  11414. $out .= '<a class="timeline-btn" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11415. $out .= $histo[$key]['id'];
  11416. $out .= '</a> ';
  11417. } else {
  11418. $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle').' ';
  11419. }
  11420. if ($user->hasRight('agenda', 'allactions', 'create') ||
  11421. (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
  11422. $out .= '<a class="timeline-btn" href="'.DOL_MAIN_URL_ROOT.'/comm/action/card.php?action=edit&token='.newToken().'&id='.$actionstatic->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?'.$param).'"><i class="fa fa-pencil" title="'.$langs->trans("Modify").'" ></i></a>';
  11423. }
  11424. $out .= '</span>';
  11425. // Date
  11426. $out .= '<span class="time"><i class="fa fa-clock-o"></i> ';
  11427. $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
  11428. if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
  11429. $tmpa = dol_getdate($histo[$key]['datestart'], true);
  11430. $tmpb = dol_getdate($histo[$key]['dateend'], true);
  11431. if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
  11432. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
  11433. } else {
  11434. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
  11435. }
  11436. }
  11437. $late = 0;
  11438. if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11439. $late = 1;
  11440. }
  11441. if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11442. $late = 1;
  11443. }
  11444. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
  11445. $late = 1;
  11446. }
  11447. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11448. $late = 1;
  11449. }
  11450. if ($late) {
  11451. $out .= img_warning($langs->trans("Late")).' ';
  11452. }
  11453. $out .= "</span>\n";
  11454. // Ref
  11455. $out .= '<h3 class="timeline-header">';
  11456. // Author of event
  11457. $out .= '<div class="messaging-author inline-block">';
  11458. if ($histo[$key]['userid'] > 0) {
  11459. if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
  11460. $userstatic->fetch($histo[$key]['userid']);
  11461. $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
  11462. }
  11463. $out .= $userGetNomUrlCache[$histo[$key]['userid']];
  11464. } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
  11465. if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
  11466. if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
  11467. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
  11468. } else {
  11469. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
  11470. }
  11471. }
  11472. $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
  11473. }
  11474. $out .= '</div>';
  11475. // Title
  11476. $libelle = '';
  11477. $out .= ' <div class="messaging-title inline-block">';
  11478. if (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11479. $out .= $langs->trans('TicketNewMessage');
  11480. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  11481. $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
  11482. } elseif (isset($histo[$key]['type'])) {
  11483. if ($histo[$key]['type'] == 'action') {
  11484. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11485. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
  11486. $libelle = $histo[$key]['note'];
  11487. $actionstatic->id = $histo[$key]['id'];
  11488. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11489. } elseif ($histo[$key]['type'] == 'mailing') {
  11490. $out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11491. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11492. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
  11493. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11494. } else {
  11495. $libelle .= $histo[$key]['note'];
  11496. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11497. }
  11498. }
  11499. $out .= '</div>';
  11500. $out .= '</h3>';
  11501. if (!empty($histo[$key]['message'] && $histo[$key]['message'] != $libelle)
  11502. && $actionstatic->code != 'AC_TICKET_CREATE'
  11503. && $actionstatic->code != 'AC_TICKET_MODIFY'
  11504. ) {
  11505. $out .= '<div class="timeline-body">';
  11506. $out .= $histo[$key]['message'];
  11507. $out .= '</div>';
  11508. }
  11509. // Timeline footer
  11510. $footer = '';
  11511. // Contact for this action
  11512. if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
  11513. $contactList = '';
  11514. foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
  11515. $contact = new Contact($db);
  11516. $result = $contact->fetch($cid);
  11517. if ($result < 0) {
  11518. dol_print_error($db, $contact->error);
  11519. }
  11520. if ($result > 0) {
  11521. $contactList .= !empty($contactList) ? ', ' : '';
  11522. $contactList .= $contact->getNomUrl(1);
  11523. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11524. if (!empty($contact->phone_pro)) {
  11525. $contactList .= '('.dol_print_phone($contact->phone_pro).')';
  11526. }
  11527. }
  11528. }
  11529. }
  11530. $footer .= $langs->trans('ActionOnContact').' : '.$contactList;
  11531. } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
  11532. $contact = new Contact($db);
  11533. $result = $contact->fetch($histo[$key]['contact_id']);
  11534. if ($result < 0) {
  11535. dol_print_error($db, $contact->error);
  11536. }
  11537. if ($result > 0) {
  11538. $footer .= $contact->getNomUrl(1);
  11539. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11540. if (!empty($contact->phone_pro)) {
  11541. $footer .= '('.dol_print_phone($contact->phone_pro).')';
  11542. }
  11543. }
  11544. }
  11545. }
  11546. $documents = getActionCommEcmList($actionstatic);
  11547. if (!empty($documents)) {
  11548. $footer .= '<div class="timeline-documents-container">';
  11549. foreach ($documents as $doc) {
  11550. $footer .= '<span id="document_'.$doc->id.'" class="timeline-documents" ';
  11551. $footer .= ' data-id="'.$doc->id.'" ';
  11552. $footer .= ' data-path="'.$doc->filepath.'"';
  11553. $footer .= ' data-filename="'.dol_escape_htmltag($doc->filename).'" ';
  11554. $footer .= '>';
  11555. $filePath = DOL_DATA_ROOT.'/'.$doc->filepath.'/'.$doc->filename;
  11556. $mime = dol_mimetype($filePath);
  11557. $file = $actionstatic->id.'/'.$doc->filename;
  11558. $thumb = $actionstatic->id.'/thumbs/'.substr($doc->filename, 0, strrpos($doc->filename, '.')).'_mini'.substr($doc->filename, strrpos($doc->filename, '.'));
  11559. $doclink = dol_buildpath('document.php', 1).'?modulepart=actions&attachment=0&file='.urlencode($file).'&entity='.$conf->entity;
  11560. $viewlink = dol_buildpath('viewimage.php', 1).'?modulepart=actions&file='.urlencode($thumb).'&entity='.$conf->entity;
  11561. $mimeAttr = ' mime="'.$mime.'" ';
  11562. $class = '';
  11563. if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
  11564. $class .= ' documentpreview';
  11565. }
  11566. $footer .= '<a href="'.$doclink.'" class="btn-link '.$class.'" target="_blank" rel="noopener noreferrer" '.$mimeAttr.' >';
  11567. $footer .= img_mime($filePath).' '.$doc->filename;
  11568. $footer .= '</a>';
  11569. $footer .= '</span>';
  11570. }
  11571. $footer .= '</div>';
  11572. }
  11573. if (!empty($footer)) {
  11574. $out .= '<div class="timeline-footer">'.$footer.'</div>';
  11575. }
  11576. $out .= '</div>'."\n"; // end timeline-item
  11577. $out .= '</li>';
  11578. $out .= '<!-- END timeline item -->';
  11579. $i++;
  11580. }
  11581. $out .= "</ul>\n";
  11582. if (empty($histo)) {
  11583. $out .= '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
  11584. }
  11585. }
  11586. if ($noprint) {
  11587. return $out;
  11588. } else {
  11589. print $out;
  11590. }
  11591. }
  11592. /**
  11593. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  11594. * optionally hour, minute, second) fields to return a timestamp.
  11595. *
  11596. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  11597. * @param string $hourTime 'getpost' to include hour, minute, second values from the HTTP request, 'XX:YY:ZZ' to set
  11598. * hour, minute, second respectively (for instance '23:59:59')
  11599. * @param string $gm Passed to dol_mktime
  11600. * @return int|string Date as a timestamp, '' or false if error
  11601. */
  11602. function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto')
  11603. {
  11604. if ($hourTime === 'getpost') {
  11605. $hour = GETPOSTINT($prefix . 'hour');
  11606. $minute = GETPOSTINT($prefix . 'minute');
  11607. $second = GETPOSTINT($prefix . 'second');
  11608. } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
  11609. $hour = intval($m[1]);
  11610. $minute = intval($m[2]);
  11611. $second = intval($m[3]);
  11612. } else {
  11613. $hour = $minute = $second = 0;
  11614. }
  11615. // normalize out of range values
  11616. $hour = min($hour, 23);
  11617. $minute = min($minute, 59);
  11618. $second = min($second, 59);
  11619. return dol_mktime($hour, $minute, $second, GETPOSTINT($prefix . 'month'), GETPOSTINT($prefix . 'day'), GETPOSTINT($prefix . 'year'), $gm);
  11620. }
  11621. /**
  11622. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  11623. * optionally hour, minute, second) fields to return a a portion of URL reproducing the values from the current HTTP
  11624. * request.
  11625. *
  11626. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  11627. * @param int $timestamp If null, the timestamp will be created from request data
  11628. * @param bool $hourTime If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  11629. * @param bool $gm If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  11630. * @return string Portion of URL with query parameters for the specified date
  11631. */
  11632. function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
  11633. {
  11634. if ($timestamp === null) $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
  11635. $TParam = array(
  11636. $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
  11637. $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
  11638. $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
  11639. );
  11640. if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
  11641. $TParam = array_merge($TParam, array(
  11642. $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
  11643. $prefix . 'minute' => intval(dol_print_date($timestamp, '%M')),
  11644. $prefix . 'second' => intval(dol_print_date($timestamp, '%S'))
  11645. ));
  11646. }
  11647. return '&' . http_build_query($TParam);
  11648. }