functions.lib.php 534 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130
  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. // Special case for backward compatibility
  127. if ($module == 'fichinter') {
  128. $module = 'ficheinter';
  129. }
  130. return $conf->$module->multidir_output[(!empty($object->entity) ? $object->entity : $conf->entity)];
  131. }
  132. /**
  133. * Return dolibarr global constant string value
  134. *
  135. * @param string $key key to return value, return '' if not set
  136. * @param string $default value to return
  137. * @return string
  138. */
  139. function getDolGlobalString($key, $default = '')
  140. {
  141. global $conf;
  142. // return $conf->global->$key ?? $default;
  143. return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
  144. }
  145. /**
  146. * Return dolibarr global constant int value
  147. *
  148. * @param string $key key to return value, return 0 if not set
  149. * @param int $default value to return
  150. * @return int
  151. */
  152. function getDolGlobalInt($key, $default = 0)
  153. {
  154. global $conf;
  155. // return $conf->global->$key ?? $default;
  156. return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
  157. }
  158. /**
  159. * Return Dolibarr user constant string value
  160. *
  161. * @param string $key key to return value, return '' if not set
  162. * @param string $default value to return
  163. * @param User $tmpuser To get another user than current user
  164. * @return string
  165. */
  166. function getDolUserString($key, $default = '', $tmpuser = null)
  167. {
  168. if (empty($tmpuser)) {
  169. global $user;
  170. $tmpuser = $user;
  171. }
  172. // return $conf->global->$key ?? $default;
  173. return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  174. }
  175. /**
  176. * Return Dolibarr user constant int value
  177. *
  178. * @param string $key key to return value, return 0 if not set
  179. * @param int $default value to return
  180. * @param User $tmpuser To get another user than current user
  181. * @return int
  182. */
  183. function getDolUserInt($key, $default = 0, $tmpuser = null)
  184. {
  185. if (empty($tmpuser)) {
  186. global $user;
  187. $tmpuser = $user;
  188. }
  189. // return $conf->global->$key ?? $default;
  190. return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  191. }
  192. /**
  193. * Is Dolibarr module enabled
  194. *
  195. * @param string $module Module name to check
  196. * @return boolean True if module is enabled
  197. */
  198. function isModEnabled($module)
  199. {
  200. global $conf;
  201. // Fix special cases
  202. $arrayconv = array(
  203. 'project' => 'projet',
  204. 'contract' => 'contrat',
  205. 'bank' => 'banque'
  206. );
  207. if (empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) {
  208. $arrayconv['supplier_order'] = 'fournisseur';
  209. $arrayconv['supplier_invoice'] = 'fournisseur';
  210. }
  211. if (!empty($arrayconv[$module])) {
  212. $module = $arrayconv[$module];
  213. }
  214. return !empty($conf->modules[$module]);
  215. //return !empty($conf->$module->enabled);
  216. }
  217. /**
  218. * Return a DoliDB instance (database handler).
  219. *
  220. * @param string $type Type of database (mysql, pgsql...)
  221. * @param string $host Address of database server
  222. * @param string $user Authorized username
  223. * @param string $pass Password
  224. * @param string $name Name of database
  225. * @param int $port Port of database server
  226. * @return DoliDB A DoliDB instance
  227. */
  228. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  229. {
  230. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  231. $class = 'DoliDB'.ucfirst($type);
  232. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  233. return $dolidb;
  234. }
  235. /**
  236. * Get list of entity id to use.
  237. *
  238. * @param string $element Current element
  239. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  240. * 'product', 'productprice', 'stock', 'bom', 'mo',
  241. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  242. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  243. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  244. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  245. * 'email_template', 'event', 'donation'
  246. * 'c_paiement', 'c_payment_term', ...
  247. * @param int $shared 0=Return id of current entity only,
  248. * 1=Return id of current entity + shared entities (default)
  249. * @param object $currentobject Current object if needed
  250. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  251. */
  252. function getEntity($element, $shared = 1, $currentobject = null)
  253. {
  254. global $conf, $mc, $hookmanager, $object, $action, $db;
  255. if (!is_object($hookmanager)) {
  256. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  257. $hookmanager = new HookManager($db);
  258. }
  259. // fix different element names (France to English)
  260. switch ($element) {
  261. case 'projet':
  262. $element = 'project';
  263. break;
  264. case 'contrat':
  265. $element = 'contract';
  266. break; // "/contrat/class/contrat.class.php"
  267. case 'order_supplier':
  268. $element = 'supplier_order';
  269. break; // "/fourn/class/fournisseur.commande.class.php"
  270. case 'invoice_supplier':
  271. $element = 'supplier_invoice';
  272. break; // "/fourn/class/fournisseur.facture.class.php"
  273. }
  274. if (is_object($mc)) {
  275. $out = $mc->getEntity($element, $shared, $currentobject);
  276. } else {
  277. $out = '';
  278. $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans');
  279. if (in_array($element, $addzero)) {
  280. $out .= '0,';
  281. }
  282. $out .= ((int) $conf->entity);
  283. }
  284. // Manipulate entities to query on the fly
  285. $parameters = array(
  286. 'element' => $element,
  287. 'shared' => $shared,
  288. 'object' => $object,
  289. 'currentobject' => $currentobject,
  290. 'out' => $out
  291. );
  292. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  293. if (is_numeric($reshook)) {
  294. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  295. $out .= ','.$hookmanager->resPrint; // add
  296. } elseif ($reshook == 1) {
  297. $out = $hookmanager->resPrint; // replace
  298. }
  299. }
  300. return $out;
  301. }
  302. /**
  303. * Set entity id to use when to create an object
  304. *
  305. * @param object $currentobject Current object
  306. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  307. */
  308. function setEntity($currentobject)
  309. {
  310. global $conf, $mc;
  311. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  312. return $mc->setEntity($currentobject);
  313. } else {
  314. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  315. }
  316. }
  317. /**
  318. * Return if string has a name dedicated to store a secret
  319. *
  320. * @param string $keyname Name of key to test
  321. * @return boolean True if key is used to store a secret
  322. */
  323. function isASecretKey($keyname)
  324. {
  325. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  326. }
  327. /**
  328. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  329. *
  330. * @param int|string $n Numeric value
  331. * @return string Column in Excel format
  332. */
  333. function num2Alpha($n)
  334. {
  335. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
  336. $r = chr($n % 26 + 0x41) . $r;
  337. return $r;
  338. }
  339. /**
  340. * Return information about user browser
  341. *
  342. * Returns array with the following format:
  343. * array(
  344. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  345. * 'browserversion' => Browser version. Empty if unknown
  346. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  347. * 'layout' => (tablet|phone|classic)
  348. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  349. * 'tablet' => true/false
  350. * )
  351. *
  352. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  353. * @return array Check function documentation
  354. */
  355. function getBrowserInfo($user_agent)
  356. {
  357. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  358. $name = 'unknown';
  359. $version = '';
  360. $os = 'unknown';
  361. $phone = '';
  362. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  363. $detectmobile = new Mobile_Detect(null, $user_agent);
  364. $tablet = $detectmobile->isTablet();
  365. if ($detectmobile->isMobile()) {
  366. $phone = 'unknown';
  367. // If phone/smartphone, we set phone os name.
  368. if ($detectmobile->is('AndroidOS')) {
  369. $os = $phone = 'android';
  370. } elseif ($detectmobile->is('BlackBerryOS')) {
  371. $os = $phone = 'blackberry';
  372. } elseif ($detectmobile->is('iOS')) {
  373. $os = 'ios';
  374. $phone = 'iphone';
  375. } elseif ($detectmobile->is('PalmOS')) {
  376. $os = $phone = 'palm';
  377. } elseif ($detectmobile->is('SymbianOS')) {
  378. $os = 'symbian';
  379. } elseif ($detectmobile->is('webOS')) {
  380. $os = 'webos';
  381. } elseif ($detectmobile->is('MaemoOS')) {
  382. $os = 'maemo';
  383. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  384. $os = 'windows';
  385. }
  386. }
  387. // OS
  388. if (preg_match('/linux/i', $user_agent)) {
  389. $os = 'linux';
  390. } elseif (preg_match('/macintosh/i', $user_agent)) {
  391. $os = 'macintosh';
  392. } elseif (preg_match('/windows/i', $user_agent)) {
  393. $os = 'windows';
  394. }
  395. // Name
  396. $reg = array();
  397. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  398. $name = 'firefox';
  399. $version = empty($reg[2]) ? '' : $reg[2];
  400. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  401. $name = 'edge';
  402. $version = empty($reg[2]) ? '' : $reg[2];
  403. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  404. $name = 'chrome';
  405. $version = empty($reg[2]) ? '' : $reg[2];
  406. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  407. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  408. $name = 'chrome';
  409. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  410. $name = 'iceweasel';
  411. } elseif (preg_match('/epiphany/i', $user_agent)) {
  412. $name = 'epiphany';
  413. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  414. $name = 'safari';
  415. $version = empty($reg[2]) ? '' : $reg[2];
  416. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  417. // Safari is often present in string for mobile but its not.
  418. $name = 'opera';
  419. $version = empty($reg[2]) ? '' : $reg[2];
  420. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  421. $name = 'ie';
  422. $version = end($reg);
  423. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  424. // MS products at end
  425. $name = 'ie';
  426. $version = end($reg);
  427. } elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  428. // MS products at end
  429. $name = 'lynxlinks';
  430. $version = empty($reg[3]) ? '' : $reg[3];
  431. }
  432. if ($tablet) {
  433. $layout = 'tablet';
  434. } elseif ($phone) {
  435. $layout = 'phone';
  436. } else {
  437. $layout = 'classic';
  438. }
  439. return array(
  440. 'browsername' => $name,
  441. 'browserversion' => $version,
  442. 'browseros' => $os,
  443. 'browserua' => $user_agent,
  444. 'layout' => $layout, // tablet, phone, classic
  445. 'phone' => $phone, // deprecated
  446. 'tablet' => $tablet // deprecated
  447. );
  448. }
  449. /**
  450. * Function called at end of web php process
  451. *
  452. * @return void
  453. */
  454. function dol_shutdown()
  455. {
  456. global $db;
  457. $disconnectdone = false;
  458. $depth = 0;
  459. if (is_object($db) && !empty($db->connected)) {
  460. $depth = $db->transaction_opened;
  461. $disconnectdone = $db->close();
  462. }
  463. dol_syslog("--- End access to ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]).(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
  464. }
  465. /**
  466. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  467. * Warning:
  468. * 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.
  469. * For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var;
  470. *
  471. * @param string $paramname Name or parameter to test
  472. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  473. */
  474. function GETPOSTISSET($paramname)
  475. {
  476. $isset = false;
  477. $relativepathstring = $_SERVER["PHP_SELF"];
  478. // Clean $relativepathstring
  479. if (constant('DOL_URL_ROOT')) {
  480. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  481. }
  482. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  483. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  484. //var_dump($relativepathstring);
  485. //var_dump($user->default_values);
  486. // Code for search criteria persistence.
  487. // Retrieve values if restore_lastsearch_values
  488. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  489. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  490. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  491. if (is_array($tmp)) {
  492. foreach ($tmp as $key => $val) {
  493. if ($key == $paramname) { // We are on the requested parameter
  494. $isset = true;
  495. break;
  496. }
  497. }
  498. }
  499. }
  500. // If there is saved contextpage, limit, page or mode
  501. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  502. $isset = true;
  503. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  504. $isset = true;
  505. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  506. $isset = true;
  507. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  508. $isset = true;
  509. }
  510. } else {
  511. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  512. }
  513. return $isset;
  514. }
  515. /**
  516. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  517. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  518. *
  519. * @param string $paramname Name or parameter to test
  520. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  521. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  522. */
  523. function GETPOSTISARRAY($paramname, $method = 0)
  524. {
  525. // for $method test need return the same $val as GETPOST
  526. if (empty($method)) {
  527. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  528. } elseif ($method == 1) {
  529. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  530. } elseif ($method == 2) {
  531. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  532. } elseif ($method == 3) {
  533. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  534. } else {
  535. $val = 'BadFirstParameterForGETPOST';
  536. }
  537. return is_array($val);
  538. }
  539. /**
  540. * Return value of a param into GET or POST supervariable.
  541. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  542. * Note: The property $user->default_values is loaded by main.php when loading the user.
  543. *
  544. * @param string $paramname Name of parameter to found
  545. * @param string $check Type of check
  546. * ''=no check (deprecated)
  547. * 'none'=no check (only for param that should have very rich content like passwords)
  548. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  549. * 'int'=check it's numeric (integer or float)
  550. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  551. * 'alpha'=Same than alphanohtml since v13
  552. * 'alphawithlgt'=alpha with lgt
  553. * 'alphanohtml'=check there is no html content and no " and no ../
  554. * 'aZ'=check it's a-z only
  555. * 'aZ09'=check it's simple alpha string (recommended for keys)
  556. * 'aZ09arobase'=check it's a string for an element type
  557. * 'aZ09comma'=check it's a string for a sortfield or sortorder
  558. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  559. * 'nohtml'=check there is no html content
  560. * 'restricthtml'=check html content is restricted to some tags only
  561. * 'custom'= custom filter specify $filter and $options)
  562. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  563. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  564. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  565. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  566. * @return string|array Value found (string or array), or '' if check fails
  567. */
  568. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  569. {
  570. global $mysoc, $user, $conf;
  571. if (empty($paramname)) {
  572. return 'BadFirstParameterForGETPOST';
  573. }
  574. if (empty($check)) {
  575. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  576. // Enable this line to know who call the GETPOST with '' $check parameter.
  577. //var_dump(debug_backtrace()[0]);
  578. }
  579. if (empty($method)) {
  580. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  581. } elseif ($method == 1) {
  582. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  583. } elseif ($method == 2) {
  584. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  585. } elseif ($method == 3) {
  586. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  587. } else {
  588. return 'BadThirdParameterForGETPOST';
  589. }
  590. if (empty($method) || $method == 3 || $method == 4) {
  591. $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
  592. // Clean $relativepathstring
  593. if (constant('DOL_URL_ROOT')) {
  594. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  595. }
  596. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  597. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  598. //var_dump($relativepathstring);
  599. //var_dump($user->default_values);
  600. // Code for search criteria persistence.
  601. // Retrieve values if restore_lastsearch_values
  602. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  603. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  604. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  605. if (is_array($tmp)) {
  606. foreach ($tmp as $key => $val) {
  607. if ($key == $paramname) { // We are on the requested parameter
  608. $out = $val;
  609. break;
  610. }
  611. }
  612. }
  613. }
  614. // If there is saved contextpage, page or limit
  615. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  616. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  617. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  618. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  619. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  620. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  621. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  622. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  623. }
  624. } elseif (!isset($_GET['sortfield'])) {
  625. // Else, retrieve default values if we are not doing a sort
  626. // 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
  627. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  628. // Search default value from $object->field
  629. global $object;
  630. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  631. $out = $object->fields[$paramname]['default'];
  632. }
  633. }
  634. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  635. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  636. // Now search in setup to overwrite default values
  637. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  638. if (isset($user->default_values[$relativepathstring]['createform'])) {
  639. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  640. $qualified = 0;
  641. if ($defkey != '_noquery_') {
  642. $tmpqueryarraytohave = explode('&', $defkey);
  643. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  644. $foundintru = 0;
  645. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  646. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  647. $foundintru = 1;
  648. }
  649. }
  650. if (!$foundintru) {
  651. $qualified = 1;
  652. }
  653. //var_dump($defkey.'-'.$qualified);
  654. } else {
  655. $qualified = 1;
  656. }
  657. if ($qualified) {
  658. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  659. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  660. break;
  661. }
  662. }
  663. }
  664. }
  665. }
  666. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  667. // Management of default search_filters and sort order
  668. if (!empty($user->default_values)) {
  669. // $user->default_values defined from menu 'Setup - Default values'
  670. //var_dump($user->default_values[$relativepathstring]);
  671. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  672. // Sorted on which fields ? ASC or DESC ?
  673. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  674. // Even if paramname is sortfield, data are stored into ['sortorder...']
  675. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  676. $qualified = 0;
  677. if ($defkey != '_noquery_') {
  678. $tmpqueryarraytohave = explode('&', $defkey);
  679. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  680. $foundintru = 0;
  681. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  682. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  683. $foundintru = 1;
  684. }
  685. }
  686. if (!$foundintru) {
  687. $qualified = 1;
  688. }
  689. //var_dump($defkey.'-'.$qualified);
  690. } else {
  691. $qualified = 1;
  692. }
  693. if ($qualified) {
  694. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  695. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  696. if ($out) {
  697. $out .= ', ';
  698. }
  699. if ($paramname == 'sortfield') {
  700. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  701. }
  702. if ($paramname == 'sortorder') {
  703. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  704. }
  705. }
  706. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  707. }
  708. }
  709. }
  710. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  711. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  712. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  713. continue;
  714. }
  715. $qualified = 0;
  716. if ($defkey != '_noquery_') {
  717. $tmpqueryarraytohave = explode('&', $defkey);
  718. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  719. $foundintru = 0;
  720. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  721. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  722. $foundintru = 1;
  723. }
  724. }
  725. if (!$foundintru) {
  726. $qualified = 1;
  727. }
  728. //var_dump($defkey.'-'.$qualified);
  729. } else {
  730. $qualified = 1;
  731. }
  732. if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
  733. // We must keep $_POST and $_GET here
  734. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  735. // We made a search from quick search menu, do we still use default filter ?
  736. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  737. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  738. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  739. }
  740. } else {
  741. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  742. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  743. }
  744. break;
  745. }
  746. }
  747. }
  748. }
  749. }
  750. }
  751. }
  752. }
  753. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  754. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  755. // 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.
  756. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  757. $reg = array();
  758. $maxloop = 20;
  759. $loopnb = 0; // Protection against infinite loop
  760. 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.
  761. $loopnb++;
  762. $newout = '';
  763. if ($reg[1] == 'DAY') {
  764. $tmp = dol_getdate(dol_now(), true);
  765. $newout = $tmp['mday'];
  766. } elseif ($reg[1] == 'MONTH') {
  767. $tmp = dol_getdate(dol_now(), true);
  768. $newout = $tmp['mon'];
  769. } elseif ($reg[1] == 'YEAR') {
  770. $tmp = dol_getdate(dol_now(), true);
  771. $newout = $tmp['year'];
  772. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  773. $tmp = dol_getdate(dol_now(), true);
  774. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  775. $newout = $tmp2['day'];
  776. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  777. $tmp = dol_getdate(dol_now(), true);
  778. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  779. $newout = $tmp2['month'];
  780. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  781. $tmp = dol_getdate(dol_now(), true);
  782. $newout = ($tmp['year'] - 1);
  783. } elseif ($reg[1] == 'NEXT_DAY') {
  784. $tmp = dol_getdate(dol_now(), true);
  785. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  786. $newout = $tmp2['day'];
  787. } elseif ($reg[1] == 'NEXT_MONTH') {
  788. $tmp = dol_getdate(dol_now(), true);
  789. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  790. $newout = $tmp2['month'];
  791. } elseif ($reg[1] == 'NEXT_YEAR') {
  792. $tmp = dol_getdate(dol_now(), true);
  793. $newout = ($tmp['year'] + 1);
  794. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  795. $newout = $mysoc->country_id;
  796. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  797. $newout = $user->id;
  798. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  799. $newout = $user->fk_user;
  800. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  801. $newout = $conf->entity;
  802. } else {
  803. $newout = ''; // Key not found, we replace with empty string
  804. }
  805. //var_dump('__'.$reg[1].'__ -> '.$newout);
  806. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  807. }
  808. }
  809. // Check rule
  810. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  811. if (!is_array($out) || empty($out)) {
  812. $out = array();
  813. } else {
  814. $tmparray = explode(':', $check);
  815. if (!empty($tmparray[1])) {
  816. $tmpcheck = $tmparray[1];
  817. } else {
  818. $tmpcheck = 'alphanohtml';
  819. }
  820. foreach ($out as $outkey => $outval) {
  821. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  822. }
  823. }
  824. } else {
  825. // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
  826. // 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
  827. if (strpos($paramname, 'search_') === 0) {
  828. $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
  829. }
  830. $out = sanitizeVal($out, $check, $filter, $options);
  831. }
  832. // Sanitizing for special parameters.
  833. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  834. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  835. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  836. $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.
  837. do {
  838. $oldstringtoclean = $out;
  839. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  840. $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'
  841. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  842. } while ($oldstringtoclean != $out);
  843. }
  844. // Code for search criteria persistence.
  845. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  846. if (empty($method) || $method == 3 || $method == 4) {
  847. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  848. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  849. // We save search key only if $out not empty that means:
  850. // - posted value not empty, or
  851. // - 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).
  852. if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
  853. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  854. }
  855. }
  856. }
  857. return $out;
  858. }
  859. /**
  860. * Return value of a param into GET or POST supervariable.
  861. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  862. * Note: The property $user->default_values is loaded by main.php when loading the user.
  863. *
  864. * @param string $paramname Name of parameter to found
  865. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  866. * @return int Value found (int)
  867. */
  868. function GETPOSTINT($paramname, $method = 0)
  869. {
  870. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  871. }
  872. /**
  873. * Return a sanitized or empty value after checking value against a rule.
  874. *
  875. * @deprecated
  876. * @param string|array $out Value to check/clear.
  877. * @param string $check Type of check/sanitizing
  878. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  879. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  880. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  881. */
  882. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  883. {
  884. return sanitizeVal($out, $check, $filter, $options);
  885. }
  886. /**
  887. * Return a sanitized or empty value after checking value against a rule.
  888. *
  889. * @param string|array $out Value to check/clear.
  890. * @param string $check Type of check/sanitizing
  891. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  892. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  893. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  894. */
  895. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  896. {
  897. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  898. // Check is done after replacement
  899. switch ($check) {
  900. case 'none':
  901. break;
  902. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  903. if (!is_numeric($out)) {
  904. $out = '';
  905. }
  906. break;
  907. case 'intcomma':
  908. if (preg_match('/[^0-9,-]+/i', $out)) {
  909. $out = '';
  910. }
  911. break;
  912. case 'san_alpha':
  913. $out = filter_var($out, FILTER_SANITIZE_STRING);
  914. break;
  915. case 'email':
  916. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  917. break;
  918. case 'aZ':
  919. if (!is_array($out)) {
  920. $out = trim($out);
  921. if (preg_match('/[^a-z]+/i', $out)) {
  922. $out = '';
  923. }
  924. }
  925. break;
  926. case 'aZ09':
  927. if (!is_array($out)) {
  928. $out = trim($out);
  929. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  930. $out = '';
  931. }
  932. }
  933. break;
  934. case 'aZ09arobase': // great to sanitize $objecttype parameter
  935. if (!is_array($out)) {
  936. $out = trim($out);
  937. if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
  938. $out = '';
  939. }
  940. }
  941. break;
  942. case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
  943. if (!is_array($out)) {
  944. $out = trim($out);
  945. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  946. $out = '';
  947. }
  948. }
  949. break;
  950. case 'alpha': // No html and no ../ and "
  951. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  952. if (!is_array($out)) {
  953. $out = trim($out);
  954. do {
  955. $oldstringtoclean = $out;
  956. // Remove html tags
  957. $out = dol_string_nohtmltag($out, 0);
  958. // Remove also other dangerous string sequences
  959. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  960. // '../' or '..\' is dangerous because it allows dir transversals
  961. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  962. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  963. } while ($oldstringtoclean != $out);
  964. // keep lines feed
  965. }
  966. break;
  967. 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'
  968. if (!is_array($out)) {
  969. $out = trim($out);
  970. do {
  971. $oldstringtoclean = $out;
  972. // Remove html tags
  973. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  974. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  975. // '../' or '..\' is dangerous because it allows dir transversals
  976. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  977. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  978. } while ($oldstringtoclean != $out);
  979. }
  980. break;
  981. case 'nohtml': // No html
  982. $out = dol_string_nohtmltag($out, 0);
  983. break;
  984. case 'restricthtmlnolink':
  985. case 'restricthtml': // Recommended for most html textarea
  986. case 'restricthtmlallowclass':
  987. case 'restricthtmlallowunvalid':
  988. $out = dol_htmlwithnojs($out, 1, $check);
  989. break;
  990. case 'custom':
  991. if (!empty($out)) {
  992. if (empty($filter)) {
  993. return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
  994. }
  995. /*if (empty($options)) {
  996. return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
  997. }*/
  998. $out = filter_var($out, $filter, $options);
  999. }
  1000. break;
  1001. }
  1002. return $out;
  1003. }
  1004. if (!function_exists('dol_getprefix')) {
  1005. /**
  1006. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  1007. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  1008. * or two instances in same virtual servers.
  1009. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  1010. *
  1011. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  1012. * @return string A calculated prefix
  1013. */
  1014. function dol_getprefix($mode = '')
  1015. {
  1016. // If prefix is for email (we need to have $conf already loaded for this case)
  1017. if ($mode == 'email') {
  1018. global $conf;
  1019. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  1020. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  1021. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  1022. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  1023. return $_SERVER["SERVER_NAME"];
  1024. }
  1025. }
  1026. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  1027. if (!empty($conf->file->instance_unique_id)) {
  1028. return sha1('dolibarr'.$conf->file->instance_unique_id);
  1029. }
  1030. // For backward compatibility when instance_unique_id is not set
  1031. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1032. }
  1033. // If prefix is for session (no need to have $conf loaded)
  1034. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  1035. $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
  1036. // The recommended value (may be not defined for old versions)
  1037. if (!empty($tmp_instance_unique_id)) {
  1038. return sha1('dolibarr'.$tmp_instance_unique_id);
  1039. }
  1040. // For backward compatibility when instance_unique_id is not set
  1041. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  1042. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1043. } else {
  1044. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1045. }
  1046. }
  1047. }
  1048. /**
  1049. * Make an include_once using default root and alternate root if it fails.
  1050. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  1051. * To link to a module file from a module file, use include './mymodulefile';
  1052. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  1053. *
  1054. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  1055. * @param string $classname Class name (deprecated)
  1056. * @return bool True if load is a success, False if it fails
  1057. */
  1058. function dol_include_once($relpath, $classname = '')
  1059. {
  1060. 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']
  1061. $fullpath = dol_buildpath($relpath);
  1062. if (!file_exists($fullpath)) {
  1063. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  1064. return false;
  1065. }
  1066. if (!empty($classname) && !class_exists($classname)) {
  1067. return include $fullpath;
  1068. } else {
  1069. return include_once $fullpath;
  1070. }
  1071. }
  1072. /**
  1073. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  1074. *
  1075. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  1076. * @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)
  1077. * @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)
  1078. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  1079. * 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
  1080. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  1081. */
  1082. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  1083. {
  1084. global $conf;
  1085. $path = preg_replace('/^\//', '', $path);
  1086. if (empty($type)) { // For a filesystem path
  1087. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  1088. if (is_array($conf->file->dol_document_root)) {
  1089. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  1090. if ($key == 'main') {
  1091. continue;
  1092. }
  1093. // if (@file_exists($dirroot.'/'.$path)) {
  1094. if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn]
  1095. $res = $dirroot.'/'.$path;
  1096. return $res;
  1097. }
  1098. }
  1099. }
  1100. if ($returnemptyifnotfound) {
  1101. // Not found into alternate dir
  1102. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  1103. return '';
  1104. }
  1105. }
  1106. } else {
  1107. // For an url path
  1108. // We try to get local path of file on filesystem from url
  1109. // Note that trying to know if a file on disk exist by forging path on disk from url
  1110. // works only for some web server and some setup. This is bugged when
  1111. // using proxy, rewriting, virtual path, etc...
  1112. $res = '';
  1113. if ($type == 1) {
  1114. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  1115. }
  1116. if ($type == 2) {
  1117. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  1118. }
  1119. if ($type == 3) {
  1120. $res = DOL_URL_ROOT.'/'.$path;
  1121. }
  1122. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  1123. if ($key == 'main') {
  1124. if ($type == 3) {
  1125. global $dolibarr_main_url_root;
  1126. // Define $urlwithroot
  1127. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1128. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1129. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1130. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  1131. }
  1132. continue;
  1133. }
  1134. $regs = array();
  1135. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  1136. if (!empty($regs[1])) {
  1137. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1138. //if (file_exists($dirroot.'/'.$regs[1])) {
  1139. if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn]
  1140. if ($type == 1) {
  1141. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1142. }
  1143. if ($type == 2) {
  1144. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1145. }
  1146. if ($type == 3) {
  1147. global $dolibarr_main_url_root;
  1148. // Define $urlwithroot
  1149. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1150. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1151. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1152. $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
  1153. }
  1154. break;
  1155. }
  1156. }
  1157. }
  1158. }
  1159. return $res;
  1160. }
  1161. /**
  1162. * Create a clone of instance of object (new instance with same value for each properties)
  1163. * 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.
  1164. * 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.
  1165. * 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.
  1166. *
  1167. * @param object $object Object to clone
  1168. * @param int $native 0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended)
  1169. * @return object Clone object
  1170. * @see https://php.net/manual/language.oop5.cloning.php
  1171. */
  1172. function dol_clone($object, $native = 0)
  1173. {
  1174. if ($native == 0) {
  1175. // deprecated method, use the method with native = 2 instead
  1176. $tmpsavdb = null;
  1177. if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
  1178. $tmpsavdb = $object->db;
  1179. unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
  1180. }
  1181. $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
  1182. if (!empty($tmpsavdb)) {
  1183. $object->db = $tmpsavdb;
  1184. }
  1185. } elseif ($native == 2) {
  1186. // recommended method to have a full isolated cloned object
  1187. $myclone = new stdClass();
  1188. $tmparray = get_object_vars($object); // return only public properties
  1189. if (is_array($tmparray)) {
  1190. foreach ($tmparray as $propertykey => $propertyval) {
  1191. if (is_scalar($propertyval) || is_array($propertyval)) {
  1192. $myclone->$propertykey = $propertyval;
  1193. }
  1194. }
  1195. }
  1196. } else {
  1197. $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)
  1198. }
  1199. return $myclone;
  1200. }
  1201. /**
  1202. * Optimize a size for some browsers (phone, smarphone, ...)
  1203. *
  1204. * @param int $size Size we want
  1205. * @param string $type Type of optimizing:
  1206. * '' = function used to define a size for truncation
  1207. * 'width' = function is used to define a width
  1208. * @return int New size after optimizing
  1209. */
  1210. function dol_size($size, $type = '')
  1211. {
  1212. global $conf;
  1213. if (empty($conf->dol_optimize_smallscreen)) {
  1214. return $size;
  1215. }
  1216. if ($type == 'width' && $size > 250) {
  1217. return 250;
  1218. } else {
  1219. return 10;
  1220. }
  1221. }
  1222. /**
  1223. * Clean a string to use it as a file name.
  1224. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1225. *
  1226. * @param string $str String to clean
  1227. * @param string $newstr String to replace bad chars with.
  1228. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1229. * @return string String cleaned (a-zA-Z_)
  1230. *
  1231. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1232. */
  1233. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1234. {
  1235. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1236. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1237. // Char '/' and '\' are file delimiters.
  1238. // 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
  1239. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
  1240. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1241. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1242. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1243. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1244. $tmp = str_replace('..', '', $tmp);
  1245. return $tmp;
  1246. }
  1247. /**
  1248. * Clean a string to use it as a path name.
  1249. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1250. *
  1251. * @param string $str String to clean
  1252. * @param string $newstr String to replace bad chars with
  1253. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1254. * @return string String cleaned (a-zA-Z_)
  1255. *
  1256. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1257. */
  1258. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1259. {
  1260. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1261. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1262. // 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
  1263. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
  1264. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1265. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1266. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1267. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1268. $tmp = str_replace('..', '', $tmp);
  1269. return $tmp;
  1270. }
  1271. /**
  1272. * Clean a string to use it as an URL (into a href or src attribute)
  1273. *
  1274. * @param string $stringtoclean String to clean
  1275. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1276. * @return string Escaped string.
  1277. */
  1278. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1279. {
  1280. // 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)
  1281. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1282. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1283. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1284. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1285. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1286. if ($type == 1) {
  1287. // removing : should disable links to external url like http:aaa)
  1288. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1289. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1290. }
  1291. do {
  1292. $oldstringtoclean = $stringtoclean;
  1293. // removing '&colon' should disable links to external url like http:aaa)
  1294. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1295. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1296. } while ($oldstringtoclean != $stringtoclean);
  1297. if ($type == 1) {
  1298. // removing '//' should disable links to external url like //aaa or http//)
  1299. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1300. }
  1301. return $stringtoclean;
  1302. }
  1303. /**
  1304. * Clean a string to use it as an Email.
  1305. *
  1306. * @param string $stringtoclean String to clean. Example 'abc@mycompany.com <My name>'
  1307. * @return string Escaped string.
  1308. */
  1309. function dol_sanitizeEmail($stringtoclean)
  1310. {
  1311. do {
  1312. $oldstringtoclean = $stringtoclean;
  1313. $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
  1314. } while ($oldstringtoclean != $stringtoclean);
  1315. return $stringtoclean;
  1316. }
  1317. /**
  1318. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1319. *
  1320. * @param string $str String to clean
  1321. * @return string Cleaned string
  1322. *
  1323. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1324. */
  1325. function dol_string_unaccent($str)
  1326. {
  1327. global $conf;
  1328. if (is_null($str)) {
  1329. return '';
  1330. }
  1331. if (utf8_check($str)) {
  1332. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1333. $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
  1334. return $transliterator->transliterate($str);
  1335. }
  1336. // See http://www.utf8-chartable.de/
  1337. $string = rawurlencode($str);
  1338. $replacements = array(
  1339. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1340. '%C3%87' => 'C',
  1341. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1342. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1343. '%C3%91' => 'N',
  1344. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1345. '%C5%A0' => 'S',
  1346. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1347. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1348. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1349. '%C3%A7' => 'c',
  1350. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1351. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1352. '%C3%B1' => 'n',
  1353. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1354. '%C5%A1' => 's',
  1355. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1356. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1357. );
  1358. $string = strtr($string, $replacements);
  1359. return rawurldecode($string);
  1360. } else {
  1361. // See http://www.ascii-code.com/
  1362. $string = strtr(
  1363. $str,
  1364. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1365. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1366. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1367. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1368. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1369. \xF9\xFA\xFB\xFC\xFD\xFF",
  1370. "AAAAAAC
  1371. EEEEIIIIDN
  1372. OOOOOUUUY
  1373. aaaaaaceeee
  1374. iiiidnooooo
  1375. uuuuyy"
  1376. );
  1377. $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"));
  1378. return $string;
  1379. }
  1380. }
  1381. /**
  1382. * Clean a string from all punctuation characters to use it as a ref or login.
  1383. * This is a more complete function than dol_sanitizeFileName().
  1384. *
  1385. * @param string $str String to clean
  1386. * @param string $newstr String to replace forbidden chars with
  1387. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1388. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1389. * @param int $keepspaces 1=Do not treat space as a special char to replace or remove
  1390. * @return string Cleaned string
  1391. *
  1392. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1393. */
  1394. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
  1395. {
  1396. $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
  1397. if (empty($keepspaces)) {
  1398. $forbidden_chars_to_replace[] = " ";
  1399. }
  1400. $forbidden_chars_to_remove = array();
  1401. //$forbidden_chars_to_remove=array("(",")");
  1402. if (is_array($badcharstoreplace)) {
  1403. $forbidden_chars_to_replace = $badcharstoreplace;
  1404. }
  1405. if (is_array($badcharstoremove)) {
  1406. $forbidden_chars_to_remove = $badcharstoremove;
  1407. }
  1408. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1409. }
  1410. /**
  1411. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1412. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1413. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1414. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1415. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1416. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1417. * @param string $str String to clean
  1418. * @param int $removetabcrlf Remove also CR-LF
  1419. * @return string Cleaned string
  1420. *
  1421. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1422. */
  1423. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1424. {
  1425. if ($removetabcrlf) {
  1426. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1427. } else {
  1428. 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
  1429. }
  1430. }
  1431. /**
  1432. * Returns text escaped for inclusion into javascript code
  1433. *
  1434. * @param string $stringtoescape String to escape
  1435. * @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 \
  1436. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1437. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1438. */
  1439. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1440. {
  1441. if (is_null($stringtoescape)) {
  1442. return '';
  1443. }
  1444. // escape quotes and backslashes, newlines, etc.
  1445. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1446. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1447. if (empty($noescapebackslashn)) {
  1448. $substitjs["\n"] = '\\n';
  1449. $substitjs['\\'] = '\\\\';
  1450. }
  1451. if (empty($mode)) {
  1452. $substitjs["'"] = "\\'";
  1453. $substitjs['"'] = "\\'";
  1454. } elseif ($mode == 1) {
  1455. $substitjs["'"] = "\\'";
  1456. } elseif ($mode == 2) {
  1457. $substitjs['"'] = '\\"';
  1458. } elseif ($mode == 3) {
  1459. $substitjs["'"] = "\\'";
  1460. $substitjs['"'] = "\\\"";
  1461. }
  1462. return strtr($stringtoescape, $substitjs);
  1463. }
  1464. /**
  1465. * Returns text escaped for inclusion into javascript code
  1466. *
  1467. * @param string $stringtoescape String to escape
  1468. * @return string Escaped string for json content.
  1469. */
  1470. function dol_escape_json($stringtoescape)
  1471. {
  1472. return str_replace('"', '\"', $stringtoescape);
  1473. }
  1474. /**
  1475. * Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields.
  1476. * When we output string on pages, we use
  1477. * - dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1), 1, 1) for notes or descriptions,
  1478. * - dol_escape_htmltag(dol_htmlentitiesbr()) for simple labels.
  1479. * - htmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords
  1480. *
  1481. * @param string $stringtoescape String to escape
  1482. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1483. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1484. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes into tag.
  1485. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1486. * @param int $cleanalsojavascript Clean also javascript. @TODO switch this option to 1 by default.
  1487. * @return string Escaped string
  1488. * @see dol_string_nohtmltag(), dol_string_onlythesehtmltags(), dol_string_nospecial(), dol_string_unaccent(), dol_htmlentitiesbr()
  1489. */
  1490. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
  1491. {
  1492. if ($noescapetags == 'common') {
  1493. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1494. }
  1495. if ($cleanalsojavascript) {
  1496. $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
  1497. }
  1498. // escape quotes and backslashes, newlines, etc.
  1499. if ($escapeonlyhtmltags) {
  1500. $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
  1501. } else {
  1502. $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
  1503. }
  1504. if (!$keepb) {
  1505. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1506. }
  1507. if (!$keepn) {
  1508. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1509. }
  1510. if ($escapeonlyhtmltags) {
  1511. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1512. } else {
  1513. // Escape tags to keep
  1514. // TODO Does not works yet when there is attributes into tag
  1515. $tmparrayoftags = array();
  1516. if ($noescapetags) {
  1517. $tmparrayoftags = explode(',', $noescapetags);
  1518. }
  1519. if (count($tmparrayoftags)) {
  1520. foreach ($tmparrayoftags as $tagtoreplace) {
  1521. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1522. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1523. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1524. }
  1525. }
  1526. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1527. if (count($tmparrayoftags)) {
  1528. foreach ($tmparrayoftags as $tagtoreplace) {
  1529. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1530. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1531. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1532. }
  1533. }
  1534. return $result;
  1535. }
  1536. }
  1537. /**
  1538. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1539. *
  1540. * @param string $string String to encode
  1541. * @param string $encoding Character set encoding
  1542. * @return string String converted
  1543. */
  1544. function dol_strtolower($string, $encoding = "UTF-8")
  1545. {
  1546. if (function_exists('mb_strtolower')) {
  1547. return mb_strtolower($string, $encoding);
  1548. } else {
  1549. return strtolower($string);
  1550. }
  1551. }
  1552. /**
  1553. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1554. *
  1555. * @param string $string String to encode
  1556. * @param string $encoding Character set encoding
  1557. * @return string String converted
  1558. * @see dol_ucfirst(), dol_ucwords()
  1559. */
  1560. function dol_strtoupper($string, $encoding = "UTF-8")
  1561. {
  1562. if (function_exists('mb_strtoupper')) {
  1563. return mb_strtoupper($string, $encoding);
  1564. } else {
  1565. return strtoupper($string);
  1566. }
  1567. }
  1568. /**
  1569. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1570. *
  1571. * @param string $string String to encode
  1572. * @param string $encoding Character set encodign
  1573. * @return string String converted
  1574. * @see dol_strtoupper(), dol_ucwords()
  1575. */
  1576. function dol_ucfirst($string, $encoding = "UTF-8")
  1577. {
  1578. if (function_exists('mb_substr')) {
  1579. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1580. } else {
  1581. return ucfirst($string);
  1582. }
  1583. }
  1584. /**
  1585. * Convert first character of all the words of a string to upper.
  1586. *
  1587. * @param string $string String to encode
  1588. * @param string $encoding Character set encodign
  1589. * @return string String converted
  1590. * @see dol_strtoupper(), dol_ucfirst()
  1591. */
  1592. function dol_ucwords($string, $encoding = "UTF-8")
  1593. {
  1594. if (function_exists('mb_convert_case')) {
  1595. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1596. } else {
  1597. return ucwords($string);
  1598. }
  1599. }
  1600. /**
  1601. * Write log message into outputs. Possible outputs can be:
  1602. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1603. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1604. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1605. * this, use logging to files instead of syslog (see setup of module).
  1606. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1607. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1608. * This function works only if syslog module is enabled.
  1609. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1610. *
  1611. * @param string $message Line to log. ''=Show nothing
  1612. * @param int $level Log level
  1613. * 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
  1614. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1615. * @param int $ident 1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log)
  1616. * @param string $suffixinfilename When output is a file, append this suffix into default log filename. Example '_stripe', '_mail'
  1617. * @param string $restricttologhandler Force output of log only to this log handler
  1618. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1619. * @return void
  1620. */
  1621. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1622. {
  1623. global $conf, $user, $debugbar;
  1624. // If syslog module enabled
  1625. if (!isModEnabled('syslog')) {
  1626. return;
  1627. }
  1628. // Check if we are into execution of code of a website
  1629. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1630. global $website, $websitekey;
  1631. if (is_object($website) && !empty($website->ref)) {
  1632. $suffixinfilename .= '_website_'.$website->ref;
  1633. } elseif (!empty($websitekey)) {
  1634. $suffixinfilename .= '_website_'.$websitekey;
  1635. }
  1636. }
  1637. // Check if we have a forced suffix
  1638. if (defined('USESUFFIXINLOG')) {
  1639. $suffixinfilename .= constant('USESUFFIXINLOG');
  1640. }
  1641. if ($ident < 0) {
  1642. foreach ($conf->loghandlers as $loghandlerinstance) {
  1643. $loghandlerinstance->setIdent($ident);
  1644. }
  1645. }
  1646. if (!empty($message)) {
  1647. // Test log level
  1648. $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');
  1649. if (!array_key_exists($level, $logLevels)) {
  1650. throw new Exception('Incorrect log level');
  1651. }
  1652. if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
  1653. return;
  1654. }
  1655. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1656. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1657. }
  1658. // If adding log inside HTML page is required
  1659. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1660. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1661. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1662. }
  1663. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1664. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1665. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1666. print "\n\n<!-- Log start\n";
  1667. print dol_escape_htmltag($message)."\n";
  1668. print "Log end -->\n";
  1669. }
  1670. $data = array(
  1671. 'message' => $message,
  1672. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1673. 'level' => $level,
  1674. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1675. 'ip' => false
  1676. );
  1677. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1678. if (!empty($remoteip)) {
  1679. $data['ip'] = $remoteip;
  1680. // This is when server run behind a reverse proxy
  1681. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1682. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1683. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1684. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1685. }
  1686. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1687. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1688. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1689. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1690. // 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).
  1691. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1692. } elseif (!empty($_SERVER['LOGNAME'])) {
  1693. // 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).
  1694. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1695. }
  1696. // Loop on each log handler and send output
  1697. foreach ($conf->loghandlers as $loghandlerinstance) {
  1698. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1699. continue;
  1700. }
  1701. $loghandlerinstance->export($data, $suffixinfilename);
  1702. }
  1703. unset($data);
  1704. }
  1705. if ($ident > 0) {
  1706. foreach ($conf->loghandlers as $loghandlerinstance) {
  1707. $loghandlerinstance->setIdent($ident);
  1708. }
  1709. }
  1710. }
  1711. /**
  1712. * Return HTML code to output a button to open a dialog popup box.
  1713. * Such buttons must be included inside a HTML form.
  1714. *
  1715. * @param string $name A name for the html component
  1716. * @param string $label Label shown in Popup title top bar
  1717. * @param string $buttonstring button string (HTML text we can click on)
  1718. * @param string $url Relative Url to open. For example '/project/card.php'
  1719. * @param string $disabled Disabled text
  1720. * @param string $morecss More CSS
  1721. * @param string $jsonopen Some JS code to execute on click/open of popup
  1722. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1723. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1724. * @param string $accesskey A key to use shortcut
  1725. * @return string HTML component with button
  1726. */
  1727. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
  1728. {
  1729. global $conf;
  1730. if (strpos($url, '?') > 0) {
  1731. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1732. } else {
  1733. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1734. }
  1735. $out = '';
  1736. $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
  1737. if ($backtopagejsfields) {
  1738. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1739. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1740. $backtopagejsfields = $name.":".$backtopagejsfields;
  1741. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1742. } else {
  1743. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1744. }
  1745. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1746. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1747. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1748. }
  1749. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1750. $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
  1751. $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
  1752. if (empty($conf->use_javascript_ajax)) {
  1753. $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
  1754. } elseif ($jsonopen) {
  1755. $out .= ' href="#" onclick="'.$jsonopen.'"';
  1756. } else {
  1757. $out .= ' href="#"';
  1758. }
  1759. $out .= '>'.$buttonstring.'</a>';
  1760. if (!empty($conf->use_javascript_ajax)) {
  1761. // Add code to open url using the popup. Add also hidden field to retreive the returned variables
  1762. $out .= '<!-- code to open popup and variables to retreive returned variables -->';
  1763. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1764. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1765. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1766. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1767. $out .= '<script nonce="'.getNonce().'" type="text/javascript">
  1768. jQuery(document).ready(function () {
  1769. jQuery(".button_'.$name.'").click(function () {
  1770. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1771. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1772. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1773. $tmpdialog.dialog({
  1774. autoOpen: false,
  1775. modal: true,
  1776. height: (window.innerHeight - 150),
  1777. width: \'80%\',
  1778. title: \''.dol_escape_js($label).'\',
  1779. open: function (event, ui) {
  1780. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1781. },
  1782. close: function (event, ui) {
  1783. var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1784. var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1785. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1786. if (returnedid != "" && returnedid != "div for returned id") {
  1787. jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
  1788. }
  1789. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1790. jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
  1791. }
  1792. }
  1793. });
  1794. $tmpdialog.dialog(\'open\');
  1795. return false;
  1796. });
  1797. });
  1798. </script>';
  1799. }
  1800. return $out;
  1801. }
  1802. /**
  1803. * Show tab header of a card
  1804. *
  1805. * @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.
  1806. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1807. * @param string $title Title
  1808. * @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
  1809. * @param string $picto Add a picto on tab title
  1810. * @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.
  1811. * @param string $morehtmlright Add more html content on right of tabs title
  1812. * @param string $morecss More Css
  1813. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1814. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1815. * @return void
  1816. * @deprecated Use print dol_get_fiche_head() instead
  1817. */
  1818. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1819. {
  1820. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1821. }
  1822. /**
  1823. * Show tabs of a record
  1824. *
  1825. * @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.
  1826. * @param string $active Active tab name
  1827. * @param string $title Title
  1828. * @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'
  1829. * @param string $picto Add a picto on tab title
  1830. * @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.
  1831. * @param string $morehtmlright Add more html content on right of tabs title
  1832. * @param string $morecss More CSS on the link <a>
  1833. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1834. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1835. * @param int $dragdropfile 0 (default) or 1. 1 enable a drop zone for file to be upload, 0 disable it
  1836. * @return string
  1837. */
  1838. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
  1839. {
  1840. global $conf, $langs, $hookmanager;
  1841. // Show title
  1842. $showtitle = 1;
  1843. if (!empty($conf->dol_optimize_smallscreen)) {
  1844. $showtitle = 0;
  1845. }
  1846. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1847. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1848. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1849. }
  1850. // Show right part
  1851. if ($morehtmlright) {
  1852. $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.
  1853. }
  1854. // Show title
  1855. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1856. $limittitle = 30;
  1857. $out .= '<a class="tabTitle">';
  1858. if ($picto) {
  1859. $noprefix = $pictoisfullpath;
  1860. if (strpos($picto, 'fontawesome_') !== false) {
  1861. $noprefix = 1;
  1862. }
  1863. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1864. }
  1865. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1866. $out .= '</a>';
  1867. }
  1868. // Show tabs
  1869. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1870. $maxkey = -1;
  1871. if (is_array($links) && !empty($links)) {
  1872. $keys = array_keys($links);
  1873. if (count($keys)) {
  1874. $maxkey = max($keys);
  1875. }
  1876. }
  1877. // Show tabs
  1878. // if =0 we don't use the feature
  1879. if (empty($limittoshow)) {
  1880. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1881. }
  1882. if (!empty($conf->dol_optimize_smallscreen)) {
  1883. $limittoshow = 2;
  1884. }
  1885. $displaytab = 0;
  1886. $nbintab = 0;
  1887. $popuptab = 0;
  1888. $outmore = '';
  1889. for ($i = 0; $i <= $maxkey; $i++) {
  1890. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1891. // If active tab is already present
  1892. if ($i >= $limittoshow) {
  1893. $limittoshow--;
  1894. }
  1895. }
  1896. }
  1897. for ($i = 0; $i <= $maxkey; $i++) {
  1898. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1899. $isactive = true;
  1900. } else {
  1901. $isactive = false;
  1902. }
  1903. if ($i < $limittoshow || $isactive) {
  1904. // Output entry with a visible tab
  1905. $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])).' -->';
  1906. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1907. if (!empty($links[$i][0])) {
  1908. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1909. } else {
  1910. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1911. }
  1912. } elseif (!empty($links[$i][1])) {
  1913. //print "x $i $active ".$links[$i][2]." z";
  1914. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1915. if (!empty($links[$i][0])) {
  1916. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1917. $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).'">';
  1918. }
  1919. $out .= $links[$i][1];
  1920. if (!empty($links[$i][0])) {
  1921. $out .= '</a>'."\n";
  1922. }
  1923. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1924. $out .= '</div>';
  1925. }
  1926. $out .= '</div>';
  1927. } else {
  1928. // Add entry into the combo popup with the other tabs
  1929. if (!$popuptab) {
  1930. $popuptab = 1;
  1931. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1932. }
  1933. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1934. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1935. if (!empty($links[$i][0])) {
  1936. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1937. } else {
  1938. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1939. }
  1940. } elseif (!empty($links[$i][1])) {
  1941. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1942. $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.
  1943. $outmore .= '</a>'."\n";
  1944. }
  1945. $outmore .= '</div>';
  1946. $nbintab++;
  1947. }
  1948. $displaytab = $i;
  1949. }
  1950. if ($popuptab) {
  1951. $outmore .= '</div>';
  1952. }
  1953. if ($popuptab) { // If there is some tabs not shown
  1954. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1955. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1956. $widthofpopup = 200;
  1957. $tabsname = $moretabssuffix;
  1958. if (empty($tabsname)) {
  1959. $tabsname = str_replace("@", "", $picto);
  1960. }
  1961. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  1962. $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".
  1963. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1964. $out .= $outmore;
  1965. $out .= '</div>';
  1966. $out .= '<div></div>';
  1967. $out .= "</div>\n";
  1968. $out .= '<script nonce="'.getNonce().'">';
  1969. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1970. var x = this.offsetLeft, y = this.offsetTop;
  1971. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1972. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1973. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1974. }
  1975. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1976. });
  1977. ";
  1978. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1979. $out .= "</script>";
  1980. }
  1981. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1982. $out .= "</div>\n";
  1983. }
  1984. if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
  1985. $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
  1986. }
  1987. if (!empty($dragdropfile)) {
  1988. $out .= dragAndDropFileUpload("dragDropAreaTabBar");
  1989. }
  1990. $parameters = array('tabname' => $active, 'out' => $out);
  1991. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1992. if ($reshook > 0) {
  1993. $out = $hookmanager->resPrint;
  1994. }
  1995. return $out;
  1996. }
  1997. /**
  1998. * Show tab footer of a card
  1999. *
  2000. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  2001. * @return void
  2002. * @deprecated Use print dol_get_fiche_end() instead
  2003. */
  2004. function dol_fiche_end($notab = 0)
  2005. {
  2006. print dol_get_fiche_end($notab);
  2007. }
  2008. /**
  2009. * Return tab footer of a card
  2010. *
  2011. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  2012. * @return string
  2013. */
  2014. function dol_get_fiche_end($notab = 0)
  2015. {
  2016. if (!$notab || $notab == -1) {
  2017. return "\n</div>\n";
  2018. } else {
  2019. return '';
  2020. }
  2021. }
  2022. /**
  2023. * Show tab footer of a card.
  2024. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  2025. *
  2026. * @param Object $object Object to show
  2027. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  2028. * @param string $morehtml More html content to output just before the nav bar
  2029. * @param int $shownav Show Condition (navigation is shown if value is 1)
  2030. * @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.
  2031. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  2032. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  2033. * @param string $moreparam More param to add in nav link url.
  2034. * @param int $nodbprefix Do not include DB prefix to forge table name
  2035. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  2036. * @param string $morehtmlstatus More html code to show under navigation arrows
  2037. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  2038. * @param string $morehtmlright More html code to show before navigation arrows
  2039. * @return void
  2040. */
  2041. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  2042. {
  2043. global $conf, $form, $user, $langs, $hookmanager, $action;
  2044. $error = 0;
  2045. $maxvisiblephotos = 1;
  2046. $showimage = 1;
  2047. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  2048. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  2049. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  2050. $showbarcode = 0;
  2051. }
  2052. $modulepart = 'unknown';
  2053. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  2054. $modulepart = $object->element;
  2055. } elseif ($object->element == 'member') {
  2056. $modulepart = 'memberphoto';
  2057. } elseif ($object->element == 'user') {
  2058. $modulepart = 'userphoto';
  2059. }
  2060. if (class_exists("Imagick")) {
  2061. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  2062. $modulepart = $object->element;
  2063. } elseif ($object->element == 'fichinter') {
  2064. $modulepart = 'ficheinter';
  2065. } elseif ($object->element == 'contrat') {
  2066. $modulepart = 'contract';
  2067. } elseif ($object->element == 'order_supplier') {
  2068. $modulepart = 'supplier_order';
  2069. } elseif ($object->element == 'invoice_supplier') {
  2070. $modulepart = 'supplier_invoice';
  2071. }
  2072. }
  2073. if ($object->element == 'product') {
  2074. $width = 80;
  2075. $cssclass = 'photowithmargin photoref';
  2076. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  2077. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  2078. if ($conf->browser->layout == 'phone') {
  2079. $maxvisiblephotos = 1;
  2080. }
  2081. if ($showimage) {
  2082. $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>';
  2083. } else {
  2084. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  2085. $nophoto = '';
  2086. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2087. } else { // Show no photo link
  2088. $nophoto = '/public/theme/common/nophoto.png';
  2089. $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>';
  2090. }
  2091. }
  2092. } elseif ($object->element == 'ticket') {
  2093. $width = 80;
  2094. $cssclass = 'photoref';
  2095. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  2096. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  2097. if ($conf->browser->layout == 'phone') {
  2098. $maxvisiblephotos = 1;
  2099. }
  2100. if ($showimage) {
  2101. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  2102. if ($object->nbphoto > 0) {
  2103. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  2104. } else {
  2105. $showimage = 0;
  2106. }
  2107. }
  2108. if (!$showimage) {
  2109. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  2110. $nophoto = '';
  2111. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2112. } else { // Show no photo link
  2113. $nophoto = img_picto('No photo', 'object_ticket');
  2114. $morehtmlleft .= '<!-- No photo to show -->';
  2115. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2116. $morehtmlleft .= $nophoto;
  2117. $morehtmlleft .= '</div></div>';
  2118. }
  2119. }
  2120. } else {
  2121. if ($showimage) {
  2122. if ($modulepart != 'unknown') {
  2123. $phototoshow = '';
  2124. // Check if a preview file is available
  2125. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  2126. $objectref = dol_sanitizeFileName($object->ref);
  2127. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  2128. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  2129. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  2130. $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
  2131. } else {
  2132. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  2133. }
  2134. if (empty($subdir)) {
  2135. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  2136. }
  2137. $filepath = $dir_output.$subdir."/";
  2138. $filepdf = $filepath.$objectref.".pdf";
  2139. $relativepath = $subdir.'/'.$objectref.'.pdf';
  2140. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  2141. $fileimage = $filepdf.'_preview.png';
  2142. $relativepathimage = $relativepath.'_preview.png';
  2143. $pdfexists = file_exists($filepdf);
  2144. // If PDF file exists
  2145. if ($pdfexists) {
  2146. // Conversion du PDF en image png si fichier png non existant
  2147. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  2148. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  2149. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2150. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  2151. if ($ret < 0) {
  2152. $error++;
  2153. }
  2154. }
  2155. }
  2156. }
  2157. if ($pdfexists && !$error) {
  2158. $heightforphotref = 80;
  2159. if (!empty($conf->dol_optimize_smallscreen)) {
  2160. $heightforphotref = 60;
  2161. }
  2162. // If the preview file is found
  2163. if (file_exists($fileimage)) {
  2164. $phototoshow = '<div class="photoref">';
  2165. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  2166. $phototoshow .= '</div>';
  2167. }
  2168. }
  2169. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  2170. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  2171. }
  2172. if ($phototoshow) {
  2173. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  2174. $morehtmlleft .= $phototoshow;
  2175. $morehtmlleft .= '</div>';
  2176. }
  2177. }
  2178. if (empty($phototoshow)) { // Show No photo link (picto of object)
  2179. if ($object->element == 'action') {
  2180. $width = 80;
  2181. $cssclass = 'photorefcenter';
  2182. $nophoto = img_picto('No photo', 'title_agenda');
  2183. } else {
  2184. $width = 14;
  2185. $cssclass = 'photorefcenter';
  2186. $picto = $object->picto;
  2187. $prefix = 'object_';
  2188. if ($object->element == 'project' && !$object->public) {
  2189. $picto = 'project'; // instead of projectpub
  2190. }
  2191. if (strpos($picto, 'fontawesome_') !== false) {
  2192. $prefix = '';
  2193. }
  2194. $nophoto = img_picto('No photo', $prefix.$picto);
  2195. }
  2196. $morehtmlleft .= '<!-- No photo to show -->';
  2197. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2198. $morehtmlleft .= $nophoto;
  2199. $morehtmlleft .= '</div></div>';
  2200. }
  2201. }
  2202. }
  2203. // Show barcode
  2204. if ($showbarcode) {
  2205. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
  2206. }
  2207. if ($object->element == 'societe') {
  2208. if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2209. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  2210. } else {
  2211. $morehtmlstatus .= $object->getLibStatut(6);
  2212. }
  2213. } elseif ($object->element == 'product') {
  2214. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  2215. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2216. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  2217. } else {
  2218. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  2219. }
  2220. $morehtmlstatus .= ' &nbsp; ';
  2221. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2222. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2223. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2224. } else {
  2225. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2226. }
  2227. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  2228. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2229. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2230. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2231. }
  2232. $morehtmlstatus .= $tmptxt;
  2233. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2234. if ($object->statut == 0) {
  2235. $morehtmlstatus .= $object->getLibStatut(5);
  2236. } else {
  2237. $morehtmlstatus .= $object->getLibStatut(4);
  2238. }
  2239. } elseif ($object->element == 'facturerec') {
  2240. if ($object->frequency == 0) {
  2241. $morehtmlstatus .= $object->getLibStatut(2);
  2242. } else {
  2243. $morehtmlstatus .= $object->getLibStatut(5);
  2244. }
  2245. } elseif ($object->element == 'project_task') {
  2246. $object->fk_statut = 1;
  2247. if ($object->progress > 0) {
  2248. $object->fk_statut = 2;
  2249. }
  2250. if ($object->progress >= 100) {
  2251. $object->fk_statut = 3;
  2252. }
  2253. $tmptxt = $object->getLibStatut(5);
  2254. $morehtmlstatus .= $tmptxt; // No status on task
  2255. } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
  2256. $tmptxt = $object->getLibStatut(6);
  2257. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2258. $tmptxt = $object->getLibStatut(5);
  2259. }
  2260. $morehtmlstatus .= $tmptxt;
  2261. }
  2262. // Add if object was dispatched "into accountancy"
  2263. if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2264. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2265. if (method_exists($object, 'getVentilExportCompta')) {
  2266. $accounted = $object->getVentilExportCompta();
  2267. $langs->load("accountancy");
  2268. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2269. }
  2270. }
  2271. // Add alias for thirdparty
  2272. if (!empty($object->name_alias)) {
  2273. $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
  2274. }
  2275. // Add label
  2276. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2277. if (!empty($object->label)) {
  2278. $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
  2279. }
  2280. }
  2281. // Show address and email
  2282. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2283. $moreaddress = $object->getBannerAddress('refaddress', $object);
  2284. if ($moreaddress) {
  2285. $morehtmlref .= '<div class="refidno refaddress">';
  2286. $morehtmlref .= $moreaddress;
  2287. $morehtmlref .= '</div>';
  2288. }
  2289. }
  2290. if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) {
  2291. $morehtmlref .= '<div style="clear: both;"></div>';
  2292. $morehtmlref .= '<div class="refidno opacitymedium">';
  2293. $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
  2294. $morehtmlref .= '</div>';
  2295. }
  2296. $parameters=array('morehtmlref'=>$morehtmlref);
  2297. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2298. if ($reshook < 0) {
  2299. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2300. } elseif (empty($reshook)) {
  2301. $morehtmlref .= $hookmanager->resPrint;
  2302. } elseif ($reshook > 0) {
  2303. $morehtmlref = $hookmanager->resPrint;
  2304. }
  2305. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2306. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2307. print '</div>';
  2308. print '<div class="underrefbanner clearboth"></div>';
  2309. }
  2310. /**
  2311. * Show a string with the label tag dedicated to the HTML edit field.
  2312. *
  2313. * @param string $langkey Translation key
  2314. * @param string $fieldkey Key of the html select field the text refers to
  2315. * @param int $fieldrequired 1=Field is mandatory
  2316. * @return string
  2317. * @deprecated Form::editfieldkey
  2318. */
  2319. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2320. {
  2321. global $langs;
  2322. $ret = '';
  2323. if ($fieldrequired) {
  2324. $ret .= '<span class="fieldrequired">';
  2325. }
  2326. $ret .= '<label for="'.$fieldkey.'">';
  2327. $ret .= $langs->trans($langkey);
  2328. $ret .= '</label>';
  2329. if ($fieldrequired) {
  2330. $ret .= '</span>';
  2331. }
  2332. return $ret;
  2333. }
  2334. /**
  2335. * Return string to add class property on html element with pair/impair.
  2336. *
  2337. * @param string $var 0 or 1
  2338. * @param string $moreclass More class to add
  2339. * @return string String to add class onto HTML element
  2340. */
  2341. function dol_bc($var, $moreclass = '')
  2342. {
  2343. global $bc;
  2344. $ret = ' '.$bc[$var];
  2345. if ($moreclass) {
  2346. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2347. }
  2348. return $ret;
  2349. }
  2350. /**
  2351. * Return a formated address (part address/zip/town/state) according to country rules.
  2352. * See https://en.wikipedia.org/wiki/Address
  2353. *
  2354. * @param Object $object A company or contact object
  2355. * @param int $withcountry 1=Add country into address string
  2356. * @param string $sep Separator to use to separate info when building string
  2357. * @param Translate $outputlangs Object lang that contains language for text translation.
  2358. * @param int $mode 0=Standard output, 1=Remove address
  2359. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2360. * @return string Formated string
  2361. * @see dol_print_address()
  2362. */
  2363. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2364. {
  2365. global $conf, $langs, $hookmanager;
  2366. $ret = '';
  2367. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2368. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2369. // Address
  2370. if (empty($mode)) {
  2371. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : preg_replace('/(\r\n|\r|\n)+/', $sep, $object->address)));
  2372. }
  2373. // Zip/Town/State
  2374. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2375. // US: title firstname name \n address lines \n town, state, zip \n country
  2376. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2377. $ret .= (($ret && $town) ? $sep : '').$town;
  2378. if (!empty($object->state)) {
  2379. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2380. }
  2381. if (!empty($object->zip)) {
  2382. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2383. }
  2384. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2385. // UK: title firstname name \n address lines \n town state \n zip \n country
  2386. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2387. $ret .= ($ret ? $sep : '').$town;
  2388. if (!empty($object->state)) {
  2389. $ret .= ($ret ? ", " : '').$object->state;
  2390. }
  2391. if (!empty($object->zip)) {
  2392. $ret .= ($ret ? $sep : '').$object->zip;
  2393. }
  2394. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2395. // ES: title firstname name \n address lines \n zip town \n state \n country
  2396. $ret .= ($ret ? $sep : '').$object->zip;
  2397. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2398. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2399. if (!empty($object->state)) {
  2400. $ret .= $sep.$object->state;
  2401. }
  2402. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2403. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2404. // See https://www.sljfaq.org/afaq/addresses.html
  2405. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2406. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2407. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2408. // IT: title firstname name\n address lines \n zip town state_code \n country
  2409. $ret .= ($ret ? $sep : '').$object->zip;
  2410. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2411. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2412. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2413. } else {
  2414. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2415. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2416. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2417. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2418. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2419. $ret .= ($ret ? ", " : '').$object->state;
  2420. }
  2421. }
  2422. if (!is_object($outputlangs)) {
  2423. $outputlangs = $langs;
  2424. }
  2425. if ($withcountry) {
  2426. $langs->load("dict");
  2427. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2428. }
  2429. if ($hookmanager) {
  2430. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2431. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2432. if ($reshook > 0) {
  2433. $ret = '';
  2434. }
  2435. $ret .= $hookmanager->resPrint;
  2436. }
  2437. return $ret;
  2438. }
  2439. /**
  2440. * Format a string.
  2441. *
  2442. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2443. * @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)
  2444. * @param int $is_gmt See comment of timestamp parameter
  2445. * @return string A formatted string
  2446. */
  2447. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2448. {
  2449. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2450. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2451. } else {
  2452. return 'Error date into a not supported range';
  2453. }
  2454. }
  2455. /**
  2456. * Output date in a string format according to outputlangs (or langs if not defined).
  2457. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2458. *
  2459. * @param int $time GM Timestamps date
  2460. * @param string $format Output date format (tag of strftime function)
  2461. * "%d %b %Y",
  2462. * "%d/%m/%Y %H:%M",
  2463. * "%d/%m/%Y %H:%M:%S",
  2464. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2465. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2466. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2467. * false or 'tzserver' => output string is for local PHP server TZ usage
  2468. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2469. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2470. * @param Translate $outputlangs Object lang that contains language for text translation.
  2471. * @param boolean $encodetooutput false=no convert into output pagecode
  2472. * @return string Formated date or '' if time is null
  2473. *
  2474. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2475. */
  2476. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2477. {
  2478. global $conf, $langs;
  2479. // If date undefined or "", we return ""
  2480. if (dol_strlen($time) == 0) {
  2481. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2482. }
  2483. if ($tzoutput === 'auto') {
  2484. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2485. }
  2486. // Clean parameters
  2487. $to_gmt = false;
  2488. $offsettz = $offsetdst = 0;
  2489. if ($tzoutput) {
  2490. $to_gmt = true; // For backward compatibility
  2491. if (is_string($tzoutput)) {
  2492. if ($tzoutput == 'tzserver') {
  2493. $to_gmt = false;
  2494. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2495. $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
  2496. $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
  2497. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2498. $to_gmt = true;
  2499. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2500. if (class_exists('DateTimeZone')) {
  2501. $user_date_tz = new DateTimeZone($offsettzstring);
  2502. $user_dt = new DateTime();
  2503. $user_dt->setTimezone($user_date_tz);
  2504. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2505. $offsettz = $user_dt->getOffset(); // should include dst ?
  2506. } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
  2507. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2508. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2509. }
  2510. }
  2511. }
  2512. }
  2513. if (!is_object($outputlangs)) {
  2514. $outputlangs = $langs;
  2515. }
  2516. if (!$format) {
  2517. $format = 'daytextshort';
  2518. }
  2519. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2520. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2521. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2522. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2523. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2524. if ($formatwithoutreduce != $format) {
  2525. $format = $formatwithoutreduce;
  2526. $reduceformat = 1;
  2527. } // so format 'dayreduceformat' is processed like day
  2528. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2529. // TODO Add format daysmallyear and dayhoursmallyear
  2530. if ($format == 'day') {
  2531. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2532. } elseif ($format == 'hour') {
  2533. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2534. } elseif ($format == 'hourduration') {
  2535. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2536. } elseif ($format == 'daytext') {
  2537. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2538. } elseif ($format == 'daytextshort') {
  2539. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2540. } elseif ($format == 'dayhour') {
  2541. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2542. } elseif ($format == 'dayhoursec') {
  2543. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2544. } elseif ($format == 'dayhourtext') {
  2545. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2546. } elseif ($format == 'dayhourtextshort') {
  2547. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2548. } elseif ($format == 'dayhourlog') {
  2549. // Format not sensitive to language
  2550. $format = '%Y%m%d%H%M%S';
  2551. } elseif ($format == 'dayhourlogsmall') {
  2552. // Format not sensitive to language
  2553. $format = '%y%m%d%H%M';
  2554. } elseif ($format == 'dayhourldap') {
  2555. $format = '%Y%m%d%H%M%SZ';
  2556. } elseif ($format == 'dayhourxcard') {
  2557. $format = '%Y%m%dT%H%M%SZ';
  2558. } elseif ($format == 'dayxcard') {
  2559. $format = '%Y%m%d';
  2560. } elseif ($format == 'dayrfc') {
  2561. $format = '%Y-%m-%d'; // DATE_RFC3339
  2562. } elseif ($format == 'dayhourrfc') {
  2563. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2564. } elseif ($format == 'standard') {
  2565. $format = '%Y-%m-%d %H:%M:%S';
  2566. }
  2567. if ($reduceformat) {
  2568. $format = str_replace('%Y', '%y', $format);
  2569. $format = str_replace('yyyy', 'yy', $format);
  2570. }
  2571. // Clean format
  2572. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2573. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2574. $format = str_replace('%b', '__b__', $format);
  2575. $format = str_replace('%B', '__B__', $format);
  2576. }
  2577. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2578. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2579. $format = str_replace('%a', '__a__', $format);
  2580. $format = str_replace('%A', '__A__', $format);
  2581. }
  2582. // Analyze date
  2583. $reg = array();
  2584. 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
  2585. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]));
  2586. return '';
  2587. } 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
  2588. // This part of code should not be used anymore.
  2589. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]), LOG_WARNING);
  2590. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2591. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2592. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2593. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2594. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2595. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2596. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2597. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2598. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2599. if ($to_gmt) {
  2600. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2601. } else {
  2602. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2603. }
  2604. $dtts = new DateTime();
  2605. $dtts->setTimestamp($time);
  2606. $dtts->setTimezone($tzo);
  2607. $newformat = str_replace(
  2608. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2609. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2610. $format);
  2611. $ret = $dtts->format($newformat);
  2612. $ret = str_replace(
  2613. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2614. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2615. $ret
  2616. );
  2617. } else {
  2618. // Date is a timestamps
  2619. if ($time < 100000000000) { // Protection against bad date values
  2620. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2621. if ($to_gmt) {
  2622. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2623. } else {
  2624. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2625. }
  2626. $dtts = new DateTime();
  2627. $dtts->setTimestamp($timetouse);
  2628. $dtts->setTimezone($tzo);
  2629. $newformat = str_replace(
  2630. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2631. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2632. $format);
  2633. $ret = $dtts->format($newformat);
  2634. $ret = str_replace(
  2635. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2636. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2637. $ret
  2638. );
  2639. //var_dump($ret);exit;
  2640. } else {
  2641. $ret = 'Bad value '.$time.' for date';
  2642. }
  2643. }
  2644. if (preg_match('/__b__/i', $format)) {
  2645. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2646. if ($to_gmt) {
  2647. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2648. } else {
  2649. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2650. }
  2651. $dtts = new DateTime();
  2652. $dtts->setTimestamp($timetouse);
  2653. $dtts->setTimezone($tzo);
  2654. $month = $dtts->format("m");
  2655. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2656. if ($encodetooutput) {
  2657. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2658. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2659. } else {
  2660. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2661. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2662. }
  2663. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2664. $ret = str_replace('__b__', $monthtextshort, $ret);
  2665. $ret = str_replace('__B__', $monthtext, $ret);
  2666. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2667. //return $ret;
  2668. }
  2669. if (preg_match('/__a__/i', $format)) {
  2670. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2671. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2672. if ($to_gmt) {
  2673. $tzo = new DateTimeZone('UTC');
  2674. } else {
  2675. $tzo = new DateTimeZone(date_default_timezone_get());
  2676. }
  2677. $dtts = new DateTime();
  2678. $dtts->setTimestamp($timetouse);
  2679. $dtts->setTimezone($tzo);
  2680. $w = $dtts->format("w");
  2681. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2682. $ret = str_replace('__A__', $dayweek, $ret);
  2683. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2684. }
  2685. return $ret;
  2686. }
  2687. /**
  2688. * Return an array with locale date info.
  2689. * WARNING: This function use PHP server timezone by default to return locale informations.
  2690. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2691. *
  2692. * @param int $timestamp Timestamp
  2693. * @param boolean $fast Fast mode. deprecated.
  2694. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2695. * @return array Array of informations
  2696. * 'seconds' => $secs,
  2697. * 'minutes' => $min,
  2698. * 'hours' => $hour,
  2699. * 'mday' => $day,
  2700. * 'wday' => $dow, 0=sunday, 6=saturday
  2701. * 'mon' => $month,
  2702. * 'year' => $year,
  2703. * 'yday' => floor($secsInYear/$_day_power)
  2704. * '0' => original timestamp
  2705. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2706. */
  2707. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2708. {
  2709. $datetimeobj = new DateTime();
  2710. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2711. if ($forcetimezone) {
  2712. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2713. }
  2714. $arrayinfo = array(
  2715. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2716. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2717. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2718. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2719. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2720. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2721. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2722. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2723. '0'=>$timestamp
  2724. );
  2725. return $arrayinfo;
  2726. }
  2727. /**
  2728. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2729. * Replace function mktime not available under Windows if year < 1970
  2730. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2731. *
  2732. * @param int $hour Hour (can be -1 for undefined)
  2733. * @param int $minute Minute (can be -1 for undefined)
  2734. * @param int $second Second (can be -1 for undefined)
  2735. * @param int $month Month (1 to 12)
  2736. * @param int $day Day (1 to 31)
  2737. * @param int $year Year
  2738. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2739. * False or 0 or 'tzserver' = local to server TZ
  2740. * 'auto'
  2741. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2742. * '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.
  2743. * 'tz,TimeZone' = use specified timezone
  2744. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2745. * @return int|string Date as a timestamp, '' or false if error
  2746. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2747. */
  2748. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2749. {
  2750. global $conf;
  2751. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2752. if ($gm === 'auto') {
  2753. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2754. }
  2755. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2756. // Clean parameters
  2757. if ($hour == -1 || empty($hour)) {
  2758. $hour = 0;
  2759. }
  2760. if ($minute == -1 || empty($minute)) {
  2761. $minute = 0;
  2762. }
  2763. if ($second == -1 || empty($second)) {
  2764. $second = 0;
  2765. }
  2766. // Check parameters
  2767. if ($check) {
  2768. if (!$month || !$day) {
  2769. return '';
  2770. }
  2771. if ($day > 31) {
  2772. return '';
  2773. }
  2774. if ($month > 12) {
  2775. return '';
  2776. }
  2777. if ($hour < 0 || $hour > 24) {
  2778. return '';
  2779. }
  2780. if ($minute < 0 || $minute > 60) {
  2781. return '';
  2782. }
  2783. if ($second < 0 || $second > 60) {
  2784. return '';
  2785. }
  2786. }
  2787. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2788. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2789. $localtz = new DateTimeZone($default_timezone);
  2790. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2791. // We use dol_tz_string first because it is more reliable.
  2792. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2793. try {
  2794. $localtz = new DateTimeZone($default_timezone);
  2795. } catch (Exception $e) {
  2796. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2797. $default_timezone = @date_default_timezone_get();
  2798. }
  2799. } elseif (strrpos($gm, "tz,") !== false) {
  2800. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2801. try {
  2802. $localtz = new DateTimeZone($timezone);
  2803. } catch (Exception $e) {
  2804. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2805. }
  2806. }
  2807. if (empty($localtz)) {
  2808. $localtz = new DateTimeZone('UTC');
  2809. }
  2810. //var_dump($localtz);
  2811. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2812. $dt = new DateTime('now', $localtz);
  2813. $dt->setDate((int) $year, (int) $month, (int) $day);
  2814. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2815. $date = $dt->getTimestamp(); // should include daylight saving time
  2816. //var_dump($date);
  2817. return $date;
  2818. }
  2819. /**
  2820. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2821. *
  2822. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2823. * 'gmt' => we return GMT timestamp,
  2824. * 'tzserver' => we add the PHP server timezone
  2825. * 'tzref' => we add the company timezone. Not implemented.
  2826. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2827. * @return int $date Timestamp
  2828. */
  2829. function dol_now($mode = 'auto')
  2830. {
  2831. $ret = 0;
  2832. if ($mode === 'auto') {
  2833. $mode = 'gmt';
  2834. }
  2835. if ($mode == 'gmt') {
  2836. $ret = time(); // Time for now at greenwich.
  2837. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2838. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2839. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2840. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2841. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2842. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2843. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2844. // $ret=dol_now('gmt')+($tzsecond*3600);
  2845. //}
  2846. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2847. // Time for now with user timezone added
  2848. //print 'time: '.time();
  2849. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2850. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2851. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2852. }
  2853. return $ret;
  2854. }
  2855. /**
  2856. * Return string with formated size
  2857. *
  2858. * @param int $size Size to print
  2859. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2860. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2861. * @return string Link
  2862. */
  2863. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2864. {
  2865. global $conf, $langs;
  2866. $level = 1024;
  2867. if (!empty($conf->dol_optimize_smallscreen)) {
  2868. $shortunit = 1;
  2869. }
  2870. // Set value text
  2871. if (empty($shortvalue) || $size < ($level * 10)) {
  2872. $ret = $size;
  2873. $textunitshort = $langs->trans("b");
  2874. $textunitlong = $langs->trans("Bytes");
  2875. } else {
  2876. $ret = round($size / $level, 0);
  2877. $textunitshort = $langs->trans("Kb");
  2878. $textunitlong = $langs->trans("KiloBytes");
  2879. }
  2880. // Use long or short text unit
  2881. if (empty($shortunit)) {
  2882. $ret .= ' '.$textunitlong;
  2883. } else {
  2884. $ret .= ' '.$textunitshort;
  2885. }
  2886. return $ret;
  2887. }
  2888. /**
  2889. * Show Url link
  2890. *
  2891. * @param string $url Url to show
  2892. * @param string $target Target for link
  2893. * @param int $max Max number of characters to show
  2894. * @param int $withpicto With picto
  2895. * @param string $morecss More CSS
  2896. * @return string HTML Link
  2897. */
  2898. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
  2899. {
  2900. global $langs;
  2901. if (empty($url)) {
  2902. return '';
  2903. }
  2904. $linkstart = '<a href="';
  2905. if (!preg_match('/^http/i', $url)) {
  2906. $linkstart .= 'http://';
  2907. }
  2908. $linkstart .= $url;
  2909. $linkstart .= '"';
  2910. if ($target) {
  2911. $linkstart .= ' target="'.$target.'"';
  2912. }
  2913. $linkstart .= ' title="'.$langs->trans("URL").': '.$url.'"';
  2914. $linkstart .= '>';
  2915. $link = '';
  2916. if (!preg_match('/^http/i', $url)) {
  2917. $link .= 'http://';
  2918. }
  2919. $link .= dol_trunc($url, $max);
  2920. $linkend = '</a>';
  2921. if ($morecss == 'float') { // deprecated
  2922. return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2923. } else {
  2924. return $linkstart.'<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto('', 'globe').' ' : '').$link.'</span>'.$linkend;
  2925. }
  2926. }
  2927. /**
  2928. * Show EMail link formatted for HTML output.
  2929. *
  2930. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2931. * @param int $cid Id of contact if known
  2932. * @param int $socid Id of third party if known
  2933. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2934. * @param int $max Max number of characters to show
  2935. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2936. * @param int|string $withpicto Show picto
  2937. * @return string HTML Link
  2938. */
  2939. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2940. {
  2941. global $conf, $user, $langs, $hookmanager;
  2942. $newemail = dol_escape_htmltag($email);
  2943. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2944. $withpicto = 0;
  2945. }
  2946. if (empty($email)) {
  2947. return '&nbsp;';
  2948. }
  2949. if (!empty($addlink)) {
  2950. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2951. if (!preg_match('/^mailto:/i', $email)) {
  2952. $newemail .= 'mailto:';
  2953. }
  2954. $newemail .= $email;
  2955. $newemail .= '">';
  2956. $newemail .= dol_trunc($email, $max);
  2957. $newemail .= '</a>';
  2958. if ($showinvalid && !isValidEmail($email)) {
  2959. $langs->load("errors");
  2960. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2961. }
  2962. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  2963. $type = 'AC_EMAIL';
  2964. $link = '';
  2965. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2966. $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>';
  2967. }
  2968. if ($link) {
  2969. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2970. }
  2971. }
  2972. } else {
  2973. if ($showinvalid && !isValidEmail($email)) {
  2974. $langs->load("errors");
  2975. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2976. }
  2977. }
  2978. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2979. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  2980. //$rep .= '</div>';
  2981. if ($hookmanager) {
  2982. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2983. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2984. if ($reshook > 0) {
  2985. $rep = '';
  2986. }
  2987. $rep .= $hookmanager->resPrint;
  2988. }
  2989. return $rep;
  2990. }
  2991. /**
  2992. * Get array of social network dictionary
  2993. *
  2994. * @return array Array of Social Networks Dictionary
  2995. */
  2996. function getArrayOfSocialNetworks()
  2997. {
  2998. global $conf, $db;
  2999. $socialnetworks = array();
  3000. // Enable caching of array
  3001. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  3002. $cachekey = 'socialnetworks_' . $conf->entity;
  3003. $dataretrieved = dol_getcache($cachekey);
  3004. if (!is_null($dataretrieved)) {
  3005. $socialnetworks = $dataretrieved;
  3006. } else {
  3007. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  3008. $sql .= " WHERE entity=".$conf->entity;
  3009. $resql = $db->query($sql);
  3010. if ($resql) {
  3011. while ($obj = $db->fetch_object($resql)) {
  3012. $socialnetworks[$obj->code] = array(
  3013. 'rowid' => $obj->rowid,
  3014. 'label' => $obj->label,
  3015. 'url' => $obj->url,
  3016. 'icon' => $obj->icon,
  3017. 'active' => $obj->active,
  3018. );
  3019. }
  3020. }
  3021. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  3022. }
  3023. return $socialnetworks;
  3024. }
  3025. /**
  3026. * Show social network link
  3027. *
  3028. * @param string $value Social network ID to show (only skype, without 'Name of recipient' before)
  3029. * @param int $cid Id of contact if known
  3030. * @param int $socid Id of third party if known
  3031. * @param string $type 'skype','facebook',...
  3032. * @param array $dictsocialnetworks List of socialnetworks availables
  3033. * @return string HTML Link
  3034. */
  3035. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  3036. {
  3037. global $conf, $user, $langs;
  3038. $htmllink = $value;
  3039. if (empty($value)) {
  3040. return '&nbsp;';
  3041. }
  3042. if (!empty($type)) {
  3043. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  3044. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  3045. $htmllink .= '<span class="fa pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  3046. if ($type == 'skype') {
  3047. $htmllink .= dol_escape_htmltag($value);
  3048. $htmllink .= '&nbsp; <a href="skype:';
  3049. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3050. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  3051. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  3052. $htmllink .= '</a><a href="skype:';
  3053. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3054. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  3055. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  3056. $htmllink .= '</a>';
  3057. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
  3058. $addlink = 'AC_SKYPE';
  3059. $link = '';
  3060. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  3061. $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>';
  3062. }
  3063. $htmllink .= ($link ? ' '.$link : '');
  3064. }
  3065. } else {
  3066. if (!empty($dictsocialnetworks[$type]['url'])) {
  3067. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  3068. if ($tmpvirginurl) {
  3069. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3070. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3071. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  3072. if ($tmpvirginurl3) {
  3073. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3074. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3075. }
  3076. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  3077. if ($tmpvirginurl2) {
  3078. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3079. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3080. }
  3081. }
  3082. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  3083. if (preg_match('/^https?:\/\//i', $link)) {
  3084. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3085. } else {
  3086. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3087. }
  3088. } else {
  3089. $htmllink .= dol_escape_htmltag($value);
  3090. }
  3091. }
  3092. $htmllink .= '</div>';
  3093. } else {
  3094. $langs->load("errors");
  3095. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  3096. }
  3097. return $htmllink;
  3098. }
  3099. /**
  3100. * Format profIDs according to country
  3101. *
  3102. * @param string $profID Value of profID to format
  3103. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  3104. * @param string $countrycode Country code to use for formatting
  3105. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  3106. * @param string $separ Separation between numbers for a better visibility example : xxx xxx xxx xxxxx
  3107. * @return string Formated profID
  3108. */
  3109. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
  3110. {
  3111. global $mysoc;
  3112. if (empty($profID) || empty($profIDtype)) {
  3113. return '';
  3114. }
  3115. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  3116. $newProfID = $profID;
  3117. $id = substr($profIDtype, -1);
  3118. $ret = '';
  3119. if (strtoupper($countrycode) == 'FR') {
  3120. // France
  3121. if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
  3122. 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);
  3123. 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);
  3124. }
  3125. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  3126. else $ret = $newProfID;
  3127. return $ret;
  3128. }
  3129. /**
  3130. * Format phone numbers according to country
  3131. *
  3132. * @param string $phone Phone number to format
  3133. * @param string $countrycode Country code to use for formatting
  3134. * @param int $cid Id of contact if known
  3135. * @param int $socid Id of third party if known
  3136. * @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
  3137. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx. You can also use 'hidenum' to hide the number, keep only the picto.
  3138. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  3139. * @param string $titlealt Text to show on alt
  3140. * @param int $adddivfloat Add div float around phone.
  3141. * @return string Formated phone number
  3142. */
  3143. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  3144. {
  3145. global $conf, $user, $langs, $mysoc, $hookmanager;
  3146. // Clean phone parameter
  3147. $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
  3148. if (empty($phone)) {
  3149. return '';
  3150. }
  3151. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  3152. $separ = $conf->global->MAIN_PHONE_SEPAR;
  3153. }
  3154. if (empty($countrycode) && is_object($mysoc)) {
  3155. $countrycode = $mysoc->country_code;
  3156. }
  3157. // Short format for small screens
  3158. if ($conf->dol_optimize_smallscreen) {
  3159. $separ = '';
  3160. }
  3161. $newphone = $phone;
  3162. if (strtoupper($countrycode) == "FR") {
  3163. // France
  3164. if (dol_strlen($phone) == 10) {
  3165. $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);
  3166. } elseif (dol_strlen($phone) == 7) {
  3167. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  3168. } elseif (dol_strlen($phone) == 9) {
  3169. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  3170. } elseif (dol_strlen($phone) == 11) {
  3171. $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);
  3172. } elseif (dol_strlen($phone) == 12) {
  3173. $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);
  3174. } elseif (dol_strlen($phone) == 13) {
  3175. $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);
  3176. }
  3177. } elseif (strtoupper($countrycode) == "CA") {
  3178. if (dol_strlen($phone) == 10) {
  3179. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  3180. }
  3181. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  3182. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  3183. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3184. }
  3185. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  3186. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  3187. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  3188. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  3189. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  3190. }
  3191. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  3192. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  3193. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  3194. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  3195. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  3196. }
  3197. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  3198. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  3199. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3200. }
  3201. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  3202. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  3203. $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);
  3204. }
  3205. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  3206. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  3207. $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);
  3208. }
  3209. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  3210. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  3211. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3212. }
  3213. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  3214. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  3215. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3216. }
  3217. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  3218. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  3219. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3220. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  3221. $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);
  3222. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  3223. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3224. }
  3225. } elseif (strtoupper($countrycode) == "ML") {//Mali
  3226. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  3227. $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);
  3228. }
  3229. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  3230. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  3231. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3232. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  3233. $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);
  3234. }
  3235. } elseif (strtoupper($countrycode) == "MU") {
  3236. //Maurice
  3237. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  3238. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  3239. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  3240. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  3241. }
  3242. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  3243. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  3244. $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);
  3245. }
  3246. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  3247. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  3248. $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);
  3249. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  3250. $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);
  3251. }
  3252. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  3253. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  3254. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3255. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  3256. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3257. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  3258. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  3259. }
  3260. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  3261. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  3262. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3263. }
  3264. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  3265. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  3266. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3267. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  3268. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3269. }
  3270. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  3271. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  3272. $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);
  3273. }
  3274. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  3275. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  3276. $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);
  3277. }
  3278. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3279. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3280. $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);
  3281. }
  3282. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3283. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3284. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3285. }
  3286. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3287. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
  3288. $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);
  3289. }
  3290. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3291. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3292. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3293. }
  3294. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3295. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3296. $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);
  3297. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3298. $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);
  3299. }
  3300. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3301. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3302. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3303. }
  3304. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3305. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3306. $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);
  3307. }
  3308. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3309. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3310. $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);
  3311. }
  3312. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3313. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3314. $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);
  3315. }
  3316. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3317. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3318. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3319. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3320. $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);
  3321. }
  3322. } elseif (strtoupper($countrycode) == "AU") {
  3323. //Australie
  3324. if (dol_strlen($phone) == 12) {
  3325. //ex: +61_A_BCDE_FGHI
  3326. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3327. }
  3328. } elseif (strtoupper($countrycode) == "LU") {
  3329. // Luxembourg
  3330. if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
  3331. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
  3332. } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
  3333. $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);
  3334. } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
  3335. $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);
  3336. } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
  3337. $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);
  3338. }
  3339. }
  3340. $newphoneastart = $newphoneaend = '';
  3341. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3342. 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
  3343. $newphoneastart = '<a href="tel:'.$phone.'">';
  3344. $newphoneaend .= '</a>';
  3345. } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3346. if (empty($user->clicktodial_loaded)) {
  3347. $user->fetch_clicktodial();
  3348. }
  3349. // Define urlmask
  3350. $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
  3351. if (!empty($user->clicktodial_url)) {
  3352. $urlmask = $user->clicktodial_url;
  3353. }
  3354. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  3355. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  3356. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  3357. // This line is for backward compatibility
  3358. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3359. // Thoose lines are for substitution
  3360. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3361. '__PHONETO__'=>urlencode($phone),
  3362. '__LOGIN__'=>$clicktodial_login,
  3363. '__PASS__'=>$clicktodial_password);
  3364. $url = make_substitutions($url, $substitarray);
  3365. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  3366. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3367. $newphoneastart = '<a href="'.$url.'" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3368. $newphoneaend = '</a>';
  3369. } else {
  3370. // Old method
  3371. $newphoneastart = '<a href="'.$url.'"';
  3372. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  3373. $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
  3374. }
  3375. $newphoneastart .= '>';
  3376. $newphoneaend .= '</a>';
  3377. }
  3378. }
  3379. //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
  3380. if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3381. $type = 'AC_TEL';
  3382. $addlinktoagenda = '';
  3383. if ($addlink == 'AC_FAX') {
  3384. $type = 'AC_FAX';
  3385. }
  3386. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  3387. $addlinktoagenda = '<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>';
  3388. }
  3389. if ($addlinktoagenda) {
  3390. $newphone = '<span>'.$newphone.' '.$addlinktoagenda.'</span>';
  3391. }
  3392. }
  3393. }
  3394. if (empty($titlealt)) {
  3395. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3396. }
  3397. $rep = '';
  3398. if ($hookmanager) {
  3399. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3400. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3401. $rep .= $hookmanager->resPrint;
  3402. }
  3403. if (empty($reshook)) {
  3404. $picto = '';
  3405. if ($withpicto) {
  3406. if ($withpicto == 'fax') {
  3407. $picto = 'phoning_fax';
  3408. } elseif ($withpicto == 'phone') {
  3409. $picto = 'phoning';
  3410. } elseif ($withpicto == 'mobile') {
  3411. $picto = 'phoning_mobile';
  3412. } else {
  3413. $picto = '';
  3414. }
  3415. }
  3416. if ($adddivfloat == 1) {
  3417. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3418. } elseif (empty($adddivfloat)) {
  3419. $rep .= '<span style="margin-right: 10px;">';
  3420. }
  3421. $rep .= $newphoneastart;
  3422. $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png') : '');
  3423. if ($separ != 'hidenum') {
  3424. $rep .= ($withpicto ? ' ' : '').$newphone;
  3425. }
  3426. $rep .= $newphoneaend;
  3427. if ($adddivfloat == 1) {
  3428. $rep .= '</div>';
  3429. } elseif (empty($adddivfloat)) {
  3430. $rep .= '</span>';
  3431. }
  3432. }
  3433. return $rep;
  3434. }
  3435. /**
  3436. * Return an IP formated to be shown on screen
  3437. *
  3438. * @param string $ip IP
  3439. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3440. * @return string Formated IP, with country if GeoIP module is enabled
  3441. */
  3442. function dol_print_ip($ip, $mode = 0)
  3443. {
  3444. global $langs;
  3445. $ret = '';
  3446. if (empty($mode)) {
  3447. $ret .= $ip;
  3448. }
  3449. if ($mode != 2) {
  3450. $countrycode = dolGetCountryCodeFromIp($ip);
  3451. if ($countrycode) { // If success, countrycode is us, fr, ...
  3452. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3453. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3454. } else {
  3455. $ret .= ' ('.$countrycode.')';
  3456. }
  3457. } else {
  3458. // Nothing
  3459. }
  3460. }
  3461. return $ret;
  3462. }
  3463. /**
  3464. * Return the IP of remote user.
  3465. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3466. * Then HTTP_CLIENT_IP if defined (rare)
  3467. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3468. *
  3469. * @return string Ip of remote user.
  3470. */
  3471. function getUserRemoteIP()
  3472. {
  3473. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3474. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3475. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3476. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3477. } else {
  3478. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3479. }
  3480. } else {
  3481. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3482. }
  3483. } else {
  3484. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3485. }
  3486. return $ip;
  3487. }
  3488. /**
  3489. * Return if we are using a HTTPS connexion
  3490. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3491. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3492. * Then HTTP_X_FORWARDED_SSL
  3493. *
  3494. * @return boolean True if user is using HTTPS
  3495. */
  3496. function isHTTPS()
  3497. {
  3498. $isSecure = false;
  3499. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3500. $isSecure = true;
  3501. } 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') {
  3502. $isSecure = true;
  3503. }
  3504. return $isSecure;
  3505. }
  3506. /**
  3507. * Return a country code from IP. Empty string if not found.
  3508. *
  3509. * @param string $ip IP
  3510. * @return string Country code ('us', 'fr', ...)
  3511. */
  3512. function dolGetCountryCodeFromIp($ip)
  3513. {
  3514. global $conf;
  3515. $countrycode = '';
  3516. if (!empty($conf->geoipmaxmind->enabled)) {
  3517. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3518. //$ip='24.24.24.24';
  3519. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3520. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3521. $geoip = new DolGeoIP('country', $datafile);
  3522. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3523. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3524. }
  3525. return $countrycode;
  3526. }
  3527. /**
  3528. * Return country code for current user.
  3529. * If software is used inside a local network, detection may fails (we need a public ip)
  3530. *
  3531. * @return string Country code (fr, es, it, us, ...)
  3532. */
  3533. function dol_user_country()
  3534. {
  3535. global $conf, $langs, $user;
  3536. //$ret=$user->xxx;
  3537. $ret = '';
  3538. if (!empty($conf->geoipmaxmind->enabled)) {
  3539. $ip = getUserRemoteIP();
  3540. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3541. //$ip='24.24.24.24';
  3542. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3543. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3544. $geoip = new DolGeoIP('country', $datafile);
  3545. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3546. $ret = $countrycode;
  3547. }
  3548. return $ret;
  3549. }
  3550. /**
  3551. * Format address string
  3552. *
  3553. * @param string $address Address string, already formatted with dol_format_address()
  3554. * @param int $htmlid Html ID (for example 'gmap')
  3555. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3556. * @param int $id Id of object
  3557. * @param int $noprint No output. Result is the function return
  3558. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3559. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3560. * @see dol_format_address()
  3561. */
  3562. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3563. {
  3564. global $conf, $user, $langs, $hookmanager;
  3565. $out = '';
  3566. if ($address) {
  3567. if ($hookmanager) {
  3568. $parameters = array('element' => $element, 'id' => $id);
  3569. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3570. $out .= $hookmanager->resPrint;
  3571. }
  3572. if (empty($reshook)) {
  3573. if (empty($charfornl)) {
  3574. $out .= nl2br($address);
  3575. } else {
  3576. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3577. }
  3578. // TODO Remove this block, we can add this using the hook now
  3579. $showgmap = $showomap = 0;
  3580. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3581. $showgmap = 1;
  3582. }
  3583. if ($element == 'contact' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3584. $showgmap = 1;
  3585. }
  3586. if ($element == 'member' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3587. $showgmap = 1;
  3588. }
  3589. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3590. $showomap = 1;
  3591. }
  3592. if ($element == 'contact' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3593. $showomap = 1;
  3594. }
  3595. if ($element == 'member' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3596. $showomap = 1;
  3597. }
  3598. if ($showgmap) {
  3599. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3600. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3601. }
  3602. if ($showomap) {
  3603. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3604. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3605. }
  3606. }
  3607. }
  3608. if ($noprint) {
  3609. return $out;
  3610. } else {
  3611. print $out;
  3612. }
  3613. }
  3614. /**
  3615. * Return true if email syntax is ok.
  3616. *
  3617. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3618. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3619. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3620. * @return boolean true if email syntax is OK, false if KO or empty string
  3621. * @see isValidMXRecord()
  3622. */
  3623. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3624. {
  3625. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3626. return true;
  3627. }
  3628. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3629. return true;
  3630. }
  3631. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3632. return true;
  3633. }
  3634. return false;
  3635. }
  3636. /**
  3637. * Return if the domain name has a valid MX record.
  3638. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3639. *
  3640. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3641. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3642. * @see isValidEmail()
  3643. */
  3644. function isValidMXRecord($domain)
  3645. {
  3646. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3647. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3648. return 0;
  3649. }
  3650. if (function_exists('getmxrr')) {
  3651. $mxhosts = array();
  3652. $weight = array();
  3653. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3654. if (count($mxhosts) > 1) {
  3655. return 1;
  3656. }
  3657. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3658. return 1;
  3659. }
  3660. return 0;
  3661. }
  3662. }
  3663. // function idn_to_ascii or checkdnsrr or getmxrr does not exists
  3664. return -1;
  3665. }
  3666. /**
  3667. * Return true if phone number syntax is ok
  3668. * TODO Decide what to do with this
  3669. *
  3670. * @param string $phone phone (Ex: "0601010101")
  3671. * @return boolean true if phone syntax is OK, false if KO or empty string
  3672. */
  3673. function isValidPhone($phone)
  3674. {
  3675. return true;
  3676. }
  3677. /**
  3678. * Return first letters of a strings.
  3679. * Example with nbofchar=1: 'ghi' will return 'g' but 'abc def' will return 'ad'
  3680. * Example with nbofchar=2: 'ghi' will return 'gh' but 'abc def' will return 'abde'
  3681. *
  3682. * @param string $s String to truncate
  3683. * @param int $nbofchar Nb of characters to keep
  3684. * @return string Return first chars.
  3685. */
  3686. function dolGetFirstLetters($s, $nbofchar = 1)
  3687. {
  3688. $ret = '';
  3689. $tmparray = explode(' ', $s);
  3690. foreach ($tmparray as $tmps) {
  3691. $ret .= dol_substr($tmps, 0, $nbofchar);
  3692. }
  3693. return $ret;
  3694. }
  3695. /**
  3696. * Make a strlen call. Works even if mbstring module not enabled
  3697. *
  3698. * @param string $string String to calculate length
  3699. * @param string $stringencoding Encoding of string
  3700. * @return int Length of string
  3701. */
  3702. function dol_strlen($string, $stringencoding = 'UTF-8')
  3703. {
  3704. if (is_null($string)) {
  3705. return 0;
  3706. }
  3707. if (function_exists('mb_strlen')) {
  3708. return mb_strlen($string, $stringencoding);
  3709. } else {
  3710. return strlen($string);
  3711. }
  3712. }
  3713. /**
  3714. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3715. *
  3716. * @param string $string String to scan
  3717. * @param string $start Start position
  3718. * @param int|null $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3719. * @param string $stringencoding Page code used for input string encoding
  3720. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3721. * @return string substring
  3722. */
  3723. function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
  3724. {
  3725. global $langs;
  3726. if (empty($stringencoding)) {
  3727. $stringencoding = $langs->charset_output;
  3728. }
  3729. $ret = '';
  3730. if (empty($trunconbytes)) {
  3731. if (function_exists('mb_substr')) {
  3732. $ret = mb_substr($string, $start, $length, $stringencoding);
  3733. } else {
  3734. $ret = substr($string, $start, $length);
  3735. }
  3736. } else {
  3737. if (function_exists('mb_strcut')) {
  3738. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3739. } else {
  3740. $ret = substr($string, $start, $length);
  3741. }
  3742. }
  3743. return $ret;
  3744. }
  3745. /**
  3746. * Truncate a string to a particular length adding '…' if string larger than length.
  3747. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3748. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3749. *
  3750. * @param string $string String to truncate
  3751. * @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 ...)
  3752. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3753. * @param string $stringencoding Tell what is source string encoding
  3754. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3755. * @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)
  3756. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3757. */
  3758. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3759. {
  3760. global $conf;
  3761. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3762. return $string;
  3763. }
  3764. if (empty($stringencoding)) {
  3765. $stringencoding = 'UTF-8';
  3766. }
  3767. // reduce for small screen
  3768. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3769. $size = round($size / 3);
  3770. }
  3771. // We go always here
  3772. if ($trunc == 'right') {
  3773. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3774. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3775. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3776. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3777. } else {
  3778. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3779. return $string;
  3780. }
  3781. } elseif ($trunc == 'middle') {
  3782. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3783. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3784. $size1 = round($size / 2);
  3785. $size2 = round($size / 2);
  3786. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3787. } else {
  3788. return $string;
  3789. }
  3790. } elseif ($trunc == 'left') {
  3791. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3792. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3793. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3794. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3795. } else {
  3796. return $string;
  3797. }
  3798. } elseif ($trunc == 'wrap') {
  3799. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3800. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3801. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3802. } else {
  3803. return $string;
  3804. }
  3805. } else {
  3806. return 'BadParam3CallingDolTrunc';
  3807. }
  3808. }
  3809. /**
  3810. * Return the picto for a data type
  3811. *
  3812. * @param string $key Key
  3813. * @return string Pïcto for the key
  3814. */
  3815. function getPictoForType($key)
  3816. {
  3817. // Set array with type -> picto
  3818. $type2picto = array(
  3819. 'varchar'=>'font',
  3820. 'text'=>'font',
  3821. 'html'=>'code',
  3822. 'int'=>'sort-numeric-down',
  3823. 'double'=>'sort-numeric-down',
  3824. 'price'=>'currency',
  3825. 'pricecy'=>'multicurrency',
  3826. 'password' => 'key',
  3827. 'boolean'=>'check-square',
  3828. 'date'=>'calendar',
  3829. 'datetime'=>'calendar',
  3830. 'phone'=> 'phone',
  3831. 'mail'=> 'email',
  3832. 'url'=> 'url',
  3833. 'ip'=> 'country',
  3834. 'select' => 'list',
  3835. 'sellist' => 'list',
  3836. 'radio' => 'check-circle',
  3837. 'checkbox' => 'check-square',
  3838. 'chkbxlst' => 'check-square',
  3839. 'link' => 'link',
  3840. 'separate'=> 'minus'
  3841. );
  3842. if (!empty($type2picto[$key])) {
  3843. return img_picto('', $type2picto[$key], 'class="pictofixedwidth"');
  3844. }
  3845. return img_picto('', 'generic', 'class="pictofixedwidth"');
  3846. }
  3847. /**
  3848. * Show picto whatever it's its name (generic function)
  3849. *
  3850. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3851. * @param string $picto Name of image file to show ('filenew', ...).
  3852. * For font awesome icon (example 'user'), you can use picto_nocolor to not have the color of picto forced.
  3853. * If no extension provided and it is not a font awesome icon, we use '.png'. Image must be stored into theme/xxx/img directory.
  3854. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3855. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3856. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3857. * 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)
  3858. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3859. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3860. * @param int $srconly Return only content of the src attribute of img.
  3861. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3862. * @param string $alt Force alt for bind people
  3863. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3864. * @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.
  3865. * @return string Return img tag
  3866. * @see img_object(), img_picto_common()
  3867. */
  3868. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3869. {
  3870. global $conf, $langs;
  3871. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3872. $url = DOL_URL_ROOT;
  3873. $theme = isset($conf->theme) ? $conf->theme : null;
  3874. $path = 'theme/'.$theme;
  3875. // Define fullpathpicto to use into src
  3876. if ($pictoisfullpath) {
  3877. // Clean parameters
  3878. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3879. $picto .= '.png';
  3880. }
  3881. $fullpathpicto = $picto;
  3882. $reg = array();
  3883. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3884. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3885. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3886. }
  3887. } else {
  3888. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3889. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3890. $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
  3891. if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
  3892. // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
  3893. $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
  3894. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  3895. // Compatibility with old fontawesome versions
  3896. if ($pictowithouttext == 'file-o') {
  3897. $pictowithouttext = 'file';
  3898. }
  3899. $pictowithouttextarray = explode('_', $pictowithouttext);
  3900. $marginleftonlyshort = 0;
  3901. if (!empty($pictowithouttextarray[1])) {
  3902. // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
  3903. $fakey = 'fa-'.$pictowithouttextarray[0];
  3904. $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
  3905. $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
  3906. $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  3907. } else {
  3908. $fakey = 'fa-'.$pictowithouttext;
  3909. $faprefix = 'fas';
  3910. $facolor = '';
  3911. $fasize = '';
  3912. }
  3913. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3914. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3915. $morestyle = '';
  3916. $reg = array();
  3917. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3918. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3919. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3920. }
  3921. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3922. $morestyle = $reg[1];
  3923. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3924. }
  3925. $moreatt = trim($moreatt);
  3926. $enabledisablehtml = '<span class="'.$faprefix.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3927. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3928. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3929. $enabledisablehtml .= $titlealt;
  3930. }*/
  3931. $enabledisablehtml .= '</span>';
  3932. return $enabledisablehtml;
  3933. }
  3934. if (empty($srconly) && in_array($pictowithouttext, array(
  3935. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3936. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3937. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  3938. 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3939. 'cash-register', 'category', 'chart', 'check', 'clock', 'clone', 'close_title', 'code', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
  3940. 'check-circle', 'check-square', 'currency', 'multicurrency',
  3941. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3942. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3943. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
  3944. 'filter', 'file', 'file-o', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus', 'font',
  3945. 'gears', 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3946. 'hands-helping', 'help', 'holiday',
  3947. 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
  3948. 'key', 'knowledgemanagement',
  3949. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
  3950. 'margin', 'map-marker-alt', 'member', 'meeting', 'minus', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3951. 'off', 'on', 'order',
  3952. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
  3953. 'stock', 'resize', 'service', 'stats', 'trip',
  3954. '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',
  3955. 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3956. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3957. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3958. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3959. 'technic', 'ticket',
  3960. 'error', 'warning',
  3961. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
  3962. 'shapes', 'skill', 'square', 'sort-numeric-down', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3963. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3964. 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
  3965. 'conferenceorbooth', 'eventorganization',
  3966. 'stamp', 'signature'
  3967. ))) {
  3968. $fakey = $pictowithouttext;
  3969. $facolor = '';
  3970. $fasize = '';
  3971. $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
  3972. if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'file', 'file-o', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3973. $fa = 'far';
  3974. }
  3975. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3976. $fa = 'fab';
  3977. }
  3978. $arrayconvpictotofa = array(
  3979. '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',
  3980. 'bank_account'=>'university',
  3981. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3982. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3983. 'bom'=>'shapes',
  3984. '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',
  3985. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3986. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3987. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3988. 'file-o'=>'file', 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3989. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3990. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3991. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3992. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3993. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'jobprofile'=>'cogs',
  3994. 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  3995. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3996. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3997. 'sign-out'=>'sign-out-alt',
  3998. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_warning'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3999. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  4000. 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  4001. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'order'=>'file-invoice',
  4002. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  4003. 'other'=>'square',
  4004. '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',
  4005. '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',
  4006. 'recent' => 'check-square', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  4007. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  4008. 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
  4009. 'service'=>'concierge-bell',
  4010. 'skill'=>'shapes', 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  4011. 'supplier'=>'building', 'technic'=>'cogs',
  4012. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  4013. 'title_agenda'=>'calendar-alt',
  4014. 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'arrow-alt-circle-down',
  4015. 'jabber'=>'comment-o',
  4016. 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
  4017. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  4018. );
  4019. if ($conf->currency == 'EUR') {
  4020. $arrayconvpictotofa['currency'] = 'euro-sign';
  4021. $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
  4022. } else {
  4023. $arrayconvpictotofa['currency'] = 'dollar-sign';
  4024. $arrayconvpictotofa['multicurrency'] = 'euro-sign';
  4025. }
  4026. if ($pictowithouttext == 'off') {
  4027. $fakey = 'fa-square';
  4028. $fasize = '1.3em';
  4029. } elseif ($pictowithouttext == 'on') {
  4030. $fakey = 'fa-check-square';
  4031. $fasize = '1.3em';
  4032. } elseif ($pictowithouttext == 'listlight') {
  4033. $fakey = 'fa-download';
  4034. $marginleftonlyshort = 1;
  4035. } elseif ($pictowithouttext == 'printer') {
  4036. $fakey = 'fa-print';
  4037. $fasize = '1.2em';
  4038. } elseif ($pictowithouttext == 'note') {
  4039. $fakey = 'fa-sticky-note';
  4040. $marginleftonlyshort = 1;
  4041. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  4042. $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');
  4043. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  4044. if (preg_match('/selected/', $pictowithouttext)) {
  4045. $facolor = '#888';
  4046. }
  4047. $marginleftonlyshort = 1;
  4048. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  4049. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  4050. } else {
  4051. $fakey = 'fa-'.$pictowithouttext;
  4052. }
  4053. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  4054. $morecss .= ' em092';
  4055. }
  4056. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  4057. $morecss .= ' em088';
  4058. }
  4059. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  4060. $morecss .= ' em080';
  4061. }
  4062. // Define $marginleftonlyshort
  4063. $arrayconvpictotomarginleftonly = array(
  4064. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  4065. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  4066. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  4067. );
  4068. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  4069. $marginleftonlyshort = 0;
  4070. }
  4071. // Add CSS
  4072. $arrayconvpictotomorcess = array(
  4073. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  4074. 'bank_account'=>'infobox-bank_account',
  4075. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  4076. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  4077. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  4078. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  4079. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  4080. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  4081. 'incoterm'=>'infobox-supplier_proposal',
  4082. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  4083. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  4084. 'order'=>'infobox-commande',
  4085. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  4086. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_warning'=>'font-status4 warning', 'switch_on_red'=>'font-status8',
  4087. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  4088. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  4089. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  4090. 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
  4091. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  4092. 'resource'=>'infobox-action',
  4093. 'salary'=>'infobox-bank_account', 'shapes'=>'infobox-adherent', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  4094. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  4095. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  4096. 'vat'=>'infobox-bank_account',
  4097. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  4098. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  4099. );
  4100. if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4101. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  4102. }
  4103. // Define $color
  4104. $arrayconvpictotocolor = array(
  4105. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  4106. 'clone'=>'#999', 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  4107. 'dynamicprice'=>'#a69944',
  4108. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  4109. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  4110. 'lock'=>'#ddd', 'lot'=>'#a69944',
  4111. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  4112. 'other'=>'#ddd', 'world'=>'#986c6a',
  4113. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  4114. //'shipment'=>'#a69944',
  4115. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  4116. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  4117. 'website'=>'#304', 'workstation'=>'#a69944'
  4118. );
  4119. if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4120. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  4121. }
  4122. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  4123. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  4124. $morestyle = '';
  4125. $reg = array();
  4126. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4127. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4128. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4129. }
  4130. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  4131. $morestyle = $reg[1];
  4132. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  4133. }
  4134. $moreatt = trim($moreatt);
  4135. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  4136. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  4137. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4138. $enabledisablehtml .= $titlealt;
  4139. }*/
  4140. $enabledisablehtml .= '</span>';
  4141. return $enabledisablehtml;
  4142. }
  4143. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  4144. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  4145. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  4146. $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
  4147. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  4148. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  4149. }
  4150. // If we ask an image into $url/$mymodule/img (instead of default path)
  4151. $regs = array();
  4152. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  4153. $picto = $regs[1];
  4154. $path = $regs[2]; // $path is $mymodule
  4155. }
  4156. // Clean parameters
  4157. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  4158. $picto .= '.png';
  4159. }
  4160. // If alt path are defined, define url where img file is, according to physical path
  4161. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  4162. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  4163. if ($type == 'main') {
  4164. continue;
  4165. }
  4166. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  4167. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  4168. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  4169. break;
  4170. }
  4171. }
  4172. // $url is '' or '/custom', $path is current theme or
  4173. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  4174. }
  4175. if ($srconly) {
  4176. return $fullpathpicto;
  4177. }
  4178. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  4179. 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
  4180. }
  4181. /**
  4182. * Show a picto called object_picto (generic function)
  4183. *
  4184. * @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.
  4185. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  4186. * For external modules use imagename@mymodule to search into directory "img" of module.
  4187. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  4188. * @param int $pictoisfullpath If 1, image path is a full path
  4189. * @param int $srconly Return only content of the src attribute of img.
  4190. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4191. * @return string Return img tag
  4192. * @see img_picto(), img_picto_common()
  4193. */
  4194. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  4195. {
  4196. if (strpos($picto, '^') === 0) {
  4197. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  4198. } else {
  4199. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  4200. }
  4201. }
  4202. /**
  4203. * Show weather picto
  4204. *
  4205. * @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.
  4206. * @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).
  4207. * @param string $moreatt Add more attribute on img tag
  4208. * @param int $pictoisfullpath If 1, image path is a full path
  4209. * @param string $morecss More CSS
  4210. * @return string Return img tag
  4211. * @see img_object(), img_picto()
  4212. */
  4213. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  4214. {
  4215. global $conf;
  4216. if (is_numeric($picto)) {
  4217. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  4218. //$picto = $leveltopicto[$picto];
  4219. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  4220. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4221. $picto .= '.png';
  4222. }
  4223. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  4224. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  4225. }
  4226. /**
  4227. * Show picto (generic function)
  4228. *
  4229. * @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.
  4230. * @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.
  4231. * @param string $moreatt Add more attribute on img tag
  4232. * @param int $pictoisfullpath If 1, image path is a full path
  4233. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4234. * @return string Return img tag
  4235. * @see img_object(), img_picto()
  4236. */
  4237. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  4238. {
  4239. global $conf;
  4240. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4241. $picto .= '.png';
  4242. }
  4243. if ($pictoisfullpath) {
  4244. $path = $picto;
  4245. } else {
  4246. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  4247. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  4248. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  4249. if (file_exists($themepath)) {
  4250. $path = $themepath;
  4251. }
  4252. }
  4253. }
  4254. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  4255. }
  4256. /**
  4257. * Show logo action
  4258. *
  4259. * @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.
  4260. * @param string $numaction Action id or code to show
  4261. * @param string $picto Name of image file to show ('filenew', ...)
  4262. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  4263. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4264. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4265. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4266. * @param string $moreatt More attributes
  4267. * @return string Return an img tag
  4268. */
  4269. function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
  4270. {
  4271. global $langs;
  4272. if (empty($titlealt) || $titlealt == 'default') {
  4273. if ($numaction == '-1' || $numaction == 'ST_NO') {
  4274. $numaction = -1;
  4275. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  4276. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  4277. $numaction = 0;
  4278. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  4279. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  4280. $numaction = 1;
  4281. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  4282. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  4283. $numaction = 2;
  4284. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  4285. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  4286. $numaction = 3;
  4287. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  4288. } else {
  4289. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  4290. $numaction = 0;
  4291. }
  4292. }
  4293. if (!is_numeric($numaction)) {
  4294. $numaction = 0;
  4295. }
  4296. return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
  4297. }
  4298. /**
  4299. * Show pdf logo
  4300. *
  4301. * @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.
  4302. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  4303. * @return string Retourne tag img
  4304. */
  4305. function img_pdf($titlealt = 'default', $size = 3)
  4306. {
  4307. global $langs;
  4308. if ($titlealt == 'default') {
  4309. $titlealt = $langs->trans('Show');
  4310. }
  4311. return img_picto($titlealt, 'pdf'.$size.'.png');
  4312. }
  4313. /**
  4314. * Show logo +
  4315. *
  4316. * @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.
  4317. * @param string $other Add more attributes on img
  4318. * @return string Return tag img
  4319. */
  4320. function img_edit_add($titlealt = 'default', $other = '')
  4321. {
  4322. global $langs;
  4323. if ($titlealt == 'default') {
  4324. $titlealt = $langs->trans('Add');
  4325. }
  4326. return img_picto($titlealt, 'edit_add.png', $other);
  4327. }
  4328. /**
  4329. * Show logo -
  4330. *
  4331. * @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.
  4332. * @param string $other Add more attributes on img
  4333. * @return string Return tag img
  4334. */
  4335. function img_edit_remove($titlealt = 'default', $other = '')
  4336. {
  4337. global $langs;
  4338. if ($titlealt == 'default') {
  4339. $titlealt = $langs->trans('Remove');
  4340. }
  4341. return img_picto($titlealt, 'edit_remove.png', $other);
  4342. }
  4343. /**
  4344. * Show logo editer/modifier fiche
  4345. *
  4346. * @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.
  4347. * @param integer $float If you have to put the style "float: right"
  4348. * @param string $other Add more attributes on img
  4349. * @return string Return tag img
  4350. */
  4351. function img_edit($titlealt = 'default', $float = 0, $other = '')
  4352. {
  4353. global $langs;
  4354. if ($titlealt == 'default') {
  4355. $titlealt = $langs->trans('Modify');
  4356. }
  4357. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  4358. }
  4359. /**
  4360. * Show logo view card
  4361. *
  4362. * @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.
  4363. * @param integer $float If you have to put the style "float: right"
  4364. * @param string $other Add more attributes on img
  4365. * @return string Return tag img
  4366. */
  4367. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  4368. {
  4369. global $langs;
  4370. if ($titlealt == 'default') {
  4371. $titlealt = $langs->trans('View');
  4372. }
  4373. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4374. return img_picto($titlealt, 'eye', $moreatt);
  4375. }
  4376. /**
  4377. * Show delete logo
  4378. *
  4379. * @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.
  4380. * @param string $other Add more attributes on img
  4381. * @param string $morecss More CSS
  4382. * @return string Retourne tag img
  4383. */
  4384. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4385. {
  4386. global $langs;
  4387. if ($titlealt == 'default') {
  4388. $titlealt = $langs->trans('Delete');
  4389. }
  4390. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4391. }
  4392. /**
  4393. * Show printer logo
  4394. *
  4395. * @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.
  4396. * @param string $other Add more attributes on img
  4397. * @return string Retourne tag img
  4398. */
  4399. function img_printer($titlealt = "default", $other = '')
  4400. {
  4401. global $langs;
  4402. if ($titlealt == "default") {
  4403. $titlealt = $langs->trans("Print");
  4404. }
  4405. return img_picto($titlealt, 'printer.png', $other);
  4406. }
  4407. /**
  4408. * Show split logo
  4409. *
  4410. * @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.
  4411. * @param string $other Add more attributes on img
  4412. * @return string Retourne tag img
  4413. */
  4414. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4415. {
  4416. global $langs;
  4417. if ($titlealt == 'default') {
  4418. $titlealt = $langs->trans('Split');
  4419. }
  4420. return img_picto($titlealt, 'split.png', $other);
  4421. }
  4422. /**
  4423. * Show help logo with cursor "?"
  4424. *
  4425. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4426. * @param int|string $usealttitle Text to use as alt title
  4427. * @return string Return tag img
  4428. */
  4429. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4430. {
  4431. global $langs;
  4432. if ($usealttitle) {
  4433. if (is_string($usealttitle)) {
  4434. $usealttitle = dol_escape_htmltag($usealttitle);
  4435. } else {
  4436. $usealttitle = $langs->trans('Info');
  4437. }
  4438. }
  4439. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4440. }
  4441. /**
  4442. * Show info logo
  4443. *
  4444. * @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.
  4445. * @return string Return img tag
  4446. */
  4447. function img_info($titlealt = 'default')
  4448. {
  4449. global $langs;
  4450. if ($titlealt == 'default') {
  4451. $titlealt = $langs->trans('Informations');
  4452. }
  4453. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4454. }
  4455. /**
  4456. * Show warning logo
  4457. *
  4458. * @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.
  4459. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4460. * @param string $morecss Add more CSS
  4461. * @return string Return img tag
  4462. */
  4463. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4464. {
  4465. global $langs;
  4466. if ($titlealt == 'default') {
  4467. $titlealt = $langs->trans('Warning');
  4468. }
  4469. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4470. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4471. }
  4472. /**
  4473. * Show error logo
  4474. *
  4475. * @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.
  4476. * @return string Return img tag
  4477. */
  4478. function img_error($titlealt = 'default')
  4479. {
  4480. global $langs;
  4481. if ($titlealt == 'default') {
  4482. $titlealt = $langs->trans('Error');
  4483. }
  4484. return img_picto($titlealt, 'error.png');
  4485. }
  4486. /**
  4487. * Show next logo
  4488. *
  4489. * @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.
  4490. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4491. * @return string Return img tag
  4492. */
  4493. function img_next($titlealt = 'default', $moreatt = '')
  4494. {
  4495. global $langs;
  4496. if ($titlealt == 'default') {
  4497. $titlealt = $langs->trans('Next');
  4498. }
  4499. //return img_picto($titlealt, 'next.png', $moreatt);
  4500. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4501. }
  4502. /**
  4503. * Show previous logo
  4504. *
  4505. * @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.
  4506. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4507. * @return string Return img tag
  4508. */
  4509. function img_previous($titlealt = 'default', $moreatt = '')
  4510. {
  4511. global $langs;
  4512. if ($titlealt == 'default') {
  4513. $titlealt = $langs->trans('Previous');
  4514. }
  4515. //return img_picto($titlealt, 'previous.png', $moreatt);
  4516. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4517. }
  4518. /**
  4519. * Show down arrow logo
  4520. *
  4521. * @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.
  4522. * @param int $selected Selected
  4523. * @param string $moreclass Add more CSS classes
  4524. * @return string Return img tag
  4525. */
  4526. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4527. {
  4528. global $langs;
  4529. if ($titlealt == 'default') {
  4530. $titlealt = $langs->trans('Down');
  4531. }
  4532. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4533. }
  4534. /**
  4535. * Show top arrow logo
  4536. *
  4537. * @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.
  4538. * @param int $selected Selected
  4539. * @param string $moreclass Add more CSS classes
  4540. * @return string Return img tag
  4541. */
  4542. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4543. {
  4544. global $langs;
  4545. if ($titlealt == 'default') {
  4546. $titlealt = $langs->trans('Up');
  4547. }
  4548. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4549. }
  4550. /**
  4551. * Show left arrow logo
  4552. *
  4553. * @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.
  4554. * @param int $selected Selected
  4555. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4556. * @return string Return img tag
  4557. */
  4558. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4559. {
  4560. global $langs;
  4561. if ($titlealt == 'default') {
  4562. $titlealt = $langs->trans('Left');
  4563. }
  4564. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4565. }
  4566. /**
  4567. * Show right arrow logo
  4568. *
  4569. * @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.
  4570. * @param int $selected Selected
  4571. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4572. * @return string Return img tag
  4573. */
  4574. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4575. {
  4576. global $langs;
  4577. if ($titlealt == 'default') {
  4578. $titlealt = $langs->trans('Right');
  4579. }
  4580. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4581. }
  4582. /**
  4583. * Show tick logo if allowed
  4584. *
  4585. * @param string $allow Allow
  4586. * @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.
  4587. * @return string Return img tag
  4588. */
  4589. function img_allow($allow, $titlealt = 'default')
  4590. {
  4591. global $langs;
  4592. if ($titlealt == 'default') {
  4593. $titlealt = $langs->trans('Active');
  4594. }
  4595. if ($allow == 1) {
  4596. return img_picto($titlealt, 'tick.png');
  4597. }
  4598. return '-';
  4599. }
  4600. /**
  4601. * Return image of a credit card according to its brand name
  4602. *
  4603. * @param string $brand Brand name of credit card
  4604. * @param string $morecss More CSS
  4605. * @return string Return img tag
  4606. */
  4607. function img_credit_card($brand, $morecss = null)
  4608. {
  4609. if (is_null($morecss)) {
  4610. $morecss = 'fa-2x';
  4611. }
  4612. if ($brand == 'visa' || $brand == 'Visa') {
  4613. $brand = 'cc-visa';
  4614. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4615. $brand = 'cc-mastercard';
  4616. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4617. $brand = 'cc-amex';
  4618. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4619. $brand = 'cc-discover';
  4620. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4621. $brand = 'cc-jcb';
  4622. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4623. $brand = 'cc-diners-club';
  4624. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4625. $brand = 'credit-card';
  4626. }
  4627. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4628. }
  4629. /**
  4630. * Show MIME img of a file
  4631. *
  4632. * @param string $file Filename
  4633. * @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.
  4634. * @param string $morecss More css
  4635. * @return string Return img tag
  4636. */
  4637. function img_mime($file, $titlealt = '', $morecss = '')
  4638. {
  4639. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4640. $mimetype = dol_mimetype($file, '', 1);
  4641. $mimeimg = dol_mimetype($file, '', 2);
  4642. $mimefa = dol_mimetype($file, '', 4);
  4643. if (empty($titlealt)) {
  4644. $titlealt = 'Mime type: '.$mimetype;
  4645. }
  4646. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4647. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4648. }
  4649. /**
  4650. * Show search logo
  4651. *
  4652. * @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.
  4653. * @param string $other Add more attributes on img
  4654. * @return string Retourne tag img
  4655. */
  4656. function img_search($titlealt = 'default', $other = '')
  4657. {
  4658. global $conf, $langs;
  4659. if ($titlealt == 'default') {
  4660. $titlealt = $langs->trans('Search');
  4661. }
  4662. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4663. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4664. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4665. return $input;
  4666. }
  4667. /**
  4668. * Show search logo
  4669. *
  4670. * @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.
  4671. * @param string $other Add more attributes on img
  4672. * @return string Retourne tag img
  4673. */
  4674. function img_searchclear($titlealt = 'default', $other = '')
  4675. {
  4676. global $conf, $langs;
  4677. if ($titlealt == 'default') {
  4678. $titlealt = $langs->trans('Search');
  4679. }
  4680. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4681. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4682. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4683. return $input;
  4684. }
  4685. /**
  4686. * Show information for admin users or standard users
  4687. *
  4688. * @param string $text Text info
  4689. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4690. * @param int $nodiv No div
  4691. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4692. * @param string $morecss More CSS ('', 'warning', 'error')
  4693. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4694. * @return string String with info text
  4695. */
  4696. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4697. {
  4698. global $conf, $langs;
  4699. if ($infoonimgalt) {
  4700. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4701. } else {
  4702. if (empty($conf->use_javascript_ajax)) {
  4703. $textfordropdown = '';
  4704. }
  4705. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4706. $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>');
  4707. if ($textfordropdown) {
  4708. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4709. $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
  4710. jQuery(document).ready(function() {
  4711. jQuery(".'.$class.'text").click(function() {
  4712. console.log("toggle text");
  4713. jQuery(".'.$class.'").toggle();
  4714. });
  4715. });
  4716. </script>';
  4717. $result = $tmpresult.$result;
  4718. }
  4719. }
  4720. return $result;
  4721. }
  4722. /**
  4723. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4724. * This function must be called when a blocking technical error is encountered.
  4725. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4726. *
  4727. * @param DoliDB|string $db Database handler
  4728. * @param string|string[] $error String or array of errors strings to show
  4729. * @param array $errors Array of errors
  4730. * @return void
  4731. * @see dol_htmloutput_errors()
  4732. */
  4733. function dol_print_error($db = '', $error = '', $errors = null)
  4734. {
  4735. global $conf, $langs, $argv;
  4736. global $dolibarr_main_prod;
  4737. $out = '';
  4738. $syslog = '';
  4739. // If error occurs before the $lang object was loaded
  4740. if (!$langs) {
  4741. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4742. $langs = new Translate('', $conf);
  4743. $langs->load("main");
  4744. }
  4745. // Load translation files required by the error messages
  4746. $langs->loadLangs(array('main', 'errors'));
  4747. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4748. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4749. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4750. $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";
  4751. }
  4752. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4753. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4754. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4755. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4756. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4757. }
  4758. if (function_exists("phpversion")) {
  4759. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4760. }
  4761. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4762. if (function_exists("php_uname")) {
  4763. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4764. }
  4765. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4766. $out .= "<br>\n";
  4767. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4768. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4769. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4770. $out .= "<br>\n";
  4771. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4772. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4773. } else { // Mode CLI
  4774. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4775. $syslog .= "pid=".dol_getmypid();
  4776. }
  4777. if (!empty($conf->modules)) {
  4778. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4779. }
  4780. if (is_object($db)) {
  4781. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4782. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4783. $lastqueryerror = $db->lastqueryerror();
  4784. if (!utf8_check($lastqueryerror)) {
  4785. $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
  4786. }
  4787. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4788. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4789. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4790. $out .= "<br>\n";
  4791. } else { // Mode CLI
  4792. // No dol_escape_htmltag for output, we are in CLI mode
  4793. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4794. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4795. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4796. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4797. }
  4798. $syslog .= ", sql=".$db->lastquery();
  4799. $syslog .= ", db_error=".$db->lasterror();
  4800. }
  4801. if ($error || $errors) {
  4802. $langs->load("errors");
  4803. // Merge all into $errors array
  4804. if (is_array($error) && is_array($errors)) {
  4805. $errors = array_merge($error, $errors);
  4806. } elseif (is_array($error)) {
  4807. $errors = $error;
  4808. } elseif (is_array($errors)) {
  4809. $errors = array_merge(array($error), $errors);
  4810. } else {
  4811. $errors = array_merge(array($error), array($errors));
  4812. }
  4813. foreach ($errors as $msg) {
  4814. if (empty($msg)) {
  4815. continue;
  4816. }
  4817. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4818. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4819. } else // Mode CLI
  4820. {
  4821. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4822. }
  4823. $syslog .= ", msg=".$msg;
  4824. }
  4825. }
  4826. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4827. xdebug_print_function_stack();
  4828. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4829. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4830. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4831. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4832. $out .= "<br>\n";
  4833. }
  4834. // Return a http header with error code if possible
  4835. if (!headers_sent()) {
  4836. if (function_exists('top_httphead')) { // In CLI context, the method does not exists
  4837. top_httphead();
  4838. }
  4839. //http_response_code(500); // If we use 500, message is not ouput with some command line tools
  4840. http_response_code(202); // If we use 202, this is not really an error message, but this allow to ouput message on command line tools
  4841. }
  4842. if (empty($dolibarr_main_prod)) {
  4843. print $out;
  4844. } else {
  4845. if (empty($langs->defaultlang)) {
  4846. $langs->setDefaultLang();
  4847. }
  4848. $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.
  4849. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4850. 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";
  4851. print $langs->trans("DolibarrHasDetectedError").'. ';
  4852. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4853. define("MAIN_CORE_ERROR", 1);
  4854. }
  4855. dol_syslog("Error ".$syslog, LOG_ERR);
  4856. }
  4857. /**
  4858. * Show a public email and error code to contact if technical error
  4859. *
  4860. * @param string $prefixcode Prefix of public error code
  4861. * @param string $errormessage Complete error message
  4862. * @param array $errormessages Array of error messages
  4863. * @param string $morecss More css
  4864. * @param string $email Email
  4865. * @return void
  4866. */
  4867. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4868. {
  4869. global $langs, $conf;
  4870. if (empty($email)) {
  4871. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4872. }
  4873. $langs->load("errors");
  4874. $now = dol_now();
  4875. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4876. print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
  4877. if ($errormessage) {
  4878. print '<br><br>'.$errormessage;
  4879. }
  4880. if (is_array($errormessages) && count($errormessages)) {
  4881. foreach ($errormessages as $mesgtoshow) {
  4882. print '<br><br>'.$mesgtoshow;
  4883. }
  4884. }
  4885. print '</div></div>';
  4886. }
  4887. /**
  4888. * Show title line of an array
  4889. *
  4890. * @param string $name Label of field
  4891. * @param string $file Url used when we click on sort picto
  4892. * @param string $field Field to use for new sorting
  4893. * @param string $begin ("" by defaut)
  4894. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4895. * @param string $moreattrib Options of attribute td ("" by defaut)
  4896. * @param string $sortfield Current field used to sort
  4897. * @param string $sortorder Current sort order
  4898. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4899. * @param string $tooltip Tooltip
  4900. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4901. * @return void
  4902. */
  4903. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4904. {
  4905. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4906. }
  4907. /**
  4908. * Get title line of an array
  4909. *
  4910. * @param string $name Translation key of field to show or complete HTML string to show
  4911. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4912. * @param string $file Url used when we click on sort picto
  4913. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4914. * @param string $begin ("" by defaut)
  4915. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4916. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  4917. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4918. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4919. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4920. * @param string $disablesortlink 1=Disable sort link
  4921. * @param string $tooltip Tooltip
  4922. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4923. * @return string
  4924. */
  4925. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4926. {
  4927. global $conf, $langs, $form;
  4928. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4929. if ($moreattrib == 'class="right"') {
  4930. $prefix .= 'right '; // For backward compatibility
  4931. }
  4932. $sortorder = strtoupper($sortorder);
  4933. $out = '';
  4934. $sortimg = '';
  4935. $tag = 'th';
  4936. if ($thead == 2) {
  4937. $tag = 'div';
  4938. }
  4939. $tmpsortfield = explode(',', $sortfield);
  4940. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4941. $tmpfield = explode(',', $field);
  4942. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4943. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4944. $prefix = 'wrapcolumntitle '.$prefix;
  4945. }
  4946. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4947. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4948. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4949. $liste_titre = 'liste_titre';
  4950. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4951. $liste_titre = 'liste_titre_sel';
  4952. }
  4953. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4954. //$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)).'"' : '');
  4955. $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4956. $tagstart .= '>';
  4957. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4958. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4959. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4960. $options = preg_replace('/&+/i', '&', $options);
  4961. if (!preg_match('/^&/', $options)) {
  4962. $options = '&'.$options;
  4963. }
  4964. $sortordertouseinlink = '';
  4965. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4966. if (preg_match('/^DESC/i', $sortorder)) {
  4967. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4968. } else { // We reverse the var $sortordertouseinlink
  4969. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4970. }
  4971. } else { // We are on field that is the first current sorting criteria
  4972. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4973. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4974. } else {
  4975. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4976. }
  4977. }
  4978. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4979. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4980. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4981. $out .= '>';
  4982. }
  4983. if ($tooltip) {
  4984. // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
  4985. if (preg_match('/:\w+$/', $tooltip)) {
  4986. $tmptooltip = explode(':', $tooltip);
  4987. } else {
  4988. $tmptooltip = array($tooltip);
  4989. }
  4990. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4991. } else {
  4992. $out .= $langs->trans($name);
  4993. }
  4994. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4995. $out .= '</a>';
  4996. }
  4997. if (empty($thead) && $field) { // If this is a sort field
  4998. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4999. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  5000. $options = preg_replace('/&+/i', '&', $options);
  5001. if (!preg_match('/^&/', $options)) {
  5002. $options = '&'.$options;
  5003. }
  5004. if (!$sortorder || ($field1 != $sortfield1)) {
  5005. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  5006. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  5007. } else {
  5008. if (preg_match('/^DESC/', $sortorder)) {
  5009. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  5010. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  5011. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  5012. }
  5013. if (preg_match('/^ASC/', $sortorder)) {
  5014. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  5015. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  5016. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  5017. }
  5018. }
  5019. }
  5020. $tagend = '</'.$tag.'>';
  5021. $out = $tagstart.$sortimg.$out.$tagend;
  5022. return $out;
  5023. }
  5024. /**
  5025. * Show a title.
  5026. *
  5027. * @param string $title Title to show
  5028. * @return void
  5029. * @deprecated Use load_fiche_titre instead
  5030. * @see load_fiche_titre()
  5031. */
  5032. function print_titre($title)
  5033. {
  5034. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  5035. print '<div class="titre">'.$title.'</div>';
  5036. }
  5037. /**
  5038. * Show a title with picto
  5039. *
  5040. * @param string $title Title to show
  5041. * @param string $mesg Added message to show on right
  5042. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5043. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5044. * @param int $id To force an id on html objects
  5045. * @return void
  5046. * @deprecated Use print load_fiche_titre instead
  5047. */
  5048. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  5049. {
  5050. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  5051. }
  5052. /**
  5053. * Load a title with picto
  5054. *
  5055. * @param string $titre Title to show
  5056. * @param string $morehtmlright Added message to show on right
  5057. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5058. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5059. * @param string $id To force an id on html objects
  5060. * @param string $morecssontable More css on table
  5061. * @param string $morehtmlcenter Added message to show on center
  5062. * @return string
  5063. * @see print_barre_liste()
  5064. */
  5065. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  5066. {
  5067. global $conf;
  5068. $return = '';
  5069. if ($picto == 'setup') {
  5070. $picto = 'generic';
  5071. }
  5072. $return .= "\n";
  5073. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  5074. $return .= '<tr class="titre">';
  5075. if ($picto) {
  5076. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  5077. }
  5078. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  5079. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  5080. $return .= '</td>';
  5081. if (dol_strlen($morehtmlcenter)) {
  5082. $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5083. }
  5084. if (dol_strlen($morehtmlright)) {
  5085. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
  5086. }
  5087. $return .= '</tr></table>'."\n";
  5088. return $return;
  5089. }
  5090. /**
  5091. * Print a title with navigation controls for pagination
  5092. *
  5093. * @param string $titre Title to show (required)
  5094. * @param int|null $page Numero of page to show in navigation links (required)
  5095. * @param string $file Url of page (required)
  5096. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  5097. * @param string $sortfield Field to sort on ('' by default)
  5098. * @param string $sortorder Order to sort ('' by default)
  5099. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  5100. * @param int $num Number of records found by select with limit+1
  5101. * @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.
  5102. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5103. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5104. * @param string $morehtmlright More html to show (after arrows)
  5105. * @param string $morecss More css to the table
  5106. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  5107. * @param int $hideselectlimit Force to hide select limit
  5108. * @param int $hidenavigation Force to hide the arrows and page for navigation
  5109. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  5110. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  5111. * @return void
  5112. */
  5113. 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 = '')
  5114. {
  5115. global $conf;
  5116. $savlimit = $limit;
  5117. $savtotalnboflines = $totalnboflines;
  5118. $totalnboflines = abs((int) $totalnboflines);
  5119. $page = (int) $page;
  5120. if ($picto == 'setup') {
  5121. $picto = 'title_setup.png';
  5122. }
  5123. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  5124. $picto = 'title.gif';
  5125. }
  5126. if ($limit < 0) {
  5127. $limit = $conf->liste_limit;
  5128. }
  5129. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  5130. $nextpage = 1;
  5131. } else {
  5132. $nextpage = 0;
  5133. }
  5134. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
  5135. print "\n";
  5136. print "<!-- Begin title -->\n";
  5137. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  5138. // Left
  5139. if ($picto && $titre) {
  5140. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  5141. }
  5142. print '<td class="nobordernopadding valignmiddle col-title">';
  5143. print '<div class="titre inline-block">'.$titre;
  5144. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  5145. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  5146. }
  5147. print '</div></td>';
  5148. // Center
  5149. if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
  5150. print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5151. }
  5152. // Right
  5153. print '<td class="nobordernopadding valignmiddle right col-right">';
  5154. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  5155. if ($sortfield) {
  5156. $options .= "&sortfield=".urlencode($sortfield);
  5157. }
  5158. if ($sortorder) {
  5159. $options .= "&sortorder=".urlencode($sortorder);
  5160. }
  5161. // Show navigation bar
  5162. $pagelist = '';
  5163. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  5164. if ($totalnboflines) { // If we know total nb of lines
  5165. // Define nb of extra page links before and after selected page + ... + first or last
  5166. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  5167. if ($limit > 0) {
  5168. $nbpages = ceil($totalnboflines / $limit);
  5169. } else {
  5170. $nbpages = 1;
  5171. }
  5172. $cpt = ($page - $maxnbofpage);
  5173. if ($cpt < 0) {
  5174. $cpt = 0;
  5175. }
  5176. if ($cpt >= 1) {
  5177. if (empty($pagenavastextinput)) {
  5178. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  5179. if ($cpt > 2) {
  5180. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5181. } elseif ($cpt == 2) {
  5182. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  5183. }
  5184. }
  5185. }
  5186. do {
  5187. if ($pagenavastextinput) {
  5188. if ($cpt == $page) {
  5189. $pagelist .= '<li class="pagination"><input type="text" class="'.($totalnboflines > 100 ? 'width40' : 'width25').' center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  5190. $pagelist .= '/';
  5191. }
  5192. } else {
  5193. if ($cpt == $page) {
  5194. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  5195. } else {
  5196. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  5197. }
  5198. }
  5199. $cpt++;
  5200. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  5201. if (empty($pagenavastextinput)) {
  5202. if ($cpt < $nbpages) {
  5203. if ($cpt < $nbpages - 2) {
  5204. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5205. } elseif ($cpt == $nbpages - 2) {
  5206. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  5207. }
  5208. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5209. }
  5210. } else {
  5211. //var_dump($page.' '.$cpt.' '.$nbpages);
  5212. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5213. }
  5214. } else {
  5215. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  5216. }
  5217. }
  5218. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  5219. 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
  5220. }
  5221. // js to autoselect page field on focus
  5222. if ($pagenavastextinput) {
  5223. print ajax_autoselect('.pageplusone');
  5224. }
  5225. print '</td>';
  5226. print '</tr>';
  5227. print '</table>'."\n";
  5228. // Center
  5229. if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
  5230. print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
  5231. }
  5232. print "<!-- End title -->\n\n";
  5233. }
  5234. /**
  5235. * Function to show navigation arrows into lists
  5236. *
  5237. * @param int $page Number of page
  5238. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  5239. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  5240. * @param integer $nextpage Do we show a next page button
  5241. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  5242. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  5243. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  5244. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  5245. * @param int $hideselectlimit Force to hide select limit
  5246. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  5247. * @param int $hidenavigation Force to hide the switch mode view and the navigation tool (select limit, arrows $betweenarrows and $afterarrows but not $beforearrows)
  5248. * @return void
  5249. */
  5250. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '', $hidenavigation = 0)
  5251. {
  5252. global $conf, $langs;
  5253. print '<div class="pagination"><ul>';
  5254. if ($beforearrows) {
  5255. print '<li class="paginationbeforearrows">';
  5256. print $beforearrows;
  5257. print '</li>';
  5258. }
  5259. if (empty($hidenavigation)) {
  5260. if ((int) $limit > 0 && empty($hideselectlimit)) {
  5261. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
  5262. $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
  5263. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  5264. //$pagesizechoices.=',2:2';
  5265. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  5266. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  5267. }
  5268. print '<li class="pagination">';
  5269. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  5270. $tmpchoice = explode(',', $pagesizechoices);
  5271. $tmpkey = $limit.':'.$limit;
  5272. if (!in_array($tmpkey, $tmpchoice)) {
  5273. $tmpchoice[] = $tmpkey;
  5274. }
  5275. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  5276. if (!in_array($tmpkey, $tmpchoice)) {
  5277. $tmpchoice[] = $tmpkey;
  5278. }
  5279. asort($tmpchoice, SORT_NUMERIC);
  5280. foreach ($tmpchoice as $val) {
  5281. $selected = '';
  5282. $tmp = explode(':', $val);
  5283. $key = $tmp[0];
  5284. $val = $tmp[1];
  5285. if ($key != '' && $val != '') {
  5286. if ((int) $key == (int) $limit) {
  5287. $selected = ' selected="selected"';
  5288. }
  5289. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  5290. }
  5291. }
  5292. print '</select>';
  5293. if ($conf->use_javascript_ajax) {
  5294. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  5295. <script>
  5296. jQuery(document).ready(function () {
  5297. jQuery(".selectlimit").change(function() {
  5298. console.log("Change limit. Send submit");
  5299. $(this).parents(\'form:first\').submit();
  5300. });
  5301. });
  5302. </script>
  5303. ';
  5304. }
  5305. print '</li>';
  5306. }
  5307. if ($page > 0) {
  5308. 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>';
  5309. }
  5310. if ($betweenarrows) {
  5311. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  5312. print $betweenarrows;
  5313. print '<!--</div>-->';
  5314. }
  5315. if ($nextpage > 0) {
  5316. 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>';
  5317. }
  5318. if ($afterarrows) {
  5319. print '<li class="paginationafterarrows">';
  5320. print $afterarrows;
  5321. print '</li>';
  5322. }
  5323. }
  5324. print '</ul></div>'."\n";
  5325. }
  5326. /**
  5327. * Return a string with VAT rate label formated for view output
  5328. * Used into pdf and HTML pages
  5329. *
  5330. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  5331. * @param boolean $addpercent Add a percent % sign in output
  5332. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  5333. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  5334. * @param int $html Used for html output
  5335. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  5336. */
  5337. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
  5338. {
  5339. $morelabel = '';
  5340. if (preg_match('/%/', $rate)) {
  5341. $rate = str_replace('%', '', $rate);
  5342. $addpercent = true;
  5343. }
  5344. $reg = array();
  5345. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  5346. $morelabel = ' ('.$reg[1].')';
  5347. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  5348. $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
  5349. }
  5350. if (preg_match('/\*/', $rate)) {
  5351. $rate = str_replace('*', '', $rate);
  5352. $info_bits |= 1;
  5353. }
  5354. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  5355. if (!preg_match('/\//', $rate)) {
  5356. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  5357. } else {
  5358. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  5359. $ret = $rate.($addpercent ? '%' : '');
  5360. }
  5361. if (($info_bits & 1) && $usestarfornpr >= 0) {
  5362. $ret .= ' *';
  5363. }
  5364. $ret .= $morelabel;
  5365. return $ret;
  5366. }
  5367. /**
  5368. * Function to format a value into an amount for visual output
  5369. * Function used into PDF and HTML pages
  5370. *
  5371. * @param float $amount Amount to format
  5372. * @param integer $form Type of format, HTML or not (not by default)
  5373. * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators.
  5374. * @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.
  5375. * @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)
  5376. * @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
  5377. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  5378. * @return string String with formated amount
  5379. *
  5380. * @see price2num() Revert function of price
  5381. */
  5382. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  5383. {
  5384. global $langs, $conf;
  5385. // Clean parameters
  5386. if (empty($amount)) {
  5387. $amount = 0; // To have a numeric value if amount not defined or = ''
  5388. }
  5389. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  5390. if ($rounding == -1) {
  5391. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  5392. }
  5393. $nbdecimal = $rounding;
  5394. if ($outlangs === 'none') {
  5395. // Use international separators
  5396. $dec = '.';
  5397. $thousand = '';
  5398. } else {
  5399. // Output separators by default (french)
  5400. $dec = ',';
  5401. $thousand = ' ';
  5402. // If $outlangs not forced, we use use language
  5403. if (!is_object($outlangs)) {
  5404. $outlangs = $langs;
  5405. }
  5406. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5407. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5408. }
  5409. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5410. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5411. }
  5412. if ($thousand == 'None') {
  5413. $thousand = '';
  5414. } elseif ($thousand == 'Space') {
  5415. $thousand = ' ';
  5416. }
  5417. }
  5418. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5419. //print "amount=".$amount."-";
  5420. $amount = str_replace(',', '.', $amount); // should be useless
  5421. //print $amount."-";
  5422. $datas = explode('.', $amount);
  5423. $decpart = isset($datas[1]) ? $datas[1] : '';
  5424. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5425. //print "decpart=".$decpart."<br>";
  5426. $end = '';
  5427. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5428. if (dol_strlen($decpart) > $nbdecimal) {
  5429. $nbdecimal = dol_strlen($decpart);
  5430. }
  5431. // Si on depasse max
  5432. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5433. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5434. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5435. // Si un affichage est tronque, on montre des ...
  5436. $end = '...';
  5437. }
  5438. }
  5439. // If force rounding
  5440. if ((string) $forcerounding != '-1') {
  5441. if ($forcerounding === 'MU') {
  5442. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5443. } elseif ($forcerounding === 'MT') {
  5444. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5445. } elseif ($forcerounding >= 0) {
  5446. $nbdecimal = $forcerounding;
  5447. }
  5448. }
  5449. // Format number
  5450. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5451. if ($form) {
  5452. $output = preg_replace('/\s/', '&nbsp;', $output);
  5453. $output = preg_replace('/\'/', '&#039;', $output);
  5454. }
  5455. // Add symbol of currency if requested
  5456. $cursymbolbefore = $cursymbolafter = '';
  5457. if ($currency_code && is_object($outlangs)) {
  5458. if ($currency_code == 'auto') {
  5459. $currency_code = $conf->currency;
  5460. }
  5461. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC');
  5462. $listoflanguagesbefore = array('nl_NL');
  5463. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5464. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5465. } else {
  5466. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5467. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5468. }
  5469. }
  5470. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5471. return $output;
  5472. }
  5473. /**
  5474. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5475. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5476. * should be roundtext2num().
  5477. *
  5478. * @param string|float $amount Amount to convert/clean or round
  5479. * @param string|int $rounding ''=No rounding
  5480. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5481. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5482. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5483. * 'CU'=Round to Max unit price of foreign currency accuracy
  5484. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5485. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5486. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5487. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5488. * @return string Amount with universal numeric format (Example: '99.99999').
  5489. * If conversion fails to return a numeric, it returns:
  5490. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5491. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5492. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5493. * If amount is null or '', it returns '' if $rounding = '', it returns '0' if $rounding is defined.
  5494. *
  5495. * @see price() Opposite function of price2num
  5496. */
  5497. function price2num($amount, $rounding = '', $option = 0)
  5498. {
  5499. global $langs, $conf;
  5500. // Clean parameters
  5501. if (is_null($amount)) {
  5502. $amount = '';
  5503. }
  5504. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5505. // Numbers must be '1234.56'
  5506. // Decimal delimiter for PHP and database SQL requests must be '.'
  5507. $dec = ',';
  5508. $thousand = ' ';
  5509. if (is_null($langs)) { // $langs is not defined, we use english values.
  5510. $dec = '.';
  5511. $thousand = ',';
  5512. } else {
  5513. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5514. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5515. }
  5516. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5517. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5518. }
  5519. }
  5520. if ($thousand == 'None') {
  5521. $thousand = '';
  5522. } elseif ($thousand == 'Space') {
  5523. $thousand = ' ';
  5524. }
  5525. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5526. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5527. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5528. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5529. if (!is_numeric($amount)) {
  5530. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5531. }
  5532. 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
  5533. $amount = str_replace($thousand, '', $amount);
  5534. }
  5535. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5536. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5537. // So if number was already a good number, it is converted into local Dolibarr setup.
  5538. if (is_numeric($amount)) {
  5539. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5540. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5541. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5542. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5543. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5544. }
  5545. //print "QQ".$amount."<br>\n";
  5546. // Now make replace (the main goal of function)
  5547. if ($thousand != ',' && $thousand != '.') {
  5548. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5549. }
  5550. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5551. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5552. $amount = str_replace($dec, '.', $amount);
  5553. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5554. }
  5555. //print ' XX'.$amount.' '.$rounding;
  5556. // Now, $amount is a real PHP float number. We make a rounding if required.
  5557. if ($rounding) {
  5558. $nbofdectoround = '';
  5559. if ($rounding == 'MU') {
  5560. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5561. } elseif ($rounding == 'MT') {
  5562. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5563. } elseif ($rounding == 'MS') {
  5564. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5565. } elseif ($rounding == 'CU') {
  5566. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5567. } elseif ($rounding == 'CT') {
  5568. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5569. } elseif (is_numeric($rounding)) {
  5570. $nbofdectoround = (int) $rounding;
  5571. }
  5572. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5573. if (dol_strlen($nbofdectoround)) {
  5574. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5575. } else {
  5576. return 'ErrorBadParameterProvidedToFunction';
  5577. }
  5578. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5579. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5580. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5581. if (is_numeric($amount)) {
  5582. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5583. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5584. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5585. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5586. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5587. }
  5588. //print "TT".$amount.'<br>';
  5589. // Always make replace because each math function (like round) replace
  5590. // with local values and we want a number that has a SQL string format x.y
  5591. if ($thousand != ',' && $thousand != '.') {
  5592. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5593. }
  5594. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5595. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5596. $amount = str_replace($dec, '.', $amount);
  5597. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5598. }
  5599. return $amount;
  5600. }
  5601. /**
  5602. * Output a dimension with best unit
  5603. *
  5604. * @param float $dimension Dimension
  5605. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5606. * @param string $type 'weight', 'volume', ...
  5607. * @param Translate $outputlangs Translate language object
  5608. * @param int $round -1 = non rounding, x = number of decimal
  5609. * @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)
  5610. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5611. * @return string String to show dimensions
  5612. */
  5613. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5614. {
  5615. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5616. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5617. $dimension = $dimension * 1000000;
  5618. $unit = $unit - 6;
  5619. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5620. $dimension = $dimension * 1000;
  5621. $unit = $unit - 3;
  5622. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5623. $dimension = $dimension / 1000000;
  5624. $unit = $unit + 6;
  5625. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5626. $dimension = $dimension / 1000;
  5627. $unit = $unit + 3;
  5628. }
  5629. // Special case when we want output unit into pound or ounce
  5630. /* TODO
  5631. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5632. {
  5633. $dimension = // convert dimension from standard unit into ounce or pound
  5634. $unit = $forceunitoutput;
  5635. }
  5636. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5637. {
  5638. $dimension = // convert dimension from standard unit into ounce or pound
  5639. $unit = $forceunitoutput;
  5640. }*/
  5641. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5642. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5643. return $ret;
  5644. }
  5645. /**
  5646. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5647. * Note: This function applies same rules than get_default_tva
  5648. *
  5649. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5650. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5651. * @param Societe $thirdparty_buyer Object of buying third party
  5652. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5653. * @param int $vatnpr If vat rate is NPR or not
  5654. * @return mixed 0 if not found, localtax rate if found
  5655. * @see get_default_tva()
  5656. */
  5657. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5658. {
  5659. global $db, $conf, $mysoc;
  5660. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5661. $thirdparty_seller = $mysoc;
  5662. }
  5663. 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);
  5664. $vatratecleaned = $vatrate;
  5665. $reg = array();
  5666. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5667. $vatratecleaned = trim($reg[1]);
  5668. $vatratecode = $reg[2];
  5669. }
  5670. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5671. {
  5672. return 0;
  5673. }*/
  5674. // Some test to guess with no need to make database access
  5675. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5676. if ($local == 1) {
  5677. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5678. return 0;
  5679. }
  5680. if ($thirdparty_seller->id == $mysoc->id) {
  5681. if (!$thirdparty_buyer->localtax1_assuj) {
  5682. return 0;
  5683. }
  5684. } else {
  5685. if (!$thirdparty_seller->localtax1_assuj) {
  5686. return 0;
  5687. }
  5688. }
  5689. }
  5690. if ($local == 2) {
  5691. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5692. if (!$mysoc->localtax2_assuj) {
  5693. return 0; // If main vat is 0, IRPF may be different than 0.
  5694. }
  5695. if ($thirdparty_seller->id == $mysoc->id) {
  5696. if (!$thirdparty_buyer->localtax2_assuj) {
  5697. return 0;
  5698. }
  5699. } else {
  5700. if (!$thirdparty_seller->localtax2_assuj) {
  5701. return 0;
  5702. }
  5703. }
  5704. }
  5705. } else {
  5706. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5707. return 0;
  5708. }
  5709. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5710. return 0;
  5711. }
  5712. }
  5713. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5714. if (in_array($mysoc->country_code, array('ES'))) {
  5715. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5716. }
  5717. // Search local taxes
  5718. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5719. if ($local == 1) {
  5720. if ($thirdparty_seller != $mysoc) {
  5721. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5722. return $thirdparty_seller->localtax1_value;
  5723. }
  5724. } else { // i am the seller
  5725. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5726. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5727. }
  5728. }
  5729. }
  5730. if ($local == 2) {
  5731. if ($thirdparty_seller != $mysoc) {
  5732. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5733. // TODO We should also return value defined on thirdparty only if defined
  5734. return $thirdparty_seller->localtax2_value;
  5735. }
  5736. } else { // i am the seller
  5737. if (in_array($mysoc->country_code, array('ES'))) {
  5738. return $thirdparty_buyer->localtax2_value;
  5739. } else {
  5740. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5741. }
  5742. }
  5743. }
  5744. }
  5745. // By default, search value of local tax on line of common tax
  5746. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5747. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5748. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5749. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5750. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5751. if (!empty($vatratecode)) {
  5752. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5753. } else {
  5754. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5755. }
  5756. $resql = $db->query($sql);
  5757. if ($resql) {
  5758. $obj = $db->fetch_object($resql);
  5759. if ($obj) {
  5760. if ($local == 1) {
  5761. return $obj->localtax1;
  5762. } elseif ($local == 2) {
  5763. return $obj->localtax2;
  5764. }
  5765. }
  5766. }
  5767. return 0;
  5768. }
  5769. /**
  5770. * Return true if LocalTax (1 or 2) is unique.
  5771. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5772. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5773. *
  5774. * @param int $local Local tax to test (1 or 2)
  5775. * @return boolean True if LocalTax have multiple values, False if not
  5776. */
  5777. function isOnlyOneLocalTax($local)
  5778. {
  5779. $tax = get_localtax_by_third($local);
  5780. $valors = explode(":", $tax);
  5781. if (count($valors) > 1) {
  5782. return false;
  5783. } else {
  5784. return true;
  5785. }
  5786. }
  5787. /**
  5788. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5789. *
  5790. * @param int $local LocalTax to get
  5791. * @return string Values of localtax (Can be '20', '-19:-15:-9') or 'Error'
  5792. */
  5793. function get_localtax_by_third($local)
  5794. {
  5795. global $db, $mysoc;
  5796. $sql = " SELECT t.localtax".$local." as localtax";
  5797. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
  5798. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.entity IN (".getEntity('c_tva').") AND t.taux = (";
  5799. $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";
  5800. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.entity IN (".getEntity('c_tva').") AND tt.active = 1)";
  5801. $sql .= " AND t.localtax".$local."_type <> '0'";
  5802. $sql .= " ORDER BY t.rowid DESC";
  5803. $resql = $db->query($sql);
  5804. if ($resql) {
  5805. $obj = $db->fetch_object($resql);
  5806. if ($obj) {
  5807. return $obj->localtax;
  5808. } else {
  5809. return '0';
  5810. }
  5811. }
  5812. return 'Error';
  5813. }
  5814. /**
  5815. * Get tax (VAT) main information from Id.
  5816. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5817. *
  5818. * @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.
  5819. * @param Societe $buyer Company object
  5820. * @param Societe $seller Company object
  5821. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5822. * @return array array('rowid'=> , 'code'=> ...)
  5823. * @see getLocalTaxesFromRate()
  5824. */
  5825. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5826. {
  5827. global $db, $mysoc;
  5828. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5829. // Search local taxes
  5830. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5831. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5832. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5833. if ($firstparamisid) {
  5834. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5835. } else {
  5836. $vatratecleaned = $vatrate;
  5837. $vatratecode = '';
  5838. $reg = array();
  5839. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5840. $vatratecleaned = $reg[1];
  5841. $vatratecode = $reg[2];
  5842. }
  5843. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5844. /*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 ??
  5845. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5846. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5847. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5848. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5849. if ($vatratecode) {
  5850. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5851. }
  5852. }
  5853. $resql = $db->query($sql);
  5854. if ($resql) {
  5855. $obj = $db->fetch_object($resql);
  5856. if ($obj) {
  5857. return array(
  5858. 'rowid'=>$obj->rowid,
  5859. 'code'=>$obj->code,
  5860. 'rate'=>$obj->rate,
  5861. 'localtax1'=>$obj->localtax1,
  5862. 'localtax1_type'=>$obj->localtax1_type,
  5863. 'localtax2'=>$obj->localtax2,
  5864. 'localtax2_type'=>$obj->localtax2_type,
  5865. 'npr'=>$obj->npr,
  5866. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5867. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5868. );
  5869. } else {
  5870. return array();
  5871. }
  5872. } else {
  5873. dol_print_error($db);
  5874. }
  5875. return array();
  5876. }
  5877. /**
  5878. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5879. * This does not take into account the seller setup if subject to vat or not, only country.
  5880. *
  5881. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5882. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5883. * provide the selected value to the function calcul_price_total.
  5884. *
  5885. * @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.
  5886. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5887. * @param Societe $buyer Company object
  5888. * @param Societe $seller Company object
  5889. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5890. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5891. * @see getTaxesFromId()
  5892. */
  5893. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5894. {
  5895. global $db, $mysoc;
  5896. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5897. // Search local taxes
  5898. $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";
  5899. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5900. if ($firstparamisid) {
  5901. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5902. } else {
  5903. $vatratecleaned = $vatrate;
  5904. $vatratecode = '';
  5905. $reg = array();
  5906. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5907. $vatratecleaned = $reg[1];
  5908. $vatratecode = $reg[2];
  5909. }
  5910. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5911. if (!empty($mysoc) && $mysoc->country_code == 'ES') {
  5912. $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
  5913. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'"; // local tax in spain use the buyer country ??
  5914. } else {
  5915. $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
  5916. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'";
  5917. }
  5918. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5919. if ($vatratecode) {
  5920. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5921. }
  5922. }
  5923. $resql = $db->query($sql);
  5924. if ($resql) {
  5925. $obj = $db->fetch_object($resql);
  5926. if ($obj) {
  5927. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5928. if ($local == 1) {
  5929. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5930. } elseif ($local == 2) {
  5931. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5932. } else {
  5933. 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);
  5934. }
  5935. }
  5936. }
  5937. return array();
  5938. }
  5939. /**
  5940. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5941. * Function called by get_default_tva().
  5942. *
  5943. * @param int $idprod Id of product or 0 if not a predefined product
  5944. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5945. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5946. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5947. * @see get_product_localtax_for_country()
  5948. */
  5949. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5950. {
  5951. global $db, $conf, $mysoc;
  5952. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5953. $ret = 0;
  5954. $found = 0;
  5955. if ($idprod > 0) {
  5956. // Load product
  5957. $product = new Product($db);
  5958. $product->fetch($idprod);
  5959. if ($mysoc->country_code == $thirdpartytouse->country_code) {
  5960. // If country to consider is ours
  5961. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5962. $result = $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5963. if ($result > 0) {
  5964. $ret = $product->vatrate_supplier;
  5965. if ($product->default_vat_code_supplier) {
  5966. $ret .= ' ('.$product->default_vat_code_supplier.')';
  5967. }
  5968. $found = 1;
  5969. }
  5970. }
  5971. if (!$found) {
  5972. $ret = $product->tva_tx; // Default sales vat of product
  5973. if ($product->default_vat_code) {
  5974. $ret .= ' ('.$product->default_vat_code.')';
  5975. }
  5976. $found = 1;
  5977. }
  5978. } else {
  5979. // TODO Read default product vat according to product and another countrycode.
  5980. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5981. }
  5982. }
  5983. if (!$found) {
  5984. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5985. // 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).
  5986. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5987. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5988. $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
  5989. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5990. $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5991. $sql .= $db->plimit(1);
  5992. $resql = $db->query($sql);
  5993. if ($resql) {
  5994. $obj = $db->fetch_object($resql);
  5995. if ($obj) {
  5996. $ret = $obj->vat_rate;
  5997. if ($obj->default_vat_code) {
  5998. $ret .= ' ('.$obj->default_vat_code.')';
  5999. }
  6000. }
  6001. $db->free($resql);
  6002. } else {
  6003. dol_print_error($db);
  6004. }
  6005. } else {
  6006. // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
  6007. // '1.23'
  6008. // or '1.23 (CODE)'
  6009. $defaulttx = '';
  6010. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  6011. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  6012. }
  6013. /*if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  6014. $defaultcode = $reg[1];
  6015. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  6016. }*/
  6017. $ret = $defaulttx;
  6018. }
  6019. }
  6020. dol_syslog("get_product_vat_for_country: ret=".$ret);
  6021. return $ret;
  6022. }
  6023. /**
  6024. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  6025. *
  6026. * @param int $idprod Id of product
  6027. * @param int $local 1 for localtax1, 2 for localtax 2
  6028. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  6029. * @return int <0 if KO, Vat rate if OK
  6030. * @see get_product_vat_for_country()
  6031. */
  6032. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  6033. {
  6034. global $db, $mysoc;
  6035. if (!class_exists('Product')) {
  6036. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6037. }
  6038. $ret = 0;
  6039. $found = 0;
  6040. if ($idprod > 0) {
  6041. // Load product
  6042. $product = new Product($db);
  6043. $result = $product->fetch($idprod);
  6044. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  6045. /* Not defined yet, so we don't use this
  6046. if ($local==1) $ret=$product->localtax1_tx;
  6047. elseif ($local==2) $ret=$product->localtax2_tx;
  6048. $found=1;
  6049. */
  6050. } else {
  6051. // TODO Read default product vat according to product and another countrycode.
  6052. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  6053. }
  6054. }
  6055. if (!$found) {
  6056. // If vat of product for the country not found or not defined, we return higher vat of country.
  6057. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  6058. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  6059. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  6060. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  6061. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  6062. $sql .= $db->plimit(1);
  6063. $resql = $db->query($sql);
  6064. if ($resql) {
  6065. $obj = $db->fetch_object($resql);
  6066. if ($obj) {
  6067. if ($local == 1) {
  6068. $ret = $obj->localtax1;
  6069. } elseif ($local == 2) {
  6070. $ret = $obj->localtax2;
  6071. }
  6072. }
  6073. } else {
  6074. dol_print_error($db);
  6075. }
  6076. }
  6077. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  6078. return $ret;
  6079. }
  6080. /**
  6081. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  6082. * VATRULE 1: If seller does not use VAT, default VAT is 0. End of rule.
  6083. * VATRULE 2: If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6084. * 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.
  6085. * 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
  6086. * VATRULE 5: If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6087. * VATRULE 6: Otherwise the VAT proposed by default=0. End of rule.
  6088. *
  6089. * @param Societe $thirdparty_seller Objet societe vendeuse
  6090. * @param Societe $thirdparty_buyer Objet societe acheteuse
  6091. * @param int $idprod Id product
  6092. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  6093. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  6094. * @see get_default_npr(), get_default_localtax()
  6095. */
  6096. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6097. {
  6098. global $conf;
  6099. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  6100. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  6101. $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;
  6102. $seller_country_code = $thirdparty_seller->country_code;
  6103. $seller_in_cee = isInEEC($thirdparty_seller);
  6104. $buyer_country_code = $thirdparty_buyer->country_code;
  6105. $buyer_in_cee = isInEEC($thirdparty_buyer);
  6106. 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 : ''));
  6107. // 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)
  6108. // we use the buyer VAT.
  6109. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  6110. if ($seller_in_cee && $buyer_in_cee) {
  6111. $isacompany = $thirdparty_buyer->isACompany();
  6112. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6113. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6114. if (!isValidVATID($thirdparty_buyer)) {
  6115. $isacompany = 0;
  6116. }
  6117. }
  6118. if (!$isacompany) {
  6119. //print 'VATRULE 0';
  6120. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  6121. }
  6122. }
  6123. }
  6124. // If seller does not use VAT, default VAT is 0. End of rule.
  6125. if (!$seller_use_vat) {
  6126. //print 'VATRULE 1';
  6127. return 0;
  6128. }
  6129. // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6130. if (($seller_country_code == $buyer_country_code)
  6131. || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  6132. //print 'VATRULE 2';
  6133. $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6134. if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
  6135. // Special case for india.
  6136. //print 'VATRULE 2b';
  6137. $reg = array();
  6138. if (preg_match('/C+S-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
  6139. // we must revert the C+S into I
  6140. $tmpvat = str_replace("C+S", "I", $tmpvat);
  6141. } elseif (preg_match('/I-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
  6142. // we must revert the I into C+S
  6143. $tmpvat = str_replace("I", "C+S", $tmpvat);
  6144. }
  6145. }
  6146. return $tmpvat;
  6147. }
  6148. // 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.
  6149. // 'VATRULE 3' - Not supported
  6150. // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6151. // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6152. if (($seller_in_cee && $buyer_in_cee)) {
  6153. $isacompany = $thirdparty_buyer->isACompany();
  6154. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6155. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6156. if (!isValidVATID($thirdparty_buyer)) {
  6157. $isacompany = 0;
  6158. }
  6159. }
  6160. if (!$isacompany) {
  6161. //print 'VATRULE 4';
  6162. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6163. } else {
  6164. //print 'VATRULE 5';
  6165. return 0;
  6166. }
  6167. }
  6168. // 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
  6169. // I don't see any use case that need this rule.
  6170. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  6171. $isacompany = $thirdparty_buyer->isACompany();
  6172. if (!$isacompany) {
  6173. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6174. //print 'VATRULE extra';
  6175. }
  6176. }
  6177. // Otherwise the VAT proposed by default=0. End of rule.
  6178. // Rem: This means that at least one of the 2 is outside the European Community and the country differs
  6179. //print 'VATRULE 6';
  6180. return 0;
  6181. }
  6182. /**
  6183. * Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
  6184. *
  6185. * @param Societe $thirdparty_seller Thirdparty seller
  6186. * @param Societe $thirdparty_buyer Thirdparty buyer
  6187. * @param int $idprod Id product
  6188. * @param int $idprodfournprice Id supplier price for product
  6189. * @return float 0 or 1
  6190. * @see get_default_tva(), get_default_localtax()
  6191. */
  6192. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6193. {
  6194. global $db;
  6195. if ($idprodfournprice > 0) {
  6196. if (!class_exists('ProductFournisseur')) {
  6197. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6198. }
  6199. $prodprice = new ProductFournisseur($db);
  6200. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  6201. return $prodprice->fourn_tva_npr;
  6202. } elseif ($idprod > 0) {
  6203. if (!class_exists('Product')) {
  6204. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6205. }
  6206. $prod = new Product($db);
  6207. $prod->fetch($idprod);
  6208. return $prod->tva_npr;
  6209. }
  6210. return 0;
  6211. }
  6212. /**
  6213. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  6214. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  6215. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  6216. * Sinon TVA proposee par defaut=0. Fin de regle.
  6217. *
  6218. * @param Societe $thirdparty_seller Thirdparty seller
  6219. * @param Societe $thirdparty_buyer Thirdparty buyer
  6220. * @param int $local Localtax to process (1 or 2)
  6221. * @param int $idprod Id product
  6222. * @return integer localtax, -1 si ne peut etre determine
  6223. * @see get_default_tva(), get_default_npr()
  6224. */
  6225. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  6226. {
  6227. global $mysoc;
  6228. if (!is_object($thirdparty_seller)) {
  6229. return -1;
  6230. }
  6231. if (!is_object($thirdparty_buyer)) {
  6232. return -1;
  6233. }
  6234. if ($local == 1) { // Localtax 1
  6235. if ($mysoc->country_code == 'ES') {
  6236. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  6237. return 0;
  6238. }
  6239. } else {
  6240. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  6241. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  6242. return 0;
  6243. }
  6244. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  6245. return 0;
  6246. }
  6247. }
  6248. } elseif ($local == 2) { //I Localtax 2
  6249. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  6250. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  6251. return 0;
  6252. }
  6253. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  6254. return 0;
  6255. }
  6256. }
  6257. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  6258. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  6259. }
  6260. return 0;
  6261. }
  6262. /**
  6263. * Return yes or no in current language
  6264. *
  6265. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  6266. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  6267. * @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.
  6268. * @return string HTML string
  6269. */
  6270. function yn($yesno, $case = 1, $color = 0)
  6271. {
  6272. global $langs;
  6273. $result = 'unknown';
  6274. $classname = '';
  6275. if ($yesno == 1 || (isset($yesno) && (strtolower($yesno) == 'yes' || strtolower($yesno) == 'true'))) { // A mettre avant test sur no a cause du == 0
  6276. $result = $langs->trans('yes');
  6277. if ($case == 1 || $case == 3) {
  6278. $result = $langs->trans("Yes");
  6279. }
  6280. if ($case == 2) {
  6281. $result = '<input type="checkbox" value="1" checked disabled>';
  6282. }
  6283. if ($case == 3) {
  6284. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  6285. }
  6286. $classname = 'ok';
  6287. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  6288. $result = $langs->trans("no");
  6289. if ($case == 1 || $case == 3) {
  6290. $result = $langs->trans("No");
  6291. }
  6292. if ($case == 2) {
  6293. $result = '<input type="checkbox" value="0" disabled>';
  6294. }
  6295. if ($case == 3) {
  6296. $result = '<input type="checkbox" value="0" disabled> '.$result;
  6297. }
  6298. if ($color == 2) {
  6299. $classname = 'ok';
  6300. } else {
  6301. $classname = 'error';
  6302. }
  6303. }
  6304. if ($color) {
  6305. return '<span class="'.$classname.'">'.$result.'</span>';
  6306. }
  6307. return $result;
  6308. }
  6309. /**
  6310. * Return a path to have a the directory according to object where files are stored.
  6311. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  6312. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  6313. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  6314. * 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/"
  6315. *
  6316. * @param string|int $num Id of object (deprecated, $object will be used in future)
  6317. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  6318. * @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)
  6319. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  6320. * @param Object $object Object to use to get ref to forge the path.
  6321. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  6322. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  6323. */
  6324. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  6325. {
  6326. global $conf;
  6327. if (empty($modulepart) && !empty($object->module)) {
  6328. $modulepart = $object->module;
  6329. }
  6330. $path = '';
  6331. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  6332. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  6333. $arrayforoldpath[] = 'product';
  6334. }
  6335. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  6336. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  6337. if (empty($alpha)) {
  6338. $num = preg_replace('/([^0-9])/i', '', $num);
  6339. } else {
  6340. $num = preg_replace('/^.*\-/i', '', $num);
  6341. }
  6342. $num = substr("000".$num, -$level);
  6343. if ($level == 1) {
  6344. $path = substr($num, 0, 1);
  6345. }
  6346. if ($level == 2) {
  6347. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  6348. }
  6349. if ($level == 3) {
  6350. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  6351. }
  6352. } else {
  6353. // We will enhance here a common way of forging path for document storage.
  6354. // In a future, we may distribute directories on several levels depending on setup and object.
  6355. // Here, $object->id, $object->ref and $modulepart are required.
  6356. //var_dump($modulepart);
  6357. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  6358. }
  6359. if (empty($withoutslash) && !empty($path)) {
  6360. $path .= '/';
  6361. }
  6362. return $path;
  6363. }
  6364. /**
  6365. * Creation of a directory (this can create recursive subdir)
  6366. *
  6367. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  6368. * @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, saying PHP has no permission when open_basedir is used)
  6369. * @param string $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  6370. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  6371. */
  6372. function dol_mkdir($dir, $dataroot = '', $newmask = '')
  6373. {
  6374. global $conf;
  6375. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  6376. $dir_osencoded = dol_osencode($dir);
  6377. if (@is_dir($dir_osencoded)) {
  6378. return 0;
  6379. }
  6380. $nberr = 0;
  6381. $nbcreated = 0;
  6382. $ccdir = '';
  6383. if (!empty($dataroot)) {
  6384. // Remove data root from loop
  6385. $dir = str_replace($dataroot.'/', '', $dir);
  6386. $ccdir = $dataroot.'/';
  6387. }
  6388. $cdir = explode("/", $dir);
  6389. $num = count($cdir);
  6390. for ($i = 0; $i < $num; $i++) {
  6391. if ($i > 0) {
  6392. $ccdir .= '/'.$cdir[$i];
  6393. } else {
  6394. $ccdir .= $cdir[$i];
  6395. }
  6396. $regs = array();
  6397. if (preg_match("/^.:$/", $ccdir, $regs)) {
  6398. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  6399. }
  6400. // Attention, le is_dir() peut echouer bien que le rep existe.
  6401. // (ex selon config de open_basedir)
  6402. if ($ccdir) {
  6403. $ccdir_osencoded = dol_osencode($ccdir);
  6404. if (!@is_dir($ccdir_osencoded)) {
  6405. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  6406. umask(0);
  6407. $dirmaskdec = octdec((string) $newmask);
  6408. if (empty($newmask)) {
  6409. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  6410. }
  6411. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  6412. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  6413. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  6414. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  6415. $nberr++;
  6416. } else {
  6417. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  6418. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  6419. $nbcreated++;
  6420. }
  6421. } else {
  6422. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  6423. }
  6424. }
  6425. }
  6426. return ($nberr ? -$nberr : $nbcreated);
  6427. }
  6428. /**
  6429. * Change mod of a file
  6430. *
  6431. * @param string $filepath Full file path
  6432. * @param string $newmask Force new mask. For example '0644'
  6433. * @return void
  6434. */
  6435. function dolChmod($filepath, $newmask = '')
  6436. {
  6437. global $conf;
  6438. if (!empty($newmask)) {
  6439. @chmod($filepath, octdec($newmask));
  6440. } elseif (!empty($conf->global->MAIN_UMASK)) {
  6441. @chmod($filepath, octdec($conf->global->MAIN_UMASK));
  6442. }
  6443. }
  6444. /**
  6445. * Return picto saying a field is required
  6446. *
  6447. * @return string Chaine avec picto obligatoire
  6448. */
  6449. function picto_required()
  6450. {
  6451. return '<span class="fieldrequired">*</span>';
  6452. }
  6453. /**
  6454. * Clean a string from all HTML tags and entities.
  6455. * This function differs from strip_tags because:
  6456. * - <br> are replaced with \n if removelinefeed=0 or 1
  6457. * - if entities are found, they are decoded BEFORE the strip
  6458. * - you can decide to convert line feed into a space
  6459. *
  6460. * @param string $stringtoclean String to clean
  6461. * @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..."
  6462. * @param string $pagecodeto Encoding of input/output string
  6463. * @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')
  6464. * @param integer $removedoublespaces Replace double space into one space
  6465. * @return string String cleaned
  6466. *
  6467. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6468. */
  6469. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6470. {
  6471. if (is_null($stringtoclean)) {
  6472. return '';
  6473. }
  6474. if ($removelinefeed == 2) {
  6475. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6476. }
  6477. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6478. // 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)
  6479. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6480. $temp = str_replace('< ', '__ltspace__', $temp);
  6481. if ($strip_tags) {
  6482. $temp = strip_tags($temp);
  6483. } else {
  6484. // 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).
  6485. $pattern = "/<[^<>]+>/";
  6486. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6487. // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6488. // pass 2 - $temp after pass 2: 0000-021
  6489. $tempbis = $temp;
  6490. do {
  6491. $temp = $tempbis;
  6492. $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6493. $tempbis = preg_replace($pattern, '', $tempbis);
  6494. //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
  6495. } while ($tempbis != $temp);
  6496. $temp = $tempbis;
  6497. // 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).
  6498. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6499. }
  6500. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6501. // Remove also carriage returns
  6502. if ($removelinefeed == 1) {
  6503. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6504. }
  6505. // And double quotes
  6506. if ($removedoublespaces) {
  6507. while (strpos($temp, " ")) {
  6508. $temp = str_replace(" ", " ", $temp);
  6509. }
  6510. }
  6511. $temp = str_replace('__ltspace__', '< ', $temp);
  6512. return trim($temp);
  6513. }
  6514. /**
  6515. * Clean a string to keep only desirable HTML tags.
  6516. * WARNING: This also clean HTML comments (because they can be used to obfuscate tag name).
  6517. *
  6518. * @param string $stringtoclean String to clean
  6519. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6520. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6521. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6522. * @param int $allowiframe Allow iframe tags.
  6523. * @param array $allowed_tags List of allowed tags to replace the default list
  6524. * @param int $allowlink Allow link tags.
  6525. * @return string String cleaned
  6526. *
  6527. * @see dol_htmlwithnojs() dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6528. */
  6529. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0)
  6530. {
  6531. if (empty($allowed_tags)) {
  6532. $allowed_tags = array(
  6533. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li",
  6534. "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"
  6535. );
  6536. }
  6537. $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6538. if ($allowiframe) {
  6539. if (!in_array('iframe', $allowed_tags)) {
  6540. $allowed_tags[] = "iframe";
  6541. }
  6542. }
  6543. if ($allowlink) {
  6544. if (!in_array('link', $allowed_tags)) {
  6545. $allowed_tags[] = "link";
  6546. }
  6547. }
  6548. $allowed_tags_string = join("><", $allowed_tags);
  6549. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6550. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6551. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6552. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6553. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6554. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6555. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6556. $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
  6557. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6558. $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
  6559. }
  6560. if ($removeclassattribute) { // Clean for remaining html tags
  6561. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6562. }
  6563. // Remove 'javascript:' that we should not find into a text with
  6564. // 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)).
  6565. if ($cleanalsojavascript) {
  6566. $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);
  6567. }
  6568. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6569. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6570. return $temp;
  6571. }
  6572. /**
  6573. * Clean a string from some undesirable HTML tags.
  6574. * Note: Complementary to dol_string_onlythesehtmltags().
  6575. * This method is used for example by dol_htmlwithnojs() when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6576. *
  6577. * @param string $stringtoclean String to clean
  6578. * @param array $allowed_attributes Array of tags not allowed
  6579. * @return string String cleaned
  6580. *
  6581. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6582. */
  6583. 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"))
  6584. {
  6585. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6586. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6587. $dom = new DOMDocument(null, 'UTF-8');
  6588. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6589. if (is_object($dom)) {
  6590. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6591. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6592. //var_dump($attrs->item($ii));
  6593. if (!empty($attrs->item($ii)->name)) {
  6594. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6595. // Delete attribute if not into allowed_attributes
  6596. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6597. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6598. // If attribute is 'style'
  6599. $valuetoclean = $attrs->item($ii)->value;
  6600. if (isset($valuetoclean)) {
  6601. do {
  6602. $oldvaluetoclean = $valuetoclean;
  6603. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6604. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6605. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6606. $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
  6607. $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
  6608. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
  6609. }
  6610. // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
  6611. $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
  6612. $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
  6613. } while ($oldvaluetoclean != $valuetoclean);
  6614. }
  6615. $attrs->item($ii)->value = $valuetoclean;
  6616. }
  6617. }
  6618. }
  6619. }
  6620. }
  6621. $return = $dom->saveHTML(); // This may add a LF at end of lines, so we will trim later
  6622. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6623. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6624. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6625. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6626. return trim($return);
  6627. } else {
  6628. return $stringtoclean;
  6629. }
  6630. }
  6631. /**
  6632. * Clean a string from some undesirable HTML tags.
  6633. * Note: You should use instead dol_string_onlythesehtmltags() that is more secured if you can.
  6634. *
  6635. * @param string $stringtoclean String to clean
  6636. * @param array $disallowed_tags Array of tags not allowed
  6637. * @param string $cleanalsosomestyles Clean also some tags
  6638. * @return string String cleaned
  6639. *
  6640. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6641. */
  6642. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6643. {
  6644. $temp = $stringtoclean;
  6645. foreach ($disallowed_tags as $tagtoremove) {
  6646. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6647. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6648. }
  6649. if ($cleanalsosomestyles) {
  6650. $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
  6651. }
  6652. return $temp;
  6653. }
  6654. /**
  6655. * Return first line of text. Cut will depends if content is HTML or not.
  6656. *
  6657. * @param string $text Input text
  6658. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6659. * @param string $charset Charset of $text string (UTF-8 by default)
  6660. * @return string Output text
  6661. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6662. */
  6663. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6664. {
  6665. if ($nboflines == 1) {
  6666. if (dol_textishtml($text)) {
  6667. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6668. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6669. } else {
  6670. if (isset($text)) {
  6671. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6672. } else {
  6673. $firstline = '';
  6674. }
  6675. }
  6676. return $firstline.(isset($firstline) && isset($text) && (strlen($firstline) != strlen($text)) ? '...' : '');
  6677. } else {
  6678. $ishtml = 0;
  6679. if (dol_textishtml($text)) {
  6680. $text = preg_replace('/\n/', '', $text);
  6681. $ishtml = 1;
  6682. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6683. } else {
  6684. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6685. }
  6686. $text = strtr($text, $repTable);
  6687. if ($charset == 'UTF-8') {
  6688. $pattern = '/(<br[^>]*>)/Uu';
  6689. } else {
  6690. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6691. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6692. }
  6693. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6694. $firstline = '';
  6695. $i = 0;
  6696. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  6697. while (($i < $nba) && ($i < ($nboflines * 2))) {
  6698. if ($i % 2 == 0) {
  6699. $firstline .= $a[$i];
  6700. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  6701. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6702. }
  6703. $i++;
  6704. }
  6705. unset($a);
  6706. return $firstline.(($i < $nba) ? '...' : '');
  6707. }
  6708. }
  6709. /**
  6710. * Replace CRLF in string with a HTML BR tag.
  6711. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have
  6712. * encoded the special chars of stringtoencode into HTML before with dol_htmlentitiesbr().
  6713. *
  6714. * @param string $stringtoencode String to encode
  6715. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6716. * @param bool $forxml false=Use <br>, true=Use <br />
  6717. * @return string String encoded
  6718. * @see dol_htmlentitiesbr(), dol_nboflines(), dolGetFirstLineOfText()
  6719. */
  6720. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6721. {
  6722. if (is_null($stringtoencode)) {
  6723. return '';
  6724. }
  6725. if (!$nl2brmode) {
  6726. return nl2br($stringtoencode, $forxml);
  6727. } else {
  6728. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6729. return $ret;
  6730. }
  6731. }
  6732. /**
  6733. * Sanitize a HTML to remove js and dangerous content
  6734. *
  6735. * @param string $stringtoencode String to encode
  6736. * @param int $nouseofiframesandbox 0=Default, 1=Allow use of option MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS for html sanitizing (not yet working)
  6737. * @param string $check 'restricthtmlnolink' or 'restricthtml' or 'restricthtmlallowclass' or 'restricthtmlallowunvalid'
  6738. * @return string HTML sanitized
  6739. */
  6740. function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
  6741. {
  6742. global $conf;
  6743. if (empty($nouseofiframesandbox) && !empty($conf->global->MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS)) {
  6744. // TODO using sandbox on inline html content is not possible yet with current browsers
  6745. //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
  6746. //$s .= $stringtoencode;
  6747. //$s .= '</body></html></iframe>';
  6748. return $stringtoencode;
  6749. } else {
  6750. $out = $stringtoencode;
  6751. do {
  6752. $oldstringtoclean = $out;
  6753. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  6754. try {
  6755. libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
  6756. $dom = new DOMDocument;
  6757. // Add a trick to solve pb with text without parent tag
  6758. // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
  6759. // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
  6760. $out = '<div class="tricktoremove">'.$out.'</div>';
  6761. $dom->loadHTML($out, LIBXML_HTML_NODEFDTD|LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6762. $out = trim($dom->saveHTML());
  6763. // Remove the trick added to solve pb with text without parent tag
  6764. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  6765. $out = preg_replace('/<\/div>$/', '', $out);
  6766. } catch (Exception $e) {
  6767. // If error, invalid HTML string with no way to clean it
  6768. //print $e->getMessage();
  6769. $out = 'InvalidHTMLStringCantBeCleaned';
  6770. }
  6771. }
  6772. // Clean some html entities that are useless so text is cleaner
  6773. $out = preg_replace('/&(tab|newline);/i', ' ', $out);
  6774. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  6775. // encoded using text entities) so we can then exclude all numeric entities.
  6776. $out = preg_replace('/&#39;/i', '&apos;', $out);
  6777. // 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).
  6778. // 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
  6779. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  6780. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  6781. return realCharForNumericEntities($m); }, $out);
  6782. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  6783. $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'.
  6784. // Keep only some html tags and remove also some 'javascript:' strings
  6785. $out = dol_string_onlythesehtmltags($out, 0, ($check == 'restricthtmlallowclass' ? 0 : 1), 1);
  6786. // Keep only some html attributes and exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
  6787. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  6788. $out = dol_string_onlythesehtmlattributes($out);
  6789. }
  6790. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  6791. $out = preg_replace('/&apos;/i', "&#39;", $out);
  6792. } while ($oldstringtoclean != $out);
  6793. // Check the limit of external links that are automatically executed in a Rich text content. We count:
  6794. // '<img' to avoid <img src="http...">
  6795. // 'url(' to avoid inline style like background: url(http...
  6796. // '<link' to avoid <link href="http...">
  6797. $reg = array();
  6798. preg_match_all('/(<img|url\(|<link)/i', $out, $reg);
  6799. $nbextlink = count($reg[0]);
  6800. if ($nbextlink > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
  6801. $out = 'TooManyLinksIntoHTMLString';
  6802. }
  6803. //
  6804. if (!empty($conf->global->MAIN_DISALLOW_EXT_URL_INTO_DESCRIPTIONS) || $check == 'restricthtmlnolink') {
  6805. if ($nbextlink > 0) {
  6806. $out = 'ExternalLinksNotAllowed';
  6807. }
  6808. }
  6809. return $out;
  6810. }
  6811. }
  6812. /**
  6813. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6814. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6815. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6816. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6817. * For PDF usage, you can show text by 2 ways:
  6818. * - writeHTMLCell -> param must be encoded into HTML.
  6819. * - MultiCell -> param must not be encoded into HTML.
  6820. * Because writeHTMLCell convert also \n into <br>, if function
  6821. * is used to build PDF, nl2brmode must be 1.
  6822. * Note: When we output string on pages, we should use
  6823. * - dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1), 1, 1) for notes or descriptions,
  6824. * - dol_escape_htmltag(dol_htmlentitiesbr()) for simple labels.
  6825. *
  6826. * @param string $stringtoencode String to encode
  6827. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6828. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6829. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6830. * @return string String encoded
  6831. * @see dol_escape_htmltag(), dolGetFirstLineOfText(), dol_string_onlythesehtmltags()
  6832. */
  6833. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6834. {
  6835. if (is_null($stringtoencode)) {
  6836. return '';
  6837. }
  6838. $newstring = $stringtoencode;
  6839. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6840. $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.
  6841. if ($removelasteolbr) {
  6842. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6843. }
  6844. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6845. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6846. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6847. } else {
  6848. if ($removelasteolbr) {
  6849. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6850. }
  6851. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6852. }
  6853. // Other substitutions that htmlentities does not do
  6854. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6855. return $newstring;
  6856. }
  6857. /**
  6858. * This function is called to decode a HTML string (it decodes entities and br tags)
  6859. *
  6860. * @param string $stringtodecode String to decode
  6861. * @param string $pagecodeto Page code for result
  6862. * @return string String decoded
  6863. */
  6864. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6865. {
  6866. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6867. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6868. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6869. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6870. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6871. return $ret;
  6872. }
  6873. /**
  6874. * This function remove all ending \n and br at end
  6875. *
  6876. * @param string $stringtodecode String to decode
  6877. * @return string String decoded
  6878. */
  6879. function dol_htmlcleanlastbr($stringtodecode)
  6880. {
  6881. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6882. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6883. return $ret;
  6884. }
  6885. /**
  6886. * Replace html_entity_decode functions to manage errors
  6887. *
  6888. * @param string $a Operand a
  6889. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6890. * @param string $c Operand c
  6891. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6892. * @return string String decoded
  6893. */
  6894. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6895. {
  6896. $newstring = $a;
  6897. if ($keepsomeentities) {
  6898. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6899. }
  6900. $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
  6901. if ($keepsomeentities) {
  6902. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6903. }
  6904. return $newstring;
  6905. }
  6906. /**
  6907. * Replace htmlentities functions.
  6908. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6909. *
  6910. * @param string $string The input string to encode
  6911. * @param int $flags Flags (see PHP doc above)
  6912. * @param string $encoding Encoding page code
  6913. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6914. * @return string $ret Encoded string
  6915. * @see dol_htmlentitiesbr()
  6916. */
  6917. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6918. {
  6919. return htmlentities($string, $flags, $encoding, $double_encode);
  6920. }
  6921. /**
  6922. * Check if a string is a correct iso string
  6923. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6924. * Example, if string contains euro symbol that has ascii code 128
  6925. *
  6926. * @param string $s String to check
  6927. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6928. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6929. */
  6930. function dol_string_is_good_iso($s, $clean = 0)
  6931. {
  6932. $len = dol_strlen($s);
  6933. $out = '';
  6934. $ok = 1;
  6935. for ($scursor = 0; $scursor < $len; $scursor++) {
  6936. $ordchar = ord($s[$scursor]);
  6937. //print $scursor.'-'.$ordchar.'<br>';
  6938. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6939. $ok = 0;
  6940. break;
  6941. } elseif ($ordchar > 126 && $ordchar < 160) {
  6942. $ok = 0;
  6943. break;
  6944. } elseif ($clean) {
  6945. $out .= $s[$scursor];
  6946. }
  6947. }
  6948. if ($clean) {
  6949. return $out;
  6950. }
  6951. return $ok;
  6952. }
  6953. /**
  6954. * Return nb of lines of a clear text
  6955. *
  6956. * @param string $s String to check
  6957. * @param int $maxchar Not yet used
  6958. * @return int Number of lines
  6959. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6960. */
  6961. function dol_nboflines($s, $maxchar = 0)
  6962. {
  6963. if ($s == '') {
  6964. return 0;
  6965. }
  6966. $arraystring = explode("\n", $s);
  6967. $nb = count($arraystring);
  6968. return $nb;
  6969. }
  6970. /**
  6971. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6972. *
  6973. * @param string $text Text
  6974. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6975. * @param string $charset Give the charset used to encode the $text variable in memory.
  6976. * @return int Number of lines
  6977. * @see dol_nboflines(), dolGetFirstLineOfText()
  6978. */
  6979. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6980. {
  6981. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6982. if (dol_textishtml($text)) {
  6983. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6984. }
  6985. $text = strtr($text, $repTable);
  6986. if ($charset == 'UTF-8') {
  6987. $pattern = '/(<br[^>]*>)/Uu';
  6988. } else {
  6989. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6990. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6991. }
  6992. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6993. $nblines = (int) floor((count($a) + 1) / 2);
  6994. // count possible auto line breaks
  6995. if ($maxlinesize) {
  6996. foreach ($a as $line) {
  6997. if (dol_strlen($line) > $maxlinesize) {
  6998. //$line_dec = html_entity_decode(strip_tags($line));
  6999. $line_dec = html_entity_decode($line);
  7000. if (dol_strlen($line_dec) > $maxlinesize) {
  7001. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  7002. $nblines += substr_count($line_dec, '\n');
  7003. }
  7004. }
  7005. }
  7006. }
  7007. unset($a);
  7008. return $nblines;
  7009. }
  7010. /**
  7011. * Return if a text is a html content
  7012. *
  7013. * @param string $msg Content to check
  7014. * @param int $option 0=Full detection, 1=Fast check
  7015. * @return boolean true/false
  7016. * @see dol_concatdesc()
  7017. */
  7018. function dol_textishtml($msg, $option = 0)
  7019. {
  7020. if (is_null($msg)) {
  7021. return false;
  7022. }
  7023. if ($option == 1) {
  7024. if (preg_match('/<html/i', $msg)) {
  7025. return true;
  7026. } elseif (preg_match('/<body/i', $msg)) {
  7027. return true;
  7028. } elseif (preg_match('/<\/textarea/i', $msg)) {
  7029. return true;
  7030. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  7031. return true;
  7032. } elseif (preg_match('/<br/i', $msg)) {
  7033. return true;
  7034. }
  7035. return false;
  7036. } else {
  7037. // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
  7038. $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
  7039. if (preg_match('/<html/i', $msg)) {
  7040. return true;
  7041. } elseif (preg_match('/<body/i', $msg)) {
  7042. return true;
  7043. } elseif (preg_match('/<\/textarea/i', $msg)) {
  7044. return true;
  7045. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  7046. return true;
  7047. } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
  7048. return true;
  7049. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
  7050. return true;
  7051. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  7052. return true;
  7053. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  7054. return true; // must accept <img src="http://example.com/aaa.png" />
  7055. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  7056. return true; // must accept <a href="http://example.com/aaa.png" />
  7057. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  7058. return true;
  7059. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  7060. // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
  7061. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  7062. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  7063. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  7064. }
  7065. return false;
  7066. }
  7067. }
  7068. /**
  7069. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  7070. * text1 html + text2 html => text1 + '<br>' + text2
  7071. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  7072. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  7073. * text1 txt + text2 txt => text1 + '\n' + text2
  7074. *
  7075. * @param string $text1 Text 1
  7076. * @param string $text2 Text 2
  7077. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  7078. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  7079. * @return string Text 1 + new line + Text2
  7080. * @see dol_textishtml()
  7081. */
  7082. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  7083. {
  7084. if (!empty($invert)) {
  7085. $tmp = $text1;
  7086. $text1 = $text2;
  7087. $text2 = $tmp;
  7088. }
  7089. $ret = '';
  7090. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  7091. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  7092. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  7093. return $ret;
  7094. }
  7095. /**
  7096. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  7097. *
  7098. * @param Translate $outputlangs Output language
  7099. * @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)
  7100. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7101. * @param Object $object Object for keys on object
  7102. * @param array $include Array of family keys we want to include. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7103. * @return array Array of substitutions
  7104. * @see setSubstitFromObject()
  7105. */
  7106. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
  7107. {
  7108. global $db, $conf, $mysoc, $user, $extrafields;
  7109. $substitutionarray = array();
  7110. if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include))) {
  7111. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  7112. // this will include signature content first and then replace var found into content of signature
  7113. //var_dump($onlykey);
  7114. $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()
  7115. $usersignature = $user->signature;
  7116. $substitutionarray = array_merge($substitutionarray, array(
  7117. '__SENDEREMAIL_SIGNATURE__' => (string) ((empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
  7118. '__USER_SIGNATURE__' => (string) (($usersignature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
  7119. ));
  7120. if (is_object($user)) {
  7121. $substitutionarray = array_merge($substitutionarray, array(
  7122. '__USER_ID__' => (string) $user->id,
  7123. '__USER_LOGIN__' => (string) $user->login,
  7124. '__USER_EMAIL__' => (string) $user->email,
  7125. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
  7126. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
  7127. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
  7128. '__USER_FAX__' => (string) $user->office_fax,
  7129. '__USER_LASTNAME__' => (string) $user->lastname,
  7130. '__USER_FIRSTNAME__' => (string) $user->firstname,
  7131. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  7132. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  7133. '__USER_JOB__' => (string) $user->job,
  7134. '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
  7135. '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
  7136. ));
  7137. }
  7138. }
  7139. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
  7140. $substitutionarray = array_merge($substitutionarray, array(
  7141. '__MYCOMPANY_NAME__' => $mysoc->name,
  7142. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  7143. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone, '', 0, 0, '', " ", '', '', -1),
  7144. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax, '', 0, 0, '', " ", '', '', -1),
  7145. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  7146. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  7147. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  7148. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  7149. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  7150. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  7151. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  7152. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  7153. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  7154. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  7155. '__MYCOMPANY_TOWN__' => $mysoc->town,
  7156. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  7157. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  7158. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  7159. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  7160. ));
  7161. }
  7162. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
  7163. if ($onlykey) {
  7164. $substitutionarray['__ID__'] = '__ID__';
  7165. $substitutionarray['__REF__'] = '__REF__';
  7166. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  7167. $substitutionarray['__LABEL__'] = '__LABEL__';
  7168. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  7169. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  7170. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  7171. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  7172. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  7173. if (isModEnabled("societe")) { // Most objects are concerned
  7174. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  7175. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  7176. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  7177. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  7178. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  7179. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  7180. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  7181. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  7182. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  7183. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  7184. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  7185. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  7186. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  7187. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  7188. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  7189. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  7190. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  7191. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  7192. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  7193. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  7194. }
  7195. if (isModEnabled('adherent') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
  7196. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  7197. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  7198. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  7199. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  7200. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  7201. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  7202. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  7203. }
  7204. // add variables subtitutions ticket
  7205. if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
  7206. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  7207. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  7208. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  7209. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  7210. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  7211. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  7212. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  7213. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  7214. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  7215. }
  7216. if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
  7217. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  7218. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  7219. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  7220. }
  7221. if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
  7222. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  7223. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  7224. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  7225. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  7226. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  7227. }
  7228. if (isModEnabled('contrat') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
  7229. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  7230. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  7231. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  7232. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  7233. }
  7234. if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
  7235. $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
  7236. }
  7237. if (isModEnabled("ficheinter") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
  7238. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
  7239. }
  7240. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  7241. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  7242. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  7243. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  7244. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  7245. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  7246. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  7247. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  7248. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  7249. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  7250. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  7251. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  7252. if (isModEnabled("expedition") && (!is_object($object) || $object->element == 'shipping')) {
  7253. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  7254. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  7255. $substitutionarray['__SHIPPINGMETHOD__'] = 'Shipping method';
  7256. }
  7257. if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
  7258. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  7259. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  7260. }
  7261. } else {
  7262. $substitutionarray['__ID__'] = $object->id;
  7263. $substitutionarray['__REF__'] = $object->ref;
  7264. $substitutionarray['__NEWREF__'] = $object->newref;
  7265. $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
  7266. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7267. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7268. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  7269. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  7270. if ($object->element == "shipping") {
  7271. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, 'day', 0, $outputlangs) : '');
  7272. } else {
  7273. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  7274. }
  7275. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  7276. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  7277. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  7278. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  7279. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  7280. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  7281. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  7282. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  7283. // For backward compatibility (deprecated)
  7284. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7285. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7286. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  7287. $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 : '')) : '');
  7288. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  7289. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  7290. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  7291. if (method_exists($object, 'getCivilityLabel')) {
  7292. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  7293. }
  7294. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  7295. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  7296. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  7297. if (method_exists($object, 'getFullName')) {
  7298. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  7299. }
  7300. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  7301. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  7302. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  7303. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  7304. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  7305. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  7306. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  7307. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  7308. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  7309. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  7310. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  7311. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  7312. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  7313. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  7314. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  7315. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
  7316. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
  7317. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  7318. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  7319. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  7320. }
  7321. if (is_object($object) && $object->element == 'societe') {
  7322. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  7323. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  7324. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  7325. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  7326. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  7327. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  7328. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  7329. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  7330. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  7331. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  7332. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  7333. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  7334. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  7335. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  7336. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  7337. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  7338. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  7339. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  7340. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  7341. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  7342. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  7343. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  7344. } elseif (is_object($object->thirdparty)) {
  7345. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  7346. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  7347. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  7348. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  7349. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  7350. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  7351. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  7352. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  7353. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  7354. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  7355. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  7356. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  7357. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  7358. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  7359. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  7360. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  7361. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  7362. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  7363. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  7364. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  7365. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  7366. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  7367. }
  7368. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  7369. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  7370. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7371. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7372. }
  7373. if (is_object($object) && $object->element == 'conferenceorboothattendee') {
  7374. $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
  7375. $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7376. $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7377. }
  7378. if (is_object($object->project)) {
  7379. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  7380. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  7381. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  7382. }
  7383. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  7384. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  7385. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  7386. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  7387. }
  7388. if (is_object($object) && $object->element == 'project') {
  7389. $substitutionarray['__PROJECT_NAME__'] = $object->title;
  7390. }
  7391. if (is_object($object) && $object->element == 'shipping') {
  7392. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  7393. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  7394. $substitutionarray['__SHIPPINGMETHOD__'] = $object->shipping_method;
  7395. }
  7396. if (is_object($object) && $object->element == 'reception') {
  7397. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  7398. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  7399. }
  7400. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  7401. $dateplannedstart = '';
  7402. $datenextexpiration = '';
  7403. foreach ($object->lines as $line) {
  7404. if ($line->date_start > $dateplannedstart) {
  7405. $dateplannedstart = $line->date_start;
  7406. }
  7407. if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
  7408. $datenextexpiration = $line->date_end;
  7409. }
  7410. }
  7411. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  7412. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  7413. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  7414. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  7415. }
  7416. // add substition variable for ticket
  7417. if (is_object($object) && $object->element == 'ticket') {
  7418. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  7419. $substitutionarray['__REF__'] = $object->ref;
  7420. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  7421. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  7422. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  7423. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  7424. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  7425. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  7426. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  7427. $userstat = new User($db);
  7428. if ($object->fk_user_assign > 0) {
  7429. $userstat->fetch($object->fk_user_assign);
  7430. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7431. }
  7432. if ($object->fk_user_create > 0) {
  7433. $userstat->fetch($object->fk_user_create);
  7434. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7435. }
  7436. }
  7437. // Create dynamic tags for __EXTRAFIELD_FIELD__
  7438. if ($object->table_element && $object->id > 0) {
  7439. if (!is_object($extrafields)) {
  7440. $extrafields = new ExtraFields($db);
  7441. }
  7442. $extrafields->fetch_name_optionals_label($object->table_element, true);
  7443. if ($object->fetch_optionals() > 0) {
  7444. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  7445. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  7446. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  7447. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  7448. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  7449. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  7450. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  7451. $datetime = $object->array_options['options_'.$key];
  7452. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  7453. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  7454. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  7455. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  7456. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  7457. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  7458. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  7459. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7460. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  7461. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
  7462. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = !empty($object->array_options['options_'.$key]) ? $object->array_options['options_'.$key] :'';
  7463. }
  7464. }
  7465. }
  7466. }
  7467. }
  7468. // Complete substitution array with the url to make online payment
  7469. $paymenturl = '';
  7470. if (empty($substitutionarray['__REF__'])) {
  7471. $paymenturl = '';
  7472. } else {
  7473. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  7474. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  7475. $outputlangs->loadLangs(array('paypal', 'other'));
  7476. $amounttouse = 0;
  7477. $typeforonlinepayment = 'free';
  7478. if (is_object($object) && $object->element == 'commande') {
  7479. $typeforonlinepayment = 'order';
  7480. }
  7481. if (is_object($object) && $object->element == 'facture') {
  7482. $typeforonlinepayment = 'invoice';
  7483. }
  7484. if (is_object($object) && $object->element == 'member') {
  7485. $typeforonlinepayment = 'member';
  7486. if (!empty($object->last_subscription_amount)) {
  7487. $amounttouse = $object->last_subscription_amount;
  7488. }
  7489. }
  7490. if (is_object($object) && $object->element == 'contrat') {
  7491. $typeforonlinepayment = 'contract';
  7492. }
  7493. if (is_object($object) && $object->element == 'fichinter') {
  7494. $typeforonlinepayment = 'ficheinter';
  7495. }
  7496. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], $amounttouse);
  7497. $paymenturl = $url;
  7498. }
  7499. if ($object->id > 0) {
  7500. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  7501. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  7502. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  7503. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7504. } else {
  7505. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  7506. }
  7507. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  7508. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  7509. } else {
  7510. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  7511. }
  7512. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  7513. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  7514. } else {
  7515. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  7516. }
  7517. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  7518. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  7519. } else {
  7520. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  7521. }
  7522. if (!empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'fichinter') {
  7523. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
  7524. } else {
  7525. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
  7526. }
  7527. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  7528. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7529. } else {
  7530. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  7531. }
  7532. if (is_object($object) && $object->element == 'propal') {
  7533. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  7534. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7535. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  7536. }
  7537. if (is_object($object) && $object->element == 'commande') {
  7538. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  7539. }
  7540. if (is_object($object) && $object->element == 'facture') {
  7541. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  7542. }
  7543. if (is_object($object) && $object->element == 'contrat') {
  7544. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  7545. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7546. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', $object->ref);
  7547. }
  7548. if (is_object($object) && $object->element == 'fichinter') {
  7549. $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT."/fichinter/card.php?id=".$object->id;
  7550. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7551. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', $object->ref);
  7552. }
  7553. if (is_object($object) && $object->element == 'supplier_proposal') {
  7554. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  7555. }
  7556. if (is_object($object) && $object->element == 'shipping') {
  7557. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  7558. }
  7559. }
  7560. if (is_object($object) && $object->element == 'action') {
  7561. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  7562. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  7563. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  7564. }
  7565. }
  7566. }
  7567. if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
  7568. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  7569. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  7570. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  7571. $already_payed_all = 0;
  7572. if (is_object($object) && ($object instanceof Facture)) {
  7573. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  7574. }
  7575. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  7576. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  7577. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  7578. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  7579. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
  7580. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7581. $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)) : '';
  7582. $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)) : '';
  7583. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7584. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  7585. }
  7586. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7587. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  7588. }
  7589. // Amount keys formated in a currency
  7590. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7591. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7592. $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) : '';
  7593. $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)) : '';
  7594. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7595. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7596. }
  7597. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7598. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7599. }
  7600. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  7601. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  7602. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  7603. // TODO Add other keys for foreign multicurrency
  7604. // For backward compatibility
  7605. if ($onlykey != 2) {
  7606. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  7607. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  7608. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7609. }
  7610. }
  7611. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  7612. if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
  7613. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  7614. $now = dol_now();
  7615. $tmp = dol_getdate($now, true);
  7616. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7617. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  7618. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7619. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  7620. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  7621. $substitutionarray = array_merge($substitutionarray, array(
  7622. '__NOW_TMS__' => (int) $now,
  7623. '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 0, $outputlangs),
  7624. '__DAY__' => (string) $tmp['mday'],
  7625. '__DAY_TEXT__' => $daytext, // Monday
  7626. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  7627. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  7628. '__MONTH__' => (string) $tmp['mon'],
  7629. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  7630. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  7631. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  7632. '__YEAR__' => (string) $tmp['year'],
  7633. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  7634. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  7635. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  7636. '__NEXT_DAY__' => (string) $tmp4['day'],
  7637. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7638. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7639. ));
  7640. }
  7641. if (isModEnabled('multicompany')) {
  7642. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7643. }
  7644. if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
  7645. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7646. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7647. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7648. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7649. }
  7650. return $substitutionarray;
  7651. }
  7652. /**
  7653. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7654. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7655. * Example of usage:
  7656. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7657. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7658. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7659. *
  7660. * @param string $text Source string in which we must do substitution
  7661. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7662. * @param Translate $outputlangs Output language
  7663. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7664. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7665. * @return string Output string after substitutions
  7666. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7667. */
  7668. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7669. {
  7670. global $conf, $langs;
  7671. if (!is_array($substitutionarray)) {
  7672. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7673. }
  7674. if (empty($outputlangs)) {
  7675. $outputlangs = $langs;
  7676. }
  7677. // Is initial text HTML or simple text ?
  7678. $msgishtml = 0;
  7679. if (dol_textishtml($text, 1)) {
  7680. $msgishtml = 1;
  7681. }
  7682. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7683. if (is_object($outputlangs)) {
  7684. $reg = array();
  7685. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7686. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7687. $tmp = explode('|', $reg[1]);
  7688. if (!empty($tmp[1])) {
  7689. $outputlangs->load($tmp[1]);
  7690. }
  7691. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7692. if (empty($converttextinhtmlifnecessary)) {
  7693. // convert $newval into HTML is necessary
  7694. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7695. } else {
  7696. if (! $msgishtml) {
  7697. $valueishtml = dol_textishtml($value, 1);
  7698. //var_dump("valueishtml=".$valueishtml);
  7699. if ($valueishtml) {
  7700. $text = dol_htmlentitiesbr($text);
  7701. $msgishtml = 1;
  7702. }
  7703. } else {
  7704. $value = dol_nl2br("$value");
  7705. }
  7706. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7707. }
  7708. }
  7709. }
  7710. // Make substitution for constant keys.
  7711. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7712. $reg = array();
  7713. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7714. $keyfound = $reg[1];
  7715. if (isASecretKey($keyfound)) {
  7716. $value = '*****forbidden*****';
  7717. } else {
  7718. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7719. }
  7720. if (empty($converttextinhtmlifnecessary)) {
  7721. // convert $newval into HTML is necessary
  7722. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7723. } else {
  7724. if (! $msgishtml) {
  7725. $valueishtml = dol_textishtml($value, 1);
  7726. if ($valueishtml) {
  7727. $text = dol_htmlentitiesbr($text);
  7728. $msgishtml = 1;
  7729. }
  7730. } else {
  7731. $value = dol_nl2br("$value");
  7732. }
  7733. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7734. }
  7735. }
  7736. // Make substitution for array $substitutionarray
  7737. foreach ($substitutionarray as $key => $value) {
  7738. if (!isset($value)) {
  7739. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7740. }
  7741. if (($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__') && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  7742. $value = ''; // Protection
  7743. }
  7744. if (empty($converttextinhtmlifnecessary)) {
  7745. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7746. } else {
  7747. if (! $msgishtml) {
  7748. $valueishtml = dol_textishtml($value, 1);
  7749. if ($valueishtml) {
  7750. $text = dol_htmlentitiesbr($text);
  7751. $msgishtml = 1;
  7752. }
  7753. } else {
  7754. $value = dol_nl2br("$value");
  7755. }
  7756. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7757. }
  7758. }
  7759. return $text;
  7760. }
  7761. /**
  7762. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  7763. * In this case, method completesubstitutionarray provided by module is called.
  7764. *
  7765. * @param array $substitutionarray Array substitution old value => new value value
  7766. * @param Translate $outputlangs Output language
  7767. * @param Object $object Source object
  7768. * @param mixed $parameters Add more parameters (useful to pass product lines)
  7769. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  7770. * @return void
  7771. * @see make_substitutions()
  7772. */
  7773. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  7774. {
  7775. global $conf, $user;
  7776. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7777. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7778. // Check if there is external substitution to do, requested by plugins
  7779. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7780. foreach ($dirsubstitutions as $reldir) {
  7781. $dir = dol_buildpath($reldir, 0);
  7782. // Check if directory exists
  7783. if (!dol_is_dir($dir)) {
  7784. continue;
  7785. }
  7786. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7787. foreach ($substitfiles as $substitfile) {
  7788. $reg = array();
  7789. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7790. $module = $reg[1];
  7791. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7792. // Include the user's functions file
  7793. require_once $dir.$substitfile['name'];
  7794. // Call the user's function, and only if it is defined
  7795. $function_name = $module."_".$callfunc;
  7796. if (function_exists($function_name)) {
  7797. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7798. }
  7799. }
  7800. }
  7801. }
  7802. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7803. // to list all tags in odt template
  7804. $tags = '';
  7805. foreach ($substitutionarray as $key => $value) {
  7806. $tags .= '{'.$key.'} => '.$value."\n";
  7807. }
  7808. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7809. }
  7810. }
  7811. /**
  7812. * Format output for start and end date
  7813. *
  7814. * @param int $date_start Start date
  7815. * @param int $date_end End date
  7816. * @param string $format Output format
  7817. * @param Translate $outputlangs Output language
  7818. * @return void
  7819. */
  7820. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7821. {
  7822. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7823. }
  7824. /**
  7825. * Format output for start and end date
  7826. *
  7827. * @param int $date_start Start date
  7828. * @param int $date_end End date
  7829. * @param string $format Output date format ('day', 'dayhour', ...)
  7830. * @param Translate $outputlangs Output language
  7831. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7832. * @return string String
  7833. */
  7834. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7835. {
  7836. global $langs;
  7837. $out = '';
  7838. if (!is_object($outputlangs)) {
  7839. $outputlangs = $langs;
  7840. }
  7841. if ($date_start && $date_end) {
  7842. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7843. }
  7844. if ($date_start && !$date_end) {
  7845. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7846. }
  7847. if (!$date_start && $date_end) {
  7848. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7849. }
  7850. return $out;
  7851. }
  7852. /**
  7853. * Return firstname and lastname in correct order
  7854. *
  7855. * @param string $firstname Firstname
  7856. * @param string $lastname Lastname
  7857. * @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
  7858. * @return string Firstname + lastname or Lastname + firstname
  7859. */
  7860. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7861. {
  7862. global $conf;
  7863. $ret = '';
  7864. // If order not defined, we use the setup
  7865. if ($nameorder < 0) {
  7866. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7867. }
  7868. if ($nameorder == 1) {
  7869. $ret .= $firstname;
  7870. if ($firstname && $lastname) {
  7871. $ret .= ' ';
  7872. }
  7873. $ret .= $lastname;
  7874. } elseif ($nameorder == 2 || $nameorder == 3) {
  7875. $ret .= $firstname;
  7876. if (empty($ret) && $nameorder == 3) {
  7877. $ret .= $lastname;
  7878. }
  7879. } else { // 0, 4 or 5
  7880. $ret .= $lastname;
  7881. if (empty($ret) && $nameorder == 5) {
  7882. $ret .= $firstname;
  7883. }
  7884. if ($nameorder == 0) {
  7885. if ($firstname && $lastname) {
  7886. $ret .= ' ';
  7887. }
  7888. $ret .= $firstname;
  7889. }
  7890. }
  7891. return $ret;
  7892. }
  7893. /**
  7894. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  7895. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7896. * Note: Prefer to use setEventMessages instead.
  7897. *
  7898. * @param string|string[] $mesgs Message string or array
  7899. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7900. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  7901. * @return void
  7902. * @see dol_htmloutput_events()
  7903. */
  7904. function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0)
  7905. {
  7906. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  7907. if (!is_array($mesgs)) {
  7908. // If mesgs is a string
  7909. if ($mesgs) {
  7910. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
  7911. return;
  7912. }
  7913. $_SESSION['dol_events'][$style][] = $mesgs;
  7914. }
  7915. } else {
  7916. // If mesgs is an array
  7917. foreach ($mesgs as $mesg) {
  7918. if ($mesg) {
  7919. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
  7920. return;
  7921. }
  7922. $_SESSION['dol_events'][$style][] = $mesg;
  7923. }
  7924. }
  7925. }
  7926. }
  7927. /**
  7928. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7929. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7930. *
  7931. * @param string $mesg Message string
  7932. * @param array|null $mesgs Message array
  7933. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7934. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7935. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  7936. * @return void
  7937. * @see dol_htmloutput_events()
  7938. */
  7939. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0)
  7940. {
  7941. if (empty($mesg) && empty($mesgs)) {
  7942. dol_syslog("Try to add a message in stack, but value to add is empty message", LOG_WARNING);
  7943. } else {
  7944. if ($messagekey) {
  7945. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7946. // TODO
  7947. $mesg .= '';
  7948. }
  7949. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7950. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7951. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7952. }
  7953. if (empty($mesgs)) {
  7954. setEventMessage($mesg, $style, $noduplicate);
  7955. } else {
  7956. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7957. setEventMessage($mesg, $style, $noduplicate); // Add message string if not already into array
  7958. }
  7959. setEventMessage($mesgs, $style, $noduplicate);
  7960. }
  7961. }
  7962. }
  7963. }
  7964. /**
  7965. * Print formated messages to output (Used to show messages on html output).
  7966. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7967. * no need to call it explicitely.
  7968. *
  7969. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7970. * @return void
  7971. * @see dol_htmloutput_mesg()
  7972. */
  7973. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7974. {
  7975. // Show mesgs
  7976. if (isset($_SESSION['dol_events']['mesgs'])) {
  7977. if (empty($disabledoutputofmessages)) {
  7978. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7979. }
  7980. unset($_SESSION['dol_events']['mesgs']);
  7981. }
  7982. // Show errors
  7983. if (isset($_SESSION['dol_events']['errors'])) {
  7984. if (empty($disabledoutputofmessages)) {
  7985. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7986. }
  7987. unset($_SESSION['dol_events']['errors']);
  7988. }
  7989. // Show warnings
  7990. if (isset($_SESSION['dol_events']['warnings'])) {
  7991. if (empty($disabledoutputofmessages)) {
  7992. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7993. }
  7994. unset($_SESSION['dol_events']['warnings']);
  7995. }
  7996. }
  7997. /**
  7998. * Get formated messages to output (Used to show messages on html output).
  7999. * This include also the translation of the message key.
  8000. *
  8001. * @param string $mesgstring Message string or message key
  8002. * @param string[] $mesgarray Array of message strings or message keys
  8003. * @param string $style Style of message output ('ok' or 'error')
  8004. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8005. * @return string Return html output
  8006. *
  8007. * @see dol_print_error()
  8008. * @see dol_htmloutput_errors()
  8009. * @see setEventMessages()
  8010. */
  8011. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  8012. {
  8013. global $conf, $langs;
  8014. $ret = 0;
  8015. $return = '';
  8016. $out = '';
  8017. $divstart = $divend = '';
  8018. // If inline message with no format, we add it.
  8019. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  8020. $divstart = '<div class="'.$style.' clearboth">';
  8021. $divend = '</div>';
  8022. }
  8023. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  8024. $langs->load("errors");
  8025. $out .= $divstart;
  8026. if (is_array($mesgarray) && count($mesgarray)) {
  8027. foreach ($mesgarray as $message) {
  8028. $ret++;
  8029. $out .= $langs->trans($message);
  8030. if ($ret < count($mesgarray)) {
  8031. $out .= "<br>\n";
  8032. }
  8033. }
  8034. }
  8035. if ($mesgstring) {
  8036. $ret++;
  8037. $out .= $langs->trans($mesgstring);
  8038. }
  8039. $out .= $divend;
  8040. }
  8041. if ($out) {
  8042. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  8043. $return = '<script nonce="'.getNonce().'">
  8044. $(document).ready(function() {
  8045. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  8046. if (block) {
  8047. $.dolEventValid("","'.dol_escape_js($out).'");
  8048. } else {
  8049. /* jnotify(message, preset of message type, keepmessage) */
  8050. $.jnotify("'.dol_escape_js($out).'",
  8051. "'.($style == "ok" ? 3000 : $style).'",
  8052. '.($style == "ok" ? "false" : "true").',
  8053. { remove: function (){} } );
  8054. }
  8055. });
  8056. </script>';
  8057. } else {
  8058. $return = $out;
  8059. }
  8060. }
  8061. return $return;
  8062. }
  8063. /**
  8064. * Get formated error messages to output (Used to show messages on html output).
  8065. *
  8066. * @param string $mesgstring Error message
  8067. * @param array $mesgarray Error messages array
  8068. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8069. * @return string Return html output
  8070. *
  8071. * @see dol_print_error()
  8072. * @see dol_htmloutput_mesg()
  8073. */
  8074. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8075. {
  8076. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8077. }
  8078. /**
  8079. * Print formated messages to output (Used to show messages on html output).
  8080. *
  8081. * @param string $mesgstring Message string or message key
  8082. * @param string[] $mesgarray Array of message strings or message keys
  8083. * @param string $style Which style to use ('ok', 'warning', 'error')
  8084. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  8085. * @return void
  8086. *
  8087. * @see dol_print_error()
  8088. * @see dol_htmloutput_errors()
  8089. * @see setEventMessages()
  8090. */
  8091. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  8092. {
  8093. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  8094. return;
  8095. }
  8096. $iserror = 0;
  8097. $iswarning = 0;
  8098. if (is_array($mesgarray)) {
  8099. foreach ($mesgarray as $val) {
  8100. if ($val && preg_match('/class="error"/i', $val)) {
  8101. $iserror++;
  8102. break;
  8103. }
  8104. if ($val && preg_match('/class="warning"/i', $val)) {
  8105. $iswarning++;
  8106. break;
  8107. }
  8108. }
  8109. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  8110. $iserror++;
  8111. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  8112. $iswarning++;
  8113. }
  8114. if ($style == 'error') {
  8115. $iserror++;
  8116. }
  8117. if ($style == 'warning') {
  8118. $iswarning++;
  8119. }
  8120. if ($iserror || $iswarning) {
  8121. // Remove div from texts
  8122. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  8123. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  8124. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  8125. // Remove div from texts array
  8126. if (is_array($mesgarray)) {
  8127. $newmesgarray = array();
  8128. foreach ($mesgarray as $val) {
  8129. if (is_string($val)) {
  8130. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  8131. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  8132. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  8133. $newmesgarray[] = $tmpmesgstring;
  8134. } else {
  8135. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  8136. }
  8137. }
  8138. $mesgarray = $newmesgarray;
  8139. }
  8140. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  8141. } else {
  8142. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  8143. }
  8144. }
  8145. /**
  8146. * Print formated error messages to output (Used to show messages on html output).
  8147. *
  8148. * @param string $mesgstring Error message
  8149. * @param array $mesgarray Error messages array
  8150. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8151. * @return void
  8152. *
  8153. * @see dol_print_error()
  8154. * @see dol_htmloutput_mesg()
  8155. */
  8156. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8157. {
  8158. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8159. }
  8160. /**
  8161. * Advanced sort array by second index function, which produces ascending (default)
  8162. * or descending output and uses optionally natural case insensitive sorting (which
  8163. * can be optionally case sensitive as well).
  8164. *
  8165. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  8166. * @param string $index Key in array to use for sorting criteria
  8167. * @param int $order Sort order ('asc' or 'desc')
  8168. * @param int $natsort If values are strings (I said value not type): 0=Use alphabetical order, 1=use "natural" sort (natsort)
  8169. * 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
  8170. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  8171. * @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.
  8172. * @return array Sorted array
  8173. */
  8174. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  8175. {
  8176. // Clean parameters
  8177. $order = strtolower($order);
  8178. if (is_array($array)) {
  8179. $sizearray = count($array);
  8180. if ($sizearray > 0) {
  8181. $temp = array();
  8182. foreach (array_keys($array) as $key) {
  8183. if (is_object($array[$key])) {
  8184. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  8185. } else {
  8186. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  8187. }
  8188. if ($natsort == -1) {
  8189. $temp[$key] = '___'.$temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
  8190. }
  8191. }
  8192. if (empty($natsort) || $natsort == -1) {
  8193. if ($order == 'asc') {
  8194. asort($temp);
  8195. } else {
  8196. arsort($temp);
  8197. }
  8198. } else {
  8199. if ($case_sensitive) {
  8200. natsort($temp);
  8201. } else {
  8202. natcasesort($temp); // natecasesort is not sensible to case
  8203. }
  8204. if ($order != 'asc') {
  8205. $temp = array_reverse($temp, true);
  8206. }
  8207. }
  8208. $sorted = array();
  8209. foreach (array_keys($temp) as $key) {
  8210. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  8211. }
  8212. return $sorted;
  8213. }
  8214. }
  8215. return $array;
  8216. }
  8217. /**
  8218. * Check if a string is in UTF8
  8219. *
  8220. * @param string $str String to check
  8221. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  8222. * @see utf8_valid()
  8223. */
  8224. function utf8_check($str)
  8225. {
  8226. $str = (string) $str; // Sometimes string is an int.
  8227. // We must use here a binary strlen function (so not dol_strlen)
  8228. $strLength = dol_strlen($str);
  8229. for ($i = 0; $i < $strLength; $i++) {
  8230. if (ord($str[$i]) < 0x80) {
  8231. continue; // 0bbbbbbb
  8232. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  8233. $n = 1; // 110bbbbb
  8234. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  8235. $n = 2; // 1110bbbb
  8236. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  8237. $n = 3; // 11110bbb
  8238. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  8239. $n = 4; // 111110bb
  8240. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  8241. $n = 5; // 1111110b
  8242. } else {
  8243. return false; // Does not match any model
  8244. }
  8245. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  8246. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  8247. return false;
  8248. }
  8249. }
  8250. }
  8251. return true;
  8252. }
  8253. /**
  8254. * Check if a string is in UTF8
  8255. *
  8256. * @param string $str String to check
  8257. * @return boolean True if string is valid UTF8 string, false if corrupted
  8258. * @see utf8_check()
  8259. */
  8260. function utf8_valid($str)
  8261. {
  8262. /* 2 other methods to test if string is utf8
  8263. $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
  8264. $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
  8265. */
  8266. return preg_match('//u', $str) ? true : false;
  8267. }
  8268. /**
  8269. * Check if a string is in ASCII
  8270. *
  8271. * @param string $str String to check
  8272. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  8273. */
  8274. function ascii_check($str)
  8275. {
  8276. if (function_exists('mb_check_encoding')) {
  8277. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  8278. if (!mb_check_encoding($str, 'ASCII')) {
  8279. return false;
  8280. }
  8281. } else {
  8282. if (preg_match('/[^\x00-\x7f]/', $str)) {
  8283. return false; // Contains a byte > 7f
  8284. }
  8285. }
  8286. return true;
  8287. }
  8288. /**
  8289. * Return a string encoded into OS filesystem encoding. This function is used to define
  8290. * value to pass to filesystem PHP functions.
  8291. *
  8292. * @param string $str String to encode (UTF-8)
  8293. * @return string Encoded string (UTF-8, ISO-8859-1)
  8294. */
  8295. function dol_osencode($str)
  8296. {
  8297. global $conf;
  8298. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  8299. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  8300. $tmp = 'iso-8859-1'; // By default for windows
  8301. }
  8302. if (empty($tmp)) {
  8303. $tmp = 'utf-8'; // By default for other
  8304. }
  8305. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  8306. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  8307. }
  8308. if ($tmp == 'iso-8859-1') {
  8309. return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
  8310. }
  8311. return $str;
  8312. }
  8313. /**
  8314. * Return an id or code from a code or id.
  8315. * Store also Code-Id into a cache to speed up next request on same key.
  8316. *
  8317. * @param DoliDB $db Database handler
  8318. * @param string $key Code or Id to get Id or Code
  8319. * @param string $tablename Table name without prefix
  8320. * @param string $fieldkey Field to search the key into
  8321. * @param string $fieldid Field to get
  8322. * @param int $entityfilter Filter by entity
  8323. * @param string $filters Filters to add. WARNING: string must be escaped for SQL and not coming from user input.
  8324. * @return int <0 if KO, Id of code if OK
  8325. * @see $langs->getLabelFromKey
  8326. */
  8327. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '')
  8328. {
  8329. global $cache_codes;
  8330. // If key empty
  8331. if ($key == '') {
  8332. return '';
  8333. }
  8334. // Check in cache
  8335. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  8336. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  8337. }
  8338. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  8339. $sql = "SELECT ".$fieldid." as valuetoget";
  8340. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  8341. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  8342. if (!empty($entityfilter)) {
  8343. $sql .= " AND entity IN (".getEntity($tablename).")";
  8344. }
  8345. if ($filters) {
  8346. $sql .= $filters;
  8347. }
  8348. $resql = $db->query($sql);
  8349. if ($resql) {
  8350. $obj = $db->fetch_object($resql);
  8351. if ($obj) {
  8352. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  8353. } else {
  8354. $cache_codes[$tablename][$key][$fieldid] = '';
  8355. }
  8356. $db->free($resql);
  8357. return $cache_codes[$tablename][$key][$fieldid];
  8358. } else {
  8359. return -1;
  8360. }
  8361. }
  8362. /**
  8363. * Check if a variable with name $var start with $text.
  8364. * Can be used to forge dol_eval() conditions.
  8365. *
  8366. * @param $var string Variable
  8367. * @param $regextext string Text that must be a valid regex string
  8368. * @param $matchrule int 1=Test if start with, 0=Test if equal
  8369. * @return boolean|string True or False, text if bad use.
  8370. */
  8371. function isStringVarMatching($var, $regextext, $matchrule = 1)
  8372. {
  8373. if ($matchrule == 1) {
  8374. if ($var == 'mainmenu') {
  8375. global $mainmenu;
  8376. return (preg_match('/^'.$regextext.'/', $mainmenu));
  8377. } elseif ($var == 'leftmenu') {
  8378. global $leftmenu;
  8379. return (preg_match('/^'.$regextext.'/', $leftmenu));
  8380. } else {
  8381. return 'This variable is not accessible with dol_eval';
  8382. }
  8383. } else {
  8384. return 'This value for matchrule is not implemented';
  8385. }
  8386. }
  8387. /**
  8388. * Verify if condition in string is ok or not
  8389. *
  8390. * @param string $strToEvaluate String with condition to check
  8391. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  8392. */
  8393. function verifCond($strToEvaluate)
  8394. {
  8395. global $conf; // Read of const is done with getDolGlobalString() but we need $conf->currency for example
  8396. global $user, $langs;
  8397. global $leftmenu;
  8398. //print $strToEvaluate."<br>\n";
  8399. $rights = true;
  8400. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  8401. //var_dump($strToEvaluate);
  8402. $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
  8403. $rights = $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
  8404. //var_dump($rights);
  8405. }
  8406. return $rights;
  8407. }
  8408. /**
  8409. * Replace eval function to add more security.
  8410. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  8411. *
  8412. * @param string $s String to evaluate
  8413. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  8414. * @param int $hideerrors 1=Hide errors
  8415. * @param string $onlysimplestring '0' (deprecated, used for computed property of extrafields)=Accept all chars,
  8416. * '1' (most common use)=Accept only simple string with char 'a-z0-9\s^$_+-.*>&|=!?():"\',/@';',
  8417. * '2' (rarely used)=Accept also '[]'
  8418. * @return mixed Nothing or return result of eval
  8419. * @see verifCond()
  8420. */
  8421. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  8422. {
  8423. // Only this global variables can be read by eval function and returned to caller
  8424. global $conf; // Read of const is done with getDolGlobalString() but we need $conf->currency for example
  8425. global $db, $langs, $user, $website, $websitepage;
  8426. global $action, $mainmenu, $leftmenu;
  8427. global $mysoc;
  8428. global $objectoffield; // To allow the use of $objectoffield in computed fields
  8429. // Old variables used
  8430. global $object;
  8431. global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
  8432. //global $rights;
  8433. //global $soc; // For backward compatibility
  8434. if (!in_array($onlysimplestring, array('0', '1', '2'))) {
  8435. return "Bad call of dol_eval. Parameter onlysimplestring must be '0' (deprecated), '1' or '2'";
  8436. }
  8437. try {
  8438. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  8439. if ($onlysimplestring == '1') {
  8440. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && getDolGlobalString("MAIN_FEATURES_LEVEL")'
  8441. // We must accept: '$user->hasRight("cabinetmed", "read") && !$object->canvas=="patient@cabinetmed"'
  8442. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@', '/').']/i', $s)) {
  8443. if ($returnvalue) {
  8444. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8445. } else {
  8446. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8447. return '';
  8448. }
  8449. }
  8450. $scheck = preg_replace('/->[a-zA-Z0-9_]+\(/', '->__METHOD__', $s); // accept parenthesis in '...->method(...'
  8451. $scheck = preg_replace('/^\(/', '__PARENTHESIS__', $scheck); // accept parenthesis in '(...'
  8452. $scheck = preg_replace('/\s\(/', '__PARENTHESIS__', $scheck); // accept parenthesis in '... ('
  8453. $scheck = preg_replace('/^[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in 'function('
  8454. $scheck = preg_replace('/\s[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in '... function('
  8455. $scheck = preg_replace('/(\^|\')\(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
  8456. //print 'scheck='.$scheck." : ".strpos($scheck, '(')."\n";
  8457. if (strpos($scheck, '(') !== false) {
  8458. if ($returnvalue) {
  8459. return 'Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s;
  8460. } else {
  8461. dol_syslog('Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s);
  8462. return '';
  8463. }
  8464. }
  8465. // TODO
  8466. // We can exclude $ char that are not: $db, $langs, $leftmenu, $topmenu, $user, $langs, $objectoffield, $object...,
  8467. } elseif ($onlysimplestring == '2') {
  8468. // 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"
  8469. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@[]', '/').']/i', $s)) {
  8470. if ($returnvalue) {
  8471. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8472. } else {
  8473. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8474. return '';
  8475. }
  8476. }
  8477. $scheck = preg_replace('/->[a-zA-Z0-9_]+\(/', '->__METHOD__', $s); // accept parenthesis in '...->method(...'
  8478. $scheck = preg_replace('/^\(/', '__PARENTHESIS__', $scheck); // accept parenthesis in '(...'
  8479. $scheck = preg_replace('/\s\(/', '__PARENTHESIS__', $scheck); // accept parenthesis in '... ('
  8480. $scheck = preg_replace('/^[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in 'function('
  8481. $scheck = preg_replace('/\s[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in '... function('
  8482. $scheck = preg_replace('/(\^|\')\(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
  8483. //print 'scheck='.$scheck." : ".strpos($scheck, '(')."\n";
  8484. if (strpos($scheck, '(') !== false) {
  8485. if ($returnvalue) {
  8486. return 'Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s;
  8487. } else {
  8488. dol_syslog('Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s);
  8489. return '';
  8490. }
  8491. }
  8492. // TODO
  8493. // We can exclude $ char that are not: $db, $leftmenu, $topmenu, $user, $langs, $object...,
  8494. }
  8495. if (is_array($s) || $s === 'Array') {
  8496. return 'Bad string syntax to evaluate (value is Array) '.var_export($s, true);
  8497. }
  8498. if (strpos($s, '::') !== false) {
  8499. if ($returnvalue) {
  8500. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  8501. } else {
  8502. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  8503. return '';
  8504. }
  8505. }
  8506. if (strpos($s, '`') !== false) {
  8507. if ($returnvalue) {
  8508. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  8509. } else {
  8510. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  8511. return '';
  8512. }
  8513. }
  8514. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  8515. if ($returnvalue) {
  8516. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  8517. } else {
  8518. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  8519. return '';
  8520. }
  8521. }
  8522. // We block use of php exec or php file functions
  8523. $forbiddenphpstrings = array('$$');
  8524. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  8525. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen");
  8526. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "executeCLI", "verifCond")); // native dolibarr functions
  8527. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("base64_decode", "rawurldecode", "urldecode")); // decode string functions
  8528. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  8529. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
  8530. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  8531. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
  8532. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  8533. do {
  8534. $oldstringtoclean = $s;
  8535. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  8536. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  8537. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  8538. } while ($oldstringtoclean != $s);
  8539. if (strpos($s, '__forbiddenstring__') !== false) {
  8540. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  8541. if ($returnvalue) {
  8542. return 'Bad string syntax to evaluate: '.$s;
  8543. } else {
  8544. dol_syslog('Bad string syntax to evaluate: '.$s);
  8545. return '';
  8546. }
  8547. }
  8548. //print $s."<br>\n";
  8549. if ($returnvalue) {
  8550. if ($hideerrors) {
  8551. return @eval('return '.$s.';');
  8552. } else {
  8553. return eval('return '.$s.';');
  8554. }
  8555. } else {
  8556. if ($hideerrors) {
  8557. @eval($s);
  8558. } else {
  8559. eval($s);
  8560. }
  8561. }
  8562. } catch (Error $e) {
  8563. $error = 'dol_eval try/catch error : ';
  8564. $error .= $e->getMessage();
  8565. dol_syslog($error, LOG_WARNING);
  8566. }
  8567. }
  8568. /**
  8569. * Return if var element is ok
  8570. *
  8571. * @param string $element Variable to check
  8572. * @return boolean Return true of variable is not empty
  8573. * @see getElementProperties()
  8574. */
  8575. function dol_validElement($element)
  8576. {
  8577. return (trim($element) != '');
  8578. }
  8579. /**
  8580. * Return img flag of country for a language code or country code.
  8581. *
  8582. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  8583. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  8584. * @param int $notitlealt No title alt
  8585. * @return string HTML img string with flag.
  8586. */
  8587. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  8588. {
  8589. if (empty($codelang)) {
  8590. return '';
  8591. }
  8592. if ($codelang == 'auto') {
  8593. return '<span class="fa fa-language"></span>';
  8594. }
  8595. $langtocountryflag = array(
  8596. 'ar_AR' => '',
  8597. 'ca_ES' => 'catalonia',
  8598. 'da_DA' => 'dk',
  8599. 'fr_CA' => 'mq',
  8600. 'sv_SV' => 'se',
  8601. 'sw_SW' => 'unknown',
  8602. 'AQ' => 'unknown',
  8603. 'CW' => 'unknown',
  8604. 'IM' => 'unknown',
  8605. 'JE' => 'unknown',
  8606. 'MF' => 'unknown',
  8607. 'BL' => 'unknown',
  8608. 'SX' => 'unknown'
  8609. );
  8610. if (isset($langtocountryflag[$codelang])) {
  8611. $flagImage = $langtocountryflag[$codelang];
  8612. } else {
  8613. $tmparray = explode('_', $codelang);
  8614. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  8615. }
  8616. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  8617. }
  8618. /**
  8619. * Return default language from country code.
  8620. * Return null if not found.
  8621. *
  8622. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  8623. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  8624. */
  8625. function getLanguageCodeFromCountryCode($countrycode)
  8626. {
  8627. global $mysoc;
  8628. if (empty($countrycode)) {
  8629. return null;
  8630. }
  8631. if (strtoupper($countrycode) == 'MQ') {
  8632. return 'fr_CA';
  8633. }
  8634. if (strtoupper($countrycode) == 'SE') {
  8635. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  8636. }
  8637. if (strtoupper($countrycode) == 'CH') {
  8638. if ($mysoc->country_code == 'FR') {
  8639. return 'fr_CH';
  8640. }
  8641. if ($mysoc->country_code == 'DE') {
  8642. return 'de_CH';
  8643. }
  8644. if ($mysoc->country_code == 'IT') {
  8645. return 'it_CH';
  8646. }
  8647. }
  8648. // Locale list taken from:
  8649. // http://stackoverflow.com/questions/3191664/
  8650. // list-of-all-locales-and-their-short-codes
  8651. $locales = array(
  8652. 'af-ZA',
  8653. 'am-ET',
  8654. 'ar-AE',
  8655. 'ar-BH',
  8656. 'ar-DZ',
  8657. 'ar-EG',
  8658. 'ar-IQ',
  8659. 'ar-JO',
  8660. 'ar-KW',
  8661. 'ar-LB',
  8662. 'ar-LY',
  8663. 'ar-MA',
  8664. 'ar-OM',
  8665. 'ar-QA',
  8666. 'ar-SA',
  8667. 'ar-SY',
  8668. 'ar-TN',
  8669. 'ar-YE',
  8670. //'as-IN', // Moved after en-IN
  8671. 'ba-RU',
  8672. 'be-BY',
  8673. 'bg-BG',
  8674. 'bn-BD',
  8675. //'bn-IN', // Moved after en-IN
  8676. 'bo-CN',
  8677. 'br-FR',
  8678. 'ca-ES',
  8679. 'co-FR',
  8680. 'cs-CZ',
  8681. 'cy-GB',
  8682. 'da-DK',
  8683. 'de-AT',
  8684. 'de-CH',
  8685. 'de-DE',
  8686. 'de-LI',
  8687. 'de-LU',
  8688. 'dv-MV',
  8689. 'el-GR',
  8690. 'en-AU',
  8691. 'en-BZ',
  8692. 'en-CA',
  8693. 'en-GB',
  8694. 'en-IE',
  8695. 'en-IN',
  8696. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  8697. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  8698. 'en-JM',
  8699. 'en-MY',
  8700. 'en-NZ',
  8701. 'en-PH',
  8702. 'en-SG',
  8703. 'en-TT',
  8704. 'en-US',
  8705. 'en-ZA',
  8706. 'en-ZW',
  8707. 'es-AR',
  8708. 'es-BO',
  8709. 'es-CL',
  8710. 'es-CO',
  8711. 'es-CR',
  8712. 'es-DO',
  8713. 'es-EC',
  8714. 'es-ES',
  8715. 'es-GT',
  8716. 'es-HN',
  8717. 'es-MX',
  8718. 'es-NI',
  8719. 'es-PA',
  8720. 'es-PE',
  8721. 'es-PR',
  8722. 'es-PY',
  8723. 'es-SV',
  8724. 'es-US',
  8725. 'es-UY',
  8726. 'es-VE',
  8727. 'et-EE',
  8728. 'eu-ES',
  8729. 'fa-IR',
  8730. 'fi-FI',
  8731. 'fo-FO',
  8732. 'fr-BE',
  8733. 'fr-CA',
  8734. 'fr-CH',
  8735. 'fr-FR',
  8736. 'fr-LU',
  8737. 'fr-MC',
  8738. 'fy-NL',
  8739. 'ga-IE',
  8740. 'gd-GB',
  8741. 'gl-ES',
  8742. 'gu-IN',
  8743. 'he-IL',
  8744. 'hi-IN',
  8745. 'hr-BA',
  8746. 'hr-HR',
  8747. 'hu-HU',
  8748. 'hy-AM',
  8749. 'id-ID',
  8750. 'ig-NG',
  8751. 'ii-CN',
  8752. 'is-IS',
  8753. 'it-CH',
  8754. 'it-IT',
  8755. 'ja-JP',
  8756. 'ka-GE',
  8757. 'kk-KZ',
  8758. 'kl-GL',
  8759. 'km-KH',
  8760. 'kn-IN',
  8761. 'ko-KR',
  8762. 'ky-KG',
  8763. 'lb-LU',
  8764. 'lo-LA',
  8765. 'lt-LT',
  8766. 'lv-LV',
  8767. 'mi-NZ',
  8768. 'mk-MK',
  8769. 'ml-IN',
  8770. 'mn-MN',
  8771. 'mr-IN',
  8772. 'ms-BN',
  8773. 'ms-MY',
  8774. 'mt-MT',
  8775. 'nb-NO',
  8776. 'ne-NP',
  8777. 'nl-BE',
  8778. 'nl-NL',
  8779. 'nn-NO',
  8780. 'oc-FR',
  8781. 'or-IN',
  8782. 'pa-IN',
  8783. 'pl-PL',
  8784. 'ps-AF',
  8785. 'pt-BR',
  8786. 'pt-PT',
  8787. 'rm-CH',
  8788. 'ro-MD',
  8789. 'ro-RO',
  8790. 'ru-RU',
  8791. 'rw-RW',
  8792. 'sa-IN',
  8793. 'se-FI',
  8794. 'se-NO',
  8795. 'se-SE',
  8796. 'si-LK',
  8797. 'sk-SK',
  8798. 'sl-SI',
  8799. 'sq-AL',
  8800. 'sv-FI',
  8801. 'sv-SE',
  8802. 'sw-KE',
  8803. 'ta-IN',
  8804. 'te-IN',
  8805. 'th-TH',
  8806. 'tk-TM',
  8807. 'tn-ZA',
  8808. 'tr-TR',
  8809. 'tt-RU',
  8810. 'ug-CN',
  8811. 'uk-UA',
  8812. 'ur-PK',
  8813. 'vi-VN',
  8814. 'wo-SN',
  8815. 'xh-ZA',
  8816. 'yo-NG',
  8817. 'zh-CN',
  8818. 'zh-HK',
  8819. 'zh-MO',
  8820. 'zh-SG',
  8821. 'zh-TW',
  8822. 'zu-ZA',
  8823. );
  8824. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  8825. if (in_array($buildprimarykeytotest, $locales)) {
  8826. return strtolower($countrycode).'_'.strtoupper($countrycode);
  8827. }
  8828. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  8829. foreach ($locales as $locale) {
  8830. $locale_language = locale_get_primary_language($locale);
  8831. $locale_region = locale_get_region($locale);
  8832. if (strtoupper($countrycode) == $locale_region) {
  8833. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  8834. return strtolower($locale_language).'_'.strtoupper($locale_region);
  8835. }
  8836. }
  8837. } else {
  8838. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  8839. }
  8840. return null;
  8841. }
  8842. /**
  8843. * Complete or removed entries into a head array (used to build tabs).
  8844. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  8845. * Or by change using hook completeTabsHead
  8846. *
  8847. * @param Conf $conf Object conf
  8848. * @param Translate $langs Object langs
  8849. * @param object|null $object Object object
  8850. * @param array $head Object head
  8851. * @param int $h New position to fill
  8852. * @param string $type Value for object where objectvalue can be
  8853. * 'thirdparty' to add a tab in third party view
  8854. * 'intervention' to add a tab in intervention view
  8855. * 'supplier_order' to add a tab in purchase order view
  8856. * 'supplier_invoice' to add a tab in purchase invoice view
  8857. * 'invoice' to add a tab in sales invoice view
  8858. * 'order' to add a tab in sales order view
  8859. * 'contract' to add a tabl in contract view
  8860. * 'product' to add a tab in product view
  8861. * 'propal' to add a tab in propal view
  8862. * 'user' to add a tab in user view
  8863. * 'group' to add a tab in group view
  8864. * 'member' to add a tab in fundation member view
  8865. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  8866. * 'ecm' to add a tab for another ecm view
  8867. * 'stock' to add a tab for warehouse view
  8868. * @param string $mode 'add' to complete head, 'remove' to remove entries
  8869. * @param string $filterorigmodule Filter on module origin: 'external' will show only external modules. 'core' only core modules. No filter (default) will add both.
  8870. * @return void
  8871. */
  8872. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
  8873. {
  8874. global $hookmanager, $db;
  8875. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  8876. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  8877. $values = explode(':', $value);
  8878. $reg = array();
  8879. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  8880. if (count($values) == 6) {
  8881. // new declaration with permissions:
  8882. // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8883. // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8884. if ($values[0] != $type) {
  8885. continue;
  8886. }
  8887. if (verifCond($values[4])) {
  8888. if ($values[3]) {
  8889. if ($filterorigmodule) { // If a filter of module origin has been requested
  8890. if (strpos($values[3], '@')) { // This is an external module
  8891. if ($filterorigmodule != 'external') {
  8892. continue;
  8893. }
  8894. } else { // This looks a core module
  8895. if ($filterorigmodule != 'core') {
  8896. continue;
  8897. }
  8898. }
  8899. }
  8900. $langs->load($values[3]);
  8901. }
  8902. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8903. // If label is "SUBSTITUION_..."
  8904. $substitutionarray = array();
  8905. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8906. $label = make_substitutions($reg[1], $substitutionarray);
  8907. } else {
  8908. // If label is "Label,Class,File,Method", we call the method to show content inside the badge
  8909. $labeltemp = explode(',', $values[2]);
  8910. $label = $langs->trans($labeltemp[0]);
  8911. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  8912. dol_include_once($labeltemp[2]);
  8913. $classtoload = $labeltemp[1];
  8914. if (class_exists($classtoload)) {
  8915. $obj = new $classtoload($db);
  8916. $function = $labeltemp[3];
  8917. if ($obj && $function && method_exists($obj, $function)) {
  8918. $nbrec = $obj->$function($object->id, $obj);
  8919. if (!empty($nbrec)) {
  8920. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  8921. }
  8922. }
  8923. }
  8924. }
  8925. }
  8926. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  8927. $head[$h][1] = $label;
  8928. $head[$h][2] = str_replace('+', '', $values[1]);
  8929. $h++;
  8930. }
  8931. } elseif (count($values) == 5) { // case deprecated
  8932. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  8933. if ($values[0] != $type) {
  8934. continue;
  8935. }
  8936. if ($values[3]) {
  8937. if ($filterorigmodule) { // If a filter of module origin has been requested
  8938. if (strpos($values[3], '@')) { // This is an external module
  8939. if ($filterorigmodule != 'external') {
  8940. continue;
  8941. }
  8942. } else { // This looks a core module
  8943. if ($filterorigmodule != 'core') {
  8944. continue;
  8945. }
  8946. }
  8947. }
  8948. $langs->load($values[3]);
  8949. }
  8950. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8951. $substitutionarray = array();
  8952. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8953. $label = make_substitutions($reg[1], $substitutionarray);
  8954. } else {
  8955. $label = $langs->trans($values[2]);
  8956. }
  8957. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  8958. $head[$h][1] = $label;
  8959. $head[$h][2] = str_replace('+', '', $values[1]);
  8960. $h++;
  8961. }
  8962. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  8963. if ($values[0] != $type) {
  8964. continue;
  8965. }
  8966. $tabname = str_replace('-', '', $values[1]);
  8967. foreach ($head as $key => $val) {
  8968. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  8969. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  8970. if ($head[$key][2] == $tabname && $condition) {
  8971. unset($head[$key]);
  8972. break;
  8973. }
  8974. }
  8975. }
  8976. }
  8977. }
  8978. // No need to make a return $head. Var is modified as a reference
  8979. if (!empty($hookmanager)) {
  8980. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
  8981. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters, $object);
  8982. if ($reshook > 0) { // Hook ask to replace completely the array
  8983. $head = $hookmanager->resArray;
  8984. } else { // Hook
  8985. $head = array_merge($head, $hookmanager->resArray);
  8986. }
  8987. $h = count($head);
  8988. }
  8989. }
  8990. /**
  8991. * Print common footer :
  8992. * conf->global->MAIN_HTML_FOOTER
  8993. * js for switch of menu hider
  8994. * js for conf->global->MAIN_GOOGLE_AN_ID
  8995. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  8996. * js for conf->logbuffer
  8997. *
  8998. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  8999. * @return void
  9000. */
  9001. function printCommonFooter($zone = 'private')
  9002. {
  9003. global $conf, $hookmanager, $user, $debugbar;
  9004. global $action;
  9005. global $micro_start_time;
  9006. if ($zone == 'private') {
  9007. print "\n".'<!-- Common footer for private page -->'."\n";
  9008. } else {
  9009. print "\n".'<!-- Common footer for public page -->'."\n";
  9010. }
  9011. // A div to store page_y POST parameter so we can read it using javascript
  9012. print "\n<!-- A div to store page_y POST parameter -->\n";
  9013. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  9014. $parameters = array();
  9015. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  9016. if (empty($reshook)) {
  9017. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  9018. print $conf->global->MAIN_HTML_FOOTER."\n";
  9019. }
  9020. print "\n";
  9021. if (!empty($conf->use_javascript_ajax)) {
  9022. print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and madatory fields, tuning info, ... -->\n";
  9023. print '<script>'."\n";
  9024. print 'jQuery(document).ready(function() {'."\n";
  9025. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  9026. print "\n";
  9027. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  9028. print 'jQuery("li.menuhider").click(function(event) {';
  9029. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  9030. print ' console.log("We click on .menuhider");'."\n";
  9031. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  9032. print '});'."\n";
  9033. }
  9034. // Management of focus and mandatory for fields
  9035. 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"])))) {
  9036. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  9037. $relativepathstring = $_SERVER["PHP_SELF"];
  9038. // Clean $relativepathstring
  9039. if (constant('DOL_URL_ROOT')) {
  9040. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  9041. }
  9042. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  9043. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  9044. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  9045. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  9046. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  9047. $qualified = 0;
  9048. if ($defkey != '_noquery_') {
  9049. $tmpqueryarraytohave = explode('&', $defkey);
  9050. $foundintru = 0;
  9051. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  9052. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  9053. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  9054. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  9055. $foundintru = 1;
  9056. }
  9057. }
  9058. if (!$foundintru) {
  9059. $qualified = 1;
  9060. }
  9061. //var_dump($defkey.'-'.$qualified);
  9062. } else {
  9063. $qualified = 1;
  9064. }
  9065. if ($qualified) {
  9066. foreach ($defval as $paramkey => $paramval) {
  9067. // Set focus on field
  9068. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  9069. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  9070. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  9071. }
  9072. }
  9073. }
  9074. }
  9075. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  9076. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  9077. $qualified = 0;
  9078. if ($defkey != '_noquery_') {
  9079. $tmpqueryarraytohave = explode('&', $defkey);
  9080. $foundintru = 0;
  9081. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  9082. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  9083. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  9084. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  9085. $foundintru = 1;
  9086. }
  9087. }
  9088. if (!$foundintru) {
  9089. $qualified = 1;
  9090. }
  9091. //var_dump($defkey.'-'.$qualified);
  9092. } else {
  9093. $qualified = 1;
  9094. }
  9095. if ($qualified) {
  9096. foreach ($defval as $paramkey => $paramval) {
  9097. // Add property 'required' on input
  9098. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9099. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9100. 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";
  9101. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9102. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  9103. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  9104. // Add 'field required' class on closest td for all input elements : input, textarea and select
  9105. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  9106. }
  9107. // If we submit the cancel button we remove the required attributes
  9108. print 'jQuery("input[name=\'cancel\']").click(function() {
  9109. console.log("We click on cancel button so removed all required attribute");
  9110. jQuery("input, textarea, select").each(function(){this.removeAttribute(\'required\');});
  9111. });'."\n";
  9112. }
  9113. }
  9114. }
  9115. }
  9116. print '});'."\n";
  9117. // End of tuning
  9118. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  9119. print "\n";
  9120. print "/* JS CODE TO ENABLE to add memory info */\n";
  9121. print 'window.console && console.log("';
  9122. if (!empty($conf->global->MEMCACHED_SERVER)) {
  9123. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  9124. }
  9125. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  9126. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  9127. $micro_end_time = microtime(true);
  9128. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  9129. }
  9130. if (function_exists("memory_get_usage")) {
  9131. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  9132. }
  9133. if (function_exists("memory_get_peak_usage")) {
  9134. print ' - Real mem peak: '.memory_get_peak_usage(true);
  9135. }
  9136. if (function_exists("zend_loader_file_encoded")) {
  9137. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  9138. }
  9139. print '");'."\n";
  9140. }
  9141. print "\n".'</script>'."\n";
  9142. // Google Analytics
  9143. // TODO Add a hook here
  9144. if (isModEnabled('google') && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  9145. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  9146. foreach ($tmptagarray as $tmptag) {
  9147. print "\n";
  9148. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  9149. print '
  9150. <!-- Global site tag (gtag.js) - Google Analytics -->
  9151. <script nonce="'.getNonce().'" async src="https://www.googletagmanager.com/gtag/js?id='.trim($tmptag).'"></script>
  9152. <script>
  9153. window.dataLayer = window.dataLayer || [];
  9154. function gtag(){dataLayer.push(arguments);}
  9155. gtag(\'js\', new Date());
  9156. gtag(\'config\', \''.trim($tmptag).'\');
  9157. </script>';
  9158. print "\n";
  9159. }
  9160. }
  9161. }
  9162. // Add Xdebug coverage of code
  9163. if (defined('XDEBUGCOVERAGE')) {
  9164. print_r(xdebug_get_code_coverage());
  9165. }
  9166. // Add DebugBar data
  9167. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  9168. $debugbar['time']->stopMeasure('pageaftermaster');
  9169. print '<!-- Output debugbar data -->'."\n";
  9170. $renderer = $debugbar->getRenderer();
  9171. print $debugbar->getRenderer()->render();
  9172. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  9173. print "\n";
  9174. print "<!-- Start of log output\n";
  9175. //print '<div class="hidden">'."\n";
  9176. foreach ($conf->logbuffer as $logline) {
  9177. print $logline."<br>\n";
  9178. }
  9179. //print '</div>'."\n";
  9180. print "End of log output -->\n";
  9181. }
  9182. }
  9183. }
  9184. /**
  9185. * Split a string with 2 keys into key array.
  9186. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  9187. *
  9188. * @param string|null $string String to explode
  9189. * @param string $delimiter Delimiter between each couple of data. Example: ';' or '[\n;]+' or '(\n\r|\r|\n|;)'
  9190. * @param string $kv Delimiter between key and value
  9191. * @return array Array of data exploded
  9192. */
  9193. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  9194. {
  9195. if (is_null($string)) {
  9196. return array();
  9197. }
  9198. if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\(.*\)$/sm', $delimiter)) {
  9199. // This is a regex string
  9200. $newdelimiter = $delimiter;
  9201. } else {
  9202. // This is a simple string
  9203. $newdelimiter = preg_quote($delimiter, '/');
  9204. }
  9205. if ($a = preg_split('/'.$newdelimiter.'/', $string)) {
  9206. $ka = array();
  9207. foreach ($a as $s) { // each part
  9208. if ($s) {
  9209. if ($pos = strpos($s, $kv)) { // key/value delimiter
  9210. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  9211. } else { // key delimiter not found
  9212. $ka[] = trim($s);
  9213. }
  9214. }
  9215. }
  9216. return $ka;
  9217. }
  9218. return array();
  9219. }
  9220. /**
  9221. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  9222. *
  9223. * @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.
  9224. * @return void
  9225. */
  9226. function dol_set_focus($selector)
  9227. {
  9228. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  9229. print '<script nonce="'.getNonce().'">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  9230. }
  9231. /**
  9232. * Return getmypid() or random PID when function is disabled
  9233. * Some web hosts disable this php function for security reasons
  9234. * and sometimes we can't redeclare function.
  9235. *
  9236. * @return int
  9237. */
  9238. function dol_getmypid()
  9239. {
  9240. if (!function_exists('getmypid')) {
  9241. return mt_rand(99900000, 99965535);
  9242. } else {
  9243. return getmypid(); // May be a number on 64 bits (depending on OS)
  9244. }
  9245. }
  9246. /**
  9247. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  9248. *
  9249. * @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")
  9250. * @param string $value The value to look for.
  9251. * If param $mode is 0, can contains several keywords separated with a space or |
  9252. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  9253. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  9254. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < -1000"
  9255. * If param $mode is 2 or -2, can contains a list of int id separated by comma like "1,3,4"
  9256. * If param $mode is 3 or -3, can contains a list of string separated by comma like "a,b,c".
  9257. * @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,
  9258. * 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'
  9259. * @param integer $nofirstand 1=Do not output the first 'AND'
  9260. * @return string $res The statement to append to the SQL query
  9261. * @see dolSqlDateFilter()
  9262. */
  9263. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  9264. {
  9265. global $db, $langs;
  9266. $value = trim($value);
  9267. if ($mode == 0) {
  9268. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  9269. }
  9270. if ($mode == 1) {
  9271. $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
  9272. }
  9273. $value = preg_replace('/\s*\|\s*/', '|', $value);
  9274. $crits = explode(' ', $value);
  9275. $res = '';
  9276. if (!is_array($fields)) {
  9277. $fields = array($fields);
  9278. }
  9279. $i1 = 0; // count the nb of and criteria added (all fields / criterias)
  9280. foreach ($crits as $crit) { // Loop on each AND criteria
  9281. $crit = trim($crit);
  9282. $i2 = 0; // count the nb of valid criteria added for this this first criteria
  9283. $newres = '';
  9284. foreach ($fields as $field) {
  9285. if ($mode == 1) {
  9286. $tmpcrits = explode('|', $crit);
  9287. $i3 = 0; // count the nb of valid criteria added for this current field
  9288. foreach ($tmpcrits as $tmpcrit) {
  9289. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9290. continue;
  9291. }
  9292. $tmpcrit = trim($tmpcrit);
  9293. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9294. $operator = '=';
  9295. $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
  9296. $reg = array();
  9297. preg_match('/([!<>=]+)/', $tmpcrit, $reg);
  9298. if (!empty($reg[1])) {
  9299. $operator = $reg[1];
  9300. }
  9301. if ($newcrit != '') {
  9302. $numnewcrit = price2num($newcrit);
  9303. if (is_numeric($numnewcrit)) {
  9304. $newres .= $field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  9305. } else {
  9306. $newres .= '1 = 2'; // force false, we received a corrupted data
  9307. }
  9308. $i3++; // a criteria was added to string
  9309. }
  9310. }
  9311. $i2++; // a criteria for 1 more field was added to string
  9312. } elseif ($mode == 2 || $mode == -2) {
  9313. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  9314. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  9315. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  9316. if ($mode == -2) {
  9317. $newres .= ' OR '.$field.' IS NULL';
  9318. }
  9319. $i2++; // a criteria for 1 more field was added to string
  9320. } elseif ($mode == 3 || $mode == -3) {
  9321. $tmparray = explode(',', $crit);
  9322. if (count($tmparray)) {
  9323. $listofcodes = '';
  9324. foreach ($tmparray as $val) {
  9325. $val = trim($val);
  9326. if ($val) {
  9327. $listofcodes .= ($listofcodes ? ',' : '');
  9328. $listofcodes .= "'".$db->escape($val)."'";
  9329. }
  9330. }
  9331. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  9332. $i2++; // a criteria for 1 more field was added to string
  9333. }
  9334. if ($mode == -3) {
  9335. $newres .= ' OR '.$field.' IS NULL';
  9336. }
  9337. } elseif ($mode == 4) {
  9338. $tmparray = explode(',', $crit);
  9339. if (count($tmparray)) {
  9340. $listofcodes = '';
  9341. foreach ($tmparray as $val) {
  9342. $val = trim($val);
  9343. if ($val) {
  9344. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  9345. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  9346. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  9347. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  9348. $newres .= ')';
  9349. $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)
  9350. }
  9351. }
  9352. }
  9353. } else { // $mode=0
  9354. $tmpcrits = explode('|', $crit);
  9355. $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
  9356. foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
  9357. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9358. continue;
  9359. }
  9360. $tmpcrit = trim($tmpcrit);
  9361. if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
  9362. $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
  9363. } else {
  9364. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9365. }
  9366. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  9367. $newres .= $field." = ".(is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
  9368. } else {
  9369. $tmpcrit2 = $tmpcrit;
  9370. $tmpbefore = '%';
  9371. $tmpafter = '%';
  9372. $tmps = '';
  9373. if (preg_match('/^!/', $tmpcrit)) {
  9374. $tmps .= $field." NOT LIKE "; // ! as exclude character
  9375. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  9376. } else {
  9377. $tmps .= $field." LIKE ";
  9378. }
  9379. $tmps .= "'";
  9380. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  9381. $tmpbefore = '';
  9382. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  9383. }
  9384. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  9385. $tmpafter = '';
  9386. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  9387. }
  9388. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9389. $tmps = "(".$tmps;
  9390. }
  9391. $newres .= $tmps;
  9392. $newres .= $tmpbefore;
  9393. $newres .= $db->escape($tmpcrit2);
  9394. $newres .= $tmpafter;
  9395. $newres .= "'";
  9396. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9397. $newres .= " OR ".$field." IS NULL)";
  9398. }
  9399. }
  9400. $i3++;
  9401. }
  9402. $i2++; // a criteria for 1 more field was added to string
  9403. }
  9404. }
  9405. if ($newres) {
  9406. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  9407. }
  9408. $i1++;
  9409. }
  9410. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  9411. return $res;
  9412. }
  9413. /**
  9414. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  9415. *
  9416. * @param Object $object Object
  9417. * @return string Url string
  9418. */
  9419. function showDirectDownloadLink($object)
  9420. {
  9421. global $conf, $langs;
  9422. $out = '';
  9423. $url = $object->getLastMainDocLink($object->element);
  9424. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  9425. if ($url) {
  9426. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  9427. $out .= ajax_autoselect("directdownloadlink", 0);
  9428. } else {
  9429. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  9430. }
  9431. return $out;
  9432. }
  9433. /**
  9434. * Return the filename of file to get the thumbs
  9435. *
  9436. * @param string $file Original filename (full or relative path)
  9437. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  9438. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  9439. * @return string New file name (full or relative path, including the thumbs/). May be the original path if no thumb can exists.
  9440. */
  9441. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  9442. {
  9443. $dirName = dirname($file);
  9444. if ($dirName == '.') {
  9445. $dirName = '';
  9446. }
  9447. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  9448. $fileName = basename($fileName);
  9449. if (empty($extImgTarget)) {
  9450. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  9451. }
  9452. if (empty($extImgTarget)) {
  9453. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  9454. }
  9455. if (empty($extImgTarget)) {
  9456. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  9457. }
  9458. if (empty($extImgTarget)) {
  9459. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  9460. }
  9461. if (empty($extImgTarget)) {
  9462. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  9463. }
  9464. if (empty($extImgTarget)) {
  9465. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  9466. }
  9467. if (!$extImgTarget) {
  9468. return $file;
  9469. }
  9470. $subdir = '';
  9471. if ($extName) {
  9472. $subdir = 'thumbs/';
  9473. }
  9474. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  9475. }
  9476. /**
  9477. * Return URL we can use for advanced preview links
  9478. *
  9479. * @param string $modulepart propal, facture, facture_fourn, ...
  9480. * @param string $relativepath Relative path of docs.
  9481. * @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)
  9482. * @param string $param More param on http links
  9483. * @return string|array Output string with href link or array with all components of link
  9484. */
  9485. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  9486. {
  9487. global $conf, $langs;
  9488. if (empty($conf->use_javascript_ajax)) {
  9489. return '';
  9490. }
  9491. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  9492. if ($alldata == 1) {
  9493. if ($isAllowedForPreview) {
  9494. 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));
  9495. } else {
  9496. return array();
  9497. }
  9498. }
  9499. // old behavior, return a string
  9500. if ($isAllowedForPreview) {
  9501. 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')).'\')';
  9502. } else {
  9503. return '';
  9504. }
  9505. }
  9506. /**
  9507. * Make content of an input box selected when we click into input field.
  9508. *
  9509. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  9510. * @param string $addlink Add a 'link to' after
  9511. * @param string $textonlink Text to show on link or 'image'
  9512. * @return string
  9513. */
  9514. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  9515. {
  9516. global $langs;
  9517. $out = '<script nonce="'.getNonce().'">
  9518. jQuery(document).ready(function () {
  9519. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  9520. });
  9521. </script>';
  9522. if ($addlink) {
  9523. if ($textonlink === 'image') {
  9524. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  9525. } else {
  9526. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  9527. }
  9528. }
  9529. return $out;
  9530. }
  9531. /**
  9532. * Return if a file is qualified for preview
  9533. *
  9534. * @param string $file Filename we looking for information
  9535. * @return int 1 If allowed, 0 otherwise
  9536. * @see dol_mimetype(), image_format_supported() from images.lib.php
  9537. */
  9538. function dolIsAllowedForPreview($file)
  9539. {
  9540. global $conf;
  9541. // Check .noexe extension in filename
  9542. if (preg_match('/\.noexe$/i', $file)) {
  9543. return 0;
  9544. }
  9545. // Check mime types
  9546. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  9547. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  9548. $mime_preview[] = 'svg+xml';
  9549. }
  9550. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  9551. //$mime_preview[]='archive';
  9552. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  9553. if ($num_mime !== false) {
  9554. return 1;
  9555. }
  9556. // By default, not allowed for preview
  9557. return 0;
  9558. }
  9559. /**
  9560. * Return MIME type of a file from its name with extension.
  9561. *
  9562. * @param string $file Filename we looking for MIME type
  9563. * @param string $default Default mime type if extension not found in known list
  9564. * @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
  9565. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  9566. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  9567. */
  9568. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  9569. {
  9570. $mime = $default;
  9571. $imgmime = 'other.png';
  9572. $famime = 'file-o';
  9573. $srclang = '';
  9574. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  9575. // Plain text files
  9576. if (preg_match('/\.txt$/i', $tmpfile)) {
  9577. $mime = 'text/plain';
  9578. $imgmime = 'text.png';
  9579. $famime = 'file-text-o';
  9580. }
  9581. if (preg_match('/\.rtx$/i', $tmpfile)) {
  9582. $mime = 'text/richtext';
  9583. $imgmime = 'text.png';
  9584. $famime = 'file-text-o';
  9585. }
  9586. if (preg_match('/\.csv$/i', $tmpfile)) {
  9587. $mime = 'text/csv';
  9588. $imgmime = 'text.png';
  9589. $famime = 'file-text-o';
  9590. }
  9591. if (preg_match('/\.tsv$/i', $tmpfile)) {
  9592. $mime = 'text/tab-separated-values';
  9593. $imgmime = 'text.png';
  9594. $famime = 'file-text-o';
  9595. }
  9596. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  9597. $mime = 'text/plain';
  9598. $imgmime = 'text.png';
  9599. $famime = 'file-text-o';
  9600. }
  9601. if (preg_match('/\.ini$/i', $tmpfile)) {
  9602. $mime = 'text/plain';
  9603. $imgmime = 'text.png';
  9604. $srclang = 'ini';
  9605. $famime = 'file-text-o';
  9606. }
  9607. if (preg_match('/\.md$/i', $tmpfile)) {
  9608. $mime = 'text/plain';
  9609. $imgmime = 'text.png';
  9610. $srclang = 'md';
  9611. $famime = 'file-text-o';
  9612. }
  9613. if (preg_match('/\.css$/i', $tmpfile)) {
  9614. $mime = 'text/css';
  9615. $imgmime = 'css.png';
  9616. $srclang = 'css';
  9617. $famime = 'file-text-o';
  9618. }
  9619. if (preg_match('/\.lang$/i', $tmpfile)) {
  9620. $mime = 'text/plain';
  9621. $imgmime = 'text.png';
  9622. $srclang = 'lang';
  9623. $famime = 'file-text-o';
  9624. }
  9625. // Certificate files
  9626. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  9627. $mime = 'text/plain';
  9628. $imgmime = 'text.png';
  9629. $famime = 'file-text-o';
  9630. }
  9631. // XML based (HTML/XML/XAML)
  9632. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  9633. $mime = 'text/html';
  9634. $imgmime = 'html.png';
  9635. $srclang = 'html';
  9636. $famime = 'file-text-o';
  9637. }
  9638. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  9639. $mime = 'text/xml';
  9640. $imgmime = 'other.png';
  9641. $srclang = 'xml';
  9642. $famime = 'file-text-o';
  9643. }
  9644. if (preg_match('/\.xaml$/i', $tmpfile)) {
  9645. $mime = 'text/xml';
  9646. $imgmime = 'other.png';
  9647. $srclang = 'xaml';
  9648. $famime = 'file-text-o';
  9649. }
  9650. // Languages
  9651. if (preg_match('/\.bas$/i', $tmpfile)) {
  9652. $mime = 'text/plain';
  9653. $imgmime = 'text.png';
  9654. $srclang = 'bas';
  9655. $famime = 'file-code-o';
  9656. }
  9657. if (preg_match('/\.(c)$/i', $tmpfile)) {
  9658. $mime = 'text/plain';
  9659. $imgmime = 'text.png';
  9660. $srclang = 'c';
  9661. $famime = 'file-code-o';
  9662. }
  9663. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  9664. $mime = 'text/plain';
  9665. $imgmime = 'text.png';
  9666. $srclang = 'cpp';
  9667. $famime = 'file-code-o';
  9668. }
  9669. if (preg_match('/\.cs$/i', $tmpfile)) {
  9670. $mime = 'text/plain';
  9671. $imgmime = 'text.png';
  9672. $srclang = 'cs';
  9673. $famime = 'file-code-o';
  9674. }
  9675. if (preg_match('/\.(h)$/i', $tmpfile)) {
  9676. $mime = 'text/plain';
  9677. $imgmime = 'text.png';
  9678. $srclang = 'h';
  9679. $famime = 'file-code-o';
  9680. }
  9681. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  9682. $mime = 'text/plain';
  9683. $imgmime = 'text.png';
  9684. $srclang = 'java';
  9685. $famime = 'file-code-o';
  9686. }
  9687. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  9688. $mime = 'text/plain';
  9689. $imgmime = 'php.png';
  9690. $srclang = 'php';
  9691. $famime = 'file-code-o';
  9692. }
  9693. if (preg_match('/\.phtml$/i', $tmpfile)) {
  9694. $mime = 'text/plain';
  9695. $imgmime = 'php.png';
  9696. $srclang = 'php';
  9697. $famime = 'file-code-o';
  9698. }
  9699. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  9700. $mime = 'text/plain';
  9701. $imgmime = 'pl.png';
  9702. $srclang = 'perl';
  9703. $famime = 'file-code-o';
  9704. }
  9705. if (preg_match('/\.sql$/i', $tmpfile)) {
  9706. $mime = 'text/plain';
  9707. $imgmime = 'text.png';
  9708. $srclang = 'sql';
  9709. $famime = 'file-code-o';
  9710. }
  9711. if (preg_match('/\.js$/i', $tmpfile)) {
  9712. $mime = 'text/x-javascript';
  9713. $imgmime = 'jscript.png';
  9714. $srclang = 'js';
  9715. $famime = 'file-code-o';
  9716. }
  9717. // Open office
  9718. if (preg_match('/\.odp$/i', $tmpfile)) {
  9719. $mime = 'application/vnd.oasis.opendocument.presentation';
  9720. $imgmime = 'ooffice.png';
  9721. $famime = 'file-powerpoint-o';
  9722. }
  9723. if (preg_match('/\.ods$/i', $tmpfile)) {
  9724. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  9725. $imgmime = 'ooffice.png';
  9726. $famime = 'file-excel-o';
  9727. }
  9728. if (preg_match('/\.odt$/i', $tmpfile)) {
  9729. $mime = 'application/vnd.oasis.opendocument.text';
  9730. $imgmime = 'ooffice.png';
  9731. $famime = 'file-word-o';
  9732. }
  9733. // MS Office
  9734. if (preg_match('/\.mdb$/i', $tmpfile)) {
  9735. $mime = 'application/msaccess';
  9736. $imgmime = 'mdb.png';
  9737. $famime = 'file-o';
  9738. }
  9739. if (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
  9740. $mime = 'application/msword';
  9741. $imgmime = 'doc.png';
  9742. $famime = 'file-word-o';
  9743. }
  9744. if (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
  9745. $mime = 'application/msword';
  9746. $imgmime = 'doc.png';
  9747. $famime = 'file-word-o';
  9748. }
  9749. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  9750. $mime = 'application/vnd.ms-excel';
  9751. $imgmime = 'xls.png';
  9752. $famime = 'file-excel-o';
  9753. }
  9754. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  9755. $mime = 'application/vnd.ms-excel';
  9756. $imgmime = 'xls.png';
  9757. $famime = 'file-excel-o';
  9758. }
  9759. if (preg_match('/\.xls$/i', $tmpfile)) {
  9760. $mime = 'application/vnd.ms-excel';
  9761. $imgmime = 'xls.png';
  9762. $famime = 'file-excel-o';
  9763. }
  9764. if (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
  9765. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  9766. $imgmime = 'xls.png';
  9767. $famime = 'file-excel-o';
  9768. }
  9769. if (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
  9770. $mime = 'application/vnd.ms-powerpoint';
  9771. $imgmime = 'ppt.png';
  9772. $famime = 'file-powerpoint-o';
  9773. }
  9774. if (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
  9775. $mime = 'application/x-mspowerpoint';
  9776. $imgmime = 'ppt.png';
  9777. $famime = 'file-powerpoint-o';
  9778. }
  9779. // Other
  9780. if (preg_match('/\.pdf$/i', $tmpfile)) {
  9781. $mime = 'application/pdf';
  9782. $imgmime = 'pdf.png';
  9783. $famime = 'file-pdf-o';
  9784. }
  9785. // Scripts
  9786. if (preg_match('/\.bat$/i', $tmpfile)) {
  9787. $mime = 'text/x-bat';
  9788. $imgmime = 'script.png';
  9789. $srclang = 'dos';
  9790. $famime = 'file-code-o';
  9791. }
  9792. if (preg_match('/\.sh$/i', $tmpfile)) {
  9793. $mime = 'text/x-sh';
  9794. $imgmime = 'script.png';
  9795. $srclang = 'bash';
  9796. $famime = 'file-code-o';
  9797. }
  9798. if (preg_match('/\.ksh$/i', $tmpfile)) {
  9799. $mime = 'text/x-ksh';
  9800. $imgmime = 'script.png';
  9801. $srclang = 'bash';
  9802. $famime = 'file-code-o';
  9803. }
  9804. if (preg_match('/\.bash$/i', $tmpfile)) {
  9805. $mime = 'text/x-bash';
  9806. $imgmime = 'script.png';
  9807. $srclang = 'bash';
  9808. $famime = 'file-code-o';
  9809. }
  9810. // Images
  9811. if (preg_match('/\.ico$/i', $tmpfile)) {
  9812. $mime = 'image/x-icon';
  9813. $imgmime = 'image.png';
  9814. $famime = 'file-image-o';
  9815. }
  9816. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  9817. $mime = 'image/jpeg';
  9818. $imgmime = 'image.png';
  9819. $famime = 'file-image-o';
  9820. }
  9821. if (preg_match('/\.png$/i', $tmpfile)) {
  9822. $mime = 'image/png';
  9823. $imgmime = 'image.png';
  9824. $famime = 'file-image-o';
  9825. }
  9826. if (preg_match('/\.gif$/i', $tmpfile)) {
  9827. $mime = 'image/gif';
  9828. $imgmime = 'image.png';
  9829. $famime = 'file-image-o';
  9830. }
  9831. if (preg_match('/\.bmp$/i', $tmpfile)) {
  9832. $mime = 'image/bmp';
  9833. $imgmime = 'image.png';
  9834. $famime = 'file-image-o';
  9835. }
  9836. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  9837. $mime = 'image/tiff';
  9838. $imgmime = 'image.png';
  9839. $famime = 'file-image-o';
  9840. }
  9841. if (preg_match('/\.svg$/i', $tmpfile)) {
  9842. $mime = 'image/svg+xml';
  9843. $imgmime = 'image.png';
  9844. $famime = 'file-image-o';
  9845. }
  9846. if (preg_match('/\.webp$/i', $tmpfile)) {
  9847. $mime = 'image/webp';
  9848. $imgmime = 'image.png';
  9849. $famime = 'file-image-o';
  9850. }
  9851. // Calendar
  9852. if (preg_match('/\.vcs$/i', $tmpfile)) {
  9853. $mime = 'text/calendar';
  9854. $imgmime = 'other.png';
  9855. $famime = 'file-text-o';
  9856. }
  9857. if (preg_match('/\.ics$/i', $tmpfile)) {
  9858. $mime = 'text/calendar';
  9859. $imgmime = 'other.png';
  9860. $famime = 'file-text-o';
  9861. }
  9862. // Other
  9863. if (preg_match('/\.torrent$/i', $tmpfile)) {
  9864. $mime = 'application/x-bittorrent';
  9865. $imgmime = 'other.png';
  9866. $famime = 'file-o';
  9867. }
  9868. // Audio
  9869. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  9870. $mime = 'audio';
  9871. $imgmime = 'audio.png';
  9872. $famime = 'file-audio-o';
  9873. }
  9874. // Video
  9875. if (preg_match('/\.mp4$/i', $tmpfile)) {
  9876. $mime = 'video/mp4';
  9877. $imgmime = 'video.png';
  9878. $famime = 'file-video-o';
  9879. }
  9880. if (preg_match('/\.ogv$/i', $tmpfile)) {
  9881. $mime = 'video/ogg';
  9882. $imgmime = 'video.png';
  9883. $famime = 'file-video-o';
  9884. }
  9885. if (preg_match('/\.webm$/i', $tmpfile)) {
  9886. $mime = 'video/webm';
  9887. $imgmime = 'video.png';
  9888. $famime = 'file-video-o';
  9889. }
  9890. if (preg_match('/\.avi$/i', $tmpfile)) {
  9891. $mime = 'video/x-msvideo';
  9892. $imgmime = 'video.png';
  9893. $famime = 'file-video-o';
  9894. }
  9895. if (preg_match('/\.divx$/i', $tmpfile)) {
  9896. $mime = 'video/divx';
  9897. $imgmime = 'video.png';
  9898. $famime = 'file-video-o';
  9899. }
  9900. if (preg_match('/\.xvid$/i', $tmpfile)) {
  9901. $mime = 'video/xvid';
  9902. $imgmime = 'video.png';
  9903. $famime = 'file-video-o';
  9904. }
  9905. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  9906. $mime = 'video';
  9907. $imgmime = 'video.png';
  9908. $famime = 'file-video-o';
  9909. }
  9910. // Archive
  9911. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  9912. $mime = 'archive';
  9913. $imgmime = 'archive.png';
  9914. $famime = 'file-archive-o';
  9915. } // application/xxx where zzz is zip, ...
  9916. // Exe
  9917. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  9918. $mime = 'application/octet-stream';
  9919. $imgmime = 'other.png';
  9920. $famime = 'file-o';
  9921. }
  9922. // Lib
  9923. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  9924. $mime = 'library';
  9925. $imgmime = 'library.png';
  9926. $famime = 'file-o';
  9927. }
  9928. // Err
  9929. if (preg_match('/\.err$/i', $tmpfile)) {
  9930. $mime = 'error';
  9931. $imgmime = 'error.png';
  9932. $famime = 'file-text-o';
  9933. }
  9934. // Return string
  9935. if ($mode == 1) {
  9936. $tmp = explode('/', $mime);
  9937. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  9938. }
  9939. if ($mode == 2) {
  9940. return $imgmime;
  9941. }
  9942. if ($mode == 3) {
  9943. return $srclang;
  9944. }
  9945. if ($mode == 4) {
  9946. return $famime;
  9947. }
  9948. return $mime;
  9949. }
  9950. /**
  9951. * Return the value of a filed into a dictionary for the record $id.
  9952. * This also set all the values into a cache for a next search.
  9953. *
  9954. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  9955. * @param string $field The name of field where to find the value to return
  9956. * @param int $id Id of line record
  9957. * @param bool $checkentity Add filter on entity
  9958. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  9959. * @return string The value of field $field. This also set $dictvalues cache.
  9960. */
  9961. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  9962. {
  9963. global $conf, $db;
  9964. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  9965. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  9966. if (is_null($dictvalues)) {
  9967. $dictvalues = array();
  9968. $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
  9969. if ($checkentity) {
  9970. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  9971. }
  9972. $resql = $db->query($sql);
  9973. if ($resql) {
  9974. while ($obj = $db->fetch_object($resql)) {
  9975. $dictvalues[$obj->$rowidfield] = $obj; // $obj is stdClass
  9976. }
  9977. } else {
  9978. dol_print_error($db);
  9979. }
  9980. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  9981. }
  9982. if (!empty($dictvalues[$id])) {
  9983. // Found
  9984. $tmp = $dictvalues[$id];
  9985. return (property_exists($tmp, $field) ? $tmp->$field : '');
  9986. } else {
  9987. // Not found
  9988. return '';
  9989. }
  9990. }
  9991. /**
  9992. * Return true if the color is light
  9993. *
  9994. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  9995. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  9996. */
  9997. function colorIsLight($stringcolor)
  9998. {
  9999. $stringcolor = str_replace('#', '', $stringcolor);
  10000. $res = -1;
  10001. if (!empty($stringcolor)) {
  10002. $res = 0;
  10003. $tmp = explode(',', $stringcolor);
  10004. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  10005. $r = $tmp[0];
  10006. $g = $tmp[1];
  10007. $b = $tmp[2];
  10008. } else {
  10009. $hexr = $stringcolor[0].$stringcolor[1];
  10010. $hexg = $stringcolor[2].$stringcolor[3];
  10011. $hexb = $stringcolor[4].$stringcolor[5];
  10012. $r = hexdec($hexr);
  10013. $g = hexdec($hexg);
  10014. $b = hexdec($hexb);
  10015. }
  10016. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  10017. if ($bright > 0.6) {
  10018. $res = 1;
  10019. }
  10020. }
  10021. return $res;
  10022. }
  10023. /**
  10024. * Function to test if an entry is enabled or not
  10025. *
  10026. * @param string $type_user 0=We test for internal user, 1=We test for external user
  10027. * @param array $menuentry Array for feature entry to test
  10028. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  10029. * @return int 0=Hide, 1=Show, 2=Show gray
  10030. */
  10031. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  10032. {
  10033. global $conf;
  10034. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  10035. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  10036. if (empty($menuentry['enabled'])) {
  10037. return 0; // Entry disabled by condition
  10038. }
  10039. if ($type_user && $menuentry['module']) {
  10040. $tmploops = explode('|', $menuentry['module']);
  10041. $found = 0;
  10042. foreach ($tmploops as $tmploop) {
  10043. if (in_array($tmploop, $listofmodulesforexternal)) {
  10044. $found++;
  10045. break;
  10046. }
  10047. }
  10048. if (!$found) {
  10049. return 0; // Entry is for menus all excluded to external users
  10050. }
  10051. }
  10052. if (!$menuentry['perms'] && $type_user) {
  10053. return 0; // No permissions and user is external
  10054. }
  10055. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  10056. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  10057. }
  10058. if (!$menuentry['perms']) {
  10059. return 2; // No permissions and user is external
  10060. }
  10061. return 1;
  10062. }
  10063. /**
  10064. * Round to next multiple.
  10065. *
  10066. * @param double $n Number to round up
  10067. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  10068. * @return integer Value rounded.
  10069. */
  10070. function roundUpToNextMultiple($n, $x = 5)
  10071. {
  10072. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  10073. }
  10074. /**
  10075. * Function dolGetBadge
  10076. *
  10077. * @param string $label label of badge no html : use in alt attribute for accessibility
  10078. * @param string $html optional : label of badge with html
  10079. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  10080. * @param string $mode default '' , 'pill', 'dot'
  10081. * @param string $url the url for link
  10082. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  10083. * @return string Html badge
  10084. */
  10085. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  10086. {
  10087. $attr = array(
  10088. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  10089. );
  10090. if (empty($html)) {
  10091. $html = $label;
  10092. }
  10093. if (!empty($url)) {
  10094. $attr['href'] = $url;
  10095. }
  10096. if ($mode === 'dot') {
  10097. $attr['class'] .= ' classfortooltip';
  10098. $attr['title'] = $html;
  10099. $attr['aria-label'] = $label;
  10100. $html = '';
  10101. }
  10102. // Override attr
  10103. if (!empty($params['attr']) && is_array($params['attr'])) {
  10104. foreach ($params['attr'] as $key => $value) {
  10105. if ($key == 'class') {
  10106. $attr['class'] .= ' '.$value;
  10107. } elseif ($key == 'classOverride') {
  10108. $attr['class'] = $value;
  10109. } else {
  10110. $attr[$key] = $value;
  10111. }
  10112. }
  10113. }
  10114. // TODO: add hook
  10115. // escape all attribute
  10116. $attr = array_map('dol_escape_htmltag', $attr);
  10117. $TCompiledAttr = array();
  10118. foreach ($attr as $key => $value) {
  10119. $TCompiledAttr[] = $key.'="'.$value.'"';
  10120. }
  10121. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  10122. $tag = !empty($url) ? 'a' : 'span';
  10123. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  10124. }
  10125. /**
  10126. * Output the badge of a status.
  10127. *
  10128. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  10129. * @param string $statusLabelShort Short label of badge no html
  10130. * @param string $html Optional : label of badge with html
  10131. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  10132. * @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
  10133. * @param string $url The url for link
  10134. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  10135. * @return string Html status string
  10136. */
  10137. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  10138. {
  10139. global $conf;
  10140. $return = '';
  10141. $dolGetBadgeParams = array();
  10142. if (!empty($params['badgeParams'])) {
  10143. $dolGetBadgeParams = $params['badgeParams'];
  10144. }
  10145. // TODO : add a hook
  10146. if ($displayMode == 0) {
  10147. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  10148. } elseif ($displayMode == 1) {
  10149. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  10150. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  10151. // Use status with images (for backward compatibility)
  10152. $return = '';
  10153. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  10154. $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>' : '');
  10155. // For small screen, we always use the short label instead of long label.
  10156. if (!empty($conf->dol_optimize_smallscreen)) {
  10157. if ($displayMode == 0) {
  10158. $displayMode = 1;
  10159. } elseif ($displayMode == 4) {
  10160. $displayMode = 2;
  10161. } elseif ($displayMode == 6) {
  10162. $displayMode = 5;
  10163. }
  10164. }
  10165. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  10166. $statusImg = array(
  10167. 'status0' => 'statut0',
  10168. 'status1' => 'statut1',
  10169. 'status2' => 'statut2',
  10170. 'status3' => 'statut3',
  10171. 'status4' => 'statut4',
  10172. 'status5' => 'statut5',
  10173. 'status6' => 'statut6',
  10174. 'status7' => 'statut7',
  10175. 'status8' => 'statut8',
  10176. 'status9' => 'statut9'
  10177. );
  10178. if (!empty($statusImg[$statusType])) {
  10179. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  10180. } else {
  10181. $htmlImg = img_picto($statusLabel, $statusType);
  10182. }
  10183. if ($displayMode === 2) {
  10184. $return = $htmlImg.' '.$htmlLabelShort;
  10185. } elseif ($displayMode === 3) {
  10186. $return = $htmlImg;
  10187. } elseif ($displayMode === 4) {
  10188. $return = $htmlImg.' '.$htmlLabel;
  10189. } elseif ($displayMode === 5) {
  10190. $return = $htmlLabelShort.' '.$htmlImg;
  10191. } else { // $displayMode >= 6
  10192. $return = $htmlLabel.' '.$htmlImg;
  10193. }
  10194. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  10195. // Use new badge
  10196. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  10197. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  10198. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  10199. if ($displayMode == 3) {
  10200. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  10201. } elseif ($displayMode === 5) {
  10202. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  10203. } else {
  10204. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  10205. }
  10206. }
  10207. return $return;
  10208. }
  10209. /**
  10210. * Function dolGetButtonAction
  10211. *
  10212. * @param string $label Label or tooltip of button if $tet is provided. Also used as tooltip in title attribute. Can be escaped HTML content or full simple text.
  10213. * @param string $text Optional : short label on button. Can be escaped HTML content or full simple text.
  10214. * @param string $actionType 'default', 'danger', 'email', 'clone', 'cancel', 'delete', ...
  10215. * @param string|array $url Url for link or array of subbutton description ('label'=>, 'url'=>, 'lang'=>, 'perm'=> )
  10216. * Example when an array is used: $arrayforbutaction = array(
  10217. * 10 => array('lang'=>'propal', 'enabled'=>isModEnabled("propal"), 'perm'=>$user->hasRight('propal', 'creer'), 'label' => 'AddProp', 'url'=>'/comm/propal/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10218. * 20 => array('lang'=>'orders', 'enabled'=>isModEnabled("commande"), 'perm'=>$user->hasRight('commande', 'creer'), 'label' => 'CreateOrder', 'url'=>'/commande/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10219. * 30 => array('lang'=>'bills', 'enabled'=>isModEnabled("facture"), 'perm'=>$user->hasRight('facture', 'creer'), 'label' => 'CreateBill', 'url'=>'/compta/facture/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10220. * );
  10221. * @param string $id Attribute id of button
  10222. * @param int|boolean $userRight User action right
  10223. * // phpcs:disable
  10224. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  10225. * 'attr' => [ // to add or override button attributes
  10226. * 'xxxxx' => '', // your xxxxx attribute you want
  10227. * 'class' => 'reposition', // to add more css class to the button class attribute
  10228. * 'classOverride' => '' // to replace class attribute of the button
  10229. * ],
  10230. * 'confirm' => [
  10231. * '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.
  10232. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  10233. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  10234. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  10235. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  10236. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  10237. * 'isDropDrown' => false, // true|false to display dialog as a dropdown (with dark background)
  10238. * ],
  10239. * ]
  10240. * // phpcs:enable
  10241. * @return string html button
  10242. */
  10243. function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  10244. {
  10245. global $hookmanager, $action, $object, $langs;
  10246. // If $url is an array, we must build a dropdown button
  10247. if (is_array($url)) {
  10248. if (count($url) > 1) {
  10249. $out = '<div class="dropdown inline-block dropdown-holder">';
  10250. $out .= '<a style="margin-right: auto;" class="dropdown-toggle classfortooltip butAction'.($userRight ? '' : 'Refused').'" title="'.dol_escape_htmltag($label).'" data-toggle="dropdown">'.($text ? $text : $label).'</a>';
  10251. $out .= '<div class="dropdown-content">';
  10252. foreach ($url as $subbutton) {
  10253. if (!empty($subbutton['lang'])) {
  10254. $langs->load($subbutton['lang']);
  10255. }
  10256. $tmpurl = DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage']));
  10257. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, '', $subbutton['perm'], array('isDropDown' => true));
  10258. }
  10259. $out .= "</div>";
  10260. $out .= "</div>";
  10261. } else {
  10262. foreach ($url as $subbutton) { // Should loop on 1 record only
  10263. if (!empty($subbutton['lang'])) {
  10264. $langs->load($subbutton['lang']);
  10265. }
  10266. $tmpurl = DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage']));
  10267. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, '', $subbutton['perm']);
  10268. }
  10269. }
  10270. return $out;
  10271. }
  10272. // Here, $url is a simple link
  10273. if (!empty($params['isDropdown']))
  10274. $class = "dropdown-item";
  10275. else {
  10276. $class = 'butAction';
  10277. if ($actionType == 'danger' || $actionType == 'delete') {
  10278. $class = 'butActionDelete';
  10279. if (!empty($url) && strpos($url, 'token=') === false) {
  10280. $url .= '&token='.newToken();
  10281. }
  10282. }
  10283. }
  10284. $attr = array(
  10285. 'class' => $class,
  10286. 'href' => empty($url) ? '' : $url,
  10287. 'title' => $label
  10288. );
  10289. if (empty($text)) {
  10290. $text = $label;
  10291. $attr['title'] = ''; // if html not set, leave label on title is redundant
  10292. } else {
  10293. $attr['title'] = $label;
  10294. $attr['aria-label'] = $label;
  10295. }
  10296. if (empty($userRight)) {
  10297. $attr['class'] = 'butActionRefused';
  10298. $attr['href'] = '';
  10299. $attr['title'] = (($label && $text && $label != $text) ? $label : $langs->trans('NotEnoughPermissions'));
  10300. }
  10301. if (!empty($id)) {
  10302. $attr['id'] = $id;
  10303. }
  10304. // Override attr
  10305. if (!empty($params['attr']) && is_array($params['attr'])) {
  10306. foreach ($params['attr'] as $key => $value) {
  10307. if ($key == 'class') {
  10308. $attr['class'] .= ' '.$value;
  10309. } elseif ($key == 'classOverride') {
  10310. $attr['class'] = $value;
  10311. } else {
  10312. $attr[$key] = $value;
  10313. }
  10314. }
  10315. }
  10316. // automatic add tooltip when title is detected
  10317. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  10318. $attr['class'].= ' classfortooltip';
  10319. }
  10320. // Js Confirm button
  10321. if ($userRight && !empty($params['confirm'])) {
  10322. if (!is_array($params['confirm'])) {
  10323. $params['confirm'] = array();
  10324. }
  10325. if (empty($params['confirm']['url'])) {
  10326. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  10327. }
  10328. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  10329. $attr['data-confirm-url'] = $params['confirm']['url'];
  10330. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  10331. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  10332. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  10333. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  10334. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  10335. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  10336. $attr['class'].= ' butActionConfirm';
  10337. }
  10338. if (isset($attr['href']) && empty($attr['href'])) {
  10339. unset($attr['href']);
  10340. }
  10341. // escape all attribute
  10342. $attr = array_map('dol_escape_htmltag', $attr);
  10343. $TCompiledAttr = array();
  10344. foreach ($attr as $key => $value) {
  10345. $TCompiledAttr[] = $key.'= "'.$value.'"';
  10346. }
  10347. $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
  10348. $tag = !empty($attr['href']) ? 'a' : 'span';
  10349. $parameters = array(
  10350. 'TCompiledAttr' => $TCompiledAttr, // array
  10351. 'compiledAttributes' => $compiledAttributes, // string
  10352. 'attr' => $attr,
  10353. 'tag' => $tag,
  10354. 'label' => $label,
  10355. 'html' => $text,
  10356. 'actionType' => $actionType,
  10357. 'url' => $url,
  10358. 'id' => $id,
  10359. 'userRight' => $userRight,
  10360. 'params' => $params
  10361. );
  10362. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  10363. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  10364. if (empty($reshook)) {
  10365. if (dol_textishtml($text)) { // If content already HTML encoded
  10366. return '<' . $tag . ' ' . $compiledAttributes . '>' . $text . '</' . $tag . '>';
  10367. } else {
  10368. return '<' . $tag . ' ' . $compiledAttributes . '>' . dol_escape_htmltag($text) . '</' . $tag . '>';
  10369. }
  10370. } else {
  10371. return $hookmanager->resPrint;
  10372. }
  10373. }
  10374. /**
  10375. * Add space between dolGetButtonTitle
  10376. *
  10377. * @param string $moreClass more css class label
  10378. * @return string html of title separator
  10379. */
  10380. function dolGetButtonTitleSeparator($moreClass = "")
  10381. {
  10382. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  10383. }
  10384. /**
  10385. * get field error icon
  10386. *
  10387. * @param string $fieldValidationErrorMsg message to add in tooltip
  10388. * @return string html output
  10389. */
  10390. function getFieldErrorIcon($fieldValidationErrorMsg)
  10391. {
  10392. $out = '';
  10393. if (!empty($fieldValidationErrorMsg)) {
  10394. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  10395. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  10396. $out.= '</span>';
  10397. }
  10398. return $out;
  10399. }
  10400. /**
  10401. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  10402. *
  10403. * @param string $label label of button
  10404. * @param string $helpText optional : content for help tooltip
  10405. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  10406. * @param string $url the url for link
  10407. * @param string $id attribute id of button
  10408. * @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
  10409. * @param array $params various params for future : recommended rather than adding more function arguments
  10410. * @return string html button
  10411. */
  10412. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  10413. {
  10414. global $langs, $conf, $user;
  10415. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  10416. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  10417. return '';
  10418. }
  10419. $class = 'btnTitle';
  10420. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
  10421. $class .= ' btnTitlePlus';
  10422. }
  10423. $useclassfortooltip = 1;
  10424. if (!empty($params['morecss'])) {
  10425. $class .= ' '.$params['morecss'];
  10426. }
  10427. $attr = array(
  10428. 'class' => $class,
  10429. 'href' => empty($url) ? '' : $url
  10430. );
  10431. if (!empty($helpText)) {
  10432. $attr['title'] = dol_escape_htmltag($helpText);
  10433. } elseif (empty($attr['title']) && $label) {
  10434. $attr['title'] = $label;
  10435. $useclassfortooltip = 0;
  10436. }
  10437. if ($status == 2) {
  10438. $attr['class'] .= ' btnTitleSelected';
  10439. } elseif ($status <= 0) {
  10440. $attr['class'] .= ' refused';
  10441. $attr['href'] = '';
  10442. if ($status == -1) { // disable
  10443. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  10444. } elseif ($status == 0) { // Not enough permissions
  10445. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  10446. }
  10447. }
  10448. if (!empty($attr['title']) && $useclassfortooltip) {
  10449. $attr['class'] .= ' classfortooltip';
  10450. }
  10451. if (!empty($id)) {
  10452. $attr['id'] = $id;
  10453. }
  10454. // Override attr
  10455. if (!empty($params['attr']) && is_array($params['attr'])) {
  10456. foreach ($params['attr'] as $key => $value) {
  10457. if ($key == 'class') {
  10458. $attr['class'] .= ' '.$value;
  10459. } elseif ($key == 'classOverride') {
  10460. $attr['class'] = $value;
  10461. } else {
  10462. $attr[$key] = $value;
  10463. }
  10464. }
  10465. }
  10466. if (isset($attr['href']) && empty($attr['href'])) {
  10467. unset($attr['href']);
  10468. }
  10469. // TODO : add a hook
  10470. // escape all attribute
  10471. $attr = array_map('dol_escape_htmltag', $attr);
  10472. $TCompiledAttr = array();
  10473. foreach ($attr as $key => $value) {
  10474. $TCompiledAttr[] = $key.'="'.$value.'"';
  10475. }
  10476. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  10477. $tag = (empty($attr['href']) ? 'span' : 'a');
  10478. $button = '<'.$tag.' '.$compiledAttributes.'>';
  10479. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  10480. if (!empty($params['forcenohideoftext'])) {
  10481. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  10482. }
  10483. $button .= '</'.$tag.'>';
  10484. return $button;
  10485. }
  10486. /**
  10487. * Get an array with properties of an element.
  10488. *
  10489. * @param string $element_type Element type (Value of $object->element). Example:
  10490. * 'action', 'facture', 'project', 'project_task' or
  10491. * 'myobject@mymodule' or
  10492. * 'myobject_mysubobject' (where mymodule = myobject, like 'project_task')
  10493. * @return array array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>)
  10494. * @see fetchObjectByElement()
  10495. */
  10496. function getElementProperties($element_type)
  10497. {
  10498. global $conf;
  10499. $regs = array();
  10500. $classfile = $classname = $classpath = $subdir = $dir_output = '';
  10501. // Parse element/subelement
  10502. $module = $element_type;
  10503. $element = $element_type;
  10504. $subelement = $element_type;
  10505. $table_element = $element_type;
  10506. // If we ask a resource form external module (instead of default path)
  10507. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) { // 'myobject@mymodule'
  10508. $element = $subelement = $regs[1];
  10509. $module = $regs[2];
  10510. }
  10511. // If we ask a resource for a string with an element and a subelement
  10512. // Example 'project_task'
  10513. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
  10514. $module = $element = $regs[1];
  10515. $subelement = $regs[2];
  10516. }
  10517. // For compat and To work with non standard path
  10518. if ($element_type == "action") {
  10519. $classpath = 'comm/action/class';
  10520. $subelement = 'Actioncomm';
  10521. $module = 'agenda';
  10522. $table_element = 'actioncomm';
  10523. } elseif ($element_type == 'cronjob') {
  10524. $classpath = 'cron/class';
  10525. $module = 'cron';
  10526. $table_element = 'cron';
  10527. } elseif ($element_type == 'adherent_type') {
  10528. $classpath = 'adherents/class';
  10529. $classfile = 'adherent_type';
  10530. $module = 'adherent';
  10531. $subelement = 'adherent_type';
  10532. $classname = 'AdherentType';
  10533. $table_element = 'adherent_type';
  10534. } elseif ($element_type == 'bank_account') {
  10535. $classpath = 'compta/bank/class';
  10536. $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
  10537. $classfile = 'account';
  10538. $classname = 'Account';
  10539. } elseif ($element_type == 'category') {
  10540. $classpath = 'categories/class';
  10541. $module = 'categorie';
  10542. $subelement = 'categorie';
  10543. $table_element = 'categorie';
  10544. } elseif ($element_type == 'contact') {
  10545. $classpath = 'contact/class';
  10546. $classfile = 'contact';
  10547. $module = 'societe';
  10548. $subelement = 'contact';
  10549. $table_element = 'socpeople';
  10550. } elseif ($element_type == 'stock') {
  10551. $classpath = 'product/stock/class';
  10552. $classfile = 'entrepot';
  10553. $classname = 'Entrepot';
  10554. $table_element = 'entrepot';
  10555. } elseif ($element_type == 'project') {
  10556. $classpath = 'projet/class';
  10557. $module = 'projet';
  10558. $table_element = 'projet';
  10559. } elseif ($element_type == 'project_task') {
  10560. $classpath = 'projet/class';
  10561. $module = 'projet';
  10562. $subelement = 'task';
  10563. $table_element = 'projet_task';
  10564. } elseif ($element_type == 'facture' || $element_type == 'invoice') {
  10565. $classpath = 'compta/facture/class';
  10566. $module = 'facture';
  10567. $subelement = 'facture';
  10568. $table_element = 'facture';
  10569. } elseif ($element_type == 'commande' || $element_type == 'order') {
  10570. $classpath = 'commande/class';
  10571. $module = 'commande';
  10572. $subelement = 'commande';
  10573. $table_element = 'commande';
  10574. } elseif ($element_type == 'propal') {
  10575. $classpath = 'comm/propal/class';
  10576. $table_element = 'propal';
  10577. } elseif ($element_type == 'shipping') {
  10578. $classpath = 'expedition/class';
  10579. $classfile = 'expedition';
  10580. $classname = 'Expedition';
  10581. $module = 'expedition';
  10582. $table_element = 'expedition';
  10583. } elseif ($element_type == 'supplier_proposal') {
  10584. $classpath = 'supplier_proposal/class';
  10585. $module = 'supplier_proposal';
  10586. $element = 'supplierproposal';
  10587. $classfile = 'supplier_proposal';
  10588. $subelement = 'supplierproposal';
  10589. } elseif ($element_type == 'shipping') {
  10590. $classpath = 'expedition/class';
  10591. $subelement = 'expedition';
  10592. $module = 'expedition_bon';
  10593. } elseif ($element_type == 'delivery') {
  10594. $classpath = 'delivery/class';
  10595. $subelement = 'delivery';
  10596. $module = 'delivery_note';
  10597. } elseif ($element_type == 'contract') {
  10598. $classpath = 'contrat/class';
  10599. $module = 'contrat';
  10600. $subelement = 'contrat';
  10601. $table_element = 'contract';
  10602. } elseif ($element_type == 'mailing') {
  10603. $classpath = 'comm/mailing/class';
  10604. $module = 'mailing';
  10605. $classfile = 'mailing';
  10606. $classname = 'Mailing';
  10607. $subelement = '';
  10608. } elseif ($element_type == 'member') {
  10609. $classpath = 'adherents/class';
  10610. $module = 'adherent';
  10611. $subelement = 'adherent';
  10612. $table_element = 'adherent';
  10613. } elseif ($element_type == 'usergroup') {
  10614. $classpath = 'user/class';
  10615. $module = 'user';
  10616. } elseif ($element_type == 'mo') {
  10617. $classpath = 'mrp/class';
  10618. $classfile = 'mo';
  10619. $classname = 'Mo';
  10620. $module = 'mrp';
  10621. $subelement = '';
  10622. $table_element = 'mrp_mo';
  10623. } elseif ($element_type == 'cabinetmed_cons') {
  10624. $classpath = 'cabinetmed/class';
  10625. $module = 'cabinetmed';
  10626. $subelement = 'cabinetmedcons';
  10627. $table_element = 'cabinetmedcons';
  10628. } elseif ($element_type == 'fichinter') {
  10629. $classpath = 'fichinter/class';
  10630. $module = 'ficheinter';
  10631. $subelement = 'fichinter';
  10632. $table_element = 'fichinter';
  10633. } elseif ($element_type == 'dolresource' || $element_type == 'resource') {
  10634. $classpath = 'resource/class';
  10635. $module = 'resource';
  10636. $subelement = 'dolresource';
  10637. $table_element = 'resource';
  10638. } elseif ($element_type == 'propaldet') {
  10639. $classpath = 'comm/propal/class';
  10640. $module = 'propal';
  10641. $subelement = 'propaleligne';
  10642. } elseif ($element_type == 'opensurvey_sondage') {
  10643. $classpath = 'opensurvey/class';
  10644. $module = 'opensurvey';
  10645. $subelement = 'opensurveysondage';
  10646. } elseif ($element_type == 'order_supplier') {
  10647. $classpath = 'fourn/class';
  10648. $module = 'fournisseur';
  10649. $classfile = 'fournisseur.commande';
  10650. $element = 'order_supplier';
  10651. $subelement = '';
  10652. $classname = 'CommandeFournisseur';
  10653. $table_element = 'commande_fournisseur';
  10654. } elseif ($element_type == 'invoice_supplier') {
  10655. $classpath = 'fourn/class';
  10656. $module = 'fournisseur';
  10657. $classfile = 'fournisseur.facture';
  10658. $element = 'invoice_supplier';
  10659. $subelement = '';
  10660. $classname = 'FactureFournisseur';
  10661. $table_element = 'facture_fourn';
  10662. } elseif ($element_type == "service") {
  10663. $classpath = 'product/class';
  10664. $subelement = 'product';
  10665. $table_element = 'product';
  10666. } elseif ($element_type == 'salary') {
  10667. $classpath = 'salaries/class';
  10668. $module = 'salaries';
  10669. } elseif ($element_type == 'productlot') {
  10670. $module = 'productbatch';
  10671. $classpath = 'product/stock/class';
  10672. $classfile = 'productlot';
  10673. $classname = 'Productlot';
  10674. $element = 'productlot';
  10675. $subelement = '';
  10676. $table_element = 'product_lot';
  10677. } elseif ($element_type == 'websitepage') {
  10678. $classpath = 'website/class';
  10679. $classfile = 'websitepage';
  10680. $classname = 'Websitepage';
  10681. $module = 'website';
  10682. $subelement = 'websitepage';
  10683. $table_element = 'website_page';
  10684. } elseif ($element_type == 'fiscalyear') {
  10685. $classpath = 'core/class';
  10686. $module = 'accounting';
  10687. $subelement = 'fiscalyear';
  10688. } elseif ($element_type == 'chargesociales') {
  10689. $classpath = 'compta/sociales/class';
  10690. $module = 'tax';
  10691. $table_element = 'chargesociales';
  10692. } elseif ($element_type == 'tva') {
  10693. $classpath = 'compta/tva/class';
  10694. $module = 'tax';
  10695. $subdir = '/vat';
  10696. $table_element = 'tva';
  10697. }
  10698. if (empty($classfile)) {
  10699. $classfile = strtolower($subelement);
  10700. }
  10701. if (empty($classname)) {
  10702. $classname = ucfirst($subelement);
  10703. }
  10704. if (empty($classpath)) {
  10705. $classpath = $module.'/class';
  10706. }
  10707. //print 'getElementProperties subdir='.$subdir;
  10708. // Set dir_output
  10709. if ($module && isset($conf->$module)) { // The generic case
  10710. if (!empty($conf->$module->multidir_output[$conf->entity])) {
  10711. $dir_output = $conf->$module->multidir_output[$conf->entity];
  10712. } elseif (!empty($conf->$module->output[$conf->entity])) {
  10713. $dir_output = $conf->$module->output[$conf->entity];
  10714. } elseif (!empty($conf->$module->dir_output)) {
  10715. $dir_output = $conf->$module->dir_output;
  10716. }
  10717. }
  10718. // Overwrite value for special cases
  10719. if ($element == 'order_supplier') {
  10720. $dir_output = $conf->fournisseur->commande->dir_output;
  10721. } elseif ($element == 'invoice_supplier') {
  10722. $dir_output = $conf->fournisseur->facture->dir_output;
  10723. }
  10724. $dir_output .= $subdir;
  10725. $element_properties = array(
  10726. 'module' => $module,
  10727. 'element' => $element,
  10728. 'table_element' => $table_element,
  10729. 'subelement' => $subelement,
  10730. 'classpath' => $classpath,
  10731. 'classfile' => $classfile,
  10732. 'classname' => $classname,
  10733. 'dir_output' => $dir_output
  10734. );
  10735. return $element_properties;
  10736. }
  10737. /**
  10738. * Fetch an object from its id and element_type
  10739. * Inclusion of classes is automatic
  10740. *
  10741. * @param int $element_id Element id
  10742. * @param string $element_type Element type ('module' or 'myobject@mymodule' or 'mymodule_myobject')
  10743. * @param string $element_ref Element ref (Use this or element_id but not both)
  10744. * @return int|object object || 0 || <0 if error
  10745. * @see getElementProperties()
  10746. */
  10747. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  10748. {
  10749. global $db;
  10750. $ret = 0;
  10751. $element_prop = getElementProperties($element_type);
  10752. if (is_array($element_prop) && isModEnabled($element_prop['module'])) {
  10753. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  10754. if (class_exists($element_prop['classname'])) {
  10755. $classname = $element_prop['classname'];
  10756. $objecttmp = new $classname($db);
  10757. $ret = $objecttmp->fetch($element_id, $element_ref);
  10758. if ($ret >= 0) {
  10759. if (empty($objecttmp->module)) {
  10760. $objecttmp->module = $element_prop['module'];
  10761. }
  10762. return $objecttmp;
  10763. }
  10764. } else {
  10765. return -1;
  10766. }
  10767. }
  10768. return $ret;
  10769. }
  10770. /**
  10771. * Return if a file can contains executable content
  10772. *
  10773. * @param string $filename File name to test
  10774. * @return boolean True if yes, False if no
  10775. */
  10776. function isAFileWithExecutableContent($filename)
  10777. {
  10778. 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)) {
  10779. return true;
  10780. }
  10781. return false;
  10782. }
  10783. /**
  10784. * Return the value of token currently saved into session with name 'newtoken'.
  10785. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  10786. *
  10787. * @since Dolibarr v10.0.7
  10788. * @return string
  10789. */
  10790. function newToken()
  10791. {
  10792. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  10793. }
  10794. /**
  10795. * Return the value of token currently saved into session with name 'token'.
  10796. * 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).
  10797. *
  10798. * @since Dolibarr v10.0.7
  10799. * @return string
  10800. */
  10801. function currentToken()
  10802. {
  10803. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  10804. }
  10805. /**
  10806. * Return a random string to be used as a nonce value for js
  10807. *
  10808. * @return string
  10809. */
  10810. function getNonce()
  10811. {
  10812. global $conf;
  10813. if (empty($conf->cache['nonce'])) {
  10814. $conf->cache['nonce'] = dolGetRandomBytes(8);
  10815. }
  10816. return $conf->cache['nonce'];
  10817. }
  10818. /**
  10819. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  10820. *
  10821. * @param string $header The first left header of the table (automatic translated)
  10822. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  10823. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  10824. * @param integer $emptyRows (optional) The count of empty rows after the first header
  10825. * @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"
  10826. * @return void
  10827. *
  10828. * @see finishSimpleTable()
  10829. */
  10830. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  10831. {
  10832. global $langs;
  10833. print '<div class="div-table-responsive-no-min">';
  10834. print '<table class="noborder centpercent">';
  10835. print '<tr class="liste_titre">';
  10836. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  10837. print $langs->trans($header);
  10838. // extra space between the first header and the number
  10839. if ($number > -1) {
  10840. print ' ';
  10841. }
  10842. if (!empty($link)) {
  10843. if (!empty($arguments)) {
  10844. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10845. } else {
  10846. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  10847. }
  10848. }
  10849. if ($number > -1) {
  10850. print '<span class="badge">'.$number.'</span>';
  10851. }
  10852. if (!empty($link)) {
  10853. print '</a>';
  10854. }
  10855. print '</th>';
  10856. if ($number < 0 && !empty($link)) {
  10857. print '<th class="right">';
  10858. if (!empty($arguments)) {
  10859. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10860. } else {
  10861. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  10862. }
  10863. print $langs->trans("FullList");
  10864. print '</a>';
  10865. print '</th>';
  10866. }
  10867. print '</tr>';
  10868. }
  10869. /**
  10870. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  10871. *
  10872. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  10873. * @return void
  10874. *
  10875. * @see startSimpleTable()
  10876. */
  10877. function finishSimpleTable($addLineBreak = false)
  10878. {
  10879. print '</table>';
  10880. print '</div>';
  10881. if ($addLineBreak) {
  10882. print '<br>';
  10883. }
  10884. }
  10885. /**
  10886. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  10887. *
  10888. * @param integer $tableColumnCount The complete count columns of the table
  10889. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  10890. * @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)
  10891. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  10892. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  10893. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  10894. * @return void
  10895. */
  10896. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  10897. {
  10898. global $langs;
  10899. if ($num === 0) {
  10900. print '<tr class="oddeven">';
  10901. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  10902. print '</tr>';
  10903. return;
  10904. }
  10905. if ($nbofloop === 0) {
  10906. // don't show a summary line
  10907. return;
  10908. }
  10909. if ($num === 0) {
  10910. $colspan = $tableColumnCount;
  10911. } elseif ($num > $nbofloop) {
  10912. $colspan = $tableColumnCount;
  10913. } else {
  10914. $colspan = $tableColumnCount - 1;
  10915. }
  10916. if ($extraRightColumn) {
  10917. $colspan--;
  10918. }
  10919. print '<tr class="liste_total">';
  10920. if ($nbofloop > 0 && $num > $nbofloop) {
  10921. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  10922. } else {
  10923. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  10924. print '<td class="right" width="100">'.price($total).'</td>';
  10925. }
  10926. if ($extraRightColumn) {
  10927. print '<td></td>';
  10928. }
  10929. print '</tr>';
  10930. }
  10931. /**
  10932. * Return a file on output using a low memory. It can return very large files with no need of memory.
  10933. * WARNING: This close output buffers.
  10934. *
  10935. * @param string $fullpath_original_file_osencoded Full path of file to return.
  10936. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  10937. * @return void
  10938. */
  10939. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  10940. {
  10941. global $conf;
  10942. if ($method == -1) {
  10943. $method = 0;
  10944. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  10945. $method = 1;
  10946. }
  10947. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  10948. $method = 2;
  10949. }
  10950. }
  10951. // Be sure we don't have output buffering enabled to have readfile working correctly
  10952. while (ob_get_level()) {
  10953. ob_end_flush();
  10954. }
  10955. // Solution 0
  10956. if ($method == 0) {
  10957. readfile($fullpath_original_file_osencoded);
  10958. } elseif ($method == 1) {
  10959. // Solution 1
  10960. $handle = fopen($fullpath_original_file_osencoded, "rb");
  10961. while (!feof($handle)) {
  10962. print fread($handle, 8192);
  10963. }
  10964. fclose($handle);
  10965. } elseif ($method == 2) {
  10966. // Solution 2
  10967. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  10968. $handle2 = fopen("php://output", "wb");
  10969. stream_copy_to_stream($handle1, $handle2);
  10970. fclose($handle1);
  10971. fclose($handle2);
  10972. }
  10973. }
  10974. /**
  10975. * Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
  10976. * Code that handle the click is inside core/js/lib_foot.js.php.
  10977. *
  10978. * @param string $valuetocopy The value to print
  10979. * @param int $showonlyonhover Show the copy-paste button only on hover
  10980. * @param string $texttoshow Replace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
  10981. * @return string The string to print for the button
  10982. */
  10983. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  10984. {
  10985. /*
  10986. global $conf;
  10987. if (!empty($conf->dol_no_mouse_hover)) {
  10988. $showonlyonhover = 0;
  10989. }*/
  10990. $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
  10991. if ($texttoshow === 'none') {
  10992. $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>';
  10993. } elseif ($texttoshow) {
  10994. $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>';
  10995. } else {
  10996. $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>';
  10997. }
  10998. return $result;
  10999. }
  11000. /**
  11001. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  11002. *
  11003. * @param string $stringtodecode String to decode (json or serialize coded)
  11004. * @return mixed The decoded object.
  11005. */
  11006. function jsonOrUnserialize($stringtodecode)
  11007. {
  11008. $result = json_decode($stringtodecode);
  11009. if ($result === null) {
  11010. $result = unserialize($stringtodecode);
  11011. }
  11012. return $result;
  11013. }
  11014. /**
  11015. * forgeSQLFromUniversalSearchCriteria
  11016. *
  11017. * @param string $filter String with universal search string. Must be '(aaa:bbb:...) OR (ccc:ddd:...) ...' with
  11018. * aaa is a field name (with alias or not) and
  11019. * bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'.
  11020. * Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
  11021. * @param string $errorstr Error message string
  11022. * @param int $noand 1=Do not add the AND before the condition string.
  11023. * @param int $nopar 1=Do not add the perenthesis around the condition string.
  11024. * @param int $noerror 1=If search criteria is not valid, does not return an error string but invalidate the SQL
  11025. * @return string Return forged SQL string
  11026. */
  11027. function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0)
  11028. {
  11029. if (!preg_match('/^\(.*\)$/', $filter)) { // If $filter does not start and end with ()
  11030. $filter = '(' . $filter . ')';
  11031. }
  11032. $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'
  11033. if (!dolCheckFilters($filter, $errorstr)) {
  11034. if ($noerror) {
  11035. return '1 = 2';
  11036. } else {
  11037. return 'Filter syntax error - '.$errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
  11038. }
  11039. }
  11040. // Test the filter syntax
  11041. $t = preg_replace_callback('/'.$regexstring.'/i', 'dolForgeDummyCriteriaCallback', $filter);
  11042. $t = str_replace(array('and','or','AND','OR',' '), '', $t); // Remove the only strings allowed between each () criteria
  11043. // If the string result contains something else than '()', the syntax was wrong
  11044. if (preg_match('/[^\(\)]/', $t)) {
  11045. $errorstr = 'Bad syntax of the search string';
  11046. if ($noerror) {
  11047. return '1 = 2';
  11048. } else {
  11049. return 'Filter syntax error - '.$errorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
  11050. }
  11051. }
  11052. return ($noand ? "" : " AND ").($nopar ? "" : '(').preg_replace_callback('/'.$regexstring.'/i', 'dolForgeCriteriaCallback', $filter).($nopar ? "" : ')');
  11053. }
  11054. /**
  11055. * Return if a $sqlfilters parameter has a valid balance of parenthesis
  11056. *
  11057. * @param string $sqlfilters sqlfilter string
  11058. * @param string $error Error message
  11059. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  11060. */
  11061. function dolCheckFilters($sqlfilters, &$error = '')
  11062. {
  11063. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  11064. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  11065. $tmp = $sqlfilters;
  11066. $i = 0; $nb = strlen($tmp);
  11067. $counter = 0;
  11068. while ($i < $nb) {
  11069. if ($tmp[$i] == '(') {
  11070. $counter++;
  11071. }
  11072. if ($tmp[$i] == ')') {
  11073. $counter--;
  11074. }
  11075. if ($counter < 0) {
  11076. $error = "Wrond balance of parenthesis in sqlfilters=".$sqlfilters;
  11077. dol_syslog($error, LOG_WARNING);
  11078. return false;
  11079. }
  11080. $i++;
  11081. }
  11082. return true;
  11083. }
  11084. /**
  11085. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  11086. * This method is called by forgeSQLFromUniversalSearchCriteria()
  11087. *
  11088. * @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"
  11089. * @return string Forged criteria. Example: "" or "()"
  11090. */
  11091. function dolForgeDummyCriteriaCallback($matches)
  11092. {
  11093. //dol_syslog("Convert matches ".$matches[1]);
  11094. if (empty($matches[1])) {
  11095. return '';
  11096. }
  11097. $tmp = explode(':', $matches[1]);
  11098. if (count($tmp) < 3) {
  11099. return '';
  11100. }
  11101. return '()'; // An empty criteria
  11102. }
  11103. /**
  11104. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  11105. * This method is called by forgeSQLFromUniversalSearchCriteria()
  11106. *
  11107. * @param array $matches Array of found string by regex search.
  11108. * 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"
  11109. * @return string Forged criteria. Example: "t.field LIKE 'abc%'"
  11110. */
  11111. function dolForgeCriteriaCallback($matches)
  11112. {
  11113. global $db;
  11114. //dol_syslog("Convert matches ".$matches[1]);
  11115. if (empty($matches[1])) {
  11116. return '';
  11117. }
  11118. $tmp = explode(':', $matches[1]);
  11119. if (count($tmp) < 3) {
  11120. return '';
  11121. }
  11122. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  11123. $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
  11124. if ($operator == 'NOTLIKE') {
  11125. $operator = 'NOT LIKE';
  11126. }
  11127. if ($operator == 'ISNOT') {
  11128. $operator = 'IS NOT';
  11129. }
  11130. if ($operator == '!=') {
  11131. $operator = '<>';
  11132. }
  11133. $tmpescaped = $tmp[2];
  11134. $regbis = array();
  11135. if ($operator == 'IN') { // IN is allowed for list of ID or code only
  11136. //if (!preg_match('/^\(.*\)$/', $tmpescaped)) {
  11137. $tmpescaped = '('.$db->escape($db->sanitize($tmpescaped, 1, 0)).')';
  11138. //} else {
  11139. // $tmpescaped = $db->escape($db->sanitize($tmpescaped, 1));
  11140. //}
  11141. } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
  11142. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  11143. $tmpescaped = $regbis[1];
  11144. }
  11145. //$tmpescaped = "'".$db->escapeforlike($db->escape($regbis[1]))."'";
  11146. $tmpescaped = "'".$db->escape($tmpescaped)."'"; // We do not escape the _ and % so the like will works
  11147. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  11148. $tmpescaped = "'".$db->escape($regbis[1])."'";
  11149. } else {
  11150. if (strtoupper($tmpescaped) == 'NULL') {
  11151. $tmpescaped = 'NULL';
  11152. } elseif (is_int($tmpescaped)) {
  11153. $tmpescaped = (int) $tmpescaped;
  11154. } else {
  11155. $tmpescaped = (float) $tmpescaped;
  11156. }
  11157. }
  11158. return '('.$db->escape($operand).' '.strtoupper($operator).' '.$tmpescaped.')';
  11159. }
  11160. /**
  11161. * Get timeline icon
  11162. *
  11163. * @param ActionComm $actionstatic actioncomm
  11164. * @param array $histo histo
  11165. * @param int $key key
  11166. * @return string String with timeline icon
  11167. * @deprecated Use actioncomm->getPictoType() instead
  11168. */
  11169. function getTimelineIcon($actionstatic, &$histo, $key)
  11170. {
  11171. global $conf, $langs;
  11172. $out = '<!-- timeline icon -->'."\n";
  11173. $iconClass = 'fa fa-comments';
  11174. $img_picto = '';
  11175. $colorClass = '';
  11176. $pictoTitle = '';
  11177. if ($histo[$key]['percent'] == -1) {
  11178. $colorClass = 'timeline-icon-not-applicble';
  11179. $pictoTitle = $langs->trans('StatusNotApplicable');
  11180. } elseif ($histo[$key]['percent'] == 0) {
  11181. $colorClass = 'timeline-icon-todo';
  11182. $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
  11183. } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
  11184. $colorClass = 'timeline-icon-in-progress';
  11185. $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
  11186. } elseif ($histo[$key]['percent'] >= 100) {
  11187. $colorClass = 'timeline-icon-done';
  11188. $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
  11189. }
  11190. if ($actionstatic->code == 'AC_TICKET_CREATE') {
  11191. $iconClass = 'fa fa-ticket';
  11192. } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
  11193. $iconClass = 'fa fa-pencilxxx';
  11194. } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11195. $iconClass = 'fa fa-comments';
  11196. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  11197. $iconClass = 'fa fa-mask';
  11198. } elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  11199. if ($actionstatic->type_picto) {
  11200. $img_picto = img_picto('', $actionstatic->type_picto);
  11201. } else {
  11202. if ($actionstatic->type_code == 'AC_RDV') {
  11203. $iconClass = 'fa fa-handshake';
  11204. } elseif ($actionstatic->type_code == 'AC_TEL') {
  11205. $iconClass = 'fa fa-phone';
  11206. } elseif ($actionstatic->type_code == 'AC_FAX') {
  11207. $iconClass = 'fa fa-fax';
  11208. } elseif ($actionstatic->type_code == 'AC_EMAIL') {
  11209. $iconClass = 'fa fa-envelope';
  11210. } elseif ($actionstatic->type_code == 'AC_INT') {
  11211. $iconClass = 'fa fa-shipping-fast';
  11212. } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
  11213. $iconClass = 'fa fa-robot';
  11214. } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
  11215. $iconClass = 'fa fa-robot';
  11216. }
  11217. }
  11218. }
  11219. $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
  11220. return $out;
  11221. }
  11222. /**
  11223. * getActionCommEcmList
  11224. *
  11225. * @param ActionComm $object Object ActionComm
  11226. * @return array Array of documents in index table
  11227. */
  11228. function getActionCommEcmList($object)
  11229. {
  11230. global $conf, $db;
  11231. $documents = array();
  11232. $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename';
  11233. $sql .= ' FROM '.MAIN_DB_PREFIX.'ecm_files ecm';
  11234. $sql .= " WHERE ecm.filepath = 'agenda/".((int) $object->id)."'";
  11235. //$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
  11236. $sql .= ' ORDER BY ecm.position ASC';
  11237. $resql = $db->query($sql);
  11238. if ($resql) {
  11239. if ($db->num_rows($resql)) {
  11240. while ($obj = $db->fetch_object($resql)) {
  11241. $documents[$obj->id] = $obj;
  11242. }
  11243. }
  11244. }
  11245. return $documents;
  11246. }
  11247. /**
  11248. * Show html area with actions in messaging format.
  11249. * Note: Global parameter $param must be defined.
  11250. *
  11251. * @param Conf $conf Object conf
  11252. * @param Translate $langs Object langs
  11253. * @param DoliDB $db Object db
  11254. * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object
  11255. * @param Contact $objcon Filter on object contact to filter events on a contact
  11256. * @param int $noprint Return string but does not output it
  11257. * @param string $actioncode Filter on actioncode
  11258. * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all).
  11259. * @param array $filters Filter on other fields
  11260. * @param string $sortfield Sort field
  11261. * @param string $sortorder Sort order
  11262. * @return string|void Return html part or void if noprint is 1
  11263. */
  11264. function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
  11265. {
  11266. global $user, $conf;
  11267. global $form;
  11268. global $param, $massactionbutton;
  11269. dol_include_once('/comm/action/class/actioncomm.class.php');
  11270. // Check parameters
  11271. if (!is_object($filterobj) && !is_object($objcon)) {
  11272. dol_print_error('', 'BadParameter');
  11273. }
  11274. $histo = array();
  11275. $numaction = 0;
  11276. $now = dol_now();
  11277. $sortfield_list = explode(',', $sortfield);
  11278. $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
  11279. $sortfield_new_list = array();
  11280. foreach ($sortfield_list as $sortfield_value) {
  11281. $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
  11282. }
  11283. $sortfield_new = implode(',', $sortfield_new_list);
  11284. if (isModEnabled('agenda')) {
  11285. // Search histo on actioncomm
  11286. if (is_object($objcon) && $objcon->id > 0) {
  11287. $sql = "SELECT DISTINCT a.id, a.label as label,";
  11288. } else {
  11289. $sql = "SELECT a.id, a.label as label,";
  11290. }
  11291. $sql .= " a.datep as dp,";
  11292. $sql .= " a.note as message,";
  11293. $sql .= " a.datep2 as dp2,";
  11294. $sql .= " a.percent as percent, 'action' as type,";
  11295. $sql .= " a.fk_element, a.elementtype,";
  11296. $sql .= " a.fk_contact,";
  11297. $sql .= " a.email_from as msg_from,";
  11298. $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
  11299. $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";
  11300. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11301. $sql .= ", sp.lastname, sp.firstname";
  11302. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11303. $sql .= ", m.lastname, m.firstname";
  11304. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11305. $sql .= ", o.ref";
  11306. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11307. $sql .= ", o.ref";
  11308. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11309. $sql .= ", o.ref";
  11310. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11311. $sql .= ", o.ref";
  11312. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11313. $sql .= ", o.ref";
  11314. }
  11315. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  11316. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
  11317. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
  11318. $force_filter_contact = false;
  11319. if (is_object($objcon) && $objcon->id > 0) {
  11320. $force_filter_contact = true;
  11321. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
  11322. $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
  11323. }
  11324. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11325. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
  11326. } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
  11327. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
  11328. $sql .= " ON er.resource_type = 'dolresource'";
  11329. $sql .= " AND er.element_id = a.id";
  11330. $sql .= " AND er.resource_id = ".((int) $filterobj->id);
  11331. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11332. $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
  11333. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11334. $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
  11335. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11336. $sql .= ", ".MAIN_DB_PREFIX."product as o";
  11337. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11338. $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
  11339. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11340. $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
  11341. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11342. $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
  11343. }
  11344. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  11345. if ($force_filter_contact === false) {
  11346. if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
  11347. $sql .= " AND a.fk_soc = ".((int) $filterobj->id);
  11348. } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
  11349. $sql .= " AND a.fk_project = ".((int) $filterobj->id);
  11350. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11351. $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
  11352. if ($filterobj->id) {
  11353. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11354. }
  11355. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11356. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
  11357. if ($filterobj->id) {
  11358. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11359. }
  11360. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11361. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
  11362. if ($filterobj->id) {
  11363. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11364. }
  11365. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11366. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
  11367. if ($filterobj->id) {
  11368. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11369. }
  11370. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11371. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
  11372. if ($filterobj->id) {
  11373. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11374. }
  11375. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11376. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
  11377. if ($filterobj->id) {
  11378. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11379. }
  11380. }
  11381. }
  11382. // Condition on actioncode
  11383. if (!empty($actioncode)) {
  11384. if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  11385. if ($actioncode == 'AC_NON_AUTO') {
  11386. $sql .= " AND c.type != 'systemauto'";
  11387. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11388. $sql .= " AND c.type = 'systemauto'";
  11389. } else {
  11390. if ($actioncode == 'AC_OTH') {
  11391. $sql .= " AND c.type != 'systemauto'";
  11392. } elseif ($actioncode == 'AC_OTH_AUTO') {
  11393. $sql .= " AND c.type = 'systemauto'";
  11394. }
  11395. }
  11396. } else {
  11397. if ($actioncode == 'AC_NON_AUTO') {
  11398. $sql .= " AND c.type != 'systemauto'";
  11399. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11400. $sql .= " AND c.type = 'systemauto'";
  11401. } else {
  11402. $sql .= " AND c.code = '".$db->escape($actioncode)."'";
  11403. }
  11404. }
  11405. }
  11406. if ($donetodo == 'todo') {
  11407. $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11408. } elseif ($donetodo == 'done') {
  11409. $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11410. }
  11411. if (is_array($filters) && $filters['search_agenda_label']) {
  11412. $sql .= natural_search('a.label', $filters['search_agenda_label']);
  11413. }
  11414. }
  11415. // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
  11416. if (isModEnabled('mailing') && !empty($objcon->email)
  11417. && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
  11418. $langs->load("mails");
  11419. $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";
  11420. $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
  11421. $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
  11422. $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
  11423. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11424. $sql2 .= ", '' as lastname, '' as firstname";
  11425. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11426. $sql2 .= ", '' as lastname, '' as firstname";
  11427. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11428. $sql2 .= ", '' as ref";
  11429. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11430. $sql2 .= ", '' as ref";
  11431. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11432. $sql2 .= ", '' as ref";
  11433. }
  11434. $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
  11435. $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
  11436. $sql2 .= " AND mc.statut = 1";
  11437. $sql2 .= " AND u.rowid = m.fk_user_valid";
  11438. $sql2 .= " AND mc.fk_mailing=m.rowid";
  11439. }
  11440. if (!empty($sql) && !empty($sql2)) {
  11441. $sql = $sql." UNION ".$sql2;
  11442. } elseif (empty($sql) && !empty($sql2)) {
  11443. $sql = $sql2;
  11444. }
  11445. // TODO Add limit in nb of results
  11446. if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too
  11447. $sql .= $db->order($sortfield_new, $sortorder);
  11448. dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
  11449. $resql = $db->query($sql);
  11450. if ($resql) {
  11451. $i = 0;
  11452. $num = $db->num_rows($resql);
  11453. while ($i < $num) {
  11454. $obj = $db->fetch_object($resql);
  11455. if ($obj->type == 'action') {
  11456. $contactaction = new ActionComm($db);
  11457. $contactaction->id = $obj->id;
  11458. $result = $contactaction->fetchResources();
  11459. if ($result < 0) {
  11460. dol_print_error($db);
  11461. setEventMessage("actions.lib::show_actions_messaging Error fetch ressource", 'errors');
  11462. }
  11463. //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11464. //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11465. $tododone = '';
  11466. if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
  11467. $tododone = 'todo';
  11468. }
  11469. $histo[$numaction] = array(
  11470. 'type'=>$obj->type,
  11471. 'tododone'=>$tododone,
  11472. 'id'=>$obj->id,
  11473. 'datestart'=>$db->jdate($obj->dp),
  11474. 'dateend'=>$db->jdate($obj->dp2),
  11475. 'note'=>$obj->label,
  11476. 'message'=>$obj->message,
  11477. 'percent'=>$obj->percent,
  11478. 'userid'=>$obj->user_id,
  11479. 'login'=>$obj->user_login,
  11480. 'userfirstname'=>$obj->user_firstname,
  11481. 'userlastname'=>$obj->user_lastname,
  11482. 'userphoto'=>$obj->user_photo,
  11483. 'msg_from'=>$obj->msg_from,
  11484. 'contact_id'=>$obj->fk_contact,
  11485. 'socpeopleassigned' => $contactaction->socpeopleassigned,
  11486. 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
  11487. 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
  11488. 'fk_element'=>$obj->fk_element,
  11489. 'elementtype'=>$obj->elementtype,
  11490. // Type of event
  11491. 'acode'=>$obj->acode,
  11492. 'alabel'=>$obj->alabel,
  11493. 'libelle'=>$obj->alabel, // deprecated
  11494. 'apicto'=>$obj->apicto
  11495. );
  11496. } else {
  11497. $histo[$numaction] = array(
  11498. 'type'=>$obj->type,
  11499. 'tododone'=>'done',
  11500. 'id'=>$obj->id,
  11501. 'datestart'=>$db->jdate($obj->dp),
  11502. 'dateend'=>$db->jdate($obj->dp2),
  11503. 'note'=>$obj->label,
  11504. 'message'=>$obj->message,
  11505. 'percent'=>$obj->percent,
  11506. 'acode'=>$obj->acode,
  11507. 'userid'=>$obj->user_id,
  11508. 'login'=>$obj->user_login,
  11509. 'userfirstname'=>$obj->user_firstname,
  11510. 'userlastname'=>$obj->user_lastname,
  11511. 'userphoto'=>$obj->user_photo
  11512. );
  11513. }
  11514. $numaction++;
  11515. $i++;
  11516. }
  11517. } else {
  11518. dol_print_error($db);
  11519. }
  11520. }
  11521. // Set $out to show events
  11522. $out = '';
  11523. if (!isModEnabled('agenda')) {
  11524. $langs->loadLangs(array("admin", "errors"));
  11525. $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
  11526. }
  11527. if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
  11528. $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
  11529. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  11530. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  11531. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  11532. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  11533. $formactions = new FormActions($db);
  11534. $actionstatic = new ActionComm($db);
  11535. $userstatic = new User($db);
  11536. $contactstatic = new Contact($db);
  11537. $userGetNomUrlCache = array();
  11538. $contactGetNomUrlCache = array();
  11539. $out .= '<div class="filters-container" >';
  11540. $out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  11541. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  11542. if ($objcon && get_class($objcon) == 'Contact' &&
  11543. (is_null($filterobj) || get_class($filterobj) == 'Societe')) {
  11544. $out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
  11545. } else {
  11546. $out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
  11547. }
  11548. if ($filterobj && get_class($filterobj) == 'Societe') {
  11549. $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
  11550. }
  11551. $out .= "\n";
  11552. $out .= '<div class="div-table-responsive-no-min">';
  11553. $out .= '<table class="noborder borderbottom centpercent">';
  11554. $out .= '<tr class="liste_titre">';
  11555. // Action column
  11556. if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  11557. $out .= '<th class="liste_titre width50 middle">';
  11558. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11559. $out .= $searchpicto;
  11560. $out .= '</th>';
  11561. }
  11562. $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n";
  11563. $out .= '<th class="liste_titre"><strong class="hideonsmartphone">'.$langs->trans("Search").' : </strong></th>';
  11564. if ($donetodo) {
  11565. $out .= '<th class="liste_titre"></th>';
  11566. }
  11567. $out .= '<th class="liste_titre">';
  11568. $out .= '<span class="fas fa-square inline-block fawidth30" style=" color: #ddd;" title="'.$langs->trans("ActionType").'"></span>';
  11569. //$out .= img_picto($langs->trans("Type"), 'type');
  11570. $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1, 'minwidth200imp');
  11571. $out .= '</th>';
  11572. $out .= '<th class="liste_titre maxwidth100onsmartphone">';
  11573. $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'" placeholder="'.$langs->trans("Label").'">';
  11574. $out .= '</th>';
  11575. // Action column
  11576. if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  11577. $out .= '<th class="liste_titre width50 middle">';
  11578. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11579. $out .= $searchpicto;
  11580. $out .= '</th>';
  11581. }
  11582. $out .= '</tr>';
  11583. $out .= '</table>';
  11584. $out .= '</form>';
  11585. $out .= '</div>';
  11586. $out .= "\n";
  11587. $out .= '<ul class="timeline">';
  11588. if ($donetodo) {
  11589. $tmp = '';
  11590. if (get_class($filterobj) == 'Societe') {
  11591. $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
  11592. }
  11593. $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
  11594. $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
  11595. $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
  11596. //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
  11597. if (get_class($filterobj) == 'Societe') {
  11598. $tmp .= '</a>';
  11599. }
  11600. $out .= getTitleFieldOfList($tmp);
  11601. }
  11602. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
  11603. $caction = new CActionComm($db);
  11604. $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1);
  11605. $actualCycleDate = false;
  11606. // Loop on each event to show it
  11607. foreach ($histo as $key => $value) {
  11608. $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
  11609. $actionstatic->type_picto = $histo[$key]['apicto'];
  11610. $actionstatic->type_code = $histo[$key]['acode'];
  11611. $labeltype = $actionstatic->type_code;
  11612. if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) {
  11613. $labeltype = 'AC_OTH';
  11614. }
  11615. if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11616. $labeltype = $langs->trans("Message");
  11617. } else {
  11618. if (!empty($arraylist[$labeltype])) {
  11619. $labeltype = $arraylist[$labeltype];
  11620. }
  11621. if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) {
  11622. $labeltype .= ' - '.$arraylist[$actionstatic->code]; // Use code in priority on type_code
  11623. }
  11624. }
  11625. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
  11626. $tmpa = dol_getdate($histo[$key]['datestart'], false);
  11627. if ($actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
  11628. $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
  11629. $out .= '<!-- timeline time label -->';
  11630. $out .= '<li class="time-label">';
  11631. $out .= '<span class="timeline-badge-date">';
  11632. $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
  11633. $out .= '</span>';
  11634. $out .= '</li>';
  11635. $out .= '<!-- /.timeline-label -->';
  11636. }
  11637. $out .= '<!-- timeline item -->'."\n";
  11638. $out .= '<li class="timeline-code-'.strtolower($actionstatic->code).'">';
  11639. //$timelineicon = getTimelineIcon($actionstatic, $histo, $key);
  11640. $typeicon = $actionstatic->getTypePicto('pictofixedwidth timeline-icon-not-applicble', $labeltype);
  11641. //$out .= $timelineicon;
  11642. //var_dump($timelineicon);
  11643. $out .= $typeicon;
  11644. $out .= '<div class="timeline-item">'."\n";
  11645. $out .= '<span class="timeline-header-action">';
  11646. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
  11647. $out .= '<a class="timeline-btn" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11648. $out .= $histo[$key]['id'];
  11649. $out .= '</a> ';
  11650. } else {
  11651. $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle').' ';
  11652. }
  11653. if ($user->hasRight('agenda', 'allactions', 'create') ||
  11654. (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
  11655. $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>';
  11656. }
  11657. $out .= '</span>';
  11658. // Date
  11659. $out .= '<span class="time"><i class="fa fa-clock-o valignmiddle"></i> <span class="valignmiddle">';
  11660. $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
  11661. if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
  11662. $tmpa = dol_getdate($histo[$key]['datestart'], true);
  11663. $tmpb = dol_getdate($histo[$key]['dateend'], true);
  11664. if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
  11665. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
  11666. } else {
  11667. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
  11668. }
  11669. }
  11670. $late = 0;
  11671. if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11672. $late = 1;
  11673. }
  11674. if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11675. $late = 1;
  11676. }
  11677. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
  11678. $late = 1;
  11679. }
  11680. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11681. $late = 1;
  11682. }
  11683. if ($late) {
  11684. $out .= img_warning($langs->trans("Late")).' ';
  11685. }
  11686. $out .= "</span></span>\n";
  11687. // Ref
  11688. $out .= '<h3 class="timeline-header">';
  11689. // Author of event
  11690. $out .= '<div class="messaging-author inline-block tdoverflowmax150 valignmiddle marginrightonly">';
  11691. if ($histo[$key]['userid'] > 0) {
  11692. if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
  11693. $userstatic->fetch($histo[$key]['userid']);
  11694. $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
  11695. }
  11696. $out .= $userGetNomUrlCache[$histo[$key]['userid']];
  11697. } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
  11698. if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
  11699. if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
  11700. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
  11701. } else {
  11702. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
  11703. }
  11704. }
  11705. $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
  11706. }
  11707. $out .= '</div>';
  11708. // Title
  11709. $out .= ' <div class="messaging-title inline-block">';
  11710. //$out .= $actionstatic->getTypePicto();
  11711. if (empty($conf->dol_optimize_smallscreen) && $actionstatic->type_code != 'AC_OTH_AUTO') {
  11712. $out .= $labeltype.' - ';
  11713. }
  11714. $libelle = '';
  11715. if (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11716. $out .= $langs->trans('TicketNewMessage');
  11717. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  11718. $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
  11719. } elseif (isset($histo[$key]['type'])) {
  11720. if ($histo[$key]['type'] == 'action') {
  11721. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11722. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
  11723. $libelle = $histo[$key]['note'];
  11724. $actionstatic->id = $histo[$key]['id'];
  11725. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11726. } elseif ($histo[$key]['type'] == 'mailing') {
  11727. $out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11728. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11729. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
  11730. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11731. } else {
  11732. $libelle .= $histo[$key]['note'];
  11733. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11734. }
  11735. }
  11736. if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) {
  11737. if (isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']]) && isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']])) {
  11738. $link = $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']];
  11739. } else {
  11740. if (!isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']])) {
  11741. $conf->cache['elementlinkcache'][$histo[$key]['elementtype']] = array();
  11742. }
  11743. $link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1);
  11744. $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link;
  11745. }
  11746. if ($link) {
  11747. $out .= ' - '.$link;
  11748. }
  11749. }
  11750. $out .= '</div>';
  11751. $out .= '</h3>';
  11752. // Message
  11753. if (!empty($histo[$key]['message'] && $histo[$key]['message'] != $libelle)
  11754. && $actionstatic->code != 'AC_TICKET_CREATE'
  11755. && $actionstatic->code != 'AC_TICKET_MODIFY'
  11756. ) {
  11757. $out .= '<div class="timeline-body classfortooltip" title="'.dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($histo[$key]['message']), 1, 1, 1)), 1, 1).'">';
  11758. $out .= dolGetFirstLineOfText($histo[$key]['message'], 3);
  11759. $out .= '</div>';
  11760. }
  11761. // Timeline footer
  11762. $footer = '';
  11763. // Contact for this action
  11764. if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
  11765. $contactList = '';
  11766. foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
  11767. if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
  11768. $contact = new Contact($db);
  11769. $contact->fetch($cid);
  11770. $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
  11771. } else {
  11772. $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
  11773. }
  11774. if ($contact) {
  11775. $contactList .= !empty($contactList) ? ', ' : '';
  11776. $contactList .= $contact->getNomUrl(1);
  11777. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11778. if (!empty($contact->phone_pro)) {
  11779. $contactList .= '('.dol_print_phone($contact->phone_pro).')';
  11780. }
  11781. }
  11782. }
  11783. }
  11784. $footer .= $langs->trans('ActionOnContact').' : '.$contactList;
  11785. } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
  11786. if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
  11787. $contact = new Contact($db);
  11788. $result = $contact->fetch($histo[$key]['contact_id']);
  11789. $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
  11790. } else {
  11791. $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
  11792. }
  11793. if ($result > 0) {
  11794. $footer .= $contact->getNomUrl(1);
  11795. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11796. if (!empty($contact->phone_pro)) {
  11797. $footer .= '('.dol_print_phone($contact->phone_pro).')';
  11798. }
  11799. }
  11800. }
  11801. }
  11802. $documents = getActionCommEcmList($actionstatic);
  11803. if (!empty($documents)) {
  11804. $footer .= '<div class="timeline-documents-container">';
  11805. foreach ($documents as $doc) {
  11806. $footer .= '<span id="document_'.$doc->id.'" class="timeline-documents" ';
  11807. $footer .= ' data-id="'.$doc->id.'" ';
  11808. $footer .= ' data-path="'.$doc->filepath.'"';
  11809. $footer .= ' data-filename="'.dol_escape_htmltag($doc->filename).'" ';
  11810. $footer .= '>';
  11811. $filePath = DOL_DATA_ROOT.'/'.$doc->filepath.'/'.$doc->filename;
  11812. $mime = dol_mimetype($filePath);
  11813. $file = $actionstatic->id.'/'.$doc->filename;
  11814. $thumb = $actionstatic->id.'/thumbs/'.substr($doc->filename, 0, strrpos($doc->filename, '.')).'_mini'.substr($doc->filename, strrpos($doc->filename, '.'));
  11815. $doclink = dol_buildpath('document.php', 1).'?modulepart=actions&attachment=0&file='.urlencode($file).'&entity='.$conf->entity;
  11816. $viewlink = dol_buildpath('viewimage.php', 1).'?modulepart=actions&file='.urlencode($thumb).'&entity='.$conf->entity;
  11817. $mimeAttr = ' mime="'.$mime.'" ';
  11818. $class = '';
  11819. if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
  11820. $class .= ' documentpreview';
  11821. }
  11822. $footer .= '<a href="'.$doclink.'" class="btn-link '.$class.'" target="_blank" rel="noopener noreferrer" '.$mimeAttr.' >';
  11823. $footer .= img_mime($filePath).' '.$doc->filename;
  11824. $footer .= '</a>';
  11825. $footer .= '</span>';
  11826. }
  11827. $footer .= '</div>';
  11828. }
  11829. if (!empty($footer)) {
  11830. $out .= '<div class="timeline-footer">'.$footer.'</div>';
  11831. }
  11832. $out .= '</div>'."\n"; // end timeline-item
  11833. $out .= '</li>';
  11834. $out .= '<!-- END timeline item -->';
  11835. $i++;
  11836. }
  11837. $out .= "</ul>\n";
  11838. if (empty($histo)) {
  11839. $out .= '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
  11840. }
  11841. }
  11842. if ($noprint) {
  11843. return $out;
  11844. } else {
  11845. print $out;
  11846. }
  11847. }
  11848. /**
  11849. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  11850. * optionally hour, minute, second) fields to return a timestamp.
  11851. *
  11852. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  11853. * @param string $hourTime 'getpost' to include hour, minute, second values from the HTTP request, 'XX:YY:ZZ' to set
  11854. * hour, minute, second respectively (for instance '23:59:59')
  11855. * @param string $gm Passed to dol_mktime
  11856. * @return int|string Date as a timestamp, '' or false if error
  11857. */
  11858. function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto')
  11859. {
  11860. if ($hourTime === 'getpost') {
  11861. $hour = GETPOSTINT($prefix . 'hour');
  11862. $minute = GETPOSTINT($prefix . 'minute');
  11863. $second = GETPOSTINT($prefix . 'second');
  11864. } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
  11865. $hour = intval($m[1]);
  11866. $minute = intval($m[2]);
  11867. $second = intval($m[3]);
  11868. } else {
  11869. $hour = $minute = $second = 0;
  11870. }
  11871. // normalize out of range values
  11872. $hour = min($hour, 23);
  11873. $minute = min($minute, 59);
  11874. $second = min($second, 59);
  11875. return dol_mktime($hour, $minute, $second, GETPOSTINT($prefix . 'month'), GETPOSTINT($prefix . 'day'), GETPOSTINT($prefix . 'year'), $gm);
  11876. }
  11877. /**
  11878. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  11879. * optionally hour, minute, second) fields to return a a portion of URL reproducing the values from the current HTTP
  11880. * request.
  11881. *
  11882. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  11883. * @param int $timestamp If null, the timestamp will be created from request data
  11884. * @param bool $hourTime If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  11885. * @param bool $gm If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  11886. * @return string Portion of URL with query parameters for the specified date
  11887. */
  11888. function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
  11889. {
  11890. if ($timestamp === null) $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
  11891. $TParam = array(
  11892. $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
  11893. $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
  11894. $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
  11895. );
  11896. if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
  11897. $TParam = array_merge($TParam, array(
  11898. $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
  11899. $prefix . 'minute' => intval(dol_print_date($timestamp, '%M')),
  11900. $prefix . 'second' => intval(dol_print_date($timestamp, '%S'))
  11901. ));
  11902. }
  11903. return '&' . http_build_query($TParam);
  11904. }