functions.lib.php 409 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. *
  21. * This program is free software; you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation; either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  33. * or see https://www.gnu.org/
  34. */
  35. /**
  36. * \file htdocs/core/lib/functions.lib.php
  37. * \brief A set of functions for Dolibarr
  38. * This file contains all frequently used functions.
  39. */
  40. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  41. /**
  42. * Return dolibarr global constant string value
  43. * @param string $key key to return value, return '' if not set
  44. * @return string
  45. */
  46. function getDolGlobalString($key)
  47. {
  48. global $conf;
  49. // return $conf->global->$key ?? '';
  50. return (string) (empty($conf->global->$key) ? '' : $conf->global->$key);
  51. }
  52. /**
  53. * Return dolibarr global constant int value
  54. * @param string $key key to return value, return 0 if not set
  55. * @return int
  56. */
  57. function getDolGlobalInt($key)
  58. {
  59. global $conf;
  60. // return $conf->global->$key ?? 0;
  61. return (int) (empty($conf->global->$key) ? 0 : $conf->global->$key);
  62. }
  63. /**
  64. * Return a DoliDB instance (database handler).
  65. *
  66. * @param string $type Type of database (mysql, pgsql...)
  67. * @param string $host Address of database server
  68. * @param string $user Authorized username
  69. * @param string $pass Password
  70. * @param string $name Name of database
  71. * @param int $port Port of database server
  72. * @return DoliDB A DoliDB instance
  73. */
  74. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  75. {
  76. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  77. $class = 'DoliDB'.ucfirst($type);
  78. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  79. return $dolidb;
  80. }
  81. /**
  82. * Get list of entity id to use.
  83. *
  84. * @param string $element Current element
  85. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  86. * 'product', 'productprice', 'stock', 'bom', 'mo',
  87. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  88. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  89. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  90. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  91. * 'email_template', 'event', 'donation'
  92. * 'c_paiement', 'c_payment_term', ...
  93. * @param int $shared 0=Return id of current entity only,
  94. * 1=Return id of current entity + shared entities (default)
  95. * @param object $currentobject Current object if needed
  96. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  97. */
  98. function getEntity($element, $shared = 1, $currentobject = null)
  99. {
  100. global $conf, $mc;
  101. // fix different element names (France to English)
  102. switch ($element) {
  103. case 'contrat':
  104. $element = 'contract';
  105. break; // "/contrat/class/contrat.class.php"
  106. case 'order_supplier':
  107. $element = 'supplier_order';
  108. break; // "/fourn/class/fournisseur.commande.class.php"
  109. }
  110. if (is_object($mc)) {
  111. return $mc->getEntity($element, $shared, $currentobject);
  112. } else {
  113. $out = '';
  114. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  115. if (in_array($element, $addzero)) {
  116. $out .= '0,';
  117. }
  118. $out .= ((int) $conf->entity);
  119. return $out;
  120. }
  121. }
  122. /**
  123. * Set entity id to use when to create an object
  124. *
  125. * @param object $currentobject Current object
  126. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  127. */
  128. function setEntity($currentobject)
  129. {
  130. global $conf, $mc;
  131. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  132. return $mc->setEntity($currentobject);
  133. } else {
  134. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  135. }
  136. }
  137. /**
  138. * Return if string has a name dedicated to store a secret
  139. *
  140. * @param string $keyname Name of key to test
  141. * @return boolean True if key is used to store a secret
  142. */
  143. function isASecretKey($keyname)
  144. {
  145. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  146. }
  147. /**
  148. * Return information about user browser
  149. *
  150. * Returns array with the following format:
  151. * array(
  152. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  153. * 'browserversion' => Browser version. Empty if unknown
  154. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  155. * 'layout' => (tablet|phone|classic)
  156. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  157. * 'tablet' => true/false
  158. * )
  159. *
  160. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  161. * @return array Check function documentation
  162. */
  163. function getBrowserInfo($user_agent)
  164. {
  165. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  166. $name = 'unknown';
  167. $version = '';
  168. $os = 'unknown';
  169. $phone = '';
  170. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  171. $detectmobile = new Mobile_Detect(null, $user_agent);
  172. $tablet = $detectmobile->isTablet();
  173. if ($detectmobile->isMobile()) {
  174. $phone = 'unknown';
  175. // If phone/smartphone, we set phone os name.
  176. if ($detectmobile->is('AndroidOS')) {
  177. $os = $phone = 'android';
  178. } elseif ($detectmobile->is('BlackBerryOS')) {
  179. $os = $phone = 'blackberry';
  180. } elseif ($detectmobile->is('iOS')) {
  181. $os = 'ios';
  182. $phone = 'iphone';
  183. } elseif ($detectmobile->is('PalmOS')) {
  184. $os = $phone = 'palm';
  185. } elseif ($detectmobile->is('SymbianOS')) {
  186. $os = 'symbian';
  187. } elseif ($detectmobile->is('webOS')) {
  188. $os = 'webos';
  189. } elseif ($detectmobile->is('MaemoOS')) {
  190. $os = 'maemo';
  191. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  192. $os = 'windows';
  193. }
  194. }
  195. // OS
  196. if (preg_match('/linux/i', $user_agent)) {
  197. $os = 'linux';
  198. } elseif (preg_match('/macintosh/i', $user_agent)) {
  199. $os = 'macintosh';
  200. } elseif (preg_match('/windows/i', $user_agent)) {
  201. $os = 'windows';
  202. }
  203. // Name
  204. $reg = array();
  205. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  206. $name = 'firefox';
  207. $version = $reg[2];
  208. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  209. $name = 'edge';
  210. $version = $reg[2];
  211. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  212. $name = 'chrome';
  213. $version = $reg[2];
  214. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  215. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  216. $name = 'chrome';
  217. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  218. $name = 'iceweasel';
  219. } elseif (preg_match('/epiphany/i', $user_agent)) {
  220. $name = 'epiphany';
  221. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  222. $name = 'safari';
  223. $version = $reg[2];
  224. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  225. // Safari is often present in string for mobile but its not.
  226. $name = 'opera';
  227. $version = $reg[2];
  228. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  229. $name = 'ie';
  230. $version = end($reg);
  231. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  232. // MS products at end
  233. $name = 'ie';
  234. $version = end($reg);
  235. } elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  236. // MS products at end
  237. $name = 'lynxlinks';
  238. $version = $reg[4];
  239. }
  240. if ($tablet) {
  241. $layout = 'tablet';
  242. } elseif ($phone) {
  243. $layout = 'phone';
  244. } else {
  245. $layout = 'classic';
  246. }
  247. return array(
  248. 'browsername' => $name,
  249. 'browserversion' => $version,
  250. 'browseros' => $os,
  251. 'layout' => $layout,
  252. 'phone' => $phone,
  253. 'tablet' => $tablet
  254. );
  255. }
  256. /**
  257. * Function called at end of web php process
  258. *
  259. * @return void
  260. */
  261. function dol_shutdown()
  262. {
  263. global $conf, $user, $langs, $db;
  264. $disconnectdone = false;
  265. $depth = 0;
  266. if (is_object($db) && !empty($db->connected)) {
  267. $depth = $db->transaction_opened;
  268. $disconnectdone = $db->close();
  269. }
  270. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  271. }
  272. /**
  273. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  274. *
  275. * @param string $paramname Name or parameter to test
  276. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  277. */
  278. function GETPOSTISSET($paramname)
  279. {
  280. $isset = false;
  281. $relativepathstring = $_SERVER["PHP_SELF"];
  282. // Clean $relativepathstring
  283. if (constant('DOL_URL_ROOT')) {
  284. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  285. }
  286. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  287. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  288. //var_dump($relativepathstring);
  289. //var_dump($user->default_values);
  290. // Code for search criteria persistence.
  291. // Retrieve values if restore_lastsearch_values
  292. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  293. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  294. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  295. if (is_array($tmp)) {
  296. foreach ($tmp as $key => $val) {
  297. if ($key == $paramname) { // We are on the requested parameter
  298. $isset = true;
  299. break;
  300. }
  301. }
  302. }
  303. }
  304. // If there is saved contextpage, page or limit
  305. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  306. $isset = true;
  307. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  308. $isset = true;
  309. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  310. $isset = true;
  311. }
  312. } else {
  313. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  314. }
  315. return $isset;
  316. }
  317. /**
  318. * Return value of a param into GET or POST supervariable.
  319. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  320. * Note: The property $user->default_values is loaded by main.php when loading the user.
  321. *
  322. * @param string $paramname Name of parameter to found
  323. * @param string $check Type of check
  324. * ''=no check (deprecated)
  325. * 'none'=no check (only for param that should have very rich content)
  326. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  327. * 'int'=check it's numeric (integer or float)
  328. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  329. * 'alpha'=Same than alphanohtml since v13
  330. * 'alphawithlgt'=alpha with lgt
  331. * 'alphanohtml'=check there is no html content and no " and no ../
  332. * 'aZ'=check it's a-z only
  333. * 'aZ09'=check it's simple alpha string (recommended for keys)
  334. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  335. * 'nohtml'=check there is no html content and no " and no ../
  336. * 'restricthtml'=check html content is restricted to some tags only
  337. * 'custom'= custom filter specify $filter and $options)
  338. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  339. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  340. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  341. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  342. * @return string|array Value found (string or array), or '' if check fails
  343. */
  344. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  345. {
  346. global $mysoc, $user, $conf;
  347. if (empty($paramname)) {
  348. return 'BadFirstParameterForGETPOST';
  349. }
  350. if (empty($check)) {
  351. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  352. // Enable this line to know who call the GETPOST with '' $check parameter.
  353. //var_dump(debug_backtrace()[0]);
  354. }
  355. if (empty($method)) {
  356. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  357. } elseif ($method == 1) {
  358. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  359. } elseif ($method == 2) {
  360. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  361. } elseif ($method == 3) {
  362. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  363. } else {
  364. return 'BadThirdParameterForGETPOST';
  365. }
  366. if (empty($method) || $method == 3 || $method == 4) {
  367. $relativepathstring = $_SERVER["PHP_SELF"];
  368. // Clean $relativepathstring
  369. if (constant('DOL_URL_ROOT')) {
  370. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  371. }
  372. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  373. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  374. //var_dump($relativepathstring);
  375. //var_dump($user->default_values);
  376. // Code for search criteria persistence.
  377. // Retrieve values if restore_lastsearch_values
  378. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  379. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  380. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  381. if (is_array($tmp)) {
  382. foreach ($tmp as $key => $val) {
  383. if ($key == $paramname) { // We are on the requested parameter
  384. $out = $val;
  385. break;
  386. }
  387. }
  388. }
  389. }
  390. // If there is saved contextpage, page or limit
  391. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  392. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  393. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  394. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  395. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  396. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  397. }
  398. } elseif (!isset($_GET['sortfield'])) {
  399. // Else, retrieve default values if we are not doing a sort
  400. // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
  401. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  402. // Search default value from $object->field
  403. global $object;
  404. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  405. $out = $object->fields[$paramname]['default'];
  406. }
  407. }
  408. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  409. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  410. // Now search in setup to overwrite default values
  411. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  412. if (isset($user->default_values[$relativepathstring]['createform'])) {
  413. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  414. $qualified = 0;
  415. if ($defkey != '_noquery_') {
  416. $tmpqueryarraytohave = explode('&', $defkey);
  417. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  418. $foundintru = 0;
  419. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  420. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  421. $foundintru = 1;
  422. }
  423. }
  424. if (!$foundintru) {
  425. $qualified = 1;
  426. }
  427. //var_dump($defkey.'-'.$qualified);
  428. } else {
  429. $qualified = 1;
  430. }
  431. if ($qualified) {
  432. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  433. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  434. break;
  435. }
  436. }
  437. }
  438. }
  439. }
  440. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  441. // Management of default search_filters and sort order
  442. if (!empty($user->default_values)) {
  443. // $user->default_values defined from menu 'Setup - Default values'
  444. //var_dump($user->default_values[$relativepathstring]);
  445. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  446. // Sorted on which fields ? ASC or DESC ?
  447. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  448. // Even if paramname is sortfield, data are stored into ['sortorder...']
  449. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  450. $qualified = 0;
  451. if ($defkey != '_noquery_') {
  452. $tmpqueryarraytohave = explode('&', $defkey);
  453. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  454. $foundintru = 0;
  455. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  456. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  457. $foundintru = 1;
  458. }
  459. }
  460. if (!$foundintru) {
  461. $qualified = 1;
  462. }
  463. //var_dump($defkey.'-'.$qualified);
  464. } else {
  465. $qualified = 1;
  466. }
  467. if ($qualified) {
  468. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  469. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  470. if ($out) {
  471. $out .= ', ';
  472. }
  473. if ($paramname == 'sortfield') {
  474. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  475. }
  476. if ($paramname == 'sortorder') {
  477. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  478. }
  479. }
  480. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  481. }
  482. }
  483. }
  484. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  485. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  486. $qualified = 0;
  487. if ($defkey != '_noquery_') {
  488. $tmpqueryarraytohave = explode('&', $defkey);
  489. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  490. $foundintru = 0;
  491. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  492. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  493. $foundintru = 1;
  494. }
  495. }
  496. if (!$foundintru) {
  497. $qualified = 1;
  498. }
  499. //var_dump($defkey.'-'.$qualified);
  500. } else {
  501. $qualified = 1;
  502. }
  503. if ($qualified) {
  504. // We must keep $_POST and $_GET here
  505. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  506. // We made a search from quick search menu, do we still use default filter ?
  507. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  508. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  509. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  510. }
  511. } else {
  512. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  513. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  514. }
  515. break;
  516. }
  517. }
  518. }
  519. }
  520. }
  521. }
  522. }
  523. }
  524. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  525. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  526. // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text.
  527. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  528. $reg = array();
  529. $maxloop = 20;
  530. $loopnb = 0; // Protection against infinite loop
  531. while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) { // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
  532. $loopnb++;
  533. $newout = '';
  534. if ($reg[1] == 'DAY') {
  535. $tmp = dol_getdate(dol_now(), true);
  536. $newout = $tmp['mday'];
  537. } elseif ($reg[1] == 'MONTH') {
  538. $tmp = dol_getdate(dol_now(), true);
  539. $newout = $tmp['mon'];
  540. } elseif ($reg[1] == 'YEAR') {
  541. $tmp = dol_getdate(dol_now(), true);
  542. $newout = $tmp['year'];
  543. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  544. $tmp = dol_getdate(dol_now(), true);
  545. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  546. $newout = $tmp2['day'];
  547. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  548. $tmp = dol_getdate(dol_now(), true);
  549. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  550. $newout = $tmp2['month'];
  551. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  552. $tmp = dol_getdate(dol_now(), true);
  553. $newout = ($tmp['year'] - 1);
  554. } elseif ($reg[1] == 'NEXT_DAY') {
  555. $tmp = dol_getdate(dol_now(), true);
  556. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  557. $newout = $tmp2['day'];
  558. } elseif ($reg[1] == 'NEXT_MONTH') {
  559. $tmp = dol_getdate(dol_now(), true);
  560. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  561. $newout = $tmp2['month'];
  562. } elseif ($reg[1] == 'NEXT_YEAR') {
  563. $tmp = dol_getdate(dol_now(), true);
  564. $newout = ($tmp['year'] + 1);
  565. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  566. $newout = $mysoc->country_id;
  567. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  568. $newout = $user->id;
  569. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  570. $newout = $user->fk_user;
  571. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  572. $newout = $conf->entity;
  573. } else {
  574. $newout = ''; // Key not found, we replace with empty string
  575. }
  576. //var_dump('__'.$reg[1].'__ -> '.$newout);
  577. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  578. }
  579. }
  580. // Check rule
  581. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09'
  582. if (!is_array($out) || empty($out)) {
  583. $out = array();
  584. } else {
  585. $tmparray = explode(':', $check);
  586. if (!empty($tmparray[1])) {
  587. $tmpcheck = $tmparray[1];
  588. } else {
  589. $tmpcheck = 'alphanohtml';
  590. }
  591. foreach ($out as $outkey => $outval) {
  592. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  593. }
  594. }
  595. } else {
  596. $out = checkVal($out, $check, $filter, $options);
  597. }
  598. // Sanitizing for special parameters.
  599. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL.
  600. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  601. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  602. $out = str_replace(array(':', ';', '@'), '', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  603. do {
  604. $oldstringtoclean = $out;
  605. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  606. } while ($oldstringtoclean != $out);
  607. $out = preg_replace(array('/^[a-z]*\/\/+/i'), '', $out); // We remove schema*// to remove external URL
  608. }
  609. // Code for search criteria persistence.
  610. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  611. if (empty($method) || $method == 3 || $method == 4) {
  612. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  613. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  614. // We save search key only if $out not empty that means:
  615. // - posted value not empty, or
  616. // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not).
  617. if ($out != '') { // $out = '0' or 'abc', it is a search criteria to keep
  618. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  619. }
  620. }
  621. }
  622. return $out;
  623. }
  624. /**
  625. * Return value of a param into GET or POST supervariable.
  626. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  627. * Note: The property $user->default_values is loaded by main.php when loading the user.
  628. *
  629. * @param string $paramname Name of parameter to found
  630. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  631. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  632. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  633. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  634. * @return int Value found (int)
  635. */
  636. function GETPOSTINT($paramname, $method = 0, $filter = null, $options = null, $noreplace = 0)
  637. {
  638. return (int) GETPOST($paramname, 'int', $method, $filter, $options, $noreplace);
  639. }
  640. /**
  641. * Return a value after checking on a rule. A sanitization may also have been done.
  642. *
  643. * @param string $out Value to check/clear.
  644. * @param string $check Type of check/sanitizing
  645. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  646. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  647. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  648. */
  649. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  650. {
  651. global $conf;
  652. // Check is done after replacement
  653. switch ($check) {
  654. case 'none':
  655. break;
  656. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  657. if (!is_numeric($out)) {
  658. $out = '';
  659. }
  660. break;
  661. case 'intcomma':
  662. if (preg_match('/[^0-9,-]+/i', $out)) {
  663. $out = '';
  664. }
  665. break;
  666. case 'san_alpha':
  667. $out = filter_var($out, FILTER_SANITIZE_STRING);
  668. break;
  669. case 'email':
  670. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  671. break;
  672. case 'aZ':
  673. if (!is_array($out)) {
  674. $out = trim($out);
  675. if (preg_match('/[^a-z]+/i', $out)) {
  676. $out = '';
  677. }
  678. }
  679. break;
  680. case 'aZ09':
  681. if (!is_array($out)) {
  682. $out = trim($out);
  683. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  684. $out = '';
  685. }
  686. }
  687. break;
  688. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  689. if (!is_array($out)) {
  690. $out = trim($out);
  691. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  692. $out = '';
  693. }
  694. }
  695. break;
  696. case 'nohtml': // No html
  697. $out = dol_string_nohtmltag($out, 0);
  698. break;
  699. case 'alpha': // No html and no ../ and "
  700. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  701. if (!is_array($out)) {
  702. $out = trim($out);
  703. do {
  704. $oldstringtoclean = $out;
  705. // Remove html tags
  706. $out = dol_string_nohtmltag($out, 0);
  707. // Remove also other dangerous string sequences
  708. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  709. // '../' is dangerous because it allows dir transversals
  710. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  711. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#x2F', '../'), '', $out);
  712. } while ($oldstringtoclean != $out);
  713. // keep lines feed
  714. }
  715. break;
  716. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>"
  717. if (!is_array($out)) {
  718. $out = trim($out);
  719. do {
  720. $oldstringtoclean = $out;
  721. // Remove html tags
  722. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  723. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  724. // '../' is dangerous because it allows dir transversals
  725. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  726. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#x2F', '../'), '', $out);
  727. } while ($oldstringtoclean != $out);
  728. }
  729. break;
  730. case 'restricthtml': // Recommended for most html textarea
  731. do {
  732. $oldstringtoclean = $out;
  733. // 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.
  734. // 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
  735. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  736. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', 'realCharForNumericEntities', $out);
  737. // Now we remove all remaining HTML entities staring with a number. We don't want such entities.
  738. $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'.
  739. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  740. // We should also exclude non expected attributes
  741. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  742. $out = dol_string_onlythesehtmlattributes($out);
  743. }
  744. } while ($oldstringtoclean != $out);
  745. break;
  746. case 'custom':
  747. if (empty($filter)) {
  748. return 'BadFourthParameterForGETPOST';
  749. }
  750. $out = filter_var($out, $filter, $options);
  751. break;
  752. }
  753. return $out;
  754. }
  755. if (!function_exists('dol_getprefix')) {
  756. /**
  757. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  758. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  759. * or two instances in same virtual servers.
  760. *
  761. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  762. * @return string A calculated prefix
  763. */
  764. function dol_getprefix($mode = '')
  765. {
  766. // If prefix is for email (we need to have $conf alreayd loaded for this case)
  767. if ($mode == 'email') {
  768. global $conf;
  769. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  770. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  771. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  772. } elseif (isset($_SERVER["SERVER_NAME"])) {
  773. return $_SERVER["SERVER_NAME"];
  774. }
  775. }
  776. // The recommended value (may be not defined for old versions)
  777. if (!empty($conf->file->instance_unique_id)) {
  778. return $conf->file->instance_unique_id;
  779. }
  780. // For backward compatibility
  781. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  782. }
  783. // If prefix is for session (no need to have $conf loaded)
  784. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  785. $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
  786. // The recommended value (may be not defined for old versions)
  787. if (!empty($tmp_instance_unique_id)) {
  788. return $tmp_instance_unique_id;
  789. }
  790. // For backward compatibility
  791. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  792. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  793. }
  794. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  795. }
  796. }
  797. /**
  798. * Make an include_once using default root and alternate root if it fails.
  799. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  800. * To link to a module file from a module file, use include './mymodulefile';
  801. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  802. *
  803. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  804. * @param string $classname Class name (deprecated)
  805. * @return bool True if load is a success, False if it fails
  806. */
  807. function dol_include_once($relpath, $classname = '')
  808. {
  809. 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']
  810. $fullpath = dol_buildpath($relpath);
  811. if (!file_exists($fullpath)) {
  812. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  813. return false;
  814. }
  815. if (!empty($classname) && !class_exists($classname)) {
  816. return include $fullpath;
  817. } else {
  818. return include_once $fullpath;
  819. }
  820. }
  821. /**
  822. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  823. *
  824. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  825. * @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)
  826. * @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)
  827. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  828. * 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
  829. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  830. */
  831. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  832. {
  833. global $conf;
  834. $path = preg_replace('/^\//', '', $path);
  835. if (empty($type)) { // For a filesystem path
  836. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  837. if (is_array($conf->file->dol_document_root)) {
  838. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  839. if ($key == 'main') {
  840. continue;
  841. }
  842. if (file_exists($dirroot.'/'.$path)) {
  843. $res = $dirroot.'/'.$path;
  844. return $res;
  845. }
  846. }
  847. }
  848. if ($returnemptyifnotfound) {
  849. // Not found into alternate dir
  850. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  851. return '';
  852. }
  853. }
  854. } else {
  855. // For an url path
  856. // We try to get local path of file on filesystem from url
  857. // Note that trying to know if a file on disk exist by forging path on disk from url
  858. // works only for some web server and some setup. This is bugged when
  859. // using proxy, rewriting, virtual path, etc...
  860. $res = '';
  861. if ($type == 1) {
  862. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  863. }
  864. if ($type == 2) {
  865. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  866. }
  867. if ($type == 3) {
  868. $res = DOL_URL_ROOT.'/'.$path;
  869. }
  870. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  871. if ($key == 'main') {
  872. if ($type == 3) {
  873. global $dolibarr_main_url_root;
  874. // Define $urlwithroot
  875. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  876. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  877. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  878. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  879. }
  880. continue;
  881. }
  882. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  883. if (!empty($regs[1])) {
  884. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  885. if (file_exists($dirroot.'/'.$regs[1])) {
  886. if ($type == 1) {
  887. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  888. }
  889. if ($type == 2) {
  890. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  891. }
  892. if ($type == 3) {
  893. global $dolibarr_main_url_root;
  894. // Define $urlwithroot
  895. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  896. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  897. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  898. $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
  899. }
  900. break;
  901. }
  902. }
  903. }
  904. }
  905. return $res;
  906. }
  907. /**
  908. * Create a clone of instance of object (new instance with same value for properties)
  909. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  910. * 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.
  911. *
  912. * @param object $object Object to clone
  913. * @param int $native 0=Full isolation method, 1=Native PHP method
  914. * @return object Clone object
  915. * @see https://php.net/manual/language.oop5.cloning.php
  916. */
  917. function dol_clone($object, $native = 0)
  918. {
  919. if (empty($native)) {
  920. $myclone = unserialize(serialize($object)); // serialize then unserialize is hack to be sure to have a new object for all fields
  921. } else {
  922. $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)
  923. }
  924. return $myclone;
  925. }
  926. /**
  927. * Optimize a size for some browsers (phone, smarphone, ...)
  928. *
  929. * @param int $size Size we want
  930. * @param string $type Type of optimizing:
  931. * '' = function used to define a size for truncation
  932. * 'width' = function is used to define a width
  933. * @return int New size after optimizing
  934. */
  935. function dol_size($size, $type = '')
  936. {
  937. global $conf;
  938. if (empty($conf->dol_optimize_smallscreen)) {
  939. return $size;
  940. }
  941. if ($type == 'width' && $size > 250) {
  942. return 250;
  943. } else {
  944. return 10;
  945. }
  946. }
  947. /**
  948. * Clean a string to use it as a file name
  949. *
  950. * @param string $str String to clean
  951. * @param string $newstr String to replace bad chars with
  952. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  953. * @return string String cleaned (a-zA-Z_)
  954. *
  955. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  956. */
  957. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  958. {
  959. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  960. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  961. // Char '/' and '\' are file delimiters.
  962. // -- car 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
  963. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '--');
  964. return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  965. }
  966. /**
  967. * Clean a string to use it as a path name
  968. *
  969. * @param string $str String to clean
  970. * @param string $newstr String to replace bad chars with
  971. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  972. * @return string String cleaned (a-zA-Z_)
  973. *
  974. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  975. */
  976. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  977. {
  978. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°');
  979. return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  980. }
  981. /**
  982. * Clean a string to use it as an URL (into a href or src attribute)
  983. *
  984. * @param string $stringtoclean String to clean
  985. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  986. * @return string Escaped string.
  987. */
  988. function dol_sanitizeUrl($stringtoclean, $type = 1)
  989. {
  990. // 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)
  991. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  992. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  993. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  994. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  995. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  996. if ($type == 1) {
  997. // removing : should disable links to external url like http:aaa)
  998. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  999. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1000. }
  1001. do {
  1002. $oldstringtoclean = $stringtoclean;
  1003. // removing '&colon' should disable links to external url like http:aaa)
  1004. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1005. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1006. } while ($oldstringtoclean != $stringtoclean);
  1007. if ($type == 1) {
  1008. // removing '//' should disable links to external url like //aaa or http//)
  1009. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1010. }
  1011. return $stringtoclean;
  1012. }
  1013. /**
  1014. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1015. *
  1016. * @param string $str String to clean
  1017. * @return string Cleaned string
  1018. *
  1019. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1020. */
  1021. function dol_string_unaccent($str)
  1022. {
  1023. if (utf8_check($str)) {
  1024. // See http://www.utf8-chartable.de/
  1025. $string = rawurlencode($str);
  1026. $replacements = array(
  1027. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1028. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1029. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1030. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1031. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1032. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1033. '%C3%A7' => 'c',
  1034. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1035. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1036. '%C3%B1' => 'n',
  1037. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1038. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1039. '%C3%BF' => 'y'
  1040. );
  1041. $string = strtr($string, $replacements);
  1042. return rawurldecode($string);
  1043. } else {
  1044. // See http://www.ascii-code.com/
  1045. $string = strtr(
  1046. $str,
  1047. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1048. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1049. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1050. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1051. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1052. \xF9\xFA\xFB\xFC\xFD\xFF",
  1053. "AAAAAAC
  1054. EEEEIIIIDN
  1055. OOOOOUUUY
  1056. aaaaaaceeee
  1057. iiiidnooooo
  1058. uuuuyy"
  1059. );
  1060. $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"));
  1061. return $string;
  1062. }
  1063. }
  1064. /**
  1065. * Clean a string from all punctuation characters to use it as a ref or login.
  1066. * This is a more complete function than dol_sanitizeFileName.
  1067. *
  1068. * @param string $str String to clean
  1069. * @param string $newstr String to replace forbidden chars with
  1070. * @param array $badcharstoreplace List of forbidden characters
  1071. * @return string Cleaned string
  1072. *
  1073. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1074. */
  1075. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
  1076. {
  1077. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1078. $forbidden_chars_to_remove = array();
  1079. if (is_array($badcharstoreplace)) {
  1080. $forbidden_chars_to_replace = $badcharstoreplace;
  1081. }
  1082. //$forbidden_chars_to_remove=array("(",")");
  1083. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1084. }
  1085. /**
  1086. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1087. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1088. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1089. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1090. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1091. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1092. * @param string $str String to clean
  1093. * @param int $removetabcrlf Remove also CR-LF
  1094. * @return string Cleaned string
  1095. *
  1096. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1097. */
  1098. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1099. {
  1100. if ($removetabcrlf) {
  1101. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1102. } else {
  1103. 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
  1104. }
  1105. }
  1106. /**
  1107. * Returns text escaped for inclusion into javascript code
  1108. *
  1109. * @param string $stringtoescape String to escape
  1110. * @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 \
  1111. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1112. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1113. */
  1114. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1115. {
  1116. // escape quotes and backslashes, newlines, etc.
  1117. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1118. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1119. if (empty($noescapebackslashn)) {
  1120. $substitjs["\n"] = '\\n';
  1121. $substitjs['\\'] = '\\\\';
  1122. }
  1123. if (empty($mode)) {
  1124. $substitjs["'"] = "\\'";
  1125. $substitjs['"'] = "\\'";
  1126. } elseif ($mode == 1) {
  1127. $substitjs["'"] = "\\'";
  1128. } elseif ($mode == 2) {
  1129. $substitjs['"'] = '\\"';
  1130. } elseif ($mode == 3) {
  1131. $substitjs["'"] = "\\'";
  1132. $substitjs['"'] = "\\\"";
  1133. }
  1134. return strtr($stringtoescape, $substitjs);
  1135. }
  1136. /**
  1137. * Returns text escaped for inclusion into javascript code
  1138. *
  1139. * @param string $stringtoescape String to escape
  1140. * @return string Escaped string for json content.
  1141. */
  1142. function dol_escape_json($stringtoescape)
  1143. {
  1144. return str_replace('"', '\"', $stringtoescape);
  1145. }
  1146. /**
  1147. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1148. *
  1149. * @param string $stringtoescape String to escape
  1150. * @param int $keepb 1=Keep b tags and escape them, 0=remove them
  1151. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1152. * @param string $keepmoretags '' or 'common' or list of tags
  1153. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1154. * @return string Escaped string
  1155. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1156. */
  1157. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $keepmoretags = '', $escapeonlyhtmltags = 0)
  1158. {
  1159. if ($keepmoretags == 'common') {
  1160. $keepmoretags = 'html,body,a,b,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1161. }
  1162. // TODO Implement $keepmoretags
  1163. // escape quotes and backslashes, newlines, etc.
  1164. if ($escapeonlyhtmltags) {
  1165. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1166. } else {
  1167. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1168. }
  1169. if (!$keepb) {
  1170. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1171. }
  1172. if (!$keepn) {
  1173. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1174. }
  1175. if ($escapeonlyhtmltags) {
  1176. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1177. } else {
  1178. return htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1179. }
  1180. }
  1181. /**
  1182. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1183. *
  1184. * @param string $string String to encode
  1185. * @param string $encoding Character set encoding
  1186. * @return string String converted
  1187. */
  1188. function dol_strtolower($string, $encoding = "UTF-8")
  1189. {
  1190. if (function_exists('mb_strtolower')) {
  1191. return mb_strtolower($string, $encoding);
  1192. } else {
  1193. return strtolower($string);
  1194. }
  1195. }
  1196. /**
  1197. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1198. *
  1199. * @param string $string String to encode
  1200. * @param string $encoding Character set encoding
  1201. * @return string String converted
  1202. */
  1203. function dol_strtoupper($string, $encoding = "UTF-8")
  1204. {
  1205. if (function_exists('mb_strtoupper')) {
  1206. return mb_strtoupper($string, $encoding);
  1207. } else {
  1208. return strtoupper($string);
  1209. }
  1210. }
  1211. /**
  1212. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1213. *
  1214. * @param string $string String to encode
  1215. * @param string $encoding Character set encodign
  1216. * @return string String converted
  1217. */
  1218. function dol_ucfirst($string, $encoding = "UTF-8")
  1219. {
  1220. if (function_exists('mb_substr')) {
  1221. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1222. } else {
  1223. return ucfirst($string);
  1224. }
  1225. }
  1226. /**
  1227. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1228. *
  1229. * @param string $string String to encode
  1230. * @param string $encoding Character set encodign
  1231. * @return string String converted
  1232. */
  1233. function dol_ucwords($string, $encoding = "UTF-8")
  1234. {
  1235. if (function_exists('mb_convert_case')) {
  1236. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1237. } else {
  1238. return ucwords($string);
  1239. }
  1240. }
  1241. /**
  1242. * Write log message into outputs. Possible outputs can be:
  1243. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1244. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1245. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1246. * this, use logging to files instead of syslog (see setup of module).
  1247. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1248. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1249. * This function works only if syslog module is enabled.
  1250. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1251. *
  1252. * @param string $message Line to log. ''=Show nothing
  1253. * @param int $level Log level
  1254. * 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
  1255. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1256. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1257. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1258. * @param string $restricttologhandler Force output of log only to this log handler
  1259. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1260. * @return void
  1261. */
  1262. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1263. {
  1264. global $conf, $user, $debugbar;
  1265. // If syslog module enabled
  1266. if (empty($conf->syslog->enabled)) {
  1267. return;
  1268. }
  1269. // Check if we are into execution of code of a website
  1270. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1271. global $website, $websitekey;
  1272. if (is_object($website) && !empty($website->ref)) {
  1273. $suffixinfilename .= '_website_'.$website->ref;
  1274. } elseif (!empty($websitekey)) {
  1275. $suffixinfilename .= '_website_'.$websitekey;
  1276. }
  1277. }
  1278. if ($ident < 0) {
  1279. foreach ($conf->loghandlers as $loghandlerinstance) {
  1280. $loghandlerinstance->setIdent($ident);
  1281. }
  1282. }
  1283. if (!empty($message)) {
  1284. // Test log level
  1285. $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');
  1286. if (!array_key_exists($level, $logLevels)) {
  1287. throw new Exception('Incorrect log level');
  1288. }
  1289. if ($level > $conf->global->SYSLOG_LEVEL) {
  1290. return;
  1291. }
  1292. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1293. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1294. }
  1295. // If adding log inside HTML page is required
  1296. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1297. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1298. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1299. }
  1300. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1301. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1302. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1303. print "\n\n<!-- Log start\n";
  1304. print dol_escape_htmltag($message)."\n";
  1305. print "Log end -->\n";
  1306. }
  1307. $data = array(
  1308. 'message' => $message,
  1309. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1310. 'level' => $level,
  1311. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1312. 'ip' => false
  1313. );
  1314. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1315. if (!empty($remoteip)) {
  1316. $data['ip'] = $remoteip;
  1317. // This is when server run behind a reverse proxy
  1318. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1319. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1320. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1321. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1322. }
  1323. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1324. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1325. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1326. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1327. // 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).
  1328. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1329. } elseif (!empty($_SERVER['LOGNAME'])) {
  1330. // 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).
  1331. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1332. }
  1333. // Loop on each log handler and send output
  1334. foreach ($conf->loghandlers as $loghandlerinstance) {
  1335. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1336. continue;
  1337. }
  1338. $loghandlerinstance->export($data, $suffixinfilename);
  1339. }
  1340. unset($data);
  1341. }
  1342. if ($ident > 0) {
  1343. foreach ($conf->loghandlers as $loghandlerinstance) {
  1344. $loghandlerinstance->setIdent($ident);
  1345. }
  1346. }
  1347. }
  1348. /**
  1349. * Return HTML code to output a button to open a dialog popup box.
  1350. * Such buttons must be included inside a HTML form.
  1351. *
  1352. * @param string $name A name for the html component
  1353. * @param string $label Label of button
  1354. * @param string $buttonstring button string
  1355. * @param string $url Url to open
  1356. * @param string $disabled Disabled text
  1357. * @return string HTML component with button
  1358. */
  1359. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1360. {
  1361. if (strpos($url, '?') > 0) {
  1362. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1363. } else {
  1364. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1365. }
  1366. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1367. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1368. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1369. $out .= '<script language="javascript">
  1370. jQuery(document).ready(function () {
  1371. jQuery(".button_'.$name.'").click(function () {
  1372. console.log("Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'")
  1373. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1374. .dialog({
  1375. autoOpen: false,
  1376. modal: true,
  1377. height: (window.innerHeight - 150),
  1378. width: \'80%\',
  1379. title: "'.dol_escape_js($label).'"
  1380. });
  1381. $dialog.dialog(\'open\');
  1382. });
  1383. });
  1384. </script>';
  1385. return $out;
  1386. }
  1387. /**
  1388. * Show tab header of a card
  1389. *
  1390. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1391. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1392. * @param string $title Title
  1393. * @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)
  1394. * @param string $picto Add a picto on tab title
  1395. * @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.
  1396. * @param string $morehtmlright Add more html content on right of tabs title
  1397. * @param string $morecss More Css
  1398. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1399. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1400. * @return void
  1401. * @deprecated Use print dol_get_fiche_head() instead
  1402. */
  1403. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1404. {
  1405. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1406. }
  1407. /**
  1408. * Show tabs of a record
  1409. *
  1410. * @param array $links Array of tabs
  1411. * @param string $active Active tab name
  1412. * @param string $title Title
  1413. * @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)
  1414. * @param string $picto Add a picto on tab title
  1415. * @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.
  1416. * @param string $morehtmlright Add more html content on right of tabs title
  1417. * @param string $morecss More Css
  1418. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1419. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1420. * @return string
  1421. */
  1422. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1423. {
  1424. global $conf, $langs, $hookmanager;
  1425. // Show title
  1426. $showtitle = 1;
  1427. if (!empty($conf->dol_optimize_smallscreen)) {
  1428. $showtitle = 0;
  1429. }
  1430. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1431. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1432. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1433. }
  1434. // Show right part
  1435. if ($morehtmlright) {
  1436. $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.
  1437. }
  1438. // Show title
  1439. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1440. $limittitle = 30;
  1441. $out .= '<a class="tabTitle">';
  1442. if ($picto) {
  1443. $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1444. }
  1445. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1446. $out .= '</a>';
  1447. }
  1448. // Show tabs
  1449. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1450. $maxkey = -1;
  1451. if (is_array($links) && !empty($links)) {
  1452. $keys = array_keys($links);
  1453. if (count($keys)) {
  1454. $maxkey = max($keys);
  1455. }
  1456. }
  1457. // Show tabs
  1458. // if =0 we don't use the feature
  1459. if (empty($limittoshow)) {
  1460. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1461. }
  1462. if (!empty($conf->dol_optimize_smallscreen)) {
  1463. $limittoshow = 2;
  1464. }
  1465. $displaytab = 0;
  1466. $nbintab = 0;
  1467. $popuptab = 0;
  1468. $outmore = '';
  1469. for ($i = 0; $i <= $maxkey; $i++) {
  1470. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1471. // If active tab is already present
  1472. if ($i >= $limittoshow) {
  1473. $limittoshow--;
  1474. }
  1475. }
  1476. }
  1477. for ($i = 0; $i <= $maxkey; $i++) {
  1478. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1479. $isactive = true;
  1480. } else {
  1481. $isactive = false;
  1482. }
  1483. if ($i < $limittoshow || $isactive) {
  1484. // Add a new entry
  1485. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : $links[$i][2]).' -->';
  1486. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1487. if (!empty($links[$i][0])) {
  1488. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1489. } else {
  1490. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1491. }
  1492. } elseif (!empty($links[$i][1])) {
  1493. //print "x $i $active ".$links[$i][2]." z";
  1494. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1495. if (!empty($links[$i][0])) {
  1496. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1497. }
  1498. $out .= $links[$i][1];
  1499. if (!empty($links[$i][0])) {
  1500. $out .= '</a>'."\n";
  1501. }
  1502. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1503. $out .= '</div>';
  1504. }
  1505. $out .= '</div>';
  1506. } else {
  1507. // The popup with the other tabs
  1508. if (!$popuptab) {
  1509. $popuptab = 1;
  1510. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1511. }
  1512. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1513. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1514. if (!empty($links[$i][0])) {
  1515. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1516. } else {
  1517. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1518. }
  1519. } elseif (!empty($links[$i][1])) {
  1520. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1521. $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.
  1522. $outmore .= '</a>'."\n";
  1523. }
  1524. $outmore .= '</div>';
  1525. $nbintab++;
  1526. }
  1527. $displaytab = $i;
  1528. }
  1529. if ($popuptab) {
  1530. $outmore .= '</div>';
  1531. }
  1532. if ($popuptab) { // If there is some tabs not shown
  1533. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1534. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1535. $widthofpopup = 200;
  1536. $tabsname = $moretabssuffix;
  1537. if (empty($tabsname)) {
  1538. $tabsname = str_replace("@", "", $picto);
  1539. }
  1540. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1541. $out .= '<a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a>'; // Do not use "reposition" class in the "More".
  1542. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1543. $out .= $outmore;
  1544. $out .= '</div>';
  1545. $out .= '<div></div>';
  1546. $out .= "</div>\n";
  1547. $out .= "<script>";
  1548. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1549. var x = this.offsetLeft, y = this.offsetTop;
  1550. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1551. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1552. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1553. }
  1554. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1555. });
  1556. ";
  1557. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1558. $out .= "</script>";
  1559. }
  1560. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1561. $out .= "</div>\n";
  1562. }
  1563. if (!$notab || $notab == -1 || $notab == -2) {
  1564. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1565. }
  1566. $parameters = array('tabname' => $active, 'out' => $out);
  1567. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1568. if ($reshook > 0) {
  1569. $out = $hookmanager->resPrint;
  1570. }
  1571. return $out;
  1572. }
  1573. /**
  1574. * Show tab footer of a card
  1575. *
  1576. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1577. * @return void
  1578. * @deprecated Use print dol_get_fiche_end() instead
  1579. */
  1580. function dol_fiche_end($notab = 0)
  1581. {
  1582. print dol_get_fiche_end($notab);
  1583. }
  1584. /**
  1585. * Return tab footer of a card
  1586. *
  1587. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1588. * @return string
  1589. */
  1590. function dol_get_fiche_end($notab = 0)
  1591. {
  1592. if (!$notab || $notab == -1) {
  1593. return "\n</div>\n";
  1594. } else {
  1595. return '';
  1596. }
  1597. }
  1598. /**
  1599. * Show tab footer of a card.
  1600. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1601. *
  1602. * @param Object $object Object to show
  1603. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1604. * @param string $morehtml More html content to output just before the nav bar
  1605. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1606. * @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.
  1607. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1608. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1609. * @param string $moreparam More param to add in nav link url.
  1610. * @param int $nodbprefix Do not include DB prefix to forge table name
  1611. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1612. * @param string $morehtmlstatus More html code to show under navigation arrows
  1613. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1614. * @param string $morehtmlright More html code to show before navigation arrows
  1615. * @return void
  1616. */
  1617. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1618. {
  1619. global $conf, $form, $user, $langs;
  1620. $error = 0;
  1621. $maxvisiblephotos = 1;
  1622. $showimage = 1;
  1623. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1624. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1625. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1626. $showbarcode = 0;
  1627. }
  1628. $modulepart = 'unknown';
  1629. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1630. $modulepart = $object->element;
  1631. } elseif ($object->element == 'member') {
  1632. $modulepart = 'memberphoto';
  1633. } elseif ($object->element == 'user') {
  1634. $modulepart = 'userphoto';
  1635. }
  1636. if (class_exists("Imagick")) {
  1637. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1638. $modulepart = $object->element;
  1639. } elseif ($object->element == 'fichinter') {
  1640. $modulepart = 'ficheinter';
  1641. } elseif ($object->element == 'contrat') {
  1642. $modulepart = 'contract';
  1643. } elseif ($object->element == 'order_supplier') {
  1644. $modulepart = 'supplier_order';
  1645. } elseif ($object->element == 'invoice_supplier') {
  1646. $modulepart = 'supplier_invoice';
  1647. }
  1648. }
  1649. if ($object->element == 'product') {
  1650. $width = 80;
  1651. $cssclass = 'photoref';
  1652. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1653. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1654. if ($conf->browser->layout == 'phone') {
  1655. $maxvisiblephotos = 1;
  1656. }
  1657. if ($showimage) {
  1658. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'</div>';
  1659. } else {
  1660. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1661. $nophoto = '';
  1662. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1663. } else { // Show no photo link
  1664. $nophoto = '/public/theme/common/nophoto.png';
  1665. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1666. }
  1667. }
  1668. } elseif ($object->element == 'ticket') {
  1669. $width = 80;
  1670. $cssclass = 'photoref';
  1671. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1672. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1673. if ($conf->browser->layout == 'phone') {
  1674. $maxvisiblephotos = 1;
  1675. }
  1676. if ($showimage) {
  1677. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1678. if ($object->nbphoto > 0) {
  1679. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1680. } else {
  1681. $showimage = 0;
  1682. }
  1683. }
  1684. if (!$showimage) {
  1685. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1686. $nophoto = '';
  1687. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1688. } else { // Show no photo link
  1689. $nophoto = img_picto('No photo', 'object_ticket');
  1690. $morehtmlleft .= '<!-- No photo to show -->';
  1691. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1692. $morehtmlleft .= $nophoto;
  1693. $morehtmlleft .= '</div></div>';
  1694. }
  1695. }
  1696. } else {
  1697. if ($showimage) {
  1698. if ($modulepart != 'unknown') {
  1699. $phototoshow = '';
  1700. // Check if a preview file is available
  1701. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1702. $objectref = dol_sanitizeFileName($object->ref);
  1703. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1704. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1705. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1706. $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
  1707. } else {
  1708. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1709. }
  1710. if (empty($subdir)) {
  1711. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1712. }
  1713. $filepath = $dir_output.$subdir."/";
  1714. $filepdf = $filepath.$objectref.".pdf";
  1715. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1716. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1717. $fileimage = $filepdf.'_preview.png';
  1718. $relativepathimage = $relativepath.'_preview.png';
  1719. $pdfexists = file_exists($filepdf);
  1720. // If PDF file exists
  1721. if ($pdfexists) {
  1722. // Conversion du PDF en image png si fichier png non existant
  1723. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1724. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1725. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1726. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1727. if ($ret < 0) {
  1728. $error++;
  1729. }
  1730. }
  1731. }
  1732. }
  1733. if ($pdfexists && !$error) {
  1734. $heightforphotref = 80;
  1735. if (!empty($conf->dol_optimize_smallscreen)) {
  1736. $heightforphotref = 60;
  1737. }
  1738. // If the preview file is found
  1739. if (file_exists($fileimage)) {
  1740. $phototoshow = '<div class="photoref">';
  1741. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1742. $phototoshow .= '</div>';
  1743. }
  1744. }
  1745. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1746. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1747. }
  1748. if ($phototoshow) {
  1749. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1750. $morehtmlleft .= $phototoshow;
  1751. $morehtmlleft .= '</div>';
  1752. }
  1753. }
  1754. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1755. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1756. if ($object->element == 'action') {
  1757. $width = 80;
  1758. $cssclass = 'photorefcenter';
  1759. $nophoto = img_picto('No photo', 'title_agenda');
  1760. } else {
  1761. $width = 14;
  1762. $cssclass = 'photorefcenter';
  1763. $picto = $object->picto;
  1764. if ($object->element == 'project' && !$object->public) {
  1765. $picto = 'project'; // instead of projectpub
  1766. }
  1767. $nophoto = img_picto('No photo', 'object_'.$picto);
  1768. }
  1769. $morehtmlleft .= '<!-- No photo to show -->';
  1770. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1771. $morehtmlleft .= $nophoto;
  1772. $morehtmlleft .= '</div></div>';
  1773. $morehtmlleft .= '</div>';
  1774. }
  1775. }
  1776. }
  1777. if ($showbarcode) {
  1778. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref').'</div>';
  1779. }
  1780. if ($object->element == 'societe') {
  1781. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1782. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1783. } else {
  1784. $morehtmlstatus .= $object->getLibStatut(6);
  1785. }
  1786. } elseif ($object->element == 'product') {
  1787. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1788. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1789. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1790. } else {
  1791. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1792. }
  1793. $morehtmlstatus .= ' &nbsp; ';
  1794. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1795. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1796. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1797. } else {
  1798. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1799. }
  1800. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  1801. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1802. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1803. $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1804. }
  1805. $morehtmlstatus .= $tmptxt;
  1806. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  1807. if ($object->statut == 0) {
  1808. $morehtmlstatus .= $object->getLibStatut(5);
  1809. } else {
  1810. $morehtmlstatus .= $object->getLibStatut(4);
  1811. }
  1812. } elseif ($object->element == 'facturerec') {
  1813. if ($object->frequency == 0) {
  1814. $morehtmlstatus .= $object->getLibStatut(2);
  1815. } else {
  1816. $morehtmlstatus .= $object->getLibStatut(5);
  1817. }
  1818. } elseif ($object->element == 'project_task') {
  1819. $object->fk_statut = 1;
  1820. if ($object->progress > 0) {
  1821. $object->fk_statut = 2;
  1822. }
  1823. if ($object->progress >= 100) {
  1824. $object->fk_statut = 3;
  1825. }
  1826. $tmptxt = $object->getLibStatut(5);
  1827. $morehtmlstatus .= $tmptxt; // No status on task
  1828. } else { // Generic case
  1829. $tmptxt = $object->getLibStatut(6);
  1830. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1831. $tmptxt = $object->getLibStatut(5);
  1832. }
  1833. $morehtmlstatus .= $tmptxt;
  1834. }
  1835. // Add if object was dispatched "into accountancy"
  1836. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  1837. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  1838. if (method_exists($object, 'getVentilExportCompta')) {
  1839. $accounted = $object->getVentilExportCompta();
  1840. $langs->load("accountancy");
  1841. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1842. }
  1843. }
  1844. // Add alias for thirdparty
  1845. if (!empty($object->name_alias)) {
  1846. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1847. }
  1848. // Add label
  1849. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  1850. if (!empty($object->label)) {
  1851. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1852. }
  1853. }
  1854. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  1855. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1856. if ($moreaddress) {
  1857. $morehtmlref .= '<div class="refidno">';
  1858. $morehtmlref .= $moreaddress;
  1859. $morehtmlref .= '</div>';
  1860. }
  1861. }
  1862. if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && ($conf->global->MAIN_SHOW_TECHNICAL_ID == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) {
  1863. $morehtmlref .= '<div style="clear: both;"></div>';
  1864. $morehtmlref .= '<div class="refidno">';
  1865. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1866. $morehtmlref .= '</div>';
  1867. }
  1868. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1869. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1870. print '</div>';
  1871. print '<div class="underrefbanner clearboth"></div>';
  1872. }
  1873. /**
  1874. * Show a string with the label tag dedicated to the HTML edit field.
  1875. *
  1876. * @param string $langkey Translation key
  1877. * @param string $fieldkey Key of the html select field the text refers to
  1878. * @param int $fieldrequired 1=Field is mandatory
  1879. * @return string
  1880. * @deprecated Form::editfieldkey
  1881. */
  1882. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1883. {
  1884. global $langs;
  1885. $ret = '';
  1886. if ($fieldrequired) {
  1887. $ret .= '<span class="fieldrequired">';
  1888. }
  1889. $ret .= '<label for="'.$fieldkey.'">';
  1890. $ret .= $langs->trans($langkey);
  1891. $ret .= '</label>';
  1892. if ($fieldrequired) {
  1893. $ret .= '</span>';
  1894. }
  1895. return $ret;
  1896. }
  1897. /**
  1898. * Return string to add class property on html element with pair/impair.
  1899. *
  1900. * @param string $var 0 or 1
  1901. * @param string $moreclass More class to add
  1902. * @return string String to add class onto HTML element
  1903. */
  1904. function dol_bc($var, $moreclass = '')
  1905. {
  1906. global $bc;
  1907. $ret = ' '.$bc[$var];
  1908. if ($moreclass) {
  1909. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  1910. }
  1911. return $ret;
  1912. }
  1913. /**
  1914. * Return a formated address (part address/zip/town/state) according to country rules.
  1915. * See https://en.wikipedia.org/wiki/Address
  1916. *
  1917. * @param Object $object A company or contact object
  1918. * @param int $withcountry 1=Add country into address string
  1919. * @param string $sep Separator to use to build string
  1920. * @param Translate $outputlangs Object lang that contains language for text translation.
  1921. * @param int $mode 0=Standard output, 1=Remove address
  1922. * @param string $extralangcode User extralanguage $langcode as values for address, town
  1923. * @return string Formated string
  1924. * @see dol_print_address()
  1925. */
  1926. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  1927. {
  1928. global $conf, $langs;
  1929. $ret = '';
  1930. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1931. // See format of addresses on https://en.wikipedia.org/wiki/Address
  1932. // Address
  1933. if (empty($mode)) {
  1934. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  1935. }
  1936. // Zip/Town/State
  1937. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  1938. // US: title firstname name \n address lines \n town, state, zip \n country
  1939. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  1940. $ret .= ($ret ? $sep : '').$town;
  1941. if (!empty($object->state)) {
  1942. $ret .= ($ret ? ", " : '').$object->state;
  1943. }
  1944. if (!empty($object->zip)) {
  1945. $ret .= ($ret ? ", " : '').$object->zip;
  1946. }
  1947. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  1948. // UK: title firstname name \n address lines \n town state \n zip \n country
  1949. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  1950. $ret .= ($ret ? $sep : '').$town;
  1951. if (!empty($object->state)) {
  1952. $ret .= ($ret ? ", " : '').$object->state;
  1953. }
  1954. if (!empty($object->zip)) {
  1955. $ret .= ($ret ? $sep : '').$object->zip;
  1956. }
  1957. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  1958. // ES: title firstname name \n address lines \n zip town \n state \n country
  1959. $ret .= ($ret ? $sep : '').$object->zip;
  1960. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  1961. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1962. if (!empty($object->state)) {
  1963. $ret .= "\n".$object->state;
  1964. }
  1965. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  1966. // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1967. $ret .= ($ret ? $sep : '').$object->zip;
  1968. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  1969. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1970. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  1971. } else { // Other: title firstname name \n address lines \n zip town \n country
  1972. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  1973. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  1974. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  1975. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  1976. $ret .= ($ret ? ", " : '').$object->state;
  1977. }
  1978. }
  1979. if (!is_object($outputlangs)) {
  1980. $outputlangs = $langs;
  1981. }
  1982. if ($withcountry) {
  1983. $langs->load("dict");
  1984. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  1985. }
  1986. return $ret;
  1987. }
  1988. /**
  1989. * Format a string.
  1990. *
  1991. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1992. * @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)
  1993. * @param int $is_gmt See comment of timestamp parameter
  1994. * @return string A formatted string
  1995. */
  1996. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  1997. {
  1998. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1999. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2000. } else {
  2001. return 'Error date into a not supported range';
  2002. }
  2003. }
  2004. /**
  2005. * Output date in a string format according to outputlangs (or langs if not defined).
  2006. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2007. *
  2008. * @param int $time GM Timestamps date
  2009. * @param string $format Output date format (tag of strftime function)
  2010. * "%d %b %Y",
  2011. * "%d/%m/%Y %H:%M",
  2012. * "%d/%m/%Y %H:%M:%S",
  2013. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2014. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2015. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2016. * false or 'tzserver' => output string is for local PHP server TZ usage
  2017. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2018. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  2019. * @param Translate $outputlangs Object lang that contains language for text translation.
  2020. * @param boolean $encodetooutput false=no convert into output pagecode
  2021. * @return string Formated date or '' if time is null
  2022. *
  2023. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2024. */
  2025. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2026. {
  2027. global $conf, $langs;
  2028. if ($tzoutput === 'auto') {
  2029. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2030. }
  2031. // Clean parameters
  2032. $to_gmt = false;
  2033. $offsettz = $offsetdst = 0;
  2034. if ($tzoutput) {
  2035. $to_gmt = true; // For backward compatibility
  2036. if (is_string($tzoutput)) {
  2037. if ($tzoutput == 'tzserver') {
  2038. $to_gmt = false;
  2039. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2040. $offsettz = 0; // Timezone offset with server timezone, so 0
  2041. $offsetdst = 0; // Dst offset with server timezone, so 0
  2042. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2043. $to_gmt = true;
  2044. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2045. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2046. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2047. }
  2048. }
  2049. }
  2050. if (!is_object($outputlangs)) {
  2051. $outputlangs = $langs;
  2052. }
  2053. if (!$format) {
  2054. $format = 'daytextshort';
  2055. }
  2056. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2057. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2058. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2059. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2060. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2061. if ($formatwithoutreduce != $format) {
  2062. $format = $formatwithoutreduce;
  2063. $reduceformat = 1;
  2064. } // so format 'dayreduceformat' is processed like day
  2065. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2066. // TODO Add format daysmallyear and dayhoursmallyear
  2067. if ($format == 'day') {
  2068. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2069. } elseif ($format == 'hour') {
  2070. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2071. } elseif ($format == 'hourduration') {
  2072. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2073. } elseif ($format == 'daytext') {
  2074. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2075. } elseif ($format == 'daytextshort') {
  2076. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2077. } elseif ($format == 'dayhour') {
  2078. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2079. } elseif ($format == 'dayhoursec') {
  2080. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2081. } elseif ($format == 'dayhourtext') {
  2082. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2083. } elseif ($format == 'dayhourtextshort') {
  2084. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2085. } elseif ($format == 'dayhourlog') {
  2086. // Format not sensitive to language
  2087. $format = '%Y%m%d%H%M%S';
  2088. } elseif ($format == 'dayhourldap') {
  2089. $format = '%Y%m%d%H%M%SZ';
  2090. } elseif ($format == 'dayhourxcard') {
  2091. $format = '%Y%m%dT%H%M%SZ';
  2092. } elseif ($format == 'dayxcard') {
  2093. $format = '%Y%m%d';
  2094. } elseif ($format == 'dayrfc') {
  2095. $format = '%Y-%m-%d'; // DATE_RFC3339
  2096. } elseif ($format == 'dayhourrfc') {
  2097. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2098. } elseif ($format == 'standard') {
  2099. $format = '%Y-%m-%d %H:%M:%S';
  2100. }
  2101. if ($reduceformat) {
  2102. $format = str_replace('%Y', '%y', $format);
  2103. $format = str_replace('yyyy', 'yy', $format);
  2104. }
  2105. // If date undefined or "", we return ""
  2106. if (dol_strlen($time) == 0) {
  2107. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2108. }
  2109. // Clean format
  2110. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2111. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2112. $format = str_replace('%b', '__b__', $format);
  2113. $format = str_replace('%B', '__B__', $format);
  2114. }
  2115. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2116. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2117. $format = str_replace('%a', '__a__', $format);
  2118. $format = str_replace('%A', '__A__', $format);
  2119. }
  2120. // Analyze date
  2121. $reg = array();
  2122. 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
  2123. dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2124. return '';
  2125. } 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
  2126. // This part of code should not be used anymore.
  2127. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2128. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2129. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2130. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2131. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2132. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2133. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2134. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2135. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2136. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2137. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2138. } else {
  2139. // Date is a timestamps
  2140. if ($time < 100000000000) { // Protection against bad date values
  2141. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2142. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2143. } else {
  2144. $ret = 'Bad value '.$time.' for date';
  2145. }
  2146. }
  2147. if (preg_match('/__b__/i', $format)) {
  2148. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2149. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2150. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2151. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2152. if ($encodetooutput) {
  2153. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2154. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2155. } else {
  2156. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2157. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2158. }
  2159. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2160. $ret = str_replace('__b__', $monthtextshort, $ret);
  2161. $ret = str_replace('__B__', $monthtext, $ret);
  2162. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2163. //return $ret;
  2164. }
  2165. if (preg_match('/__a__/i', $format)) {
  2166. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2167. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2168. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2169. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2170. $ret = str_replace('__A__', $dayweek, $ret);
  2171. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2172. }
  2173. return $ret;
  2174. }
  2175. /**
  2176. * Return an array with locale date info.
  2177. * WARNING: This function use PHP server timezone by default to return locale informations.
  2178. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2179. *
  2180. * @param int $timestamp Timestamp
  2181. * @param boolean $fast Fast mode. deprecated.
  2182. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2183. * @return array Array of informations
  2184. * 'seconds' => $secs,
  2185. * 'minutes' => $min,
  2186. * 'hours' => $hour,
  2187. * 'mday' => $day,
  2188. * 'wday' => $dow, 0=sunday, 6=saturday
  2189. * 'mon' => $month,
  2190. * 'year' => $year,
  2191. * 'yday' => floor($secsInYear/$_day_power)
  2192. * '0' => original timestamp
  2193. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2194. */
  2195. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2196. {
  2197. //$datetimeobj = new DateTime('@'.$timestamp);
  2198. $datetimeobj = new DateTime();
  2199. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2200. if ($forcetimezone) {
  2201. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2202. }
  2203. $arrayinfo = array(
  2204. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2205. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2206. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2207. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2208. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2209. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2210. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2211. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2212. '0'=>$timestamp
  2213. );
  2214. return $arrayinfo;
  2215. }
  2216. /**
  2217. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2218. * Replace function mktime not available under Windows if year < 1970
  2219. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2220. *
  2221. * @param int $hour Hour (can be -1 for undefined)
  2222. * @param int $minute Minute (can be -1 for undefined)
  2223. * @param int $second Second (can be -1 for undefined)
  2224. * @param int $month Month (1 to 12)
  2225. * @param int $day Day (1 to 31)
  2226. * @param int $year Year
  2227. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2228. * False or 0 or 'tzserver' = local to server TZ
  2229. * 'auto'
  2230. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2231. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user.
  2232. * 'tz,TimeZone' = use specified timezone
  2233. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2234. * @return int|string Date as a timestamp, '' or false if error
  2235. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2236. */
  2237. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2238. {
  2239. global $conf;
  2240. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2241. //print 'gm:'.$gm.' gm==auto:'.($gm == 'auto').'<br>';
  2242. if ($gm === 'auto') {
  2243. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2244. }
  2245. // Clean parameters
  2246. if ($hour == -1 || empty($hour)) {
  2247. $hour = 0;
  2248. }
  2249. if ($minute == -1 || empty($minute)) {
  2250. $minute = 0;
  2251. }
  2252. if ($second == -1 || empty($second)) {
  2253. $second = 0;
  2254. }
  2255. // Check parameters
  2256. if ($check) {
  2257. if (!$month || !$day) {
  2258. return '';
  2259. }
  2260. if ($day > 31) {
  2261. return '';
  2262. }
  2263. if ($month > 12) {
  2264. return '';
  2265. }
  2266. if ($hour < 0 || $hour > 24) {
  2267. return '';
  2268. }
  2269. if ($minute < 0 || $minute > 60) {
  2270. return '';
  2271. }
  2272. if ($second < 0 || $second > 60) {
  2273. return '';
  2274. }
  2275. }
  2276. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2277. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2278. $localtz = new DateTimeZone($default_timezone);
  2279. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2280. // We use dol_tz_string first because it is more reliable.
  2281. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2282. try {
  2283. $localtz = new DateTimeZone($default_timezone);
  2284. } catch (Exception $e) {
  2285. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2286. $default_timezone = @date_default_timezone_get();
  2287. }
  2288. } elseif (strrpos($gm, "tz,") !== false) {
  2289. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2290. try {
  2291. $localtz = new DateTimeZone($timezone);
  2292. } catch (Exception $e) {
  2293. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2294. }
  2295. }
  2296. if (empty($localtz)) {
  2297. $localtz = new DateTimeZone('UTC');
  2298. }
  2299. //var_dump($localtz);
  2300. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2301. $dt = new DateTime(null, $localtz);
  2302. $dt->setDate((int) $year, (int) $month, (int) $day);
  2303. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2304. $date = $dt->getTimestamp(); // should include daylight saving time
  2305. //var_dump($date);
  2306. return $date;
  2307. }
  2308. /**
  2309. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2310. *
  2311. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2312. * 'gmt' => we return GMT timestamp,
  2313. * 'tzserver' => we add the PHP server timezone
  2314. * 'tzref' => we add the company timezone. Not implemented.
  2315. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2316. * @return int $date Timestamp
  2317. */
  2318. function dol_now($mode = 'auto')
  2319. {
  2320. $ret = 0;
  2321. if ($mode === 'auto') {
  2322. $mode = 'gmt';
  2323. }
  2324. if ($mode == 'gmt') {
  2325. $ret = time(); // Time for now at greenwich.
  2326. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2327. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2328. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2329. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2330. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2331. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2332. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2333. // $ret=dol_now('gmt')+($tzsecond*3600);
  2334. //}
  2335. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2336. // Time for now with user timezone added
  2337. //print 'time: '.time();
  2338. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2339. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2340. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2341. }
  2342. return $ret;
  2343. }
  2344. /**
  2345. * Return string with formated size
  2346. *
  2347. * @param int $size Size to print
  2348. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2349. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2350. * @return string Link
  2351. */
  2352. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2353. {
  2354. global $conf, $langs;
  2355. $level = 1024;
  2356. if (!empty($conf->dol_optimize_smallscreen)) {
  2357. $shortunit = 1;
  2358. }
  2359. // Set value text
  2360. if (empty($shortvalue) || $size < ($level * 10)) {
  2361. $ret = $size;
  2362. $textunitshort = $langs->trans("b");
  2363. $textunitlong = $langs->trans("Bytes");
  2364. } else {
  2365. $ret = round($size / $level, 0);
  2366. $textunitshort = $langs->trans("Kb");
  2367. $textunitlong = $langs->trans("KiloBytes");
  2368. }
  2369. // Use long or short text unit
  2370. if (empty($shortunit)) {
  2371. $ret .= ' '.$textunitlong;
  2372. } else {
  2373. $ret .= ' '.$textunitshort;
  2374. }
  2375. return $ret;
  2376. }
  2377. /**
  2378. * Show Url link
  2379. *
  2380. * @param string $url Url to show
  2381. * @param string $target Target for link
  2382. * @param int $max Max number of characters to show
  2383. * @param int $withpicto With picto
  2384. * @return string HTML Link
  2385. */
  2386. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2387. {
  2388. global $langs;
  2389. if (empty($url)) {
  2390. return '';
  2391. }
  2392. $link = '<a href="';
  2393. if (!preg_match('/^http/i', $url)) {
  2394. $link .= 'http://';
  2395. }
  2396. $link .= $url;
  2397. $link .= '"';
  2398. if ($target) {
  2399. $link .= ' target="'.$target.'"';
  2400. }
  2401. $link .= '>';
  2402. if (!preg_match('/^http/i', $url)) {
  2403. $link .= 'http://';
  2404. }
  2405. $link .= dol_trunc($url, $max);
  2406. $link .= '</a>';
  2407. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2408. }
  2409. /**
  2410. * Show EMail link formatted for HTML output.
  2411. *
  2412. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2413. * @param int $cid Id of contact if known
  2414. * @param int $socid Id of third party if known
  2415. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2416. * @param int $max Max number of characters to show
  2417. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2418. * @param int $withpicto Show picto
  2419. * @return string HTML Link
  2420. */
  2421. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2422. {
  2423. global $conf, $user, $langs, $hookmanager;
  2424. $newemail = dol_escape_htmltag($email);
  2425. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2426. $withpicto = 0;
  2427. }
  2428. if (empty($email)) {
  2429. return '&nbsp;';
  2430. }
  2431. if (!empty($addlink)) {
  2432. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2433. if (!preg_match('/^mailto:/i', $email)) {
  2434. $newemail .= 'mailto:';
  2435. }
  2436. $newemail .= $email;
  2437. $newemail .= '">';
  2438. $newemail .= dol_trunc($email, $max);
  2439. $newemail .= '</a>';
  2440. if ($showinvalid && !isValidEmail($email)) {
  2441. $langs->load("errors");
  2442. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2443. }
  2444. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2445. $type = 'AC_EMAIL';
  2446. $link = '';
  2447. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2448. $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>';
  2449. }
  2450. if ($link) {
  2451. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2452. }
  2453. }
  2454. } else {
  2455. if ($showinvalid && !isValidEmail($email)) {
  2456. $langs->load("errors");
  2457. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2458. }
  2459. }
  2460. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2461. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2462. //$rep .= '</div>';
  2463. if ($hookmanager) {
  2464. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2465. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2466. if ($reshook > 0) {
  2467. $rep = '';
  2468. }
  2469. $rep .= $hookmanager->resPrint;
  2470. }
  2471. return $rep;
  2472. }
  2473. /**
  2474. * Get array of social network dictionary
  2475. *
  2476. * @return array Array of Social Networks Dictionary
  2477. */
  2478. function getArrayOfSocialNetworks()
  2479. {
  2480. global $conf, $db;
  2481. $socialnetworks = array();
  2482. // Enable caching of array
  2483. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2484. $cachekey = 'socialnetworks_' . $conf->entity;
  2485. $dataretrieved = dol_getcache($cachekey);
  2486. if (!is_null($dataretrieved)) {
  2487. $socialnetworks = $dataretrieved;
  2488. } else {
  2489. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2490. $sql .= " WHERE entity=".$conf->entity;
  2491. $resql = $db->query($sql);
  2492. if ($resql) {
  2493. while ($obj = $db->fetch_object($resql)) {
  2494. $socialnetworks[$obj->code] = array(
  2495. 'rowid' => $obj->rowid,
  2496. 'label' => $obj->label,
  2497. 'url' => $obj->url,
  2498. 'icon' => $obj->icon,
  2499. 'active' => $obj->active,
  2500. );
  2501. }
  2502. }
  2503. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2504. }
  2505. return $socialnetworks;
  2506. }
  2507. /**
  2508. * Show social network link
  2509. *
  2510. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2511. * @param int $cid Id of contact if known
  2512. * @param int $socid Id of third party if known
  2513. * @param string $type 'skype','facebook',...
  2514. * @param array $dictsocialnetworks socialnetworks availables
  2515. * @return string HTML Link
  2516. */
  2517. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2518. {
  2519. global $conf, $user, $langs;
  2520. $htmllink = $value;
  2521. if (empty($value)) {
  2522. return '&nbsp;';
  2523. }
  2524. if (!empty($type)) {
  2525. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2526. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2527. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2528. if ($type == 'skype') {
  2529. $htmllink .= $value;
  2530. $htmllink .= '&nbsp;';
  2531. $htmllink .= '<a href="skype:';
  2532. $htmllink .= $value;
  2533. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2534. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2535. $htmllink .= '</a><a href="skype:';
  2536. $htmllink .= $value;
  2537. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2538. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2539. $htmllink .= '</a>';
  2540. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2541. $addlink = 'AC_SKYPE';
  2542. $link = '';
  2543. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2544. $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>';
  2545. }
  2546. $htmllink .= ($link ? ' '.$link : '');
  2547. }
  2548. } else {
  2549. if (!empty($dictsocialnetworks[$type]['url'])) {
  2550. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2551. $htmllink .= '&nbsp;<a href="'.$link.'" target="_blank">'.$value.'</a>';
  2552. } else {
  2553. $htmllink .= $value;
  2554. }
  2555. }
  2556. $htmllink .= '</div>';
  2557. } else {
  2558. $langs->load("errors");
  2559. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2560. }
  2561. return $htmllink;
  2562. }
  2563. /**
  2564. * Format phone numbers according to country
  2565. *
  2566. * @param string $phone Phone number to format
  2567. * @param string $countrycode Country code to use for formatting
  2568. * @param int $cid Id of contact if known
  2569. * @param int $socid Id of third party if known
  2570. * @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)
  2571. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2572. * @param string $withpicto Show picto
  2573. * @param string $titlealt Text to show on alt
  2574. * @param int $adddivfloat Add div float around phone.
  2575. * @return string Formated phone number
  2576. */
  2577. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2578. {
  2579. global $conf, $user, $langs, $mysoc, $hookmanager;
  2580. // Clean phone parameter
  2581. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2582. if (empty($phone)) {
  2583. return '';
  2584. }
  2585. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2586. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2587. }
  2588. if (empty($countrycode)) {
  2589. $countrycode = $mysoc->country_code;
  2590. }
  2591. // Short format for small screens
  2592. if ($conf->dol_optimize_smallscreen) {
  2593. $separ = '';
  2594. }
  2595. $newphone = $phone;
  2596. if (strtoupper($countrycode) == "FR") {
  2597. // France
  2598. if (dol_strlen($phone) == 10) {
  2599. $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);
  2600. } elseif (dol_strlen($phone) == 7) {
  2601. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2602. } elseif (dol_strlen($phone) == 9) {
  2603. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2604. } elseif (dol_strlen($phone) == 11) {
  2605. $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);
  2606. } elseif (dol_strlen($phone) == 12) {
  2607. $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);
  2608. }
  2609. } elseif (strtoupper($countrycode) == "CA") {
  2610. if (dol_strlen($phone) == 10) {
  2611. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2612. }
  2613. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2614. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2615. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2616. }
  2617. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2618. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2619. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2620. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2621. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2622. }
  2623. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2624. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2625. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2626. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2627. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2628. }
  2629. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2630. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2631. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2632. }
  2633. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2634. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2635. $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);
  2636. }
  2637. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2638. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2639. $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);
  2640. }
  2641. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2642. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2643. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2644. }
  2645. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2646. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2647. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2648. }
  2649. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2650. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2651. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2652. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2653. $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);
  2654. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2655. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2656. }
  2657. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2658. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2659. $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);
  2660. }
  2661. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2662. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2663. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2664. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2665. $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);
  2666. }
  2667. } elseif (strtoupper($countrycode) == "MU") {
  2668. //Maurice
  2669. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  2670. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2671. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  2672. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2673. }
  2674. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  2675. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  2676. $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);
  2677. }
  2678. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  2679. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  2680. $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);
  2681. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  2682. $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);
  2683. }
  2684. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  2685. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  2686. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2687. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  2688. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2689. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  2690. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2691. }
  2692. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  2693. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  2694. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2695. }
  2696. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  2697. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  2698. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2699. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  2700. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2701. }
  2702. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  2703. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  2704. $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);
  2705. }
  2706. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  2707. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  2708. $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);
  2709. }
  2710. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  2711. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  2712. $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);
  2713. }
  2714. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  2715. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  2716. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2717. }
  2718. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  2719. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
  2720. $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);
  2721. }
  2722. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  2723. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  2724. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2725. }
  2726. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  2727. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  2728. $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);
  2729. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  2730. $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);
  2731. }
  2732. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  2733. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  2734. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2735. }
  2736. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  2737. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2738. $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);
  2739. }
  2740. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  2741. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2742. $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);
  2743. }
  2744. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  2745. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2746. $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);
  2747. }
  2748. } elseif (strtoupper($countrycode) == "IT") {//Italie
  2749. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  2750. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2751. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  2752. $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);
  2753. }
  2754. } elseif (strtoupper($countrycode) == "AU") {
  2755. //Australie
  2756. if (dol_strlen($phone) == 12) {
  2757. //ex: +61_A_BCDE_FGHI
  2758. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2759. }
  2760. }
  2761. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2762. if ($conf->browser->layout == 'phone' || (!empty($conf->clicktodial->enabled) && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) { // If phone or option for, we use link of phone
  2763. $newphoneform = $newphone;
  2764. $newphone = '<a href="tel:'.$phone.'"';
  2765. $newphone .= '>'.$newphoneform.'</a>';
  2766. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  2767. if (empty($user->clicktodial_loaded)) {
  2768. $user->fetch_clicktodial();
  2769. }
  2770. // Define urlmask
  2771. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2772. if (!empty($conf->global->CLICKTODIAL_URL)) {
  2773. $urlmask = $conf->global->CLICKTODIAL_URL;
  2774. }
  2775. if (!empty($user->clicktodial_url)) {
  2776. $urlmask = $user->clicktodial_url;
  2777. }
  2778. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2779. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2780. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2781. // This line is for backward compatibility
  2782. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2783. // Thoose lines are for substitution
  2784. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2785. '__PHONETO__'=>urlencode($phone),
  2786. '__LOGIN__'=>$clicktodial_login,
  2787. '__PASS__'=>$clicktodial_password);
  2788. $url = make_substitutions($url, $substitarray);
  2789. $newphonesav = $newphone;
  2790. $newphone = '<a href="'.$url.'"';
  2791. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  2792. $newphone .= ' target="_blank"';
  2793. }
  2794. $newphone .= '>'.$newphonesav.'</a>';
  2795. }
  2796. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2797. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2798. $type = 'AC_TEL';
  2799. $link = '';
  2800. if ($addlink == 'AC_FAX') {
  2801. $type = 'AC_FAX';
  2802. }
  2803. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  2804. $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  2805. }
  2806. if ($link) {
  2807. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2808. }
  2809. }
  2810. }
  2811. if (empty($titlealt)) {
  2812. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2813. }
  2814. $rep = '';
  2815. if ($hookmanager) {
  2816. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2817. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2818. $rep .= $hookmanager->resPrint;
  2819. }
  2820. if (empty($reshook)) {
  2821. $picto = '';
  2822. if ($withpicto) {
  2823. if ($withpicto == 'fax') {
  2824. $picto = 'phoning_fax';
  2825. } elseif ($withpicto == 'phone') {
  2826. $picto = 'phoning';
  2827. } elseif ($withpicto == 'mobile') {
  2828. $picto = 'phoning_mobile';
  2829. } else {
  2830. $picto = '';
  2831. }
  2832. }
  2833. if ($adddivfloat) {
  2834. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2835. } else {
  2836. $rep .= '<span style="margin-right: 10px;">';
  2837. }
  2838. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2839. if ($adddivfloat) {
  2840. $rep .= '</div>';
  2841. } else {
  2842. $rep .= '</span>';
  2843. }
  2844. }
  2845. return $rep;
  2846. }
  2847. /**
  2848. * Return an IP formated to be shown on screen
  2849. *
  2850. * @param string $ip IP
  2851. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2852. * @return string Formated IP, with country if GeoIP module is enabled
  2853. */
  2854. function dol_print_ip($ip, $mode = 0)
  2855. {
  2856. global $conf, $langs;
  2857. $ret = '';
  2858. if (empty($mode)) {
  2859. $ret .= $ip;
  2860. }
  2861. if ($mode != 2) {
  2862. $countrycode = dolGetCountryCodeFromIp($ip);
  2863. if ($countrycode) { // If success, countrycode is us, fr, ...
  2864. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  2865. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2866. } else {
  2867. $ret .= ' ('.$countrycode.')';
  2868. }
  2869. } else {
  2870. // Nothing
  2871. }
  2872. }
  2873. return $ret;
  2874. }
  2875. /**
  2876. * Return the IP of remote user.
  2877. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2878. * Then HTTP_CLIENT_IP if defined (rare)
  2879. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2880. *
  2881. * @return string Ip of remote user.
  2882. */
  2883. function getUserRemoteIP()
  2884. {
  2885. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  2886. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  2887. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  2888. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  2889. } else {
  2890. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  2891. }
  2892. } else {
  2893. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  2894. }
  2895. } else {
  2896. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  2897. }
  2898. return $ip;
  2899. }
  2900. /**
  2901. * Return if we are using a HTTPS connexion
  2902. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  2903. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  2904. * Then HTTP_X_FORWARDED_SSL
  2905. *
  2906. * @return boolean True if user is using HTTPS
  2907. */
  2908. function isHTTPS()
  2909. {
  2910. $isSecure = false;
  2911. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  2912. $isSecure = true;
  2913. } 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') {
  2914. $isSecure = true;
  2915. }
  2916. return $isSecure;
  2917. }
  2918. /**
  2919. * Return a country code from IP. Empty string if not found.
  2920. *
  2921. * @param string $ip IP
  2922. * @return string Country code ('us', 'fr', ...)
  2923. */
  2924. function dolGetCountryCodeFromIp($ip)
  2925. {
  2926. global $conf;
  2927. $countrycode = '';
  2928. if (!empty($conf->geoipmaxmind->enabled)) {
  2929. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2930. //$ip='24.24.24.24';
  2931. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  2932. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2933. $geoip = new DolGeoIP('country', $datafile);
  2934. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2935. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2936. }
  2937. return $countrycode;
  2938. }
  2939. /**
  2940. * Return country code for current user.
  2941. * If software is used inside a local network, detection may fails (we need a public ip)
  2942. *
  2943. * @return string Country code (fr, es, it, us, ...)
  2944. */
  2945. function dol_user_country()
  2946. {
  2947. global $conf, $langs, $user;
  2948. //$ret=$user->xxx;
  2949. $ret = '';
  2950. if (!empty($conf->geoipmaxmind->enabled)) {
  2951. $ip = getUserRemoteIP();
  2952. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2953. //$ip='24.24.24.24';
  2954. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2955. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2956. $geoip = new DolGeoIP('country', $datafile);
  2957. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2958. $ret = $countrycode;
  2959. }
  2960. return $ret;
  2961. }
  2962. /**
  2963. * Format address string
  2964. *
  2965. * @param string $address Address string, already formatted with dol_format_address()
  2966. * @param int $htmlid Html ID (for example 'gmap')
  2967. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  2968. * @param int $id Id of object
  2969. * @param int $noprint No output. Result is the function return
  2970. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2971. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2972. * @see dol_format_address()
  2973. */
  2974. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  2975. {
  2976. global $conf, $user, $langs, $hookmanager;
  2977. $out = '';
  2978. if ($address) {
  2979. if ($hookmanager) {
  2980. $parameters = array('element' => $element, 'id' => $id);
  2981. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2982. $out .= $hookmanager->resPrint;
  2983. }
  2984. if (empty($reshook)) {
  2985. if (empty($charfornl)) {
  2986. $out .= nl2br($address);
  2987. } else {
  2988. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  2989. }
  2990. // TODO Remove this block, we can add this using the hook now
  2991. $showgmap = $showomap = 0;
  2992. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  2993. $showgmap = 1;
  2994. }
  2995. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  2996. $showgmap = 1;
  2997. }
  2998. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  2999. $showgmap = 1;
  3000. }
  3001. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3002. $showomap = 1;
  3003. }
  3004. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3005. $showomap = 1;
  3006. }
  3007. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3008. $showomap = 1;
  3009. }
  3010. if ($showgmap) {
  3011. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3012. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3013. }
  3014. if ($showomap) {
  3015. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3016. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3017. }
  3018. }
  3019. }
  3020. if ($noprint) {
  3021. return $out;
  3022. } else {
  3023. print $out;
  3024. }
  3025. }
  3026. /**
  3027. * Return true if email syntax is ok.
  3028. *
  3029. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3030. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3031. * @return boolean true if email syntax is OK, false if KO or empty string
  3032. * @see isValidMXRecord()
  3033. */
  3034. function isValidEmail($address, $acceptsupervisorkey = 0)
  3035. {
  3036. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3037. return true;
  3038. }
  3039. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3040. return true;
  3041. }
  3042. return false;
  3043. }
  3044. /**
  3045. * Return if the domain name has a valid MX record.
  3046. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3047. *
  3048. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3049. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3050. * @see isValidEmail()
  3051. */
  3052. function isValidMXRecord($domain)
  3053. {
  3054. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3055. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3056. return 0;
  3057. }
  3058. if (function_exists('getmxrr')) {
  3059. $mxhosts = array();
  3060. $weight = array();
  3061. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3062. if (count($mxhosts) > 1) {
  3063. return 1;
  3064. }
  3065. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3066. return 1;
  3067. }
  3068. return 0;
  3069. }
  3070. }
  3071. return -1;
  3072. }
  3073. /**
  3074. * Return true if phone number syntax is ok
  3075. * TODO Decide what to do with this
  3076. *
  3077. * @param string $phone phone (Ex: "0601010101")
  3078. * @return boolean true if phone syntax is OK, false if KO or empty string
  3079. */
  3080. function isValidPhone($phone)
  3081. {
  3082. return true;
  3083. }
  3084. /**
  3085. * Make a strlen call. Works even if mbstring module not enabled
  3086. *
  3087. * @param string $string String to calculate length
  3088. * @param string $stringencoding Encoding of string
  3089. * @return int Length of string
  3090. */
  3091. function dol_strlen($string, $stringencoding = 'UTF-8')
  3092. {
  3093. if (function_exists('mb_strlen')) {
  3094. return mb_strlen($string, $stringencoding);
  3095. } else {
  3096. return strlen($string);
  3097. }
  3098. }
  3099. /**
  3100. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3101. *
  3102. * @param string $string String to scan
  3103. * @param string $start Start position
  3104. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3105. * @param string $stringencoding Page code used for input string encoding
  3106. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3107. * @return string substring
  3108. */
  3109. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3110. {
  3111. global $langs;
  3112. if (empty($stringencoding)) {
  3113. $stringencoding = $langs->charset_output;
  3114. }
  3115. $ret = '';
  3116. if (empty($trunconbytes)) {
  3117. if (function_exists('mb_substr')) {
  3118. $ret = mb_substr($string, $start, $length, $stringencoding);
  3119. } else {
  3120. $ret = substr($string, $start, $length);
  3121. }
  3122. } else {
  3123. if (function_exists('mb_strcut')) {
  3124. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3125. } else {
  3126. $ret = substr($string, $start, $length);
  3127. }
  3128. }
  3129. return $ret;
  3130. }
  3131. /**
  3132. * Truncate a string to a particular length adding '…' if string larger than length.
  3133. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3134. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3135. *
  3136. * @param string $string String to truncate
  3137. * @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 ...)
  3138. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3139. * @param string $stringencoding Tell what is source string encoding
  3140. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3141. * @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)
  3142. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3143. */
  3144. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3145. {
  3146. global $conf;
  3147. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3148. return $string;
  3149. }
  3150. if (empty($stringencoding)) {
  3151. $stringencoding = 'UTF-8';
  3152. }
  3153. // reduce for small screen
  3154. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3155. $size = round($size / 3);
  3156. }
  3157. // We go always here
  3158. if ($trunc == 'right') {
  3159. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3160. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3161. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3162. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3163. } else {
  3164. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3165. return $string;
  3166. }
  3167. } elseif ($trunc == 'middle') {
  3168. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3169. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3170. $size1 = round($size / 2);
  3171. $size2 = round($size / 2);
  3172. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3173. } else {
  3174. return $string;
  3175. }
  3176. } elseif ($trunc == 'left') {
  3177. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3178. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3179. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3180. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3181. } else {
  3182. return $string;
  3183. }
  3184. } elseif ($trunc == 'wrap') {
  3185. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3186. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3187. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3188. } else {
  3189. return $string;
  3190. }
  3191. } else {
  3192. return 'BadParam3CallingDolTrunc';
  3193. }
  3194. }
  3195. /**
  3196. * Show picto whatever it's its name (generic function)
  3197. *
  3198. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3199. * @param string $picto Name of image file to show ('filenew', ...)
  3200. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3201. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3202. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3203. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3204. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3205. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3206. * @param int $srconly Return only content of the src attribute of img.
  3207. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3208. * @param string $alt Force alt for bind people
  3209. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3210. * @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.
  3211. * @return string Return img tag
  3212. * @see img_object(), img_picto_common()
  3213. */
  3214. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3215. {
  3216. global $conf, $langs;
  3217. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3218. $url = DOL_URL_ROOT;
  3219. $theme = isset($conf->theme) ? $conf->theme : null;
  3220. $path = 'theme/'.$theme;
  3221. // Define fullpathpicto to use into src
  3222. if ($pictoisfullpath) {
  3223. // Clean parameters
  3224. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3225. $picto .= '.png';
  3226. }
  3227. $fullpathpicto = $picto;
  3228. $reg = array();
  3229. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3230. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3231. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3232. }
  3233. } else {
  3234. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3235. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3236. if (empty($srconly) && in_array($pictowithouttext, array(
  3237. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3238. 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3239. 'bank_account', 'barcode', 'bank', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'bug', 'building',
  3240. 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3241. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3242. 'multicurrency',
  3243. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3244. 'edit', 'ellipsis-h', 'email', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3245. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3246. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3247. 'help', 'holiday',
  3248. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3249. 'label', 'language', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3250. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3251. 'off', 'on', 'order',
  3252. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'stock', 'resize', 'service', 'stats', 'trip',
  3253. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3254. 'github', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3255. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3256. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3257. 'partnership', 'payment', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'salary', 'shipment',
  3258. 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3259. 'technic', 'ticket',
  3260. 'error', 'warning',
  3261. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource',
  3262. 'shapes', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3263. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3264. 'uncheck', 'user-cog', 'website', 'workstation',
  3265. 'conferenceorbooth', 'eventorganization'
  3266. ))) {
  3267. $fakey = $pictowithouttext;
  3268. $facolor = '';
  3269. $fasize = '';
  3270. $fa = 'fas';
  3271. if (in_array($pictowithouttext, array('clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3272. $fa = 'far';
  3273. }
  3274. if (in_array($pictowithouttext, array('black-tie', 'github', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3275. $fa = 'fab';
  3276. }
  3277. $arrayconvpictotofa = array(
  3278. 'account'=>'university', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  3279. 'bank_account'=>'university',
  3280. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3281. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3282. 'bom'=>'shapes',
  3283. 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3284. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3285. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3286. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3287. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3288. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3289. 'email'=>'at', 'establishment'=>'building',
  3290. 'edit'=>'pencil-alt', 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3291. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3292. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'loan'=>'money-bill-alt',
  3293. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3294. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3295. 'sign-out'=>'sign-out-alt',
  3296. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star',
  3297. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter',
  3298. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3299. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3300. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3301. 'other'=>'square',
  3302. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3303. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell',
  3304. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3305. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3306. 'refresh'=>'redo', 'resource'=>'laptop-house',
  3307. 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3308. 'supplier'=>'building', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt',
  3309. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3310. 'title_agenda'=>'calendar-alt',
  3311. 'uncheck'=>'times', 'uparrow'=>'share', 'vcard'=>'address-card',
  3312. 'jabber'=>'comment-o',
  3313. 'website'=>'globe-americas', 'workstation'=>'pallet',
  3314. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3315. );
  3316. if ($pictowithouttext == 'off') {
  3317. $fakey = 'fa-square';
  3318. $fasize = '1.3em';
  3319. } elseif ($pictowithouttext == 'on') {
  3320. $fakey = 'fa-check-square';
  3321. $fasize = '1.3em';
  3322. } elseif ($pictowithouttext == 'listlight') {
  3323. $fakey = 'fa-download';
  3324. $marginleftonlyshort = 1;
  3325. } elseif ($pictowithouttext == 'printer') {
  3326. $fakey = 'fa-print';
  3327. $fasize = '1.2em';
  3328. } elseif ($pictowithouttext == 'note') {
  3329. $fakey = 'fa-sticky-note';
  3330. $marginleftonlyshort = 1;
  3331. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3332. $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');
  3333. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3334. if (preg_match('/selected/', $pictowithouttext)) {
  3335. $facolor = '#888';
  3336. }
  3337. $marginleftonlyshort = 1;
  3338. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3339. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3340. } else {
  3341. $fakey = 'fa-'.$pictowithouttext;
  3342. }
  3343. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3344. $morecss = 'em092';
  3345. }
  3346. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3347. $morecss = 'em088';
  3348. }
  3349. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3350. $morecss = 'em080';
  3351. }
  3352. // Define $marginleftonlyshort
  3353. $arrayconvpictotomarginleftonly = array(
  3354. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3355. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_off',
  3356. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3357. );
  3358. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3359. $marginleftonlyshort = 0;
  3360. }
  3361. // Add CSS
  3362. $arrayconvpictotomorcess = array(
  3363. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3364. 'bank_account'=>'bg-infobox-bank_account',
  3365. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3366. 'conferenceorbooth'=>'infobox-project',
  3367. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3368. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3369. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3370. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3371. 'incoterm'=>'infobox-supplier_proposal',
  3372. 'multicurrency'=>'infobox-bank_account',
  3373. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3374. 'order'=>'infobox-commande',
  3375. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3376. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4',
  3377. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3378. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3379. 'payment'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  3380. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3381. 'resource'=>'infobox-action',
  3382. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3383. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3384. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3385. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3386. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3387. );
  3388. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3389. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3390. }
  3391. // Define $color
  3392. $arrayconvpictotocolor = array(
  3393. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3394. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3395. 'dynamicprice'=>'#a69944',
  3396. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3397. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3398. 'lot'=>'#a69944',
  3399. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3400. 'other'=>'#ddd',
  3401. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3402. //'shipment'=>'#a69944',
  3403. 'security'=>'#999', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3404. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa',
  3405. 'website'=>'#304', 'workstation'=>'#a69944'
  3406. );
  3407. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3408. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3409. }
  3410. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3411. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3412. $morestyle = '';
  3413. $reg = array();
  3414. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3415. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3416. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3417. }
  3418. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3419. $morestyle = $reg[1];
  3420. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3421. }
  3422. $moreatt = trim($moreatt);
  3423. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3424. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3425. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3426. $enabledisablehtml .= $titlealt;
  3427. }*/
  3428. $enabledisablehtml .= '</span>';
  3429. return $enabledisablehtml;
  3430. }
  3431. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3432. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3433. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3434. $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
  3435. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3436. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3437. }
  3438. // If we ask an image into $url/$mymodule/img (instead of default path)
  3439. $regs = array();
  3440. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3441. $picto = $regs[1];
  3442. $path = $regs[2]; // $path is $mymodule
  3443. }
  3444. // Clean parameters
  3445. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3446. $picto .= '.png';
  3447. }
  3448. // If alt path are defined, define url where img file is, according to physical path
  3449. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3450. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3451. if ($type == 'main') {
  3452. continue;
  3453. }
  3454. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3455. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3456. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3457. break;
  3458. }
  3459. }
  3460. // $url is '' or '/custom', $path is current theme or
  3461. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3462. }
  3463. if ($srconly) {
  3464. return $fullpathpicto;
  3465. }
  3466. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3467. return '<img src="'.$fullpathpicto.'" 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
  3468. }
  3469. /**
  3470. * Show a picto called object_picto (generic function)
  3471. *
  3472. * @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.
  3473. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3474. * For external modules use imagename@mymodule to search into directory "img" of module.
  3475. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3476. * @param int $pictoisfullpath If 1, image path is a full path
  3477. * @param int $srconly Return only content of the src attribute of img.
  3478. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3479. * @return string Return img tag
  3480. * @see img_picto(), img_picto_common()
  3481. */
  3482. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3483. {
  3484. if (strpos($picto, '^') === 0) {
  3485. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3486. } else {
  3487. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3488. }
  3489. }
  3490. /**
  3491. * Show weather picto
  3492. *
  3493. * @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.
  3494. * @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).
  3495. * @param string $moreatt Add more attribute on img tag
  3496. * @param int $pictoisfullpath If 1, image path is a full path
  3497. * @param string $morecss More CSS
  3498. * @return string Return img tag
  3499. * @see img_object(), img_picto()
  3500. */
  3501. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3502. {
  3503. global $conf;
  3504. if (is_numeric($picto)) {
  3505. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3506. //$picto = $leveltopicto[$picto];
  3507. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3508. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3509. $picto .= '.png';
  3510. }
  3511. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3512. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3513. }
  3514. /**
  3515. * Show picto (generic function)
  3516. *
  3517. * @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.
  3518. * @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.
  3519. * @param string $moreatt Add more attribute on img tag
  3520. * @param int $pictoisfullpath If 1, image path is a full path
  3521. * @return string Return img tag
  3522. * @see img_object(), img_picto()
  3523. */
  3524. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  3525. {
  3526. global $conf;
  3527. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3528. $picto .= '.png';
  3529. }
  3530. if ($pictoisfullpath) {
  3531. $path = $picto;
  3532. } else {
  3533. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3534. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3535. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3536. if (file_exists($themepath)) {
  3537. $path = $themepath;
  3538. }
  3539. }
  3540. }
  3541. return img_picto($titlealt, $path, $moreatt, 1);
  3542. }
  3543. /**
  3544. * Show logo action
  3545. *
  3546. * @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.
  3547. * @param string $numaction Action id or code to show
  3548. * @param string $picto Name of image file to show ('filenew', ...)
  3549. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3550. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3551. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3552. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3553. * @return string Return an img tag
  3554. */
  3555. function img_action($titlealt, $numaction, $picto = '')
  3556. {
  3557. global $langs;
  3558. if (empty($titlealt) || $titlealt == 'default') {
  3559. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3560. $numaction = -1;
  3561. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3562. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3563. $numaction = 0;
  3564. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3565. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3566. $numaction = 1;
  3567. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3568. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3569. $numaction = 2;
  3570. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3571. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3572. $numaction = 3;
  3573. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3574. } else {
  3575. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3576. $numaction = 0;
  3577. }
  3578. }
  3579. if (!is_numeric($numaction)) {
  3580. $numaction = 0;
  3581. }
  3582. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3583. }
  3584. /**
  3585. * Show pdf logo
  3586. *
  3587. * @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.
  3588. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3589. * @return string Retourne tag img
  3590. */
  3591. function img_pdf($titlealt = 'default', $size = 3)
  3592. {
  3593. global $langs;
  3594. if ($titlealt == 'default') {
  3595. $titlealt = $langs->trans('Show');
  3596. }
  3597. return img_picto($titlealt, 'pdf'.$size.'.png');
  3598. }
  3599. /**
  3600. * Show logo +
  3601. *
  3602. * @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.
  3603. * @param string $other Add more attributes on img
  3604. * @return string Return tag img
  3605. */
  3606. function img_edit_add($titlealt = 'default', $other = '')
  3607. {
  3608. global $langs;
  3609. if ($titlealt == 'default') {
  3610. $titlealt = $langs->trans('Add');
  3611. }
  3612. return img_picto($titlealt, 'edit_add.png', $other);
  3613. }
  3614. /**
  3615. * Show logo -
  3616. *
  3617. * @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.
  3618. * @param string $other Add more attributes on img
  3619. * @return string Return tag img
  3620. */
  3621. function img_edit_remove($titlealt = 'default', $other = '')
  3622. {
  3623. global $langs;
  3624. if ($titlealt == 'default') {
  3625. $titlealt = $langs->trans('Remove');
  3626. }
  3627. return img_picto($titlealt, 'edit_remove.png', $other);
  3628. }
  3629. /**
  3630. * Show logo editer/modifier fiche
  3631. *
  3632. * @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.
  3633. * @param integer $float If you have to put the style "float: right"
  3634. * @param string $other Add more attributes on img
  3635. * @return string Return tag img
  3636. */
  3637. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3638. {
  3639. global $langs;
  3640. if ($titlealt == 'default') {
  3641. $titlealt = $langs->trans('Modify');
  3642. }
  3643. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3644. }
  3645. /**
  3646. * Show logo view card
  3647. *
  3648. * @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.
  3649. * @param integer $float If you have to put the style "float: right"
  3650. * @param string $other Add more attributes on img
  3651. * @return string Return tag img
  3652. */
  3653. function img_view($titlealt = 'default', $float = 0, $other = '')
  3654. {
  3655. global $langs;
  3656. if ($titlealt == 'default') {
  3657. $titlealt = $langs->trans('View');
  3658. }
  3659. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3660. return img_picto($titlealt, 'view.png', $moreatt);
  3661. }
  3662. /**
  3663. * Show delete logo
  3664. *
  3665. * @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.
  3666. * @param string $other Add more attributes on img
  3667. * @param string $morecss More CSS
  3668. * @return string Retourne tag img
  3669. */
  3670. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3671. {
  3672. global $langs;
  3673. if ($titlealt == 'default') {
  3674. $titlealt = $langs->trans('Delete');
  3675. }
  3676. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3677. }
  3678. /**
  3679. * Show printer logo
  3680. *
  3681. * @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.
  3682. * @param string $other Add more attributes on img
  3683. * @return string Retourne tag img
  3684. */
  3685. function img_printer($titlealt = "default", $other = '')
  3686. {
  3687. global $langs;
  3688. if ($titlealt == "default") {
  3689. $titlealt = $langs->trans("Print");
  3690. }
  3691. return img_picto($titlealt, 'printer.png', $other);
  3692. }
  3693. /**
  3694. * Show split logo
  3695. *
  3696. * @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.
  3697. * @param string $other Add more attributes on img
  3698. * @return string Retourne tag img
  3699. */
  3700. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3701. {
  3702. global $langs;
  3703. if ($titlealt == 'default') {
  3704. $titlealt = $langs->trans('Split');
  3705. }
  3706. return img_picto($titlealt, 'split.png', $other);
  3707. }
  3708. /**
  3709. * Show help logo with cursor "?"
  3710. *
  3711. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3712. * @param int|string $usealttitle Text to use as alt title
  3713. * @return string Return tag img
  3714. */
  3715. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3716. {
  3717. global $langs;
  3718. if ($usealttitle) {
  3719. if (is_string($usealttitle)) {
  3720. $usealttitle = dol_escape_htmltag($usealttitle);
  3721. } else {
  3722. $usealttitle = $langs->trans('Info');
  3723. }
  3724. }
  3725. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3726. }
  3727. /**
  3728. * Show info logo
  3729. *
  3730. * @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.
  3731. * @return string Return img tag
  3732. */
  3733. function img_info($titlealt = 'default')
  3734. {
  3735. global $langs;
  3736. if ($titlealt == 'default') {
  3737. $titlealt = $langs->trans('Informations');
  3738. }
  3739. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3740. }
  3741. /**
  3742. * Show warning logo
  3743. *
  3744. * @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.
  3745. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3746. * @param string $morecss Add more CSS
  3747. * @return string Return img tag
  3748. */
  3749. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3750. {
  3751. global $langs;
  3752. if ($titlealt == 'default') {
  3753. $titlealt = $langs->trans('Warning');
  3754. }
  3755. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3756. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3757. }
  3758. /**
  3759. * Show error logo
  3760. *
  3761. * @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.
  3762. * @return string Return img tag
  3763. */
  3764. function img_error($titlealt = 'default')
  3765. {
  3766. global $langs;
  3767. if ($titlealt == 'default') {
  3768. $titlealt = $langs->trans('Error');
  3769. }
  3770. return img_picto($titlealt, 'error.png');
  3771. }
  3772. /**
  3773. * Show next logo
  3774. *
  3775. * @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.
  3776. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3777. * @return string Return img tag
  3778. */
  3779. function img_next($titlealt = 'default', $moreatt = '')
  3780. {
  3781. global $langs;
  3782. if ($titlealt == 'default') {
  3783. $titlealt = $langs->trans('Next');
  3784. }
  3785. //return img_picto($titlealt, 'next.png', $moreatt);
  3786. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3787. }
  3788. /**
  3789. * Show previous logo
  3790. *
  3791. * @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.
  3792. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3793. * @return string Return img tag
  3794. */
  3795. function img_previous($titlealt = 'default', $moreatt = '')
  3796. {
  3797. global $langs;
  3798. if ($titlealt == 'default') {
  3799. $titlealt = $langs->trans('Previous');
  3800. }
  3801. //return img_picto($titlealt, 'previous.png', $moreatt);
  3802. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3803. }
  3804. /**
  3805. * Show down arrow logo
  3806. *
  3807. * @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.
  3808. * @param int $selected Selected
  3809. * @param string $moreclass Add more CSS classes
  3810. * @return string Return img tag
  3811. */
  3812. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3813. {
  3814. global $langs;
  3815. if ($titlealt == 'default') {
  3816. $titlealt = $langs->trans('Down');
  3817. }
  3818. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3819. }
  3820. /**
  3821. * Show top arrow logo
  3822. *
  3823. * @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.
  3824. * @param int $selected Selected
  3825. * @param string $moreclass Add more CSS classes
  3826. * @return string Return img tag
  3827. */
  3828. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3829. {
  3830. global $langs;
  3831. if ($titlealt == 'default') {
  3832. $titlealt = $langs->trans('Up');
  3833. }
  3834. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3835. }
  3836. /**
  3837. * Show left arrow logo
  3838. *
  3839. * @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.
  3840. * @param int $selected Selected
  3841. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3842. * @return string Return img tag
  3843. */
  3844. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3845. {
  3846. global $langs;
  3847. if ($titlealt == 'default') {
  3848. $titlealt = $langs->trans('Left');
  3849. }
  3850. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3851. }
  3852. /**
  3853. * Show right arrow logo
  3854. *
  3855. * @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.
  3856. * @param int $selected Selected
  3857. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3858. * @return string Return img tag
  3859. */
  3860. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3861. {
  3862. global $langs;
  3863. if ($titlealt == 'default') {
  3864. $titlealt = $langs->trans('Right');
  3865. }
  3866. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3867. }
  3868. /**
  3869. * Show tick logo if allowed
  3870. *
  3871. * @param string $allow Allow
  3872. * @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.
  3873. * @return string Return img tag
  3874. */
  3875. function img_allow($allow, $titlealt = 'default')
  3876. {
  3877. global $langs;
  3878. if ($titlealt == 'default') {
  3879. $titlealt = $langs->trans('Active');
  3880. }
  3881. if ($allow == 1) {
  3882. return img_picto($titlealt, 'tick.png');
  3883. }
  3884. return '-';
  3885. }
  3886. /**
  3887. * Return image of a credit card according to its brand name
  3888. *
  3889. * @param string $brand Brand name of credit card
  3890. * @param string $morecss More CSS
  3891. * @return string Return img tag
  3892. */
  3893. function img_credit_card($brand, $morecss = null)
  3894. {
  3895. if (is_null($morecss)) {
  3896. $morecss = 'fa-2x';
  3897. }
  3898. if ($brand == 'visa' || $brand == 'Visa') {
  3899. $brand = 'cc-visa';
  3900. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  3901. $brand = 'cc-mastercard';
  3902. } elseif ($brand == 'amex' || $brand == 'American Express') {
  3903. $brand = 'cc-amex';
  3904. } elseif ($brand == 'discover' || $brand == 'Discover') {
  3905. $brand = 'cc-discover';
  3906. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  3907. $brand = 'cc-jcb';
  3908. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  3909. $brand = 'cc-diners-club';
  3910. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  3911. $brand = 'credit-card';
  3912. }
  3913. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  3914. }
  3915. /**
  3916. * Show MIME img of a file
  3917. *
  3918. * @param string $file Filename
  3919. * @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.
  3920. * @param string $morecss More css
  3921. * @return string Return img tag
  3922. */
  3923. function img_mime($file, $titlealt = '', $morecss = '')
  3924. {
  3925. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3926. $mimetype = dol_mimetype($file, '', 1);
  3927. $mimeimg = dol_mimetype($file, '', 2);
  3928. $mimefa = dol_mimetype($file, '', 4);
  3929. if (empty($titlealt)) {
  3930. $titlealt = 'Mime type: '.$mimetype;
  3931. }
  3932. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3933. return '<i class="fa fa-'.$mimefa.' paddingright"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  3934. }
  3935. /**
  3936. * Show search logo
  3937. *
  3938. * @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.
  3939. * @param string $other Add more attributes on img
  3940. * @return string Retourne tag img
  3941. */
  3942. function img_search($titlealt = 'default', $other = '')
  3943. {
  3944. global $conf, $langs;
  3945. if ($titlealt == 'default') {
  3946. $titlealt = $langs->trans('Search');
  3947. }
  3948. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3949. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3950. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3951. return $input;
  3952. }
  3953. /**
  3954. * Show search logo
  3955. *
  3956. * @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.
  3957. * @param string $other Add more attributes on img
  3958. * @return string Retourne tag img
  3959. */
  3960. function img_searchclear($titlealt = 'default', $other = '')
  3961. {
  3962. global $conf, $langs;
  3963. if ($titlealt == 'default') {
  3964. $titlealt = $langs->trans('Search');
  3965. }
  3966. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3967. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3968. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3969. return $input;
  3970. }
  3971. /**
  3972. * Show information for admin users or standard users
  3973. *
  3974. * @param string $text Text info
  3975. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3976. * @param int $nodiv No div
  3977. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  3978. * @param string $morecss More CSS ('', 'warning', 'error')
  3979. * @param string $textfordropdown Show a text to click to dropdown the info box.
  3980. * @return string String with info text
  3981. */
  3982. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  3983. {
  3984. global $conf, $langs;
  3985. if ($infoonimgalt) {
  3986. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  3987. } else {
  3988. if (empty($conf->use_javascript_ajax)) {
  3989. $textfordropdown = '';
  3990. }
  3991. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  3992. $result = ($nodiv ? '' : '<div class="'.$class.' hideonsmartphone'.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  3993. if ($textfordropdown) {
  3994. $tmpresult .= '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  3995. $tmpresult .= '<script type="text/javascript" language="javascript">
  3996. jQuery(document).ready(function() {
  3997. jQuery(".'.$class.'text").click(function() {
  3998. console.log("toggle text");
  3999. jQuery(".'.$class.'").toggle();
  4000. });
  4001. });
  4002. </script>';
  4003. $result = $tmpresult.$result;
  4004. }
  4005. }
  4006. return $result;
  4007. }
  4008. /**
  4009. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4010. * This function must be called when a blocking technical error is encountered.
  4011. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4012. *
  4013. * @param DoliDB $db Database handler
  4014. * @param string|string[] $error String or array of errors strings to show
  4015. * @param array $errors Array of errors
  4016. * @return void
  4017. * @see dol_htmloutput_errors()
  4018. */
  4019. function dol_print_error($db = '', $error = '', $errors = null)
  4020. {
  4021. global $conf, $langs, $argv;
  4022. global $dolibarr_main_prod;
  4023. $out = '';
  4024. $syslog = '';
  4025. // If error occurs before the $lang object was loaded
  4026. if (!$langs) {
  4027. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4028. $langs = new Translate('', $conf);
  4029. $langs->load("main");
  4030. }
  4031. // Load translation files required by the error messages
  4032. $langs->loadLangs(array('main', 'errors'));
  4033. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4034. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4035. if (!empty($conf->global->MAIN_FEATURES_LEVEL)) {
  4036. $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";
  4037. }
  4038. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4039. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4040. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4041. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4042. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".dol_htmlentities($conf->global->MAIN_FEATURES_LEVEL, ENT_COMPAT)."<br>\n";
  4043. }
  4044. if (function_exists("phpversion")) {
  4045. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4046. }
  4047. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4048. if (function_exists("php_uname")) {
  4049. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4050. }
  4051. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4052. $out .= "<br>\n";
  4053. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4054. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4055. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4056. $out .= "<br>\n";
  4057. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4058. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4059. } else // Mode CLI
  4060. {
  4061. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4062. $syslog .= "pid=".dol_getmypid();
  4063. }
  4064. if (!empty($conf->modules)) {
  4065. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4066. }
  4067. if (is_object($db)) {
  4068. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4069. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4070. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4071. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4072. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4073. $out .= "<br>\n";
  4074. } else // Mode CLI
  4075. {
  4076. // No dol_escape_htmltag for output, we are in CLI mode
  4077. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4078. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4079. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4080. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4081. }
  4082. $syslog .= ", sql=".$db->lastquery();
  4083. $syslog .= ", db_error=".$db->lasterror();
  4084. }
  4085. if ($error || $errors) {
  4086. $langs->load("errors");
  4087. // Merge all into $errors array
  4088. if (is_array($error) && is_array($errors)) {
  4089. $errors = array_merge($error, $errors);
  4090. } elseif (is_array($error)) {
  4091. $errors = $error;
  4092. } elseif (is_array($errors)) {
  4093. $errors = array_merge(array($error), $errors);
  4094. } else {
  4095. $errors = array_merge(array($error));
  4096. }
  4097. foreach ($errors as $msg) {
  4098. if (empty($msg)) {
  4099. continue;
  4100. }
  4101. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4102. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4103. } else // Mode CLI
  4104. {
  4105. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4106. }
  4107. $syslog .= ", msg=".$msg;
  4108. }
  4109. }
  4110. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4111. xdebug_print_function_stack();
  4112. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4113. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4114. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4115. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4116. $out .= "<br>\n";
  4117. }
  4118. // Return a http error code if possible
  4119. if (!headers_sent()) {
  4120. http_response_code(500);
  4121. }
  4122. if (empty($dolibarr_main_prod)) {
  4123. print $out;
  4124. } else {
  4125. if (empty($langs->defaultlang)) {
  4126. $langs->setDefaultLang();
  4127. }
  4128. $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.
  4129. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4130. 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";
  4131. print $langs->trans("DolibarrHasDetectedError").'. ';
  4132. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4133. define("MAIN_CORE_ERROR", 1);
  4134. }
  4135. dol_syslog("Error ".$syslog, LOG_ERR);
  4136. }
  4137. /**
  4138. * Show a public email and error code to contact if technical error
  4139. *
  4140. * @param string $prefixcode Prefix of public error code
  4141. * @param string $errormessage Complete error message
  4142. * @param array $errormessages Array of error messages
  4143. * @param string $morecss More css
  4144. * @param string $email Email
  4145. * @return void
  4146. */
  4147. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4148. {
  4149. global $langs, $conf;
  4150. if (empty($email)) {
  4151. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4152. }
  4153. $langs->load("errors");
  4154. $now = dol_now();
  4155. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4156. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4157. if ($errormessage) {
  4158. print '<br><br>'.$errormessage;
  4159. }
  4160. if (is_array($errormessages) && count($errormessages)) {
  4161. foreach ($errormessages as $mesgtoshow) {
  4162. print '<br><br>'.$mesgtoshow;
  4163. }
  4164. }
  4165. print '</div></div>';
  4166. }
  4167. /**
  4168. * Show title line of an array
  4169. *
  4170. * @param string $name Label of field
  4171. * @param string $file Url used when we click on sort picto
  4172. * @param string $field Field to use for new sorting
  4173. * @param string $begin ("" by defaut)
  4174. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4175. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  4176. * @param string $sortfield Current field used to sort
  4177. * @param string $sortorder Current sort order
  4178. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4179. * @param string $tooltip Tooltip
  4180. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4181. * @return void
  4182. */
  4183. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4184. {
  4185. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4186. }
  4187. /**
  4188. * Get title line of an array
  4189. *
  4190. * @param string $name Translation key of field to show or complete HTML string to show
  4191. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4192. * @param string $file Url used when we click on sort picto
  4193. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4194. * @param string $begin ("" by defaut)
  4195. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4196. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  4197. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4198. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4199. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4200. * @param string $disablesortlink 1=Disable sort link
  4201. * @param string $tooltip Tooltip
  4202. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4203. * @return string
  4204. */
  4205. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4206. {
  4207. global $conf, $langs, $form;
  4208. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4209. if ($moreattrib == 'class="right"') {
  4210. $prefix .= 'right '; // For backward compatibility
  4211. }
  4212. $sortorder = strtoupper($sortorder);
  4213. $out = '';
  4214. $sortimg = '';
  4215. $tag = 'th';
  4216. if ($thead == 2) {
  4217. $tag = 'div';
  4218. }
  4219. $tmpsortfield = explode(',', $sortfield);
  4220. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4221. $tmpfield = explode(',', $field);
  4222. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4223. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4224. $prefix = 'wrapcolumntitle '.$prefix;
  4225. }
  4226. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4227. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4228. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4229. $liste_titre = 'liste_titre';
  4230. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4231. $liste_titre = 'liste_titre_sel';
  4232. }
  4233. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4234. //$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)).'"' : '');
  4235. $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4236. $out .= '>';
  4237. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4238. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4239. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4240. $options = preg_replace('/&+/i', '&', $options);
  4241. if (!preg_match('/^&/', $options)) {
  4242. $options = '&'.$options;
  4243. }
  4244. $sortordertouseinlink = '';
  4245. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4246. if (preg_match('/^DESC/i', $sortorder)) {
  4247. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4248. } else // We reverse the var $sortordertouseinlink
  4249. {
  4250. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4251. }
  4252. } else // We are on field that is the first current sorting criteria
  4253. {
  4254. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4255. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4256. } else {
  4257. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4258. }
  4259. }
  4260. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4261. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4262. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4263. $out .= '>';
  4264. }
  4265. if ($tooltip) {
  4266. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4267. $tmptooltip = explode(':', $tooltip);
  4268. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4269. } else {
  4270. $out .= $langs->trans($name);
  4271. }
  4272. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4273. $out .= '</a>';
  4274. }
  4275. if (empty($thead) && $field) { // If this is a sort field
  4276. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4277. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4278. $options = preg_replace('/&+/i', '&', $options);
  4279. if (!preg_match('/^&/', $options)) {
  4280. $options = '&'.$options;
  4281. }
  4282. if (!$sortorder || $field1 != $sortfield1) {
  4283. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4284. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4285. } else {
  4286. if (preg_match('/^DESC/', $sortorder)) {
  4287. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4288. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4289. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  4290. }
  4291. if (preg_match('/^ASC/', $sortorder)) {
  4292. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4293. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4294. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  4295. }
  4296. }
  4297. }
  4298. $out .= $sortimg;
  4299. $out .= '</'.$tag.'>';
  4300. return $out;
  4301. }
  4302. /**
  4303. * Show a title.
  4304. *
  4305. * @param string $title Title to show
  4306. * @return string Title to show
  4307. * @deprecated Use load_fiche_titre instead
  4308. * @see load_fiche_titre()
  4309. */
  4310. function print_titre($title)
  4311. {
  4312. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4313. print '<div class="titre">'.$title.'</div>';
  4314. }
  4315. /**
  4316. * Show a title with picto
  4317. *
  4318. * @param string $title Title to show
  4319. * @param string $mesg Added message to show on right
  4320. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4321. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4322. * @param int $id To force an id on html objects
  4323. * @return void
  4324. * @deprecated Use print load_fiche_titre instead
  4325. */
  4326. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4327. {
  4328. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4329. }
  4330. /**
  4331. * Load a title with picto
  4332. *
  4333. * @param string $titre Title to show
  4334. * @param string $morehtmlright Added message to show on right
  4335. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4336. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4337. * @param string $id To force an id on html objects
  4338. * @param string $morecssontable More css on table
  4339. * @param string $morehtmlcenter Added message to show on center
  4340. * @return string
  4341. * @see print_barre_liste()
  4342. */
  4343. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4344. {
  4345. global $conf;
  4346. $return = '';
  4347. if ($picto == 'setup') {
  4348. $picto = 'generic';
  4349. }
  4350. $return .= "\n";
  4351. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4352. $return .= '<tr class="titre">';
  4353. if ($picto) {
  4354. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4355. }
  4356. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4357. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4358. $return .= '</td>';
  4359. if (dol_strlen($morehtmlcenter)) {
  4360. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4361. }
  4362. if (dol_strlen($morehtmlright)) {
  4363. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4364. }
  4365. $return .= '</tr></table>'."\n";
  4366. return $return;
  4367. }
  4368. /**
  4369. * Print a title with navigation controls for pagination
  4370. *
  4371. * @param string $titre Title to show (required)
  4372. * @param int $page Numero of page to show in navigation links (required)
  4373. * @param string $file Url of page (required)
  4374. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4375. * @param string $sortfield Field to sort on ('' by default)
  4376. * @param string $sortorder Order to sort ('' by default)
  4377. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4378. * @param int $num Number of records found by select with limit+1
  4379. * @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.
  4380. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4381. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4382. * @param string $morehtmlright More html to show (after arrows)
  4383. * @param string $morecss More css to the table
  4384. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4385. * @param int $hideselectlimit Force to hide select limit
  4386. * @param int $hidenavigation Force to hide all navigation tools
  4387. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4388. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4389. * @return void
  4390. */
  4391. 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 = '')
  4392. {
  4393. global $conf, $langs;
  4394. $savlimit = $limit;
  4395. $savtotalnboflines = $totalnboflines;
  4396. $totalnboflines = abs((int) $totalnboflines);
  4397. if ($picto == 'setup') {
  4398. $picto = 'title_setup.png';
  4399. }
  4400. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4401. $picto = 'title.gif';
  4402. }
  4403. if ($limit < 0) {
  4404. $limit = $conf->liste_limit;
  4405. }
  4406. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4407. $nextpage = 1;
  4408. } else {
  4409. $nextpage = 0;
  4410. }
  4411. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4412. print "\n";
  4413. print "<!-- Begin title -->\n";
  4414. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4415. // Left
  4416. if ($picto && $titre) {
  4417. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4418. }
  4419. print '<td class="nobordernopadding valignmiddle col-title">';
  4420. print '<div class="titre inline-block">'.$titre;
  4421. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4422. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4423. }
  4424. print '</div></td>';
  4425. // Center
  4426. if ($morehtmlcenter) {
  4427. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4428. }
  4429. // Right
  4430. print '<td class="nobordernopadding valignmiddle right">';
  4431. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4432. if ($sortfield) {
  4433. $options .= "&sortfield=".urlencode($sortfield);
  4434. }
  4435. if ($sortorder) {
  4436. $options .= "&sortorder=".urlencode($sortorder);
  4437. }
  4438. // Show navigation bar
  4439. $pagelist = '';
  4440. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4441. if ($totalnboflines) { // If we know total nb of lines
  4442. // Define nb of extra page links before and after selected page + ... + first or last
  4443. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4444. if ($limit > 0) {
  4445. $nbpages = ceil($totalnboflines / $limit);
  4446. } else {
  4447. $nbpages = 1;
  4448. }
  4449. $cpt = ($page - $maxnbofpage);
  4450. if ($cpt < 0) {
  4451. $cpt = 0;
  4452. }
  4453. if ($cpt >= 1) {
  4454. if (empty($pagenavastextinput)) {
  4455. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4456. if ($cpt > 2) {
  4457. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4458. } elseif ($cpt == 2) {
  4459. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4460. }
  4461. }
  4462. }
  4463. do {
  4464. if ($pagenavastextinput) {
  4465. if ($cpt == $page) {
  4466. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4467. $pagelist .= '/';
  4468. //if (($cpt + 1) < $nbpages) $pagelist .= '/';
  4469. }
  4470. } else {
  4471. if ($cpt == $page) {
  4472. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4473. } else {
  4474. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4475. }
  4476. }
  4477. $cpt++;
  4478. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4479. if (empty($pagenavastextinput)) {
  4480. if ($cpt < $nbpages) {
  4481. if ($cpt < $nbpages - 2) {
  4482. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4483. } elseif ($cpt == $nbpages - 2) {
  4484. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4485. }
  4486. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4487. }
  4488. } else {
  4489. //var_dump($page.' '.$cpt.' '.$nbpages);
  4490. //if (($page + 1) < $nbpages) {
  4491. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4492. //}
  4493. }
  4494. } else {
  4495. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4496. }
  4497. }
  4498. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4499. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow); // output the div and ul for previous/last completed with page numbers into $pagelist
  4500. }
  4501. // js to autoselect page field on focus
  4502. if ($pagenavastextinput) {
  4503. print ajax_autoselect('.pageplusone');
  4504. }
  4505. print '</td>';
  4506. print '</tr></table>'."\n";
  4507. print "<!-- End title -->\n\n";
  4508. }
  4509. /**
  4510. * Function to show navigation arrows into lists
  4511. *
  4512. * @param int $page Number of page
  4513. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4514. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4515. * @param integer $nextpage Do we show a next page button
  4516. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4517. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4518. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4519. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4520. * @param int $hideselectlimit Force to hide select limit
  4521. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4522. * @return void
  4523. */
  4524. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4525. {
  4526. global $conf, $langs;
  4527. print '<div class="pagination"><ul>';
  4528. if ($beforearrows) {
  4529. print '<li class="paginationbeforearrows">';
  4530. print $beforearrows;
  4531. print '</li>';
  4532. }
  4533. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4534. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000,25000:25000';
  4535. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4536. //$pagesizechoices.=',2:2';
  4537. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4538. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4539. }
  4540. print '<li class="pagination">';
  4541. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4542. $tmpchoice = explode(',', $pagesizechoices);
  4543. $tmpkey = $limit.':'.$limit;
  4544. if (!in_array($tmpkey, $tmpchoice)) {
  4545. $tmpchoice[] = $tmpkey;
  4546. }
  4547. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4548. if (!in_array($tmpkey, $tmpchoice)) {
  4549. $tmpchoice[] = $tmpkey;
  4550. }
  4551. asort($tmpchoice, SORT_NUMERIC);
  4552. foreach ($tmpchoice as $val) {
  4553. $selected = '';
  4554. $tmp = explode(':', $val);
  4555. $key = $tmp[0];
  4556. $val = $tmp[1];
  4557. if ($key != '' && $val != '') {
  4558. if ((int) $key == (int) $limit) {
  4559. $selected = ' selected="selected"';
  4560. }
  4561. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4562. }
  4563. }
  4564. print '</select>';
  4565. if ($conf->use_javascript_ajax) {
  4566. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4567. <script>
  4568. jQuery(document).ready(function () {
  4569. jQuery(".selectlimit").change(function() {
  4570. console.log("Change limit. Send submit");
  4571. $(this).parents(\'form:first\').submit();
  4572. });
  4573. });
  4574. </script>
  4575. ';
  4576. }
  4577. print '</li>';
  4578. }
  4579. if ($page > 0) {
  4580. 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>';
  4581. }
  4582. if ($betweenarrows) {
  4583. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4584. print $betweenarrows;
  4585. print '<!--</div>-->';
  4586. }
  4587. if ($nextpage > 0) {
  4588. 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>';
  4589. }
  4590. if ($afterarrows) {
  4591. print '<li class="paginationafterarrows">';
  4592. print $afterarrows;
  4593. print '</li>';
  4594. }
  4595. print '</ul></div>'."\n";
  4596. }
  4597. /**
  4598. * Return a string with VAT rate label formated for view output
  4599. * Used into pdf and HTML pages
  4600. *
  4601. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4602. * @param boolean $addpercent Add a percent % sign in output
  4603. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4604. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4605. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4606. */
  4607. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4608. {
  4609. $morelabel = '';
  4610. if (preg_match('/%/', $rate)) {
  4611. $rate = str_replace('%', '', $rate);
  4612. $addpercent = true;
  4613. }
  4614. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  4615. $morelabel = ' ('.$reg[1].')';
  4616. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4617. }
  4618. if (preg_match('/\*/', $rate)) {
  4619. $rate = str_replace('*', '', $rate);
  4620. $info_bits |= 1;
  4621. }
  4622. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4623. if (!preg_match('/\//', $rate)) {
  4624. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4625. } else {
  4626. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4627. $ret = $rate.($addpercent ? '%' : '');
  4628. }
  4629. if (($info_bits & 1) && $usestarfornpr >= 0) {
  4630. $ret .= ' *';
  4631. }
  4632. $ret .= $morelabel;
  4633. return $ret;
  4634. }
  4635. /**
  4636. * Function to format a value into an amount for visual output
  4637. * Function used into PDF and HTML pages
  4638. *
  4639. * @param float $amount Amount to format
  4640. * @param integer $form Type of format, HTML or not (not by default)
  4641. * @param Translate $outlangs Object langs for output
  4642. * @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.
  4643. * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  4644. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4645. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4646. * @return string Chaine avec montant formate
  4647. *
  4648. * @see price2num() Revert function of price
  4649. */
  4650. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4651. {
  4652. global $langs, $conf;
  4653. // Clean parameters
  4654. if (empty($amount)) {
  4655. $amount = 0; // To have a numeric value if amount not defined or = ''
  4656. }
  4657. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4658. if ($rounding < 0) {
  4659. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4660. }
  4661. $nbdecimal = $rounding;
  4662. // Output separators by default (french)
  4663. $dec = ',';
  4664. $thousand = ' ';
  4665. // If $outlangs not forced, we use use language
  4666. if (!is_object($outlangs)) {
  4667. $outlangs = $langs;
  4668. }
  4669. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4670. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4671. }
  4672. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4673. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4674. }
  4675. if ($thousand == 'None') {
  4676. $thousand = '';
  4677. } elseif ($thousand == 'Space') {
  4678. $thousand = ' ';
  4679. }
  4680. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4681. //print "amount=".$amount."-";
  4682. $amount = str_replace(',', '.', $amount); // should be useless
  4683. //print $amount."-";
  4684. $datas = explode('.', $amount);
  4685. $decpart = isset($datas[1]) ? $datas[1] : '';
  4686. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4687. //print "decpart=".$decpart."<br>";
  4688. $end = '';
  4689. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4690. if (dol_strlen($decpart) > $nbdecimal) {
  4691. $nbdecimal = dol_strlen($decpart);
  4692. }
  4693. // Si on depasse max
  4694. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  4695. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4696. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  4697. // Si un affichage est tronque, on montre des ...
  4698. $end = '...';
  4699. }
  4700. }
  4701. // If force rounding
  4702. if ($forcerounding >= 0) {
  4703. $nbdecimal = $forcerounding;
  4704. }
  4705. // Format number
  4706. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4707. if ($form) {
  4708. $output = preg_replace('/\s/', '&nbsp;', $output);
  4709. $output = preg_replace('/\'/', '&#039;', $output);
  4710. }
  4711. // Add symbol of currency if requested
  4712. $cursymbolbefore = $cursymbolafter = '';
  4713. if ($currency_code) {
  4714. if ($currency_code == 'auto') {
  4715. $currency_code = $conf->currency;
  4716. }
  4717. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4718. $listoflanguagesbefore = array('nl_NL');
  4719. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  4720. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4721. } else {
  4722. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4723. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4724. }
  4725. }
  4726. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4727. return $output;
  4728. }
  4729. /**
  4730. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4731. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4732. * should be roundtext2num().
  4733. *
  4734. * @param string|float $amount Amount to convert/clean or round
  4735. * @param string|int $rounding ''=No rounding
  4736. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4737. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4738. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4739. * 'CU'=Round to Max unit price of foreign currency accuracy
  4740. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  4741. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  4742. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4743. * Put 2 if you know that number is a user input (so we know we don't have to fix decimal separator).
  4744. * @return string Amount with universal numeric format (Example: '99.99999').
  4745. * If conversion fails, it return text unchanged if ($rounding = '' and $option = 1) or '0' if ($rounding is defined and $option = 1).
  4746. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined..
  4747. *
  4748. * @see price() Opposite function of price2num
  4749. */
  4750. function price2num($amount, $rounding = '', $option = 0)
  4751. {
  4752. global $langs, $conf;
  4753. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4754. // Numbers must be '1234.56'
  4755. // Decimal delimiter for PHP and database SQL requests must be '.'
  4756. $dec = ',';
  4757. $thousand = ' ';
  4758. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4759. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4760. }
  4761. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4762. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4763. }
  4764. if ($thousand == 'None') {
  4765. $thousand = '';
  4766. } elseif ($thousand == 'Space') {
  4767. $thousand = ' ';
  4768. }
  4769. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4770. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4771. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4772. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4773. if (!is_numeric($amount)) {
  4774. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  4775. }
  4776. 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
  4777. $amount = str_replace($thousand, '', $amount);
  4778. }
  4779. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4780. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4781. // So if number was already a good number, it is converted into local Dolibarr setup.
  4782. if (is_numeric($amount)) {
  4783. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4784. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4785. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4786. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4787. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4788. }
  4789. //print "QQ".$amount."<br>\n";
  4790. // Now make replace (the main goal of function)
  4791. if ($thousand != ',' && $thousand != '.') {
  4792. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4793. }
  4794. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4795. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4796. $amount = str_replace($dec, '.', $amount);
  4797. }
  4798. //print ' XX'.$amount.' '.$rounding;
  4799. // Now, make a rounding if required
  4800. if ($rounding) {
  4801. $nbofdectoround = '';
  4802. if ($rounding == 'MU') {
  4803. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4804. } elseif ($rounding == 'MT') {
  4805. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4806. } elseif ($rounding == 'MS') {
  4807. $nbofdectoround = empty($conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : $conf->global->MAIN_MAX_DECIMALS_STOCK;
  4808. } elseif ($rounding == 'CU') {
  4809. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  4810. } elseif ($rounding == 'CT') {
  4811. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  4812. } elseif (is_numeric($rounding)) {
  4813. $nbofdectoround = (int) $rounding;
  4814. }
  4815. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  4816. if (dol_strlen($nbofdectoround)) {
  4817. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  4818. } else {
  4819. return 'ErrorBadParameterProvidedToFunction';
  4820. }
  4821. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4822. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4823. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4824. if (is_numeric($amount)) {
  4825. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4826. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4827. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4828. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4829. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4830. }
  4831. //print "TT".$amount.'<br>';
  4832. // Always make replace because each math function (like round) replace
  4833. // with local values and we want a number that has a SQL string format x.y
  4834. if ($thousand != ',' && $thousand != '.') {
  4835. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4836. }
  4837. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4838. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4839. $amount = str_replace($dec, '.', $amount);
  4840. }
  4841. return $amount;
  4842. }
  4843. /**
  4844. * Output a dimension with best unit
  4845. *
  4846. * @param float $dimension Dimension
  4847. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4848. * @param string $type 'weight', 'volume', ...
  4849. * @param Translate $outputlangs Translate language object
  4850. * @param int $round -1 = non rounding, x = number of decimal
  4851. * @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)
  4852. * @return string String to show dimensions
  4853. */
  4854. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
  4855. {
  4856. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4857. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  4858. $dimension = $dimension * 1000000;
  4859. $unit = $unit - 6;
  4860. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  4861. $dimension = $dimension * 1000;
  4862. $unit = $unit - 3;
  4863. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  4864. $dimension = $dimension / 1000000;
  4865. $unit = $unit + 6;
  4866. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  4867. $dimension = $dimension / 1000;
  4868. $unit = $unit + 3;
  4869. }
  4870. // Special case when we want output unit into pound or ounce
  4871. /* TODO
  4872. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4873. {
  4874. $dimension = // convert dimension from standard unit into ounce or pound
  4875. $unit = $forceunitoutput;
  4876. }
  4877. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4878. {
  4879. $dimension = // convert dimension from standard unit into ounce or pound
  4880. $unit = $forceunitoutput;
  4881. }*/
  4882. $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuringUnitString(0, $type, $unit);
  4883. return $ret;
  4884. }
  4885. /**
  4886. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4887. * Note: This function applies same rules than get_default_tva
  4888. *
  4889. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4890. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4891. * @param Societe $thirdparty_buyer Object of buying third party
  4892. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4893. * @param int $vatnpr If vat rate is NPR or not
  4894. * @return mixed 0 if not found, localtax rate if found
  4895. * @see get_default_tva()
  4896. */
  4897. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  4898. {
  4899. global $db, $conf, $mysoc;
  4900. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  4901. $thirdparty_seller = $mysoc;
  4902. }
  4903. 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);
  4904. $vatratecleaned = $vatrate;
  4905. $reg = array();
  4906. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  4907. $vatratecleaned = trim($reg[1]);
  4908. $vatratecode = $reg[2];
  4909. }
  4910. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4911. {
  4912. return 0;
  4913. }*/
  4914. // Some test to guess with no need to make database access
  4915. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4916. if ($local == 1) {
  4917. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  4918. return 0;
  4919. }
  4920. if ($thirdparty_seller->id == $mysoc->id) {
  4921. if (!$thirdparty_buyer->localtax1_assuj) {
  4922. return 0;
  4923. }
  4924. } else {
  4925. if (!$thirdparty_seller->localtax1_assuj) {
  4926. return 0;
  4927. }
  4928. }
  4929. }
  4930. if ($local == 2) {
  4931. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4932. if (!$mysoc->localtax2_assuj) {
  4933. return 0; // If main vat is 0, IRPF may be different than 0.
  4934. }
  4935. if ($thirdparty_seller->id == $mysoc->id) {
  4936. if (!$thirdparty_buyer->localtax2_assuj) {
  4937. return 0;
  4938. }
  4939. } else {
  4940. if (!$thirdparty_seller->localtax2_assuj) {
  4941. return 0;
  4942. }
  4943. }
  4944. }
  4945. } else {
  4946. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  4947. return 0;
  4948. }
  4949. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  4950. return 0;
  4951. }
  4952. }
  4953. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4954. if (in_array($mysoc->country_code, array('ES'))) {
  4955. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4956. }
  4957. // Search local taxes
  4958. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  4959. if ($local == 1) {
  4960. if ($thirdparty_seller != $mysoc) {
  4961. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4962. return $thirdparty_seller->localtax1_value;
  4963. }
  4964. } else { // i am the seller
  4965. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4966. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4967. }
  4968. }
  4969. }
  4970. if ($local == 2) {
  4971. if ($thirdparty_seller != $mysoc) {
  4972. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4973. // TODO We should also return value defined on thirdparty only if defined
  4974. return $thirdparty_seller->localtax2_value;
  4975. }
  4976. } else { // i am the seller
  4977. if (in_array($mysoc->country_code, array('ES'))) {
  4978. return $thirdparty_buyer->localtax2_value;
  4979. } else {
  4980. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4981. }
  4982. }
  4983. }
  4984. }
  4985. // By default, search value of local tax on line of common tax
  4986. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4987. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4988. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  4989. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4990. if (!empty($vatratecode)) {
  4991. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  4992. } else {
  4993. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  4994. }
  4995. dol_syslog("get_localtax", LOG_DEBUG);
  4996. $resql = $db->query($sql);
  4997. if ($resql) {
  4998. $obj = $db->fetch_object($resql);
  4999. if ($obj) {
  5000. if ($local == 1) {
  5001. return $obj->localtax1;
  5002. } elseif ($local == 2) {
  5003. return $obj->localtax2;
  5004. }
  5005. }
  5006. }
  5007. return 0;
  5008. }
  5009. /**
  5010. * Return true if LocalTax (1 or 2) is unique.
  5011. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5012. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5013. *
  5014. * @param int $local Local tax to test (1 or 2)
  5015. * @return boolean True if LocalTax have multiple values, False if not
  5016. */
  5017. function isOnlyOneLocalTax($local)
  5018. {
  5019. $tax = get_localtax_by_third($local);
  5020. $valors = explode(":", $tax);
  5021. if (count($valors) > 1) {
  5022. return false;
  5023. } else {
  5024. return true;
  5025. }
  5026. }
  5027. /**
  5028. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5029. *
  5030. * @param int $local LocalTax to get
  5031. * @return number Values of localtax
  5032. */
  5033. function get_localtax_by_third($local)
  5034. {
  5035. global $db, $mysoc;
  5036. $sql = "SELECT t.localtax1, t.localtax2 ";
  5037. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5038. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5039. $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";
  5040. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5041. $sql .= " )";
  5042. $resql = $db->query($sql);
  5043. if ($resql) {
  5044. $obj = $db->fetch_object($resql);
  5045. if ($local == 1) {
  5046. return $obj->localtax1;
  5047. } elseif ($local == 2) {
  5048. return $obj->localtax2;
  5049. }
  5050. }
  5051. return 0;
  5052. }
  5053. /**
  5054. * Get tax (VAT) main information from Id.
  5055. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5056. *
  5057. * @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.
  5058. * @param Societe $buyer Company object
  5059. * @param Societe $seller Company object
  5060. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5061. * @return array array('rowid'=> , 'code'=> ...)
  5062. * @see getLocalTaxesFromRate()
  5063. */
  5064. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5065. {
  5066. global $db, $mysoc;
  5067. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5068. // Search local taxes
  5069. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5070. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5071. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5072. if ($firstparamisid) {
  5073. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5074. } else {
  5075. $vatratecleaned = $vatrate;
  5076. $vatratecode = '';
  5077. $reg = array();
  5078. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5079. $vatratecleaned = $reg[1];
  5080. $vatratecode = $reg[2];
  5081. }
  5082. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5083. /*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 ??
  5084. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5085. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5086. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5087. if ($vatratecode) {
  5088. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5089. }
  5090. }
  5091. $resql = $db->query($sql);
  5092. if ($resql) {
  5093. $obj = $db->fetch_object($resql);
  5094. if ($obj) {
  5095. return array(
  5096. 'rowid'=>$obj->rowid,
  5097. 'code'=>$obj->code,
  5098. 'rate'=>$obj->rate,
  5099. 'localtax1'=>$obj->localtax1,
  5100. 'localtax1_type'=>$obj->localtax1_type,
  5101. 'localtax2'=>$obj->localtax2,
  5102. 'localtax2_type'=>$obj->localtax2_type,
  5103. 'npr'=>$obj->npr,
  5104. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5105. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5106. );
  5107. } else {
  5108. return array();
  5109. }
  5110. } else {
  5111. dol_print_error($db);
  5112. }
  5113. return array();
  5114. }
  5115. /**
  5116. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5117. * This does not take into account the seller setup if subject to vat or not, only country.
  5118. *
  5119. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5120. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5121. * provide the selected value to the function calcul_price_total.
  5122. *
  5123. * @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.
  5124. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5125. * @param Societe $buyer Company object
  5126. * @param Societe $seller Company object
  5127. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5128. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5129. * @see getTaxesFromId()
  5130. */
  5131. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5132. {
  5133. global $db, $mysoc;
  5134. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5135. // Search local taxes
  5136. $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";
  5137. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5138. if ($firstparamisid) {
  5139. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5140. } else {
  5141. $vatratecleaned = $vatrate;
  5142. $vatratecode = '';
  5143. $reg = array();
  5144. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5145. $vatratecleaned = $reg[1];
  5146. $vatratecode = $reg[2];
  5147. }
  5148. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5149. if ($mysoc->country_code == 'ES') {
  5150. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5151. } else {
  5152. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5153. }
  5154. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5155. if ($vatratecode) {
  5156. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5157. }
  5158. }
  5159. $resql = $db->query($sql);
  5160. if ($resql) {
  5161. $obj = $db->fetch_object($resql);
  5162. if ($obj) {
  5163. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5164. if ($local == 1) {
  5165. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5166. } elseif ($local == 2) {
  5167. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5168. } else {
  5169. 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);
  5170. }
  5171. }
  5172. }
  5173. return array();
  5174. }
  5175. /**
  5176. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5177. * Function called by get_default_tva().
  5178. *
  5179. * @param int $idprod Id of product or 0 if not a predefined product
  5180. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5181. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5182. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5183. * @see get_product_localtax_for_country()
  5184. */
  5185. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5186. {
  5187. global $db, $conf, $mysoc;
  5188. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5189. $ret = 0;
  5190. $found = 0;
  5191. if ($idprod > 0) {
  5192. // Load product
  5193. $product = new Product($db);
  5194. $result = $product->fetch($idprod);
  5195. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5196. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5197. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5198. $ret = $product->vatrate_supplier;
  5199. if ($product->default_vat_code) {
  5200. $ret .= ' ('.$product->default_vat_code.')';
  5201. }
  5202. } else {
  5203. $ret = $product->tva_tx; // Default vat of product we defined
  5204. if ($product->default_vat_code) {
  5205. $ret .= ' ('.$product->default_vat_code.')';
  5206. }
  5207. }
  5208. $found = 1;
  5209. } else {
  5210. // TODO Read default product vat according to product and another countrycode.
  5211. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5212. }
  5213. }
  5214. if (!$found) {
  5215. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5216. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5217. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5218. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5219. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5220. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5221. $sql .= $db->plimit(1);
  5222. $resql = $db->query($sql);
  5223. if ($resql) {
  5224. $obj = $db->fetch_object($resql);
  5225. if ($obj) {
  5226. $ret = $obj->vat_rate;
  5227. if ($obj->default_vat_code) {
  5228. $ret .= ' ('.$obj->default_vat_code.')';
  5229. }
  5230. }
  5231. $db->free($sql);
  5232. } else {
  5233. dol_print_error($db);
  5234. }
  5235. } else {
  5236. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5237. }
  5238. }
  5239. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5240. return $ret;
  5241. }
  5242. /**
  5243. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5244. *
  5245. * @param int $idprod Id of product
  5246. * @param int $local 1 for localtax1, 2 for localtax 2
  5247. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5248. * @return int <0 if KO, Vat rate if OK
  5249. * @see get_product_vat_for_country()
  5250. */
  5251. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5252. {
  5253. global $db, $mysoc;
  5254. if (!class_exists('Product')) {
  5255. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5256. }
  5257. $ret = 0;
  5258. $found = 0;
  5259. if ($idprod > 0) {
  5260. // Load product
  5261. $product = new Product($db);
  5262. $result = $product->fetch($idprod);
  5263. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5264. /* Not defined yet, so we don't use this
  5265. if ($local==1) $ret=$product->localtax1_tx;
  5266. elseif ($local==2) $ret=$product->localtax2_tx;
  5267. $found=1;
  5268. */
  5269. } else {
  5270. // TODO Read default product vat according to product and another countrycode.
  5271. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5272. }
  5273. }
  5274. if (!$found) {
  5275. // If vat of product for the country not found or not defined, we return higher vat of country.
  5276. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5277. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5278. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5279. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5280. $sql .= $db->plimit(1);
  5281. $resql = $db->query($sql);
  5282. if ($resql) {
  5283. $obj = $db->fetch_object($resql);
  5284. if ($obj) {
  5285. if ($local == 1) {
  5286. $ret = $obj->localtax1;
  5287. } elseif ($local == 2) {
  5288. $ret = $obj->localtax2;
  5289. }
  5290. }
  5291. } else {
  5292. dol_print_error($db);
  5293. }
  5294. }
  5295. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5296. return $ret;
  5297. }
  5298. /**
  5299. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5300. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5301. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5302. * VATRULE 3: Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  5303. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5304. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5305. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5306. *
  5307. * @param Societe $thirdparty_seller Objet societe vendeuse
  5308. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5309. * @param int $idprod Id product
  5310. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5311. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5312. * @see get_default_npr(), get_default_localtax()
  5313. */
  5314. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5315. {
  5316. global $conf;
  5317. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5318. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5319. $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;
  5320. $seller_country_code = $thirdparty_seller->country_code;
  5321. $seller_in_cee = isInEEC($thirdparty_seller);
  5322. $buyer_country_code = $thirdparty_buyer->country_code;
  5323. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5324. 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 : ''));
  5325. // 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)
  5326. // we use the buyer VAT.
  5327. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5328. if ($seller_in_cee && $buyer_in_cee) {
  5329. $isacompany = $thirdparty_buyer->isACompany();
  5330. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5331. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5332. if (!isValidVATID($thirdparty_buyer)) {
  5333. $isacompany = 0;
  5334. }
  5335. }
  5336. if (!$isacompany) {
  5337. //print 'VATRULE 0';
  5338. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5339. }
  5340. }
  5341. }
  5342. // If seller does not use VAT
  5343. if (!$seller_use_vat) {
  5344. //print 'VATRULE 1';
  5345. return 0;
  5346. }
  5347. // Le test ci-dessus ne devrait pas etre necessaire. Me signaler l'exemple du cas juridique concerne si le test suivant n'est pas suffisant.
  5348. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5349. if (($seller_country_code == $buyer_country_code)
  5350. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5351. //print 'VATRULE 2';
  5352. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5353. }
  5354. // Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  5355. // 'VATRULE 3' - Not supported
  5356. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5357. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5358. if (($seller_in_cee && $buyer_in_cee)) {
  5359. $isacompany = $thirdparty_buyer->isACompany();
  5360. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5361. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5362. if (!isValidVATID($thirdparty_buyer)) {
  5363. $isacompany = 0;
  5364. }
  5365. }
  5366. if (!$isacompany) {
  5367. //print 'VATRULE 4';
  5368. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5369. } else {
  5370. //print 'VATRULE 5';
  5371. return 0;
  5372. }
  5373. }
  5374. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5375. // I don't see any use case that need this rule.
  5376. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5377. $isacompany = $thirdparty_buyer->isACompany();
  5378. if (!$isacompany) {
  5379. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5380. //print 'VATRULE extra';
  5381. }
  5382. }
  5383. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5384. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5385. //print 'VATRULE 6';
  5386. return 0;
  5387. }
  5388. /**
  5389. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5390. *
  5391. * @param Societe $thirdparty_seller Thirdparty seller
  5392. * @param Societe $thirdparty_buyer Thirdparty buyer
  5393. * @param int $idprod Id product
  5394. * @param int $idprodfournprice Id supplier price for product
  5395. * @return float 0 or 1
  5396. * @see get_default_tva(), get_default_localtax()
  5397. */
  5398. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5399. {
  5400. global $db;
  5401. if ($idprodfournprice > 0) {
  5402. if (!class_exists('ProductFournisseur')) {
  5403. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5404. }
  5405. $prodprice = new ProductFournisseur($db);
  5406. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5407. return $prodprice->fourn_tva_npr;
  5408. } elseif ($idprod > 0) {
  5409. if (!class_exists('Product')) {
  5410. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5411. }
  5412. $prod = new Product($db);
  5413. $prod->fetch($idprod);
  5414. return $prod->tva_npr;
  5415. }
  5416. return 0;
  5417. }
  5418. /**
  5419. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5420. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5421. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5422. * Sinon TVA proposee par defaut=0. Fin de regle.
  5423. *
  5424. * @param Societe $thirdparty_seller Thirdparty seller
  5425. * @param Societe $thirdparty_buyer Thirdparty buyer
  5426. * @param int $local Localtax to process (1 or 2)
  5427. * @param int $idprod Id product
  5428. * @return integer localtax, -1 si ne peut etre determine
  5429. * @see get_default_tva(), get_default_npr()
  5430. */
  5431. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5432. {
  5433. global $mysoc;
  5434. if (!is_object($thirdparty_seller)) {
  5435. return -1;
  5436. }
  5437. if (!is_object($thirdparty_buyer)) {
  5438. return -1;
  5439. }
  5440. if ($local == 1) { // Localtax 1
  5441. if ($mysoc->country_code == 'ES') {
  5442. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5443. return 0;
  5444. }
  5445. } else {
  5446. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5447. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5448. return 0;
  5449. }
  5450. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5451. return 0;
  5452. }
  5453. }
  5454. } elseif ($local == 2) { //I Localtax 2
  5455. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5456. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5457. return 0;
  5458. }
  5459. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5460. return 0;
  5461. }
  5462. }
  5463. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5464. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5465. }
  5466. return 0;
  5467. }
  5468. /**
  5469. * Return yes or no in current language
  5470. *
  5471. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5472. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5473. * @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.
  5474. * @return string HTML string
  5475. */
  5476. function yn($yesno, $case = 1, $color = 0)
  5477. {
  5478. global $langs;
  5479. $result = 'unknown';
  5480. $classname = '';
  5481. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5482. $result = $langs->trans('yes');
  5483. if ($case == 1 || $case == 3) {
  5484. $result = $langs->trans("Yes");
  5485. }
  5486. if ($case == 2) {
  5487. $result = '<input type="checkbox" value="1" checked disabled>';
  5488. }
  5489. if ($case == 3) {
  5490. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5491. }
  5492. $classname = 'ok';
  5493. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5494. $result = $langs->trans("no");
  5495. if ($case == 1 || $case == 3) {
  5496. $result = $langs->trans("No");
  5497. }
  5498. if ($case == 2) {
  5499. $result = '<input type="checkbox" value="0" disabled>';
  5500. }
  5501. if ($case == 3) {
  5502. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5503. }
  5504. if ($color == 2) {
  5505. $classname = 'ok';
  5506. } else {
  5507. $classname = 'error';
  5508. }
  5509. }
  5510. if ($color) {
  5511. return '<font class="'.$classname.'">'.$result.'</font>';
  5512. }
  5513. return $result;
  5514. }
  5515. /**
  5516. * Return a path to have a the directory according to object where files are stored.
  5517. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5518. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5519. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5520. * 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/"
  5521. *
  5522. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5523. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5524. * @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)
  5525. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5526. * @param Object $object Object to use to get ref to forge the path.
  5527. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5528. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5529. */
  5530. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5531. {
  5532. global $conf;
  5533. if (empty($modulepart) && !empty($object->module)) {
  5534. $modulepart = $object->module;
  5535. }
  5536. $path = '';
  5537. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5538. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5539. $arrayforoldpath[] = 'product';
  5540. }
  5541. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5542. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5543. if (empty($alpha)) {
  5544. $num = preg_replace('/([^0-9])/i', '', $num);
  5545. } else {
  5546. $num = preg_replace('/^.*\-/i', '', $num);
  5547. }
  5548. $num = substr("000".$num, -$level);
  5549. if ($level == 1) {
  5550. $path = substr($num, 0, 1);
  5551. }
  5552. if ($level == 2) {
  5553. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5554. }
  5555. if ($level == 3) {
  5556. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5557. }
  5558. } else {
  5559. // We will enhance here a common way of forging path for document storage.
  5560. // In a future, we may distribute directories on several levels depending on setup and object.
  5561. // Here, $object->id, $object->ref and $modulepart are required.
  5562. //var_dump($modulepart);
  5563. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5564. }
  5565. if (empty($withoutslash) && !empty($path)) {
  5566. $path .= '/';
  5567. }
  5568. return $path;
  5569. }
  5570. /**
  5571. * Creation of a directory (this can create recursive subdir)
  5572. *
  5573. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5574. * @param string $dataroot Data root directory (To avoid having the data root in the loop. Using this will also lost the warning on first dir PHP has no permission when open_basedir is used)
  5575. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5576. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5577. */
  5578. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5579. {
  5580. global $conf;
  5581. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5582. $dir_osencoded = dol_osencode($dir);
  5583. if (@is_dir($dir_osencoded)) {
  5584. return 0;
  5585. }
  5586. $nberr = 0;
  5587. $nbcreated = 0;
  5588. $ccdir = '';
  5589. if (!empty($dataroot)) {
  5590. // Remove data root from loop
  5591. $dir = str_replace($dataroot.'/', '', $dir);
  5592. $ccdir = $dataroot.'/';
  5593. }
  5594. $cdir = explode("/", $dir);
  5595. $num = count($cdir);
  5596. for ($i = 0; $i < $num; $i++) {
  5597. if ($i > 0) {
  5598. $ccdir .= '/'.$cdir[$i];
  5599. } else {
  5600. $ccdir .= $cdir[$i];
  5601. }
  5602. if (preg_match("/^.:$/", $ccdir, $regs)) {
  5603. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5604. }
  5605. // Attention, le is_dir() peut echouer bien que le rep existe.
  5606. // (ex selon config de open_basedir)
  5607. if ($ccdir) {
  5608. $ccdir_osencoded = dol_osencode($ccdir);
  5609. if (!@is_dir($ccdir_osencoded)) {
  5610. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5611. umask(0);
  5612. $dirmaskdec = octdec($newmask);
  5613. if (empty($newmask)) {
  5614. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5615. }
  5616. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5617. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  5618. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5619. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5620. $nberr++;
  5621. } else {
  5622. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5623. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5624. $nbcreated++;
  5625. }
  5626. } else {
  5627. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5628. }
  5629. }
  5630. }
  5631. return ($nberr ? -$nberr : $nbcreated);
  5632. }
  5633. /**
  5634. * Return picto saying a field is required
  5635. *
  5636. * @return string Chaine avec picto obligatoire
  5637. */
  5638. function picto_required()
  5639. {
  5640. return '<span class="fieldrequired">*</span>';
  5641. }
  5642. /**
  5643. * Clean a string from all HTML tags and entities.
  5644. * This function differs from strip_tags because:
  5645. * - <br> are replaced with \n if removelinefeed=0 or 1
  5646. * - if entities are found, they are decoded BEFORE the strip
  5647. * - you can decide to convert line feed into a space
  5648. *
  5649. * @param string $stringtoclean String to clean
  5650. * @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..."
  5651. * @param string $pagecodeto Encoding of input/output string
  5652. * @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')
  5653. * @param integer $removedoublespaces Replace double space into one space
  5654. * @return string String cleaned
  5655. *
  5656. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5657. */
  5658. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5659. {
  5660. if ($removelinefeed == 2) {
  5661. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5662. }
  5663. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5664. // 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)
  5665. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5666. $temp = str_replace('< ', '__ltspace__', $temp);
  5667. if ($strip_tags) {
  5668. $temp = strip_tags($temp);
  5669. } else {
  5670. $temp = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  5671. $pattern = "/<[^<>]+>/";
  5672. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5673. $temp = preg_replace($pattern, "", $temp); // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5674. $temp = preg_replace($pattern, "", $temp); // pass 2 - $temp after pass 2: 0000-021
  5675. // 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).
  5676. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  5677. }
  5678. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5679. // Remove also carriage returns
  5680. if ($removelinefeed == 1) {
  5681. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5682. }
  5683. // And double quotes
  5684. if ($removedoublespaces) {
  5685. while (strpos($temp, " ")) {
  5686. $temp = str_replace(" ", " ", $temp);
  5687. }
  5688. }
  5689. $temp = str_replace('__ltspace__', '< ', $temp);
  5690. return trim($temp);
  5691. }
  5692. /**
  5693. * Clean a string to keep only desirable HTML tags.
  5694. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  5695. *
  5696. * @param string $stringtoclean String to clean
  5697. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5698. * @param int $removeclassattribute 1=Remove the class attribute from tags
  5699. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  5700. * @param int $allowiframe Allow iframe tags.
  5701. * @return string String cleaned
  5702. *
  5703. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5704. */
  5705. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  5706. {
  5707. $allowed_tags = array(
  5708. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5709. "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"
  5710. );
  5711. if ($allowiframe) {
  5712. $allowed_tags[] = "iframe";
  5713. }
  5714. $allowed_tags_string = join("><", $allowed_tags);
  5715. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5716. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  5717. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5718. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  5719. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5720. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  5721. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  5722. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  5723. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5724. $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
  5725. }
  5726. if ($removeclassattribute) { // Clean for remaining html tags
  5727. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5728. }
  5729. // Remove 'javascript:' that we should not find into a text with
  5730. // 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)).
  5731. if ($cleanalsojavascript) {
  5732. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5733. }
  5734. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  5735. return $temp;
  5736. }
  5737. /**
  5738. * Clean a string from some undesirable HTML tags.
  5739. * Note. Not as secured as dol_string_onlythesehtmltags().
  5740. *
  5741. * @param string $stringtoclean String to clean
  5742. * @param array $allowed_attributes Array of tags not allowed
  5743. * @return string String cleaned
  5744. *
  5745. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  5746. */
  5747. 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"))
  5748. {
  5749. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  5750. $stringtoclean = '<html><body>'.$stringtoclean.'</body></html>';
  5751. $dom = new DOMDocument();
  5752. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  5753. if (is_object($dom)) {
  5754. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  5755. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  5756. // Delete attribute if not into allowed_attributes
  5757. if (! empty($attrs->item($ii)->name) && ! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  5758. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  5759. }
  5760. }
  5761. }
  5762. }
  5763. $return = $dom->saveHTML();
  5764. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  5765. $return = preg_replace('/^<html><body>/', '', $return);
  5766. $return = preg_replace('/<\/body><\/html>$/', '', $return);
  5767. return $return;
  5768. } else {
  5769. return $stringtoclean;
  5770. }
  5771. }
  5772. /**
  5773. * Clean a string from some undesirable HTML tags.
  5774. * Note. Not as secured as dol_string_onlythesehtmltags().
  5775. *
  5776. * @param string $stringtoclean String to clean
  5777. * @param array $disallowed_tags Array of tags not allowed
  5778. * @param string $cleanalsosomestyles Clean also some tags
  5779. * @return string String cleaned
  5780. *
  5781. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  5782. */
  5783. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5784. {
  5785. $temp = $stringtoclean;
  5786. foreach ($disallowed_tags as $tagtoremove) {
  5787. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5788. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5789. }
  5790. if ($cleanalsosomestyles) {
  5791. $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
  5792. }
  5793. return $temp;
  5794. }
  5795. /**
  5796. * Return first line of text. Cut will depends if content is HTML or not.
  5797. *
  5798. * @param string $text Input text
  5799. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5800. * @param string $charset Charset of $text string (UTF-8 by default)
  5801. * @return string Output text
  5802. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5803. */
  5804. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5805. {
  5806. if ($nboflines == 1) {
  5807. if (dol_textishtml($text)) {
  5808. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5809. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5810. } else {
  5811. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5812. }
  5813. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5814. } else {
  5815. $ishtml = 0;
  5816. if (dol_textishtml($text)) {
  5817. $text = preg_replace('/\n/', '', $text);
  5818. $ishtml = 1;
  5819. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5820. } else {
  5821. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5822. }
  5823. $text = strtr($text, $repTable);
  5824. if ($charset == 'UTF-8') {
  5825. $pattern = '/(<br[^>]*>)/Uu';
  5826. } else {
  5827. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5828. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5829. }
  5830. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5831. $firstline = '';
  5832. $i = 0;
  5833. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5834. while (($i < $nba) && ($i < ($nboflines * 2))) {
  5835. if ($i % 2 == 0) {
  5836. $firstline .= $a[$i];
  5837. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  5838. $firstline .= ($ishtml ? "<br>\n" : "\n");
  5839. }
  5840. $i++;
  5841. }
  5842. unset($a);
  5843. return $firstline.(($i < $nba) ? '...' : '');
  5844. }
  5845. }
  5846. /**
  5847. * Replace CRLF in string with a HTML BR tag.
  5848. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have encode the special chars of stringtoencode into HTML before.
  5849. *
  5850. * @param string $stringtoencode String to encode
  5851. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5852. * @param bool $forxml false=Use <br>, true=Use <br />
  5853. * @return string String encoded
  5854. * @see dol_nboflines(), dolGetFirstLineOfText()
  5855. */
  5856. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5857. {
  5858. if (!$nl2brmode) {
  5859. return nl2br($stringtoencode, $forxml);
  5860. } else {
  5861. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  5862. return $ret;
  5863. }
  5864. }
  5865. /**
  5866. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5867. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5868. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5869. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5870. * For PDF usage, you can show text by 2 ways:
  5871. * - writeHTMLCell -> param must be encoded into HTML.
  5872. * - MultiCell -> param must not be encoded into HTML.
  5873. * Because writeHTMLCell convert also \n into <br>, if function
  5874. * is used to build PDF, nl2brmode must be 1.
  5875. *
  5876. * @param string $stringtoencode String to encode
  5877. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5878. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5879. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5880. * @return string String encoded
  5881. */
  5882. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  5883. {
  5884. $newstring = $stringtoencode;
  5885. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  5886. $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.
  5887. if ($removelasteolbr) {
  5888. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  5889. }
  5890. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  5891. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  5892. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  5893. } else {
  5894. if ($removelasteolbr) {
  5895. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  5896. }
  5897. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  5898. }
  5899. // Other substitutions that htmlentities does not do
  5900. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5901. return $newstring;
  5902. }
  5903. /**
  5904. * This function is called to decode a HTML string (it decodes entities and br tags)
  5905. *
  5906. * @param string $stringtodecode String to decode
  5907. * @param string $pagecodeto Page code for result
  5908. * @return string String decoded
  5909. */
  5910. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  5911. {
  5912. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5913. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  5914. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  5915. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  5916. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  5917. return $ret;
  5918. }
  5919. /**
  5920. * This function remove all ending \n and br at end
  5921. *
  5922. * @param string $stringtodecode String to decode
  5923. * @return string String decoded
  5924. */
  5925. function dol_htmlcleanlastbr($stringtodecode)
  5926. {
  5927. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
  5928. return $ret;
  5929. }
  5930. /**
  5931. * Replace html_entity_decode functions to manage errors
  5932. *
  5933. * @param string $a Operand a
  5934. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  5935. * @param string $c Operand c
  5936. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  5937. * @return string String decoded
  5938. */
  5939. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  5940. {
  5941. $newstring = $a;
  5942. if ($keepsomeentities) {
  5943. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  5944. }
  5945. $newstring = html_entity_decode($newstring, $b, $c);
  5946. if ($keepsomeentities) {
  5947. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  5948. }
  5949. return $newstring;
  5950. }
  5951. /**
  5952. * Replace htmlentities functions.
  5953. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5954. *
  5955. * @param string $string The input string to encode
  5956. * @param int $flags Flags (see PHP doc above)
  5957. * @param string $encoding Encoding page code
  5958. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5959. * @return string $ret Encoded string
  5960. */
  5961. function dol_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = false)
  5962. {
  5963. return htmlentities($string, $flags, $encoding, $double_encode);
  5964. }
  5965. /**
  5966. * Check if a string is a correct iso string
  5967. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5968. * Example, if string contains euro symbol that has ascii code 128
  5969. *
  5970. * @param string $s String to check
  5971. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  5972. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  5973. */
  5974. function dol_string_is_good_iso($s, $clean = 0)
  5975. {
  5976. $len = dol_strlen($s);
  5977. $out = '';
  5978. $ok = 1;
  5979. for ($scursor = 0; $scursor < $len; $scursor++) {
  5980. $ordchar = ord($s[$scursor]);
  5981. //print $scursor.'-'.$ordchar.'<br>';
  5982. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  5983. $ok = 0;
  5984. break;
  5985. } elseif ($ordchar > 126 && $ordchar < 160) {
  5986. $ok = 0;
  5987. break;
  5988. } elseif ($clean) {
  5989. $out .= $s[$scursor];
  5990. }
  5991. }
  5992. if ($clean) {
  5993. return $out;
  5994. }
  5995. return $ok;
  5996. }
  5997. /**
  5998. * Return nb of lines of a clear text
  5999. *
  6000. * @param string $s String to check
  6001. * @param int $maxchar Not yet used
  6002. * @return int Number of lines
  6003. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6004. */
  6005. function dol_nboflines($s, $maxchar = 0)
  6006. {
  6007. if ($s == '') {
  6008. return 0;
  6009. }
  6010. $arraystring = explode("\n", $s);
  6011. $nb = count($arraystring);
  6012. return $nb;
  6013. }
  6014. /**
  6015. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6016. *
  6017. * @param string $text Text
  6018. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6019. * @param string $charset Give the charset used to encode the $text variable in memory.
  6020. * @return int Number of lines
  6021. * @see dol_nboflines(), dolGetFirstLineOfText()
  6022. */
  6023. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6024. {
  6025. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6026. if (dol_textishtml($text)) {
  6027. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6028. }
  6029. $text = strtr($text, $repTable);
  6030. if ($charset == 'UTF-8') {
  6031. $pattern = '/(<br[^>]*>)/Uu';
  6032. } else {
  6033. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6034. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6035. }
  6036. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6037. $nblines = (int) floor((count($a) + 1) / 2);
  6038. // count possible auto line breaks
  6039. if ($maxlinesize) {
  6040. foreach ($a as $line) {
  6041. if (dol_strlen($line) > $maxlinesize) {
  6042. //$line_dec = html_entity_decode(strip_tags($line));
  6043. $line_dec = html_entity_decode($line);
  6044. if (dol_strlen($line_dec) > $maxlinesize) {
  6045. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6046. $nblines += substr_count($line_dec, '\n');
  6047. }
  6048. }
  6049. }
  6050. }
  6051. unset($a);
  6052. return $nblines;
  6053. }
  6054. /**
  6055. * Return if a text is a html content
  6056. *
  6057. * @param string $msg Content to check
  6058. * @param int $option 0=Full detection, 1=Fast check
  6059. * @return boolean true/false
  6060. * @see dol_concatdesc()
  6061. */
  6062. function dol_textishtml($msg, $option = 0)
  6063. {
  6064. if ($option == 1) {
  6065. if (preg_match('/<html/i', $msg)) {
  6066. return true;
  6067. } elseif (preg_match('/<body/i', $msg)) {
  6068. return true;
  6069. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6070. return true;
  6071. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6072. return true;
  6073. } elseif (preg_match('/<br/i', $msg)) {
  6074. return true;
  6075. }
  6076. return false;
  6077. } else {
  6078. if (preg_match('/<html/i', $msg)) {
  6079. return true;
  6080. } elseif (preg_match('/<body/i', $msg)) {
  6081. return true;
  6082. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6083. return true;
  6084. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6085. return true;
  6086. } elseif (preg_match('/<br\/>/i', $msg)) {
  6087. return true;
  6088. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6089. return true;
  6090. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6091. return true;
  6092. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6093. return true; // must accept <img src="http://example.com/aaa.png" />
  6094. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6095. return true; // must accept <a href="http://example.com/aaa.png" />
  6096. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6097. return true;
  6098. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6099. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6100. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6101. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6102. }
  6103. return false;
  6104. }
  6105. }
  6106. /**
  6107. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6108. * text1 html + text2 html => text1 + '<br>' + text2
  6109. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6110. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6111. * text1 txt + text2 txt => text1 + '\n' + text2
  6112. *
  6113. * @param string $text1 Text 1
  6114. * @param string $text2 Text 2
  6115. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6116. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6117. * @return string Text 1 + new line + Text2
  6118. * @see dol_textishtml()
  6119. */
  6120. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6121. {
  6122. if (!empty($invert)) {
  6123. $tmp = $text1;
  6124. $text1 = $text2;
  6125. $text2 = $tmp;
  6126. }
  6127. $ret = '';
  6128. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6129. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6130. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6131. return $ret;
  6132. }
  6133. /**
  6134. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6135. *
  6136. * @param Translate $outputlangs Output language
  6137. * @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)
  6138. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6139. * @param Object $object Object for keys on object
  6140. * @return array Array of substitutions
  6141. * @see setSubstitFromObject()
  6142. */
  6143. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6144. {
  6145. global $db, $conf, $mysoc, $user, $extrafields;
  6146. $substitutionarray = array();
  6147. if (empty($exclude) || !in_array('user', $exclude)) {
  6148. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6149. // this will include signature content first and then replace var found into content of signature
  6150. $signature = $user->signature;
  6151. $substitutionarray = array_merge($substitutionarray, array(
  6152. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6153. ));
  6154. if (is_object($user)) {
  6155. $substitutionarray = array_merge($substitutionarray, array(
  6156. '__USER_ID__' => (string) $user->id,
  6157. '__USER_LOGIN__' => (string) $user->login,
  6158. '__USER_EMAIL__' => (string) $user->email,
  6159. '__USER_LASTNAME__' => (string) $user->lastname,
  6160. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6161. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6162. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6163. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6164. ));
  6165. }
  6166. }
  6167. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6168. $substitutionarray = array_merge($substitutionarray, array(
  6169. '__MYCOMPANY_NAME__' => $mysoc->name,
  6170. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6171. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6172. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6173. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6174. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6175. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6176. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6177. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6178. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6179. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6180. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6181. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6182. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6183. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6184. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6185. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6186. ));
  6187. }
  6188. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6189. if ($onlykey) {
  6190. $substitutionarray['__ID__'] = '__ID__';
  6191. $substitutionarray['__REF__'] = '__REF__';
  6192. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6193. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6194. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6195. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6196. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6197. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6198. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6199. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6200. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6201. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6202. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6203. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6204. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6205. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6206. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6207. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6208. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6209. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6210. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6211. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6212. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6213. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6214. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6215. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6216. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6217. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6218. }
  6219. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6220. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6221. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6222. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6223. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6224. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6225. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6226. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6227. }
  6228. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature')) {
  6229. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6230. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6231. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6232. }
  6233. if (!empty($conf->projet->enabled)) { // Most objects
  6234. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6235. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6236. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6237. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6238. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6239. }
  6240. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6241. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6242. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6243. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6244. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6245. }
  6246. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6247. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6248. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6249. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6250. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6251. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6252. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  6253. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6254. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6255. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6256. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6257. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6258. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6259. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6260. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6261. }
  6262. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6263. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6264. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6265. }
  6266. } else {
  6267. $substitutionarray['__ID__'] = $object->id;
  6268. $substitutionarray['__REF__'] = $object->ref;
  6269. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6270. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6271. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6272. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6273. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6274. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6275. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6276. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6277. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6278. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6279. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6280. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6281. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6282. // For backward compatibility
  6283. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6284. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6285. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6286. $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 : '')) : '');
  6287. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6288. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6289. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6290. if (method_exists($object, 'getCivilityLabel')) {
  6291. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6292. }
  6293. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6294. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6295. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6296. if (method_exists($object, 'getFullName')) {
  6297. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6298. }
  6299. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6300. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6301. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6302. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6303. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6304. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6305. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6306. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6307. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6308. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6309. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  6310. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  6311. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  6312. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6313. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6314. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  6315. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  6316. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6317. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6318. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6319. }
  6320. if (is_object($object) && $object->element == 'societe') {
  6321. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6322. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6323. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6324. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6325. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6326. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6327. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  6328. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  6329. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6330. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6331. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6332. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6333. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6334. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6335. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6336. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6337. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6338. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6339. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6340. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6341. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6342. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6343. } elseif (is_object($object->thirdparty)) {
  6344. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6345. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6346. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6347. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6348. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6349. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6350. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  6351. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  6352. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6353. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6354. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6355. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6356. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6357. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6358. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6359. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6360. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6361. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6362. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6363. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6364. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6365. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6366. }
  6367. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6368. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6369. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  6370. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  6371. }
  6372. if (is_object($object->project)) {
  6373. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6374. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6375. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6376. }
  6377. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6378. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6379. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6380. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6381. }
  6382. if (is_object($object) && $object->element == 'shipping') {
  6383. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6384. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6385. }
  6386. if (is_object($object) && $object->element == 'reception') {
  6387. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6388. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6389. }
  6390. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6391. $dateplannedstart = '';
  6392. $datenextexpiration = '';
  6393. foreach ($object->lines as $line) {
  6394. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6395. $dateplannedstart = $line->date_ouverture_prevue;
  6396. }
  6397. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6398. $datenextexpiration = $line->date_fin_prevue;
  6399. }
  6400. }
  6401. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6402. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6403. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6404. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6405. }
  6406. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6407. if ($object->table_element && $object->id > 0) {
  6408. if (!is_object($extrafields)) {
  6409. $extrafields = new ExtraFields($db);
  6410. }
  6411. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6412. if ($object->fetch_optionals() > 0) {
  6413. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6414. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6415. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6416. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6417. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6418. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6419. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6420. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6421. $datetime = $object->array_options['options_'.$key];
  6422. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6423. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6424. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6425. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6426. }
  6427. }
  6428. }
  6429. }
  6430. }
  6431. // Complete substitution array with the url to make online payment
  6432. $paymenturl = '';
  6433. if (empty($substitutionarray['__REF__'])) {
  6434. $paymenturl = '';
  6435. } else {
  6436. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6437. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6438. $outputlangs->loadLangs(array('paypal', 'other'));
  6439. $typeforonlinepayment = 'free';
  6440. if (is_object($object) && $object->element == 'commande') {
  6441. $typeforonlinepayment = 'order';
  6442. }
  6443. if (is_object($object) && $object->element == 'facture') {
  6444. $typeforonlinepayment = 'invoice';
  6445. }
  6446. if (is_object($object) && $object->element == 'member') {
  6447. $typeforonlinepayment = 'member';
  6448. }
  6449. if (is_object($object) && $object->element == 'contrat') {
  6450. $typeforonlinepayment = 'contract';
  6451. }
  6452. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6453. $paymenturl = $url;
  6454. }
  6455. if ($object->id > 0) {
  6456. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6457. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6458. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6459. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6460. } else {
  6461. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6462. }
  6463. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6464. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6465. } else {
  6466. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6467. }
  6468. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6469. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6470. } else {
  6471. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6472. }
  6473. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6474. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6475. } else {
  6476. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6477. }
  6478. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6479. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6480. } else {
  6481. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6482. }
  6483. if (is_object($object) && $object->element == 'propal') {
  6484. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6485. }
  6486. if (is_object($object) && $object->element == 'commande') {
  6487. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6488. }
  6489. if (is_object($object) && $object->element == 'facture') {
  6490. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6491. }
  6492. if (is_object($object) && $object->element == 'contrat') {
  6493. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6494. }
  6495. if (is_object($object) && $object->element == 'supplier_proposal') {
  6496. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6497. }
  6498. }
  6499. if (is_object($object) && $object->element == 'action') {
  6500. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6501. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  6502. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  6503. }
  6504. }
  6505. }
  6506. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  6507. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  6508. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  6509. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  6510. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  6511. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  6512. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  6513. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  6514. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6515. $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)) : '';
  6516. $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)) : '';
  6517. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6518. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  6519. }
  6520. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6521. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  6522. }
  6523. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6524. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6525. $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)) : '';
  6526. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6527. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6528. }
  6529. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6530. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6531. }
  6532. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  6533. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  6534. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  6535. // TODO Add other keys for foreign multicurrency
  6536. // For backward compatibility
  6537. if ($onlykey != 2) {
  6538. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  6539. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  6540. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6541. }
  6542. }
  6543. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  6544. if (empty($exclude) || !in_array('date', $exclude)) {
  6545. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6546. $tmp = dol_getdate(dol_now(), true);
  6547. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6548. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  6549. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6550. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  6551. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  6552. $substitutionarray = array_merge($substitutionarray, array(
  6553. '__DAY__' => (string) $tmp['mday'],
  6554. '__DAY_TEXT__' => $daytext, // Monday
  6555. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  6556. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  6557. '__MONTH__' => (string) $tmp['mon'],
  6558. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  6559. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  6560. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  6561. '__YEAR__' => (string) $tmp['year'],
  6562. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  6563. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  6564. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  6565. '__NEXT_DAY__' => (string) $tmp4['day'],
  6566. '__NEXT_MONTH__' => (string) $tmp5['month'],
  6567. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  6568. ));
  6569. }
  6570. if (!empty($conf->multicompany->enabled)) {
  6571. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  6572. }
  6573. if (empty($exclude) || !in_array('system', $exclude)) {
  6574. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  6575. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  6576. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  6577. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  6578. }
  6579. return $substitutionarray;
  6580. }
  6581. /**
  6582. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  6583. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  6584. * Example of usage:
  6585. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  6586. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  6587. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  6588. *
  6589. * @param string $text Source string in which we must do substitution
  6590. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  6591. * @param Translate $outputlangs Output language
  6592. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  6593. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  6594. * @return string Output string after substitutions
  6595. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  6596. */
  6597. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  6598. {
  6599. global $conf, $langs;
  6600. if (!is_array($substitutionarray)) {
  6601. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  6602. }
  6603. if (empty($outputlangs)) {
  6604. $outputlangs = $langs;
  6605. }
  6606. // Is initial text HTML or simple text ?
  6607. $msgishtml = 0;
  6608. if (dol_textishtml($text, 1)) {
  6609. $msgishtml = 1;
  6610. }
  6611. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  6612. if (is_object($outputlangs)) {
  6613. $reg = array();
  6614. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  6615. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  6616. $tmp = explode('|', $reg[1]);
  6617. if (!empty($tmp[1])) {
  6618. $outputlangs->load($tmp[1]);
  6619. }
  6620. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  6621. if (empty($converttextinhtmlifnecessary)) {
  6622. // convert $newval into HTML is necessary
  6623. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6624. } else {
  6625. if (! $msgishtml) {
  6626. $valueishtml = dol_textishtml($value, 1);
  6627. if ($valueishtml) {
  6628. $text = dol_htmlentitiesbr($text);
  6629. $msgishtml = 1;
  6630. }
  6631. } else {
  6632. $value = dol_nl2br("$value");
  6633. }
  6634. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  6635. }
  6636. }
  6637. }
  6638. // Make substitution for constant keys.
  6639. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  6640. $reg = array();
  6641. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  6642. $keyfound = $reg[1];
  6643. if (isASecretKey($keyfound)) {
  6644. $value = '*****forbidden*****';
  6645. } else {
  6646. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  6647. }
  6648. if (empty($converttextinhtmlifnecessary)) {
  6649. // convert $newval into HTML is necessary
  6650. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6651. } else {
  6652. if (! $msgishtml) {
  6653. $valueishtml = dol_textishtml($value, 1);
  6654. if ($valueishtml) {
  6655. $text = dol_htmlentitiesbr($text);
  6656. $msgishtml = 1;
  6657. }
  6658. } else {
  6659. $value = dol_nl2br("$value");
  6660. }
  6661. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  6662. }
  6663. }
  6664. // Make substitition for array $substitutionarray
  6665. foreach ($substitutionarray as $key => $value) {
  6666. if (!isset($value)) {
  6667. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  6668. }
  6669. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  6670. $value = ''; // Protection
  6671. }
  6672. if (empty($converttextinhtmlifnecessary)) {
  6673. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6674. } else {
  6675. if (! $msgishtml) {
  6676. $valueishtml = dol_textishtml($value, 1);
  6677. if ($valueishtml) {
  6678. $text = dol_htmlentitiesbr($text);
  6679. $msgishtml = 1;
  6680. }
  6681. } else {
  6682. $value = dol_nl2br("$value");
  6683. }
  6684. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6685. }
  6686. }
  6687. return $text;
  6688. }
  6689. /**
  6690. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6691. * In this case, method completesubstitutionarray provided by module is called.
  6692. *
  6693. * @param array $substitutionarray Array substitution old value => new value value
  6694. * @param Translate $outputlangs Output language
  6695. * @param Object $object Source object
  6696. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6697. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6698. * @return void
  6699. * @see make_substitutions()
  6700. */
  6701. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6702. {
  6703. global $conf, $user;
  6704. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6705. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  6706. // Check if there is external substitution to do, requested by plugins
  6707. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  6708. foreach ($dirsubstitutions as $reldir) {
  6709. $dir = dol_buildpath($reldir, 0);
  6710. // Check if directory exists
  6711. if (!dol_is_dir($dir)) {
  6712. continue;
  6713. }
  6714. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  6715. foreach ($substitfiles as $substitfile) {
  6716. $reg = array();
  6717. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  6718. $module = $reg[1];
  6719. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  6720. // Include the user's functions file
  6721. require_once $dir.$substitfile['name'];
  6722. // Call the user's function, and only if it is defined
  6723. $function_name = $module."_".$callfunc;
  6724. if (function_exists($function_name)) {
  6725. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  6726. }
  6727. }
  6728. }
  6729. }
  6730. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  6731. // to list all tags in odt template
  6732. $tags = '';
  6733. foreach ($substitutionarray as $key => $value) {
  6734. $tags .= '{'.$key.'} => '.$value."\n";
  6735. }
  6736. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  6737. }
  6738. }
  6739. /**
  6740. * Format output for start and end date
  6741. *
  6742. * @param int $date_start Start date
  6743. * @param int $date_end End date
  6744. * @param string $format Output format
  6745. * @param Translate $outputlangs Output language
  6746. * @return void
  6747. */
  6748. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  6749. {
  6750. print get_date_range($date_start, $date_end, $format, $outputlangs);
  6751. }
  6752. /**
  6753. * Format output for start and end date
  6754. *
  6755. * @param int $date_start Start date
  6756. * @param int $date_end End date
  6757. * @param string $format Output format
  6758. * @param Translate $outputlangs Output language
  6759. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  6760. * @return string String
  6761. */
  6762. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  6763. {
  6764. global $langs;
  6765. $out = '';
  6766. if (!is_object($outputlangs)) {
  6767. $outputlangs = $langs;
  6768. }
  6769. if ($date_start && $date_end) {
  6770. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6771. }
  6772. if ($date_start && !$date_end) {
  6773. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6774. }
  6775. if (!$date_start && $date_end) {
  6776. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6777. }
  6778. return $out;
  6779. }
  6780. /**
  6781. * Return firstname and lastname in correct order
  6782. *
  6783. * @param string $firstname Firstname
  6784. * @param string $lastname Lastname
  6785. * @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
  6786. * @return string Firstname + lastname or Lastname + firstname
  6787. */
  6788. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  6789. {
  6790. global $conf;
  6791. $ret = '';
  6792. // If order not defined, we use the setup
  6793. if ($nameorder < 0) {
  6794. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  6795. }
  6796. if ($nameorder == 1) {
  6797. $ret .= $firstname;
  6798. if ($firstname && $lastname) {
  6799. $ret .= ' ';
  6800. }
  6801. $ret .= $lastname;
  6802. } elseif ($nameorder == 2 || $nameorder == 3) {
  6803. $ret .= $firstname;
  6804. if (empty($ret) && $nameorder == 3) {
  6805. $ret .= $lastname;
  6806. }
  6807. } else { // 0, 4 or 5
  6808. $ret .= $lastname;
  6809. if (empty($ret) && $nameorder == 5) {
  6810. $ret .= $firstname;
  6811. }
  6812. if ($nameorder == 0) {
  6813. if ($firstname && $lastname) {
  6814. $ret .= ' ';
  6815. }
  6816. $ret .= $firstname;
  6817. }
  6818. }
  6819. return $ret;
  6820. }
  6821. /**
  6822. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  6823. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6824. * Note: Prefer to use setEventMessages instead.
  6825. *
  6826. * @param string|string[] $mesgs Message string or array
  6827. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6828. * @return void
  6829. * @see dol_htmloutput_events()
  6830. */
  6831. function setEventMessage($mesgs, $style = 'mesgs')
  6832. {
  6833. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  6834. if (!is_array($mesgs)) {
  6835. // If mesgs is a string
  6836. if ($mesgs) {
  6837. $_SESSION['dol_events'][$style][] = $mesgs;
  6838. }
  6839. } else {
  6840. // If mesgs is an array
  6841. foreach ($mesgs as $mesg) {
  6842. if ($mesg) {
  6843. $_SESSION['dol_events'][$style][] = $mesg;
  6844. }
  6845. }
  6846. }
  6847. }
  6848. /**
  6849. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  6850. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6851. *
  6852. * @param string $mesg Message string
  6853. * @param array $mesgs Message array
  6854. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6855. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  6856. * @return void
  6857. * @see dol_htmloutput_events()
  6858. */
  6859. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  6860. {
  6861. if (empty($mesg) && empty($mesgs)) {
  6862. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  6863. } else {
  6864. if ($messagekey) {
  6865. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  6866. // TODO
  6867. $mesg .= '';
  6868. }
  6869. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  6870. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  6871. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  6872. }
  6873. if (empty($mesgs)) {
  6874. setEventMessage($mesg, $style);
  6875. } else {
  6876. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  6877. setEventMessage($mesg, $style); // Add message string if not already into array
  6878. }
  6879. setEventMessage($mesgs, $style);
  6880. }
  6881. }
  6882. }
  6883. }
  6884. /**
  6885. * Print formated messages to output (Used to show messages on html output).
  6886. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  6887. * no need to call it explicitely.
  6888. *
  6889. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  6890. * @return void
  6891. * @see dol_htmloutput_mesg()
  6892. */
  6893. function dol_htmloutput_events($disabledoutputofmessages = 0)
  6894. {
  6895. // Show mesgs
  6896. if (isset($_SESSION['dol_events']['mesgs'])) {
  6897. if (empty($disabledoutputofmessages)) {
  6898. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  6899. }
  6900. unset($_SESSION['dol_events']['mesgs']);
  6901. }
  6902. // Show errors
  6903. if (isset($_SESSION['dol_events']['errors'])) {
  6904. if (empty($disabledoutputofmessages)) {
  6905. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  6906. }
  6907. unset($_SESSION['dol_events']['errors']);
  6908. }
  6909. // Show warnings
  6910. if (isset($_SESSION['dol_events']['warnings'])) {
  6911. if (empty($disabledoutputofmessages)) {
  6912. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  6913. }
  6914. unset($_SESSION['dol_events']['warnings']);
  6915. }
  6916. }
  6917. /**
  6918. * Get formated messages to output (Used to show messages on html output).
  6919. * This include also the translation of the message key.
  6920. *
  6921. * @param string $mesgstring Message string or message key
  6922. * @param string[] $mesgarray Array of message strings or message keys
  6923. * @param string $style Style of message output ('ok' or 'error')
  6924. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6925. * @return string Return html output
  6926. *
  6927. * @see dol_print_error()
  6928. * @see dol_htmloutput_errors()
  6929. * @see setEventMessages()
  6930. */
  6931. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  6932. {
  6933. global $conf, $langs;
  6934. $ret = 0;
  6935. $return = '';
  6936. $out = '';
  6937. $divstart = $divend = '';
  6938. // If inline message with no format, we add it.
  6939. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  6940. $divstart = '<div class="'.$style.' clearboth">';
  6941. $divend = '</div>';
  6942. }
  6943. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  6944. $langs->load("errors");
  6945. $out .= $divstart;
  6946. if (is_array($mesgarray) && count($mesgarray)) {
  6947. foreach ($mesgarray as $message) {
  6948. $ret++;
  6949. $out .= $langs->trans($message);
  6950. if ($ret < count($mesgarray)) {
  6951. $out .= "<br>\n";
  6952. }
  6953. }
  6954. }
  6955. if ($mesgstring) {
  6956. $langs->load("errors");
  6957. $ret++;
  6958. $out .= $langs->trans($mesgstring);
  6959. }
  6960. $out .= $divend;
  6961. }
  6962. if ($out) {
  6963. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  6964. $return = '<script>
  6965. $(document).ready(function() {
  6966. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  6967. if (block) {
  6968. $.dolEventValid("","'.dol_escape_js($out).'");
  6969. } else {
  6970. /* jnotify(message, preset of message type, keepmessage) */
  6971. $.jnotify("'.dol_escape_js($out).'",
  6972. "'.($style == "ok" ? 3000 : $style).'",
  6973. '.($style == "ok" ? "false" : "true").',
  6974. { remove: function (){} } );
  6975. }
  6976. });
  6977. </script>';
  6978. } else {
  6979. $return = $out;
  6980. }
  6981. }
  6982. return $return;
  6983. }
  6984. /**
  6985. * Get formated error messages to output (Used to show messages on html output).
  6986. *
  6987. * @param string $mesgstring Error message
  6988. * @param array $mesgarray Error messages array
  6989. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6990. * @return string Return html output
  6991. *
  6992. * @see dol_print_error()
  6993. * @see dol_htmloutput_mesg()
  6994. */
  6995. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6996. {
  6997. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6998. }
  6999. /**
  7000. * Print formated messages to output (Used to show messages on html output).
  7001. *
  7002. * @param string $mesgstring Message string or message key
  7003. * @param string[] $mesgarray Array of message strings or message keys
  7004. * @param string $style Which style to use ('ok', 'warning', 'error')
  7005. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7006. * @return void
  7007. *
  7008. * @see dol_print_error()
  7009. * @see dol_htmloutput_errors()
  7010. * @see setEventMessages()
  7011. */
  7012. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7013. {
  7014. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7015. return;
  7016. }
  7017. $iserror = 0;
  7018. $iswarning = 0;
  7019. if (is_array($mesgarray)) {
  7020. foreach ($mesgarray as $val) {
  7021. if ($val && preg_match('/class="error"/i', $val)) {
  7022. $iserror++;
  7023. break;
  7024. }
  7025. if ($val && preg_match('/class="warning"/i', $val)) {
  7026. $iswarning++;
  7027. break;
  7028. }
  7029. }
  7030. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7031. $iserror++;
  7032. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7033. $iswarning++;
  7034. }
  7035. if ($style == 'error') {
  7036. $iserror++;
  7037. }
  7038. if ($style == 'warning') {
  7039. $iswarning++;
  7040. }
  7041. if ($iserror || $iswarning) {
  7042. // Remove div from texts
  7043. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7044. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7045. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7046. // Remove div from texts array
  7047. if (is_array($mesgarray)) {
  7048. $newmesgarray = array();
  7049. foreach ($mesgarray as $val) {
  7050. if (is_string($val)) {
  7051. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7052. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7053. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7054. $newmesgarray[] = $tmpmesgstring;
  7055. } else {
  7056. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7057. }
  7058. }
  7059. $mesgarray = $newmesgarray;
  7060. }
  7061. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7062. } else {
  7063. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7064. }
  7065. }
  7066. /**
  7067. * Print formated error messages to output (Used to show messages on html output).
  7068. *
  7069. * @param string $mesgstring Error message
  7070. * @param array $mesgarray Error messages array
  7071. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7072. * @return void
  7073. *
  7074. * @see dol_print_error()
  7075. * @see dol_htmloutput_mesg()
  7076. */
  7077. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7078. {
  7079. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7080. }
  7081. /**
  7082. * Advanced sort array by second index function, which produces ascending (default)
  7083. * or descending output and uses optionally natural case insensitive sorting (which
  7084. * can be optionally case sensitive as well).
  7085. *
  7086. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7087. * @param string $index Key in array to use for sorting criteria
  7088. * @param int $order Sort order ('asc' or 'desc')
  7089. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7090. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7091. * @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.
  7092. * @return array Sorted array
  7093. */
  7094. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7095. {
  7096. // Clean parameters
  7097. $order = strtolower($order);
  7098. if (is_array($array)) {
  7099. $sizearray = count($array);
  7100. if ($sizearray > 0) {
  7101. $temp = array();
  7102. foreach (array_keys($array) as $key) {
  7103. if (is_object($array[$key])) {
  7104. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7105. } else {
  7106. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7107. }
  7108. }
  7109. if (!$natsort) {
  7110. if ($order == 'asc') {
  7111. asort($temp);
  7112. } else {
  7113. arsort($temp);
  7114. }
  7115. } else {
  7116. if ($case_sensitive) {
  7117. natsort($temp);
  7118. } else {
  7119. natcasesort($temp); // natecasesort is not sensible to case
  7120. }
  7121. if ($order != 'asc') {
  7122. $temp = array_reverse($temp, true);
  7123. }
  7124. }
  7125. $sorted = array();
  7126. foreach (array_keys($temp) as $key) {
  7127. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7128. }
  7129. return $sorted;
  7130. }
  7131. }
  7132. return $array;
  7133. }
  7134. /**
  7135. * Check if a string is in UTF8
  7136. *
  7137. * @param string $str String to check
  7138. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7139. */
  7140. function utf8_check($str)
  7141. {
  7142. $str = (string) $str; // Sometimes string is an int.
  7143. // We must use here a binary strlen function (so not dol_strlen)
  7144. $strLength = dol_strlen($str);
  7145. for ($i = 0; $i < $strLength; $i++) {
  7146. if (ord($str[$i]) < 0x80) {
  7147. continue; // 0bbbbbbb
  7148. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7149. $n = 1; // 110bbbbb
  7150. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7151. $n = 2; // 1110bbbb
  7152. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7153. $n = 3; // 11110bbb
  7154. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7155. $n = 4; // 111110bb
  7156. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7157. $n = 5; // 1111110b
  7158. } else {
  7159. return false; // Does not match any model
  7160. }
  7161. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7162. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7163. return false;
  7164. }
  7165. }
  7166. }
  7167. return true;
  7168. }
  7169. /**
  7170. * Check if a string is in ASCII
  7171. *
  7172. * @param string $str String to check
  7173. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7174. */
  7175. function ascii_check($str)
  7176. {
  7177. if (function_exists('mb_check_encoding')) {
  7178. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7179. if (!mb_check_encoding($str, 'ASCII')) {
  7180. return false;
  7181. }
  7182. } else {
  7183. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7184. return false; // Contains a byte > 7f
  7185. }
  7186. }
  7187. return true;
  7188. }
  7189. /**
  7190. * Return a string encoded into OS filesystem encoding. This function is used to define
  7191. * value to pass to filesystem PHP functions.
  7192. *
  7193. * @param string $str String to encode (UTF-8)
  7194. * @return string Encoded string (UTF-8, ISO-8859-1)
  7195. */
  7196. function dol_osencode($str)
  7197. {
  7198. global $conf;
  7199. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7200. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7201. $tmp = 'iso-8859-1'; // By default for windows
  7202. }
  7203. if (empty($tmp)) {
  7204. $tmp = 'utf-8'; // By default for other
  7205. }
  7206. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7207. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7208. }
  7209. if ($tmp == 'iso-8859-1') {
  7210. return utf8_decode($str);
  7211. }
  7212. return $str;
  7213. }
  7214. /**
  7215. * Return an id or code from a code or id.
  7216. * Store also Code-Id into a cache to speed up next request on same key.
  7217. *
  7218. * @param DoliDB $db Database handler
  7219. * @param string $key Code or Id to get Id or Code
  7220. * @param string $tablename Table name without prefix
  7221. * @param string $fieldkey Field to search the key into
  7222. * @param string $fieldid Field to get
  7223. * @param int $entityfilter Filter by entity
  7224. * @return int <0 if KO, Id of code if OK
  7225. * @see $langs->getLabelFromKey
  7226. */
  7227. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  7228. {
  7229. global $cache_codes;
  7230. // If key empty
  7231. if ($key == '') {
  7232. return '';
  7233. }
  7234. // Check in cache
  7235. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7236. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7237. }
  7238. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7239. $sql = "SELECT ".$fieldid." as valuetoget";
  7240. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7241. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7242. if (!empty($entityfilter)) {
  7243. $sql .= " AND entity IN (".getEntity($tablename).")";
  7244. }
  7245. $resql = $db->query($sql);
  7246. if ($resql) {
  7247. $obj = $db->fetch_object($resql);
  7248. if ($obj) {
  7249. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7250. } else {
  7251. $cache_codes[$tablename][$key][$fieldid] = '';
  7252. }
  7253. $db->free($resql);
  7254. return $cache_codes[$tablename][$key][$fieldid];
  7255. } else {
  7256. return -1;
  7257. }
  7258. }
  7259. /**
  7260. * Verify if condition in string is ok or not
  7261. *
  7262. * @param string $strRights String with condition to check
  7263. * @return boolean True or False. Return True if strRights is ''
  7264. */
  7265. function verifCond($strRights)
  7266. {
  7267. global $user, $conf, $langs;
  7268. global $leftmenu;
  7269. global $rights; // To export to dol_eval function
  7270. //print $strRights."<br>\n";
  7271. $rights = true;
  7272. if ($strRights != '') {
  7273. $str = 'if(!('.$strRights.')) { $rights = false; }';
  7274. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  7275. }
  7276. return $rights;
  7277. }
  7278. /**
  7279. * Replace eval function to add more security.
  7280. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7281. *
  7282. * @param string $s String to evaluate
  7283. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7284. * @param int $hideerrors 1=Hide errors
  7285. * @return mixed Nothing or return result of eval
  7286. */
  7287. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  7288. {
  7289. // Only global variables can be changed by eval function and returned to caller
  7290. global $db, $langs, $user, $conf, $website, $websitepage;
  7291. global $action, $mainmenu, $leftmenu;
  7292. global $rights;
  7293. global $object;
  7294. global $mysoc;
  7295. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7296. global $soc; // For backward compatibility
  7297. // Replace dangerous char (used for RCE), we allow only PHP variable testing.
  7298. if (strpos($s, '`') !== false) {
  7299. return 'Bad string syntax to evaluate: '.$s;
  7300. }
  7301. // We block using of php exec or php file functions
  7302. $forbiddenphpstrings = array("exec(", "passthru(", "shell_exec(", "system(", "proc_open(", "popen(", "eval(", "dol_eval(", "executeCLI(");
  7303. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array("fopen(", "file_put_contents(", "fputs(", "fputscsv(", "fwrite(", "fpassthru(", "unlink(", "mkdir(", "rmdir(", "symlink(", "touch(", "umask("));
  7304. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('function(', '$$', 'call_user_func('));
  7305. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7306. $forbiddenphpregex = 'global\s+\$';
  7307. do {
  7308. $oldstringtoclean = $s;
  7309. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7310. $s = preg_replace('/'.$forbiddenphpregex.'/', '__forbiddenstring__', $s);
  7311. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7312. } while ($oldstringtoclean != $s);
  7313. if (strpos($s, '__forbiddenstring__') !== false) {
  7314. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7315. return 'Bad string syntax to evaluate: '.$s;
  7316. }
  7317. //print $s."<br>\n";
  7318. if ($returnvalue) {
  7319. if ($hideerrors) {
  7320. return @eval('return '.$s.';');
  7321. } else {
  7322. return eval('return '.$s.';');
  7323. }
  7324. } else {
  7325. if ($hideerrors) {
  7326. @eval($s);
  7327. } else {
  7328. eval($s);
  7329. }
  7330. }
  7331. }
  7332. /**
  7333. * Return if var element is ok
  7334. *
  7335. * @param string $element Variable to check
  7336. * @return boolean Return true of variable is not empty
  7337. */
  7338. function dol_validElement($element)
  7339. {
  7340. return (trim($element) != '');
  7341. }
  7342. /**
  7343. * Return img flag of country for a language code or country code.
  7344. *
  7345. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7346. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7347. * @return string HTML img string with flag.
  7348. */
  7349. function picto_from_langcode($codelang, $moreatt = '')
  7350. {
  7351. if (empty($codelang)) {
  7352. return '';
  7353. }
  7354. if ($codelang == 'auto') {
  7355. return '<span class="fa fa-globe"></span>';
  7356. }
  7357. $langtocountryflag = array(
  7358. 'ar_AR' => '',
  7359. 'ca_ES' => 'catalonia',
  7360. 'da_DA' => 'dk',
  7361. 'fr_CA' => 'mq',
  7362. 'sv_SV' => 'se',
  7363. 'sw_SW' => 'unknown',
  7364. 'AQ' => 'unknown',
  7365. 'CW' => 'unknown',
  7366. 'IM' => 'unknown',
  7367. 'JE' => 'unknown',
  7368. 'MF' => 'unknown',
  7369. 'BL' => 'unknown',
  7370. 'SX' => 'unknown'
  7371. );
  7372. if (isset($langtocountryflag[$codelang])) {
  7373. $flagImage = $langtocountryflag[$codelang];
  7374. } else {
  7375. $tmparray = explode('_', $codelang);
  7376. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7377. }
  7378. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  7379. }
  7380. /**
  7381. * Return default language from country code.
  7382. * Return null if not found.
  7383. *
  7384. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'MX', ...
  7385. * @return string Value of locale like 'en_US', 'fr_FR', ...
  7386. */
  7387. function getLanguageCodeFromCountryCode($countrycode)
  7388. {
  7389. global $mysoc;
  7390. if (empty($countrycode)) {
  7391. return null;
  7392. }
  7393. if (strtoupper($countrycode) == 'MQ') {
  7394. return 'fr_CA';
  7395. }
  7396. if (strtoupper($countrycode) == 'SE') {
  7397. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7398. }
  7399. if (strtoupper($countrycode) == 'CH') {
  7400. if ($mysoc->country_code == 'FR') {
  7401. return 'fr_CH';
  7402. }
  7403. if ($mysoc->country_code == 'DE') {
  7404. return 'de_CH';
  7405. }
  7406. if ($mysoc->country_code == 'IT') {
  7407. return 'it_CH';
  7408. }
  7409. }
  7410. // Locale list taken from:
  7411. // http://stackoverflow.com/questions/3191664/
  7412. // list-of-all-locales-and-their-short-codes
  7413. $locales = array(
  7414. 'af-ZA',
  7415. 'am-ET',
  7416. 'ar-AE',
  7417. 'ar-BH',
  7418. 'ar-DZ',
  7419. 'ar-EG',
  7420. 'ar-IQ',
  7421. 'ar-JO',
  7422. 'ar-KW',
  7423. 'ar-LB',
  7424. 'ar-LY',
  7425. 'ar-MA',
  7426. 'ar-OM',
  7427. 'ar-QA',
  7428. 'ar-SA',
  7429. 'ar-SY',
  7430. 'ar-TN',
  7431. 'ar-YE',
  7432. 'as-IN',
  7433. 'ba-RU',
  7434. 'be-BY',
  7435. 'bg-BG',
  7436. 'bn-BD',
  7437. 'bn-IN',
  7438. 'bo-CN',
  7439. 'br-FR',
  7440. 'ca-ES',
  7441. 'co-FR',
  7442. 'cs-CZ',
  7443. 'cy-GB',
  7444. 'da-DK',
  7445. 'de-AT',
  7446. 'de-CH',
  7447. 'de-DE',
  7448. 'de-LI',
  7449. 'de-LU',
  7450. 'dv-MV',
  7451. 'el-GR',
  7452. 'en-AU',
  7453. 'en-BZ',
  7454. 'en-CA',
  7455. 'en-GB',
  7456. 'en-IE',
  7457. 'en-IN',
  7458. 'en-JM',
  7459. 'en-MY',
  7460. 'en-NZ',
  7461. 'en-PH',
  7462. 'en-SG',
  7463. 'en-TT',
  7464. 'en-US',
  7465. 'en-ZA',
  7466. 'en-ZW',
  7467. 'es-AR',
  7468. 'es-BO',
  7469. 'es-CL',
  7470. 'es-CO',
  7471. 'es-CR',
  7472. 'es-DO',
  7473. 'es-EC',
  7474. 'es-ES',
  7475. 'es-GT',
  7476. 'es-HN',
  7477. 'es-MX',
  7478. 'es-NI',
  7479. 'es-PA',
  7480. 'es-PE',
  7481. 'es-PR',
  7482. 'es-PY',
  7483. 'es-SV',
  7484. 'es-US',
  7485. 'es-UY',
  7486. 'es-VE',
  7487. 'et-EE',
  7488. 'eu-ES',
  7489. 'fa-IR',
  7490. 'fi-FI',
  7491. 'fo-FO',
  7492. 'fr-BE',
  7493. 'fr-CA',
  7494. 'fr-CH',
  7495. 'fr-FR',
  7496. 'fr-LU',
  7497. 'fr-MC',
  7498. 'fy-NL',
  7499. 'ga-IE',
  7500. 'gd-GB',
  7501. 'gl-ES',
  7502. 'gu-IN',
  7503. 'he-IL',
  7504. 'hi-IN',
  7505. 'hr-BA',
  7506. 'hr-HR',
  7507. 'hu-HU',
  7508. 'hy-AM',
  7509. 'id-ID',
  7510. 'ig-NG',
  7511. 'ii-CN',
  7512. 'is-IS',
  7513. 'it-CH',
  7514. 'it-IT',
  7515. 'ja-JP',
  7516. 'ka-GE',
  7517. 'kk-KZ',
  7518. 'kl-GL',
  7519. 'km-KH',
  7520. 'kn-IN',
  7521. 'ko-KR',
  7522. 'ky-KG',
  7523. 'lb-LU',
  7524. 'lo-LA',
  7525. 'lt-LT',
  7526. 'lv-LV',
  7527. 'mi-NZ',
  7528. 'mk-MK',
  7529. 'ml-IN',
  7530. 'mn-MN',
  7531. 'mr-IN',
  7532. 'ms-BN',
  7533. 'ms-MY',
  7534. 'mt-MT',
  7535. 'nb-NO',
  7536. 'ne-NP',
  7537. 'nl-BE',
  7538. 'nl-NL',
  7539. 'nn-NO',
  7540. 'oc-FR',
  7541. 'or-IN',
  7542. 'pa-IN',
  7543. 'pl-PL',
  7544. 'ps-AF',
  7545. 'pt-BR',
  7546. 'pt-PT',
  7547. 'rm-CH',
  7548. 'ro-MD',
  7549. 'ro-RO',
  7550. 'ru-RU',
  7551. 'rw-RW',
  7552. 'sa-IN',
  7553. 'se-FI',
  7554. 'se-NO',
  7555. 'se-SE',
  7556. 'si-LK',
  7557. 'sk-SK',
  7558. 'sl-SI',
  7559. 'sq-AL',
  7560. 'sv-FI',
  7561. 'sv-SE',
  7562. 'sw-KE',
  7563. 'ta-IN',
  7564. 'te-IN',
  7565. 'th-TH',
  7566. 'tk-TM',
  7567. 'tn-ZA',
  7568. 'tr-TR',
  7569. 'tt-RU',
  7570. 'ug-CN',
  7571. 'uk-UA',
  7572. 'ur-PK',
  7573. 'vi-VN',
  7574. 'wo-SN',
  7575. 'xh-ZA',
  7576. 'yo-NG',
  7577. 'zh-CN',
  7578. 'zh-HK',
  7579. 'zh-MO',
  7580. 'zh-SG',
  7581. 'zh-TW',
  7582. 'zu-ZA',
  7583. );
  7584. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  7585. if (in_array($buildprimarykeytotest, $locales)) {
  7586. return strtolower($countrycode).'_'.strtoupper($countrycode);
  7587. }
  7588. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  7589. foreach ($locales as $locale) {
  7590. $locale_language = locale_get_primary_language($locale);
  7591. $locale_region = locale_get_region($locale);
  7592. if (strtoupper($countrycode) == $locale_region) {
  7593. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  7594. return strtolower($locale_language).'_'.strtoupper($locale_region);
  7595. }
  7596. }
  7597. } else {
  7598. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  7599. }
  7600. return null;
  7601. }
  7602. /**
  7603. * Complete or removed entries into a head array (used to build tabs).
  7604. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  7605. * Or by change using hook completeTabsHead
  7606. *
  7607. * @param Conf $conf Object conf
  7608. * @param Translate $langs Object langs
  7609. * @param object|null $object Object object
  7610. * @param array $head Object head
  7611. * @param int $h New position to fill
  7612. * @param string $type Value for object where objectvalue can be
  7613. * 'thirdparty' to add a tab in third party view
  7614. * 'intervention' to add a tab in intervention view
  7615. * 'supplier_order' to add a tab in supplier order view
  7616. * 'supplier_invoice' to add a tab in supplier invoice view
  7617. * 'invoice' to add a tab in customer invoice view
  7618. * 'order' to add a tab in customer order view
  7619. * 'contract' to add a tabl in contract view
  7620. * 'product' to add a tab in product view
  7621. * 'propal' to add a tab in propal view
  7622. * 'user' to add a tab in user view
  7623. * 'group' to add a tab in group view
  7624. * 'member' to add a tab in fundation member view
  7625. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  7626. * 'ecm' to add a tab for another ecm view
  7627. * 'stock' to add a tab for warehouse view
  7628. * @param string $mode 'add' to complete head, 'remove' to remove entries
  7629. * @return void
  7630. */
  7631. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  7632. {
  7633. global $hookmanager;
  7634. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  7635. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  7636. $values = explode(':', $value);
  7637. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  7638. if (count($values) == 6) { // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  7639. if ($values[0] != $type) {
  7640. continue;
  7641. }
  7642. if (verifCond($values[4])) {
  7643. if ($values[3]) {
  7644. $langs->load($values[3]);
  7645. }
  7646. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7647. $substitutionarray = array();
  7648. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7649. $label = make_substitutions($reg[1], $substitutionarray);
  7650. } else {
  7651. $label = $langs->trans($values[2]);
  7652. }
  7653. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  7654. $head[$h][1] = $label;
  7655. $head[$h][2] = str_replace('+', '', $values[1]);
  7656. $h++;
  7657. }
  7658. } elseif (count($values) == 5) { // deprecated
  7659. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  7660. if ($values[0] != $type) {
  7661. continue;
  7662. }
  7663. if ($values[3]) {
  7664. $langs->load($values[3]);
  7665. }
  7666. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7667. $substitutionarray = array();
  7668. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7669. $label = make_substitutions($reg[1], $substitutionarray);
  7670. } else {
  7671. $label = $langs->trans($values[2]);
  7672. }
  7673. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  7674. $head[$h][1] = $label;
  7675. $head[$h][2] = str_replace('+', '', $values[1]);
  7676. $h++;
  7677. }
  7678. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  7679. if ($values[0] != $type) {
  7680. continue;
  7681. }
  7682. $tabname = str_replace('-', '', $values[1]);
  7683. foreach ($head as $key => $val) {
  7684. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  7685. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  7686. if ($head[$key][2] == $tabname && $condition) {
  7687. unset($head[$key]);
  7688. break;
  7689. }
  7690. }
  7691. }
  7692. }
  7693. }
  7694. // No need to make a return $head. Var is modified as a reference
  7695. if (!empty($hookmanager)) {
  7696. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  7697. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  7698. if ($reshook > 0) {
  7699. $head = $hookmanager->resArray;
  7700. }
  7701. $h = count($head);
  7702. }
  7703. }
  7704. /**
  7705. * Print common footer :
  7706. * conf->global->MAIN_HTML_FOOTER
  7707. * js for switch of menu hider
  7708. * js for conf->global->MAIN_GOOGLE_AN_ID
  7709. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  7710. * js for conf->logbuffer
  7711. *
  7712. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  7713. * @return void
  7714. */
  7715. function printCommonFooter($zone = 'private')
  7716. {
  7717. global $conf, $hookmanager, $user, $debugbar;
  7718. global $action;
  7719. global $micro_start_time;
  7720. if ($zone == 'private') {
  7721. print "\n".'<!-- Common footer for private page -->'."\n";
  7722. } else {
  7723. print "\n".'<!-- Common footer for public page -->'."\n";
  7724. }
  7725. // A div to store page_y POST parameter so we can read it using javascript
  7726. print "\n<!-- A div to store page_y POST parameter -->\n";
  7727. print '<div id="page_y" style="display: none;">'.(empty($_POST['page_y']) ? '' : $_POST['page_y']).'</div>'."\n";
  7728. $parameters = array();
  7729. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  7730. if (empty($reshook)) {
  7731. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  7732. print $conf->global->MAIN_HTML_FOOTER."\n";
  7733. }
  7734. print "\n";
  7735. if (!empty($conf->use_javascript_ajax)) {
  7736. print '<script>'."\n";
  7737. print 'jQuery(document).ready(function() {'."\n";
  7738. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  7739. print "\n";
  7740. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  7741. print 'jQuery("li.menuhider").click(function(event) {';
  7742. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  7743. print ' console.log("We click on .menuhider");'."\n";
  7744. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  7745. print '});'."\n";
  7746. }
  7747. // Management of focus and mandatory for fields
  7748. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  7749. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  7750. $relativepathstring = $_SERVER["PHP_SELF"];
  7751. // Clean $relativepathstring
  7752. if (constant('DOL_URL_ROOT')) {
  7753. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  7754. }
  7755. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  7756. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  7757. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  7758. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  7759. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  7760. $qualified = 0;
  7761. if ($defkey != '_noquery_') {
  7762. $tmpqueryarraytohave = explode('&', $defkey);
  7763. $foundintru = 0;
  7764. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7765. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7766. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7767. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7768. $foundintru = 1;
  7769. }
  7770. }
  7771. if (!$foundintru) {
  7772. $qualified = 1;
  7773. }
  7774. //var_dump($defkey.'-'.$qualified);
  7775. } else {
  7776. $qualified = 1;
  7777. }
  7778. if ($qualified) {
  7779. foreach ($defval as $paramkey => $paramval) {
  7780. // Set focus on field
  7781. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  7782. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  7783. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  7784. }
  7785. }
  7786. }
  7787. }
  7788. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  7789. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  7790. $qualified = 0;
  7791. if ($defkey != '_noquery_') {
  7792. $tmpqueryarraytohave = explode('&', $defkey);
  7793. $foundintru = 0;
  7794. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7795. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7796. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7797. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7798. $foundintru = 1;
  7799. }
  7800. }
  7801. if (!$foundintru) {
  7802. $qualified = 1;
  7803. }
  7804. //var_dump($defkey.'-'.$qualified);
  7805. } else {
  7806. $qualified = 1;
  7807. }
  7808. if ($qualified) {
  7809. foreach ($defval as $paramkey => $paramval) {
  7810. // Add property 'required' on input
  7811. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7812. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7813. 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";
  7814. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7815. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  7816. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  7817. }
  7818. }
  7819. }
  7820. }
  7821. }
  7822. print '});'."\n";
  7823. // End of tuning
  7824. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  7825. print "\n";
  7826. print "/* JS CODE TO ENABLE to add memory info */\n";
  7827. print 'window.console && console.log("';
  7828. if (!empty($conf->global->MEMCACHED_SERVER)) {
  7829. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  7830. }
  7831. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  7832. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  7833. $micro_end_time = microtime(true);
  7834. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  7835. }
  7836. if (function_exists("memory_get_usage")) {
  7837. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  7838. }
  7839. if (function_exists("memory_get_peak_usage")) {
  7840. print ' - Real mem peak: '.memory_get_peak_usage(true);
  7841. }
  7842. if (function_exists("zend_loader_file_encoded")) {
  7843. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  7844. }
  7845. print '");'."\n";
  7846. }
  7847. print "\n".'</script>'."\n";
  7848. // Google Analytics
  7849. // TODO Add a hook here
  7850. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  7851. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  7852. foreach ($tmptagarray as $tmptag) {
  7853. print "\n";
  7854. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  7855. print "
  7856. <!-- Global site tag (gtag.js) - Google Analytics -->
  7857. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  7858. <script>
  7859. window.dataLayer = window.dataLayer || [];
  7860. function gtag(){dataLayer.push(arguments);}
  7861. gtag('js', new Date());
  7862. gtag('config', '".trim($tmptag)."');
  7863. </script>";
  7864. print "\n";
  7865. }
  7866. }
  7867. }
  7868. // Add Xdebug coverage of code
  7869. if (defined('XDEBUGCOVERAGE')) {
  7870. print_r(xdebug_get_code_coverage());
  7871. }
  7872. // Add DebugBar data
  7873. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  7874. $debugbar['time']->stopMeasure('pageaftermaster');
  7875. print '<!-- Output debugbar data -->'."\n";
  7876. $renderer = $debugbar->getRenderer();
  7877. print $debugbar->getRenderer()->render();
  7878. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  7879. print "\n";
  7880. print "<!-- Start of log output\n";
  7881. //print '<div class="hidden">'."\n";
  7882. foreach ($conf->logbuffer as $logline) {
  7883. print $logline."<br>\n";
  7884. }
  7885. //print '</div>'."\n";
  7886. print "End of log output -->\n";
  7887. }
  7888. }
  7889. }
  7890. /**
  7891. * Split a string with 2 keys into key array.
  7892. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  7893. *
  7894. * @param string $string String to explode
  7895. * @param string $delimiter Delimiter between each couple of data
  7896. * @param string $kv Delimiter between key and value
  7897. * @return array Array of data exploded
  7898. */
  7899. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  7900. {
  7901. if ($a = explode($delimiter, $string)) {
  7902. $ka = array();
  7903. foreach ($a as $s) { // each part
  7904. if ($s) {
  7905. if ($pos = strpos($s, $kv)) { // key/value delimiter
  7906. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  7907. } else { // key delimiter not found
  7908. $ka[] = trim($s);
  7909. }
  7910. }
  7911. }
  7912. return $ka;
  7913. }
  7914. return array();
  7915. }
  7916. /**
  7917. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  7918. *
  7919. * @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.
  7920. * @return string HTML code to set focus
  7921. */
  7922. function dol_set_focus($selector)
  7923. {
  7924. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  7925. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  7926. }
  7927. /**
  7928. * Return getmypid() or random PID when function is disabled
  7929. * Some web hosts disable this php function for security reasons
  7930. * and sometimes we can't redeclare function
  7931. *
  7932. * @return int
  7933. */
  7934. function dol_getmypid()
  7935. {
  7936. if (!function_exists('getmypid')) {
  7937. return mt_rand(1, 32768);
  7938. } else {
  7939. return getmypid();
  7940. }
  7941. }
  7942. /**
  7943. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  7944. *
  7945. * @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")
  7946. * @param string $value The value to look for.
  7947. * If param $mode is 0, can contains several keywords separated with a space or |
  7948. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  7949. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  7950. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  7951. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  7952. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  7953. * @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')
  7954. * 3=value is list of string separated with comma (Example 'text 1,text 2'), 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
  7955. * @param integer $nofirstand 1=Do not output the first 'AND'
  7956. * @return string $res The statement to append to the SQL query
  7957. */
  7958. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  7959. {
  7960. global $db, $langs;
  7961. $value = trim($value);
  7962. if ($mode == 0) {
  7963. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  7964. }
  7965. if ($mode == 1) {
  7966. $value = preg_replace('/([<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do
  7967. }
  7968. $value = preg_replace('/\s*\|\s*/', '|', $value);
  7969. $crits = explode(' ', $value);
  7970. $res = '';
  7971. if (!is_array($fields)) {
  7972. $fields = array($fields);
  7973. }
  7974. $j = 0;
  7975. foreach ($crits as $crit) {
  7976. $crit = trim($crit);
  7977. $i = 0;
  7978. $i2 = 0;
  7979. $newres = '';
  7980. foreach ($fields as $field) {
  7981. if ($mode == 1) {
  7982. $operator = '=';
  7983. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  7984. $reg = array();
  7985. preg_match('/([<>=]+)/', $crit, $reg);
  7986. if ($reg[1]) {
  7987. $operator = $reg[1];
  7988. }
  7989. if ($newcrit != '') {
  7990. $numnewcrit = price2num($newcrit);
  7991. if (is_numeric($numnewcrit)) {
  7992. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric
  7993. } else {
  7994. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  7995. }
  7996. $i2++; // a criteria was added to string
  7997. }
  7998. } elseif ($mode == 2 || $mode == -2) {
  7999. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8000. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8001. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8002. if ($mode == -2) {
  8003. $newres .= ' OR '.$field.' IS NULL';
  8004. }
  8005. $i2++; // a criteria was added to string
  8006. } elseif ($mode == 3 || $mode == -3) {
  8007. $tmparray = explode(',', $crit);
  8008. if (count($tmparray)) {
  8009. $listofcodes = '';
  8010. foreach ($tmparray as $val) {
  8011. $val = trim($val);
  8012. if ($val) {
  8013. $listofcodes .= ($listofcodes ? ',' : '');
  8014. $listofcodes .= "'".$db->escape($val)."'";
  8015. }
  8016. }
  8017. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8018. $i2++; // a criteria was added to string
  8019. }
  8020. if ($mode == -3) {
  8021. $newres .= ' OR '.$field.' IS NULL';
  8022. }
  8023. } elseif ($mode == 4) {
  8024. $tmparray = explode(',', $crit);
  8025. if (count($tmparray)) {
  8026. $listofcodes = '';
  8027. foreach ($tmparray as $val) {
  8028. $val = trim($val);
  8029. if ($val) {
  8030. $newres .= ($i2 > 0 ? ' OR (' : '(').$field.' LIKE \''.$db->escape($val).',%\'';
  8031. $newres .= ' OR '.$field.' = \''.$db->escape($val).'\'';
  8032. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).'\'';
  8033. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).',%\'';
  8034. $newres .= ')';
  8035. $i2++;
  8036. }
  8037. }
  8038. }
  8039. } else // $mode=0
  8040. {
  8041. $tmpcrits = explode('|', $crit);
  8042. $i3 = 0;
  8043. foreach ($tmpcrits as $tmpcrit) {
  8044. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8045. continue;
  8046. }
  8047. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8048. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8049. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ?trim($tmpcrit) : '0');
  8050. } else {
  8051. $newres .= $field." LIKE '";
  8052. $tmpcrit = trim($tmpcrit);
  8053. $tmpcrit2 = $tmpcrit;
  8054. $tmpbefore = '%';
  8055. $tmpafter = '%';
  8056. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8057. $tmpbefore = '';
  8058. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8059. }
  8060. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8061. $tmpafter = '';
  8062. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8063. }
  8064. $newres .= $tmpbefore;
  8065. $newres .= $db->escape($tmpcrit2);
  8066. $newres .= $tmpafter;
  8067. $newres .= "'";
  8068. if ($tmpcrit2 == '') {
  8069. $newres .= ' OR '.$field." IS NULL";
  8070. }
  8071. }
  8072. $i3++;
  8073. }
  8074. $i2++; // a criteria was added to string
  8075. }
  8076. $i++;
  8077. }
  8078. if ($newres) {
  8079. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8080. }
  8081. $j++;
  8082. }
  8083. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8084. //print 'xx'.$res.'yy';
  8085. return $res;
  8086. }
  8087. /**
  8088. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8089. *
  8090. * @param Object $object Object
  8091. * @return string Url string
  8092. */
  8093. function showDirectDownloadLink($object)
  8094. {
  8095. global $conf, $langs;
  8096. $out = '';
  8097. $url = $object->getLastMainDocLink($object->element);
  8098. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8099. if ($url) {
  8100. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8101. $out .= ajax_autoselect("directdownloadlink", 0);
  8102. } else {
  8103. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8104. }
  8105. return $out;
  8106. }
  8107. /**
  8108. * Return the filename of file to get the thumbs
  8109. *
  8110. * @param string $file Original filename (full or relative path)
  8111. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8112. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8113. * @return string New file name (full or relative path, including the thumbs/)
  8114. */
  8115. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8116. {
  8117. $dirName = dirname($file);
  8118. if ($dirName == '.') {
  8119. $dirName = '';
  8120. }
  8121. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8122. $fileName = basename($fileName);
  8123. if (empty($extImgTarget)) {
  8124. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8125. }
  8126. if (empty($extImgTarget)) {
  8127. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8128. }
  8129. if (empty($extImgTarget)) {
  8130. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8131. }
  8132. if (empty($extImgTarget)) {
  8133. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8134. }
  8135. if (empty($extImgTarget)) {
  8136. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8137. }
  8138. if (empty($extImgTarget)) {
  8139. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8140. }
  8141. if (!$extImgTarget) {
  8142. return $file;
  8143. }
  8144. $subdir = '';
  8145. if ($extName) {
  8146. $subdir = 'thumbs/';
  8147. }
  8148. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8149. }
  8150. /**
  8151. * Return URL we can use for advanced preview links
  8152. *
  8153. * @param string $modulepart propal, facture, facture_fourn, ...
  8154. * @param string $relativepath Relative path of docs.
  8155. * @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)
  8156. * @param string $param More param on http links
  8157. * @return string|array Output string with href link or array with all components of link
  8158. */
  8159. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8160. {
  8161. global $conf, $langs;
  8162. if (empty($conf->use_javascript_ajax)) {
  8163. return '';
  8164. }
  8165. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8166. if ($alldata == 1) {
  8167. if ($isAllowedForPreview) {
  8168. 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));
  8169. } else {
  8170. return array();
  8171. }
  8172. }
  8173. // old behavior, return a string
  8174. if ($isAllowedForPreview) {
  8175. 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')).'\')';
  8176. } else {
  8177. return '';
  8178. }
  8179. }
  8180. /**
  8181. * Make content of an input box selected when we click into input field.
  8182. *
  8183. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8184. * @param string $addlink Add a 'link to' after
  8185. * @return string
  8186. */
  8187. function ajax_autoselect($htmlname, $addlink = '')
  8188. {
  8189. global $langs;
  8190. $out = '<script>
  8191. jQuery(document).ready(function () {
  8192. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8193. });
  8194. </script>';
  8195. if ($addlink) {
  8196. $out .= ' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  8197. }
  8198. return $out;
  8199. }
  8200. /**
  8201. * Return if a file is qualified for preview
  8202. *
  8203. * @param string $file Filename we looking for information
  8204. * @return int 1 If allowed, 0 otherwise
  8205. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8206. */
  8207. function dolIsAllowedForPreview($file)
  8208. {
  8209. global $conf;
  8210. // Check .noexe extension in filename
  8211. if (preg_match('/\.noexe$/i', $file)) {
  8212. return 0;
  8213. }
  8214. // Check mime types
  8215. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8216. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8217. $mime_preview[] = 'svg+xml';
  8218. }
  8219. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8220. //$mime_preview[]='archive';
  8221. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8222. if ($num_mime !== false) {
  8223. return 1;
  8224. }
  8225. // By default, not allowed for preview
  8226. return 0;
  8227. }
  8228. /**
  8229. * Return mime type of a file
  8230. *
  8231. * @param string $file Filename we looking for MIME type
  8232. * @param string $default Default mime type if extension not found in known list
  8233. * @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
  8234. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8235. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8236. */
  8237. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8238. {
  8239. $mime = $default;
  8240. $imgmime = 'other.png';
  8241. $famime = 'file-o';
  8242. $srclang = '';
  8243. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8244. // Plain text files
  8245. if (preg_match('/\.txt$/i', $tmpfile)) {
  8246. $mime = 'text/plain';
  8247. $imgmime = 'text.png';
  8248. $famime = 'file-text-o';
  8249. }
  8250. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8251. $mime = 'text/richtext';
  8252. $imgmime = 'text.png';
  8253. $famime = 'file-text-o';
  8254. }
  8255. if (preg_match('/\.csv$/i', $tmpfile)) {
  8256. $mime = 'text/csv';
  8257. $imgmime = 'text.png';
  8258. $famime = 'file-text-o';
  8259. }
  8260. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8261. $mime = 'text/tab-separated-values';
  8262. $imgmime = 'text.png';
  8263. $famime = 'file-text-o';
  8264. }
  8265. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8266. $mime = 'text/plain';
  8267. $imgmime = 'text.png';
  8268. $famime = 'file-text-o';
  8269. }
  8270. if (preg_match('/\.ini$/i', $tmpfile)) {
  8271. $mime = 'text/plain';
  8272. $imgmime = 'text.png';
  8273. $srclang = 'ini';
  8274. $famime = 'file-text-o';
  8275. }
  8276. if (preg_match('/\.md$/i', $tmpfile)) {
  8277. $mime = 'text/plain';
  8278. $imgmime = 'text.png';
  8279. $srclang = 'md';
  8280. $famime = 'file-text-o';
  8281. }
  8282. if (preg_match('/\.css$/i', $tmpfile)) {
  8283. $mime = 'text/css';
  8284. $imgmime = 'css.png';
  8285. $srclang = 'css';
  8286. $famime = 'file-text-o';
  8287. }
  8288. if (preg_match('/\.lang$/i', $tmpfile)) {
  8289. $mime = 'text/plain';
  8290. $imgmime = 'text.png';
  8291. $srclang = 'lang';
  8292. $famime = 'file-text-o';
  8293. }
  8294. // Certificate files
  8295. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8296. $mime = 'text/plain';
  8297. $imgmime = 'text.png';
  8298. $famime = 'file-text-o';
  8299. }
  8300. // XML based (HTML/XML/XAML)
  8301. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8302. $mime = 'text/html';
  8303. $imgmime = 'html.png';
  8304. $srclang = 'html';
  8305. $famime = 'file-text-o';
  8306. }
  8307. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8308. $mime = 'text/xml';
  8309. $imgmime = 'other.png';
  8310. $srclang = 'xml';
  8311. $famime = 'file-text-o';
  8312. }
  8313. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8314. $mime = 'text/xml';
  8315. $imgmime = 'other.png';
  8316. $srclang = 'xaml';
  8317. $famime = 'file-text-o';
  8318. }
  8319. // Languages
  8320. if (preg_match('/\.bas$/i', $tmpfile)) {
  8321. $mime = 'text/plain';
  8322. $imgmime = 'text.png';
  8323. $srclang = 'bas';
  8324. $famime = 'file-code-o';
  8325. }
  8326. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8327. $mime = 'text/plain';
  8328. $imgmime = 'text.png';
  8329. $srclang = 'c';
  8330. $famime = 'file-code-o';
  8331. }
  8332. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8333. $mime = 'text/plain';
  8334. $imgmime = 'text.png';
  8335. $srclang = 'cpp';
  8336. $famime = 'file-code-o';
  8337. }
  8338. if (preg_match('/\.cs$/i', $tmpfile)) {
  8339. $mime = 'text/plain';
  8340. $imgmime = 'text.png';
  8341. $srclang = 'cs';
  8342. $famime = 'file-code-o';
  8343. }
  8344. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8345. $mime = 'text/plain';
  8346. $imgmime = 'text.png';
  8347. $srclang = 'h';
  8348. $famime = 'file-code-o';
  8349. }
  8350. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8351. $mime = 'text/plain';
  8352. $imgmime = 'text.png';
  8353. $srclang = 'java';
  8354. $famime = 'file-code-o';
  8355. }
  8356. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8357. $mime = 'text/plain';
  8358. $imgmime = 'php.png';
  8359. $srclang = 'php';
  8360. $famime = 'file-code-o';
  8361. }
  8362. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8363. $mime = 'text/plain';
  8364. $imgmime = 'php.png';
  8365. $srclang = 'php';
  8366. $famime = 'file-code-o';
  8367. }
  8368. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8369. $mime = 'text/plain';
  8370. $imgmime = 'pl.png';
  8371. $srclang = 'perl';
  8372. $famime = 'file-code-o';
  8373. }
  8374. if (preg_match('/\.sql$/i', $tmpfile)) {
  8375. $mime = 'text/plain';
  8376. $imgmime = 'text.png';
  8377. $srclang = 'sql';
  8378. $famime = 'file-code-o';
  8379. }
  8380. if (preg_match('/\.js$/i', $tmpfile)) {
  8381. $mime = 'text/x-javascript';
  8382. $imgmime = 'jscript.png';
  8383. $srclang = 'js';
  8384. $famime = 'file-code-o';
  8385. }
  8386. // Open office
  8387. if (preg_match('/\.odp$/i', $tmpfile)) {
  8388. $mime = 'application/vnd.oasis.opendocument.presentation';
  8389. $imgmime = 'ooffice.png';
  8390. $famime = 'file-powerpoint-o';
  8391. }
  8392. if (preg_match('/\.ods$/i', $tmpfile)) {
  8393. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8394. $imgmime = 'ooffice.png';
  8395. $famime = 'file-excel-o';
  8396. }
  8397. if (preg_match('/\.odt$/i', $tmpfile)) {
  8398. $mime = 'application/vnd.oasis.opendocument.text';
  8399. $imgmime = 'ooffice.png';
  8400. $famime = 'file-word-o';
  8401. }
  8402. // MS Office
  8403. if (preg_match('/\.mdb$/i', $tmpfile)) {
  8404. $mime = 'application/msaccess';
  8405. $imgmime = 'mdb.png';
  8406. $famime = 'file-o';
  8407. }
  8408. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  8409. $mime = 'application/msword';
  8410. $imgmime = 'doc.png';
  8411. $famime = 'file-word-o';
  8412. }
  8413. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  8414. $mime = 'application/msword';
  8415. $imgmime = 'doc.png';
  8416. $famime = 'file-word-o';
  8417. }
  8418. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  8419. $mime = 'application/vnd.ms-excel';
  8420. $imgmime = 'xls.png';
  8421. $famime = 'file-excel-o';
  8422. }
  8423. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  8424. $mime = 'application/vnd.ms-excel';
  8425. $imgmime = 'xls.png';
  8426. $famime = 'file-excel-o';
  8427. }
  8428. if (preg_match('/\.xls$/i', $tmpfile)) {
  8429. $mime = 'application/vnd.ms-excel';
  8430. $imgmime = 'xls.png';
  8431. $famime = 'file-excel-o';
  8432. }
  8433. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  8434. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  8435. $imgmime = 'xls.png';
  8436. $famime = 'file-excel-o';
  8437. }
  8438. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  8439. $mime = 'application/vnd.ms-powerpoint';
  8440. $imgmime = 'ppt.png';
  8441. $famime = 'file-powerpoint-o';
  8442. }
  8443. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  8444. $mime = 'application/x-mspowerpoint';
  8445. $imgmime = 'ppt.png';
  8446. $famime = 'file-powerpoint-o';
  8447. }
  8448. // Other
  8449. if (preg_match('/\.pdf$/i', $tmpfile)) {
  8450. $mime = 'application/pdf';
  8451. $imgmime = 'pdf.png';
  8452. $famime = 'file-pdf-o';
  8453. }
  8454. // Scripts
  8455. if (preg_match('/\.bat$/i', $tmpfile)) {
  8456. $mime = 'text/x-bat';
  8457. $imgmime = 'script.png';
  8458. $srclang = 'dos';
  8459. $famime = 'file-code-o';
  8460. }
  8461. if (preg_match('/\.sh$/i', $tmpfile)) {
  8462. $mime = 'text/x-sh';
  8463. $imgmime = 'script.png';
  8464. $srclang = 'bash';
  8465. $famime = 'file-code-o';
  8466. }
  8467. if (preg_match('/\.ksh$/i', $tmpfile)) {
  8468. $mime = 'text/x-ksh';
  8469. $imgmime = 'script.png';
  8470. $srclang = 'bash';
  8471. $famime = 'file-code-o';
  8472. }
  8473. if (preg_match('/\.bash$/i', $tmpfile)) {
  8474. $mime = 'text/x-bash';
  8475. $imgmime = 'script.png';
  8476. $srclang = 'bash';
  8477. $famime = 'file-code-o';
  8478. }
  8479. // Images
  8480. if (preg_match('/\.ico$/i', $tmpfile)) {
  8481. $mime = 'image/x-icon';
  8482. $imgmime = 'image.png';
  8483. $famime = 'file-image-o';
  8484. }
  8485. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  8486. $mime = 'image/jpeg';
  8487. $imgmime = 'image.png';
  8488. $famime = 'file-image-o';
  8489. }
  8490. if (preg_match('/\.png$/i', $tmpfile)) {
  8491. $mime = 'image/png';
  8492. $imgmime = 'image.png';
  8493. $famime = 'file-image-o';
  8494. }
  8495. if (preg_match('/\.gif$/i', $tmpfile)) {
  8496. $mime = 'image/gif';
  8497. $imgmime = 'image.png';
  8498. $famime = 'file-image-o';
  8499. }
  8500. if (preg_match('/\.bmp$/i', $tmpfile)) {
  8501. $mime = 'image/bmp';
  8502. $imgmime = 'image.png';
  8503. $famime = 'file-image-o';
  8504. }
  8505. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  8506. $mime = 'image/tiff';
  8507. $imgmime = 'image.png';
  8508. $famime = 'file-image-o';
  8509. }
  8510. if (preg_match('/\.svg$/i', $tmpfile)) {
  8511. $mime = 'image/svg+xml';
  8512. $imgmime = 'image.png';
  8513. $famime = 'file-image-o';
  8514. }
  8515. if (preg_match('/\.webp$/i', $tmpfile)) {
  8516. $mime = 'image/webp';
  8517. $imgmime = 'image.png';
  8518. $famime = 'file-image-o';
  8519. }
  8520. // Calendar
  8521. if (preg_match('/\.vcs$/i', $tmpfile)) {
  8522. $mime = 'text/calendar';
  8523. $imgmime = 'other.png';
  8524. $famime = 'file-text-o';
  8525. }
  8526. if (preg_match('/\.ics$/i', $tmpfile)) {
  8527. $mime = 'text/calendar';
  8528. $imgmime = 'other.png';
  8529. $famime = 'file-text-o';
  8530. }
  8531. // Other
  8532. if (preg_match('/\.torrent$/i', $tmpfile)) {
  8533. $mime = 'application/x-bittorrent';
  8534. $imgmime = 'other.png';
  8535. $famime = 'file-o';
  8536. }
  8537. // Audio
  8538. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  8539. $mime = 'audio';
  8540. $imgmime = 'audio.png';
  8541. $famime = 'file-audio-o';
  8542. }
  8543. // Video
  8544. if (preg_match('/\.mp4$/i', $tmpfile)) {
  8545. $mime = 'video/mp4';
  8546. $imgmime = 'video.png';
  8547. $famime = 'file-video-o';
  8548. }
  8549. if (preg_match('/\.ogv$/i', $tmpfile)) {
  8550. $mime = 'video/ogg';
  8551. $imgmime = 'video.png';
  8552. $famime = 'file-video-o';
  8553. }
  8554. if (preg_match('/\.webm$/i', $tmpfile)) {
  8555. $mime = 'video/webm';
  8556. $imgmime = 'video.png';
  8557. $famime = 'file-video-o';
  8558. }
  8559. if (preg_match('/\.avi$/i', $tmpfile)) {
  8560. $mime = 'video/x-msvideo';
  8561. $imgmime = 'video.png';
  8562. $famime = 'file-video-o';
  8563. }
  8564. if (preg_match('/\.divx$/i', $tmpfile)) {
  8565. $mime = 'video/divx';
  8566. $imgmime = 'video.png';
  8567. $famime = 'file-video-o';
  8568. }
  8569. if (preg_match('/\.xvid$/i', $tmpfile)) {
  8570. $mime = 'video/xvid';
  8571. $imgmime = 'video.png';
  8572. $famime = 'file-video-o';
  8573. }
  8574. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  8575. $mime = 'video';
  8576. $imgmime = 'video.png';
  8577. $famime = 'file-video-o';
  8578. }
  8579. // Archive
  8580. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  8581. $mime = 'archive';
  8582. $imgmime = 'archive.png';
  8583. $famime = 'file-archive-o';
  8584. } // application/xxx where zzz is zip, ...
  8585. // Exe
  8586. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  8587. $mime = 'application/octet-stream';
  8588. $imgmime = 'other.png';
  8589. $famime = 'file-o';
  8590. }
  8591. // Lib
  8592. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  8593. $mime = 'library';
  8594. $imgmime = 'library.png';
  8595. $famime = 'file-o';
  8596. }
  8597. // Err
  8598. if (preg_match('/\.err$/i', $tmpfile)) {
  8599. $mime = 'error';
  8600. $imgmime = 'error.png';
  8601. $famime = 'file-text-o';
  8602. }
  8603. // Return string
  8604. if ($mode == 1) {
  8605. $tmp = explode('/', $mime);
  8606. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  8607. }
  8608. if ($mode == 2) {
  8609. return $imgmime;
  8610. }
  8611. if ($mode == 3) {
  8612. return $srclang;
  8613. }
  8614. if ($mode == 4) {
  8615. return $famime;
  8616. }
  8617. return $mime;
  8618. }
  8619. /**
  8620. * Return value from dictionary
  8621. *
  8622. * @param string $tablename name of dictionary
  8623. * @param string $field the value to return
  8624. * @param int $id id of line
  8625. * @param bool $checkentity add filter on entity
  8626. * @param string $rowidfield name of the column rowid
  8627. * @return string
  8628. */
  8629. function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  8630. {
  8631. global $dictvalues, $db, $langs;
  8632. if (!isset($dictvalues[$tablename])) {
  8633. $dictvalues[$tablename] = array();
  8634. $sql = 'SELECT * FROM '.$tablename.' WHERE 1 = 1'; // Here select * is allowed as it is generic code and we don't have list of fields
  8635. if ($checkentity) {
  8636. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  8637. }
  8638. $resql = $db->query($sql);
  8639. if ($resql) {
  8640. while ($obj = $db->fetch_object($resql)) {
  8641. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  8642. }
  8643. } else {
  8644. dol_print_error($db);
  8645. }
  8646. }
  8647. if (!empty($dictvalues[$tablename][$id])) {
  8648. return $dictvalues[$tablename][$id]->{$field}; // Found
  8649. } else // Not found
  8650. {
  8651. if ($id > 0) {
  8652. return $id;
  8653. }
  8654. return '';
  8655. }
  8656. }
  8657. /**
  8658. * Return true if the color is light
  8659. *
  8660. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  8661. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  8662. */
  8663. function colorIsLight($stringcolor)
  8664. {
  8665. $stringcolor = str_replace('#', '', $stringcolor);
  8666. $res = -1;
  8667. if (!empty($stringcolor)) {
  8668. $res = 0;
  8669. $tmp = explode(',', $stringcolor);
  8670. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  8671. $r = $tmp[0];
  8672. $g = $tmp[1];
  8673. $b = $tmp[2];
  8674. } else {
  8675. $hexr = $stringcolor[0].$stringcolor[1];
  8676. $hexg = $stringcolor[2].$stringcolor[3];
  8677. $hexb = $stringcolor[4].$stringcolor[5];
  8678. $r = hexdec($hexr);
  8679. $g = hexdec($hexg);
  8680. $b = hexdec($hexb);
  8681. }
  8682. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  8683. if ($bright > 0.6) {
  8684. $res = 1;
  8685. }
  8686. }
  8687. return $res;
  8688. }
  8689. /**
  8690. * Function to test if an entry is enabled or not
  8691. *
  8692. * @param string $type_user 0=We test for internal user, 1=We test for external user
  8693. * @param array $menuentry Array for feature entry to test
  8694. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  8695. * @return int 0=Hide, 1=Show, 2=Show gray
  8696. */
  8697. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  8698. {
  8699. global $conf;
  8700. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  8701. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  8702. if (empty($menuentry['enabled'])) {
  8703. return 0; // Entry disabled by condition
  8704. }
  8705. if ($type_user && $menuentry['module']) {
  8706. $tmploops = explode('|', $menuentry['module']);
  8707. $found = 0;
  8708. foreach ($tmploops as $tmploop) {
  8709. if (in_array($tmploop, $listofmodulesforexternal)) {
  8710. $found++;
  8711. break;
  8712. }
  8713. }
  8714. if (!$found) {
  8715. return 0; // Entry is for menus all excluded to external users
  8716. }
  8717. }
  8718. if (!$menuentry['perms'] && $type_user) {
  8719. return 0; // No permissions and user is external
  8720. }
  8721. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  8722. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  8723. }
  8724. if (!$menuentry['perms']) {
  8725. return 2; // No permissions and user is external
  8726. }
  8727. return 1;
  8728. }
  8729. /**
  8730. * Round to next multiple.
  8731. *
  8732. * @param double $n Number to round up
  8733. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  8734. * @return integer Value rounded.
  8735. */
  8736. function roundUpToNextMultiple($n, $x = 5)
  8737. {
  8738. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  8739. }
  8740. /**
  8741. * Function dolGetBadge
  8742. *
  8743. * @param string $label label of badge no html : use in alt attribute for accessibility
  8744. * @param string $html optional : label of badge with html
  8745. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  8746. * @param string $mode default '' , 'pill', 'dot'
  8747. * @param string $url the url for link
  8748. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  8749. * @return string Html badge
  8750. */
  8751. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  8752. {
  8753. $attr = array(
  8754. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  8755. );
  8756. if (empty($html)) {
  8757. $html = $label;
  8758. }
  8759. if (!empty($url)) {
  8760. $attr['href'] = $url;
  8761. }
  8762. if ($mode === 'dot') {
  8763. $attr['class'] .= ' classfortooltip';
  8764. $attr['title'] = $html;
  8765. $attr['aria-label'] = $label;
  8766. $html = '';
  8767. }
  8768. // Override attr
  8769. if (!empty($params['attr']) && is_array($params['attr'])) {
  8770. foreach ($params['attr'] as $key => $value) {
  8771. if ($key == 'class') {
  8772. $attr['class'] .= ' '.$value;
  8773. } elseif ($key == 'classOverride') {
  8774. $attr['class'] = $value;
  8775. } else {
  8776. $attr[$key] = $value;
  8777. }
  8778. }
  8779. }
  8780. // TODO: add hook
  8781. // escape all attribute
  8782. $attr = array_map('dol_escape_htmltag', $attr);
  8783. $TCompiledAttr = array();
  8784. foreach ($attr as $key => $value) {
  8785. $TCompiledAttr[] = $key.'="'.$value.'"';
  8786. }
  8787. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  8788. $tag = !empty($url) ? 'a' : 'span';
  8789. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  8790. }
  8791. /**
  8792. * Output the badge of a status.
  8793. *
  8794. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  8795. * @param string $statusLabelShort Short label of badge no html
  8796. * @param string $html Optional : label of badge with html
  8797. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  8798. * @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
  8799. * @param string $url The url for link
  8800. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  8801. * @return string Html status string
  8802. */
  8803. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  8804. {
  8805. global $conf;
  8806. $return = '';
  8807. $dolGetBadgeParams = array();
  8808. if (!empty($params['badgeParams'])) {
  8809. $dolGetBadgeParams = $params['badgeParams'];
  8810. }
  8811. // TODO : add a hook
  8812. if ($displayMode == 0) {
  8813. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  8814. } elseif ($displayMode == 1) {
  8815. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  8816. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  8817. // Use status with images (for backward compatibility)
  8818. $return = '';
  8819. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  8820. $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>' : '');
  8821. // For small screen, we always use the short label instead of long label.
  8822. if (!empty($conf->dol_optimize_smallscreen)) {
  8823. if ($displayMode == 0) {
  8824. $displayMode = 1;
  8825. } elseif ($displayMode == 4) {
  8826. $displayMode = 2;
  8827. } elseif ($displayMode == 6) {
  8828. $displayMode = 5;
  8829. }
  8830. }
  8831. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  8832. $statusImg = array(
  8833. 'status0' => 'statut0',
  8834. 'status1' => 'statut1',
  8835. 'status2' => 'statut2',
  8836. 'status3' => 'statut3',
  8837. 'status4' => 'statut4',
  8838. 'status5' => 'statut5',
  8839. 'status6' => 'statut6',
  8840. 'status7' => 'statut7',
  8841. 'status8' => 'statut8',
  8842. 'status9' => 'statut9'
  8843. );
  8844. if (!empty($statusImg[$statusType])) {
  8845. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  8846. } else {
  8847. $htmlImg = img_picto($statusLabel, $statusType);
  8848. }
  8849. if ($displayMode === 2) {
  8850. $return = $htmlImg.' '.$htmlLabelShort;
  8851. } elseif ($displayMode === 3) {
  8852. $return = $htmlImg;
  8853. } elseif ($displayMode === 4) {
  8854. $return = $htmlImg.' '.$htmlLabel;
  8855. } elseif ($displayMode === 5) {
  8856. $return = $htmlLabelShort.' '.$htmlImg;
  8857. } else { // $displayMode >= 6
  8858. $return = $htmlLabel.' '.$htmlImg;
  8859. }
  8860. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  8861. // Use new badge
  8862. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  8863. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  8864. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  8865. if ($displayMode == 3) {
  8866. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  8867. } elseif ($displayMode === 5) {
  8868. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  8869. } else {
  8870. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  8871. }
  8872. }
  8873. return $return;
  8874. }
  8875. /**
  8876. * Function dolGetButtonAction
  8877. *
  8878. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  8879. * @param string $html optional : content with html
  8880. * @param string $actionType default, delete, danger
  8881. * @param string $url the url for link
  8882. * @param string $id attribute id of button
  8883. * @param int $userRight user action right
  8884. * @param array $params various params for future : recommended rather than adding more function arguments
  8885. * @return string html button
  8886. */
  8887. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  8888. {
  8889. $class = 'butAction';
  8890. if ($actionType == 'danger' || $actionType == 'delete') {
  8891. $class = 'butActionDelete';
  8892. if (strpos($url, 'token=') === false) $url .= '&token='.newToken();
  8893. }
  8894. $attr = array(
  8895. 'class' => $class,
  8896. 'href' => empty($url) ? '' : $url,
  8897. 'title' => $label
  8898. );
  8899. if (empty($html)) {
  8900. $html = $label;
  8901. } else {
  8902. $attr['aria-label'] = $label;
  8903. }
  8904. if (empty($userRight)) {
  8905. $attr['class'] = 'butActionRefused';
  8906. $attr['href'] = '';
  8907. }
  8908. if (!empty($id)) {
  8909. $attr['id'] = $id;
  8910. }
  8911. // Override attr
  8912. if (!empty($params['attr']) && is_array($params['attr'])) {
  8913. foreach ($params['attr'] as $key => $value) {
  8914. if ($key == 'class') {
  8915. $attr['class'] .= ' '.$value;
  8916. } elseif ($key == 'classOverride') {
  8917. $attr['class'] = $value;
  8918. } else {
  8919. $attr[$key] = $value;
  8920. }
  8921. }
  8922. }
  8923. if (isset($attr['href']) && empty($attr['href'])) {
  8924. unset($attr['href']);
  8925. }
  8926. // TODO : add a hook
  8927. // escape all attribute
  8928. $attr = array_map('dol_escape_htmltag', $attr);
  8929. $TCompiledAttr = array();
  8930. foreach ($attr as $key => $value) {
  8931. $TCompiledAttr[] = $key.'="'.$value.'"';
  8932. }
  8933. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  8934. $tag = !empty($attr['href']) ? 'a' : 'span';
  8935. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  8936. }
  8937. /**
  8938. * Add space between dolGetButtonTitle
  8939. *
  8940. * @param string $moreClass more css class label
  8941. * @return string html of title separator
  8942. */
  8943. function dolGetButtonTitleSeparator($moreClass = "")
  8944. {
  8945. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  8946. }
  8947. /**
  8948. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  8949. *
  8950. * @param string $label label of button
  8951. * @param string $helpText optional : content for help tooltip
  8952. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  8953. * @param string $url the url for link
  8954. * @param string $id attribute id of button
  8955. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  8956. * @param array $params various params for future : recommended rather than adding more function arguments
  8957. * @return string html button
  8958. */
  8959. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  8960. {
  8961. global $langs, $conf, $user;
  8962. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  8963. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  8964. return '';
  8965. }
  8966. $class = 'btnTitle';
  8967. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) {
  8968. $class .= ' btnTitlePlus';
  8969. }
  8970. $useclassfortooltip = 1;
  8971. if (!empty($params['morecss'])) {
  8972. $class .= ' '.$params['morecss'];
  8973. }
  8974. $attr = array(
  8975. 'class' => $class,
  8976. 'href' => empty($url) ? '' : $url
  8977. );
  8978. if (!empty($helpText)) {
  8979. $attr['title'] = dol_escape_htmltag($helpText);
  8980. } elseif (empty($attr['title']) && $label) {
  8981. $attr['title'] = $label;
  8982. $useclassfortooltip = 0;
  8983. }
  8984. if ($status == 2) {
  8985. $attr['class'] .= ' btnTitleSelected';
  8986. } elseif ($status <= 0) {
  8987. $attr['class'] .= ' refused';
  8988. $attr['href'] = '';
  8989. if ($status == -1) { // disable
  8990. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  8991. } elseif ($status == 0) { // Not enough permissions
  8992. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  8993. }
  8994. }
  8995. if (!empty($attr['title']) && $useclassfortooltip) {
  8996. $attr['class'] .= ' classfortooltip';
  8997. }
  8998. if (!empty($id)) {
  8999. $attr['id'] = $id;
  9000. }
  9001. // Override attr
  9002. if (!empty($params['attr']) && is_array($params['attr'])) {
  9003. foreach ($params['attr'] as $key => $value) {
  9004. if ($key == 'class') {
  9005. $attr['class'] .= ' '.$value;
  9006. } elseif ($key == 'classOverride') {
  9007. $attr['class'] = $value;
  9008. } else {
  9009. $attr[$key] = $value;
  9010. }
  9011. }
  9012. }
  9013. if (isset($attr['href']) && empty($attr['href'])) {
  9014. unset($attr['href']);
  9015. }
  9016. // TODO : add a hook
  9017. // escape all attribute
  9018. $attr = array_map('dol_escape_htmltag', $attr);
  9019. $TCompiledAttr = array();
  9020. foreach ($attr as $key => $value) {
  9021. $TCompiledAttr[] = $key.'="'.$value.'"';
  9022. }
  9023. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9024. $tag = (empty($attr['href']) ? 'span' : 'a');
  9025. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9026. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9027. if (!empty($params['forcenohideoftext'])) {
  9028. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9029. }
  9030. $button .= '</'.$tag.'>';
  9031. return $button;
  9032. }
  9033. /**
  9034. * Get an array with properties of an element.
  9035. * Called by fetchObjectByElement.
  9036. *
  9037. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9038. * @return array (module, classpath, element, subelement, classfile, classname)
  9039. */
  9040. function getElementProperties($element_type)
  9041. {
  9042. $regs = array();
  9043. $classfile = $classname = $classpath = '';
  9044. // Parse element/subelement (ex: project_task)
  9045. $module = $element_type;
  9046. $element = $element_type;
  9047. $subelement = $element_type;
  9048. // If we ask an resource form external module (instead of default path)
  9049. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9050. $element = $subelement = $regs[1];
  9051. $module = $regs[2];
  9052. }
  9053. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9054. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9055. $module = $element = $regs[1];
  9056. $subelement = $regs[2];
  9057. }
  9058. // For compat
  9059. if ($element_type == "action") {
  9060. $classpath = 'comm/action/class';
  9061. $subelement = 'Actioncomm';
  9062. $module = 'agenda';
  9063. }
  9064. // To work with non standard path
  9065. if ($element_type == 'facture' || $element_type == 'invoice') {
  9066. $classpath = 'compta/facture/class';
  9067. $module = 'facture';
  9068. $subelement = 'facture';
  9069. }
  9070. if ($element_type == 'commande' || $element_type == 'order') {
  9071. $classpath = 'commande/class';
  9072. $module = 'commande';
  9073. $subelement = 'commande';
  9074. }
  9075. if ($element_type == 'propal') {
  9076. $classpath = 'comm/propal/class';
  9077. }
  9078. if ($element_type == 'supplier_proposal') {
  9079. $classpath = 'supplier_proposal/class';
  9080. }
  9081. if ($element_type == 'shipping') {
  9082. $classpath = 'expedition/class';
  9083. $subelement = 'expedition';
  9084. $module = 'expedition_bon';
  9085. }
  9086. if ($element_type == 'delivery') {
  9087. $classpath = 'delivery/class';
  9088. $subelement = 'delivery';
  9089. $module = 'delivery_note';
  9090. }
  9091. if ($element_type == 'contract') {
  9092. $classpath = 'contrat/class';
  9093. $module = 'contrat';
  9094. $subelement = 'contrat';
  9095. }
  9096. if ($element_type == 'member') {
  9097. $classpath = 'adherents/class';
  9098. $module = 'adherent';
  9099. $subelement = 'adherent';
  9100. }
  9101. if ($element_type == 'cabinetmed_cons') {
  9102. $classpath = 'cabinetmed/class';
  9103. $module = 'cabinetmed';
  9104. $subelement = 'cabinetmedcons';
  9105. }
  9106. if ($element_type == 'fichinter') {
  9107. $classpath = 'fichinter/class';
  9108. $module = 'ficheinter';
  9109. $subelement = 'fichinter';
  9110. }
  9111. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9112. $classpath = 'resource/class';
  9113. $module = 'resource';
  9114. $subelement = 'dolresource';
  9115. }
  9116. if ($element_type == 'propaldet') {
  9117. $classpath = 'comm/propal/class';
  9118. $module = 'propal';
  9119. $subelement = 'propaleligne';
  9120. }
  9121. if ($element_type == 'order_supplier') {
  9122. $classpath = 'fourn/class';
  9123. $module = 'fournisseur';
  9124. $subelement = 'commandefournisseur';
  9125. $classfile = 'fournisseur.commande';
  9126. }
  9127. if ($element_type == 'invoice_supplier') {
  9128. $classpath = 'fourn/class';
  9129. $module = 'fournisseur';
  9130. $subelement = 'facturefournisseur';
  9131. $classfile = 'fournisseur.facture';
  9132. }
  9133. if ($element_type == "service") {
  9134. $classpath = 'product/class';
  9135. $subelement = 'product';
  9136. }
  9137. if (empty($classfile)) {
  9138. $classfile = strtolower($subelement);
  9139. }
  9140. if (empty($classname)) {
  9141. $classname = ucfirst($subelement);
  9142. }
  9143. if (empty($classpath)) {
  9144. $classpath = $module.'/class';
  9145. }
  9146. $element_properties = array(
  9147. 'module' => $module,
  9148. 'classpath' => $classpath,
  9149. 'element' => $element,
  9150. 'subelement' => $subelement,
  9151. 'classfile' => $classfile,
  9152. 'classname' => $classname
  9153. );
  9154. return $element_properties;
  9155. }
  9156. /**
  9157. * Fetch an object from its id and element_type
  9158. * Inclusion of classes is automatic
  9159. *
  9160. * @param int $element_id Element id
  9161. * @param string $element_type Element type
  9162. * @param string $element_ref Element ref (Use this or element_id but not both)
  9163. * @return int|object object || 0 || -1 if error
  9164. */
  9165. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9166. {
  9167. global $conf, $db;
  9168. $element_prop = getElementProperties($element_type);
  9169. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9170. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9171. $objecttmp = new $element_prop['classname']($db);
  9172. $ret = $objecttmp->fetch($element_id, $element_ref);
  9173. if ($ret >= 0) {
  9174. return $objecttmp;
  9175. }
  9176. }
  9177. return 0;
  9178. }
  9179. /**
  9180. * Return if a file can contains executable content
  9181. *
  9182. * @param string $filename File name to test
  9183. * @return boolean True if yes, False if no
  9184. */
  9185. function isAFileWithExecutableContent($filename)
  9186. {
  9187. 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)) {
  9188. return true;
  9189. }
  9190. return false;
  9191. }
  9192. /**
  9193. * Return the value of token currently saved into session with name 'newtoken'.
  9194. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9195. *
  9196. * @return string
  9197. */
  9198. function newToken()
  9199. {
  9200. return $_SESSION['newtoken'];
  9201. }
  9202. /**
  9203. * Return the value of token currently saved into session with name 'token'.
  9204. *
  9205. * @return string
  9206. */
  9207. function currentToken()
  9208. {
  9209. return $_SESSION['token'];
  9210. }
  9211. /**
  9212. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9213. *
  9214. * @param string $header The first left header of the table (automatic translated)
  9215. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9216. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9217. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9218. * @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"
  9219. * @return void
  9220. *
  9221. * @see finishSimpleTable()
  9222. */
  9223. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9224. {
  9225. global $langs;
  9226. print '<div class="div-table-responsive-no-min">';
  9227. print '<table class="noborder centpercent">';
  9228. print '<tr class="liste_titre">';
  9229. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9230. print $langs->trans($header);
  9231. // extra space between the first header and the number
  9232. if ($number > -1) {
  9233. print ' ';
  9234. }
  9235. if (!empty($link)) {
  9236. if (!empty($arguments)) {
  9237. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9238. } else {
  9239. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9240. }
  9241. }
  9242. if ($number > -1) {
  9243. print '<span class="badge">'.$number.'</span>';
  9244. }
  9245. if (!empty($link)) {
  9246. print '</a>';
  9247. }
  9248. print '</th>';
  9249. if ($number < 0 && !empty($link)) {
  9250. print '<th class="right">';
  9251. if (!empty($arguments)) {
  9252. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9253. } else {
  9254. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9255. }
  9256. print $langs->trans("FullList");
  9257. print '</a>';
  9258. print '</th>';
  9259. }
  9260. print '</tr>';
  9261. }
  9262. /**
  9263. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9264. *
  9265. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9266. * @return void
  9267. *
  9268. * @see startSimpleTable()
  9269. */
  9270. function finishSimpleTable($addLineBreak = false)
  9271. {
  9272. print '</table>';
  9273. print '</div>';
  9274. if ($addLineBreak) {
  9275. print '<br>';
  9276. }
  9277. }
  9278. /**
  9279. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9280. *
  9281. * @param integer $tableColumnCount The complete count columns of the table
  9282. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9283. * @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)
  9284. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9285. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9286. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9287. * @return void
  9288. */
  9289. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9290. {
  9291. global $langs;
  9292. if ($num === 0) {
  9293. print '<tr class="oddeven">';
  9294. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9295. print '</tr>';
  9296. return;
  9297. }
  9298. if ($nbofloop === 0) {
  9299. // don't show a summary line
  9300. return;
  9301. }
  9302. if ($num === 0) {
  9303. $colspan = $tableColumnCount;
  9304. } elseif ($num > $nbofloop) {
  9305. $colspan = $tableColumnCount;
  9306. } else {
  9307. $colspan = $tableColumnCount - 1;
  9308. }
  9309. if ($extraRightColumn) {
  9310. $colspan--;
  9311. }
  9312. print '<tr class="liste_total">';
  9313. if ($nbofloop > 0 && $num > $nbofloop) {
  9314. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9315. } else {
  9316. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  9317. print '<td class="right" width="100">'.price($total).'</td>';
  9318. }
  9319. if ($extraRightColumn) {
  9320. print '<td></td>';
  9321. }
  9322. print '</tr>';
  9323. }
  9324. /**
  9325. * Return a file on output using a low memory. It can return very large files with no need of memory.
  9326. * WARNING: This close output buffers.
  9327. *
  9328. * @param string $fullpath_original_file_osencoded Full path of file to return.
  9329. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  9330. * @return void
  9331. */
  9332. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  9333. {
  9334. global $conf;
  9335. if ($method == -1) {
  9336. $method = 0;
  9337. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  9338. $method = 1;
  9339. }
  9340. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  9341. $method = 2;
  9342. }
  9343. }
  9344. // Be sure we don't have output buffering enabled to have readfile working correctly
  9345. while (ob_get_level()) {
  9346. ob_end_flush();
  9347. }
  9348. // Solution 0
  9349. if ($method == 0) {
  9350. readfile($fullpath_original_file_osencoded);
  9351. } elseif ($method == 1) {
  9352. // Solution 1
  9353. $handle = fopen($fullpath_original_file_osencoded, "rb");
  9354. while (!feof($handle)) {
  9355. print fread($handle, 8192);
  9356. }
  9357. fclose($handle);
  9358. } elseif ($method == 2) {
  9359. // Solution 2
  9360. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  9361. $handle2 = fopen("php://output", "wb");
  9362. stream_copy_to_stream($handle1, $handle2);
  9363. fclose($handle1);
  9364. fclose($handle2);
  9365. }
  9366. }
  9367. /**
  9368. * Create a button to copy $valuetocopy in the clipboard.
  9369. * Code that handle the click is inside lib_foot.jsp.php
  9370. *
  9371. * @param string $valuetocopy The value to print
  9372. * @param int $showonlyonhover Show the copy-paste button only on hover
  9373. * @param string $texttoshow Replace the value to show with this text
  9374. * @return string The string to print for the button
  9375. */
  9376. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  9377. {
  9378. /*
  9379. global $conf;
  9380. if (!empty($conf->dol_no_mouse_hover)) {
  9381. $showonlyonhover = 0;
  9382. }*/
  9383. if ($texttoshow) {
  9384. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><span class="clipboardCPValue hidewithsize">'.$valuetocopy.'</span><span class="clipboardCPValueToPrint">'.$texttoshow.'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText opacitymedium"></span></span>';
  9385. } else {
  9386. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><span class="clipboardCPValue">'.$valuetocopy.'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText opacitymedium"></span></span>';
  9387. }
  9388. return $result;
  9389. }
  9390. /**
  9391. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  9392. *
  9393. * @param string $stringtodecode String to decode (json or serialize coded)
  9394. */
  9395. function jsonOrUnserialize($stringtodecode)
  9396. {
  9397. $result = json_decode($stringtodecode);
  9398. if ($result === null) {
  9399. $result = unserialize($stringtodecode);
  9400. }
  9401. return $result;
  9402. }