functions.lib.php 540 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2022 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019-2023 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
  21. * Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
  22. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  23. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. * or see https://www.gnu.org/
  38. */
  39. /**
  40. * \file htdocs/core/lib/functions.lib.php
  41. * \brief A set of functions for Dolibarr
  42. * This file contains all frequently used functions.
  43. */
  44. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  45. // Function for better PHP x compatibility
  46. if (!function_exists('utf8_encode')) {
  47. /**
  48. * Implement utf8_encode for PHP that does not support it.
  49. *
  50. * @param mixed $elements PHP Object to json encode
  51. * @return string Json encoded string
  52. */
  53. function utf8_encode($elements)
  54. {
  55. return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
  56. }
  57. }
  58. if (!function_exists('utf8_decode')) {
  59. /**
  60. * Implement utf8_decode for PHP that does not support it.
  61. *
  62. * @param mixed $elements PHP Object to json encode
  63. * @return string Json encoded string
  64. */
  65. function utf8_decode($elements)
  66. {
  67. return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
  68. }
  69. }
  70. if (!function_exists('str_starts_with')) {
  71. /**
  72. * str_starts_with
  73. *
  74. * @param string $haystack haystack
  75. * @param string $needle needle
  76. * @return boolean
  77. */
  78. function str_starts_with($haystack, $needle)
  79. {
  80. return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
  81. }
  82. }
  83. if (!function_exists('str_ends_with')) {
  84. /**
  85. * str_ends_with
  86. *
  87. * @param string $haystack haystack
  88. * @param string $needle needle
  89. * @return boolean
  90. */
  91. function str_ends_with($haystack, $needle)
  92. {
  93. return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
  94. }
  95. }
  96. if (!function_exists('str_contains')) {
  97. /**
  98. * str_contains
  99. *
  100. * @param string $haystack haystack
  101. * @param string $needle needle
  102. * @return boolean
  103. */
  104. function str_contains($haystack, $needle)
  105. {
  106. return $needle !== '' && mb_strpos($haystack, $needle) !== false;
  107. }
  108. }
  109. /**
  110. * Return the full path of the directory where a module (or an object of a module) stores its files. Path may depends on the entity if a multicompany module is enabled.
  111. *
  112. * @param CommonObject $object Dolibarr common object
  113. * @param string $module Override object element, for example to use 'mycompany' instead of 'societe'
  114. * @return string|void The path of the relative directory of the module
  115. * @since Dolibarr V18
  116. */
  117. function getMultidirOutput($object, $module = '')
  118. {
  119. global $conf;
  120. if (!is_object($object) && empty($module)) {
  121. return null;
  122. }
  123. if (empty($module) && !empty($object->element)) {
  124. $module = $object->element;
  125. }
  126. // Special case for backward compatibility
  127. if ($module == 'fichinter') {
  128. $module = 'ficheinter';
  129. }
  130. if (isset($conf->$module)) {
  131. return $conf->$module->multidir_output[(!empty($object->entity) ? $object->entity : $conf->entity)];
  132. } else {
  133. return 'error-diroutput-not-defined-ffor-this-object='.$module;
  134. }
  135. }
  136. /**
  137. * Return dolibarr global constant string value
  138. *
  139. * @param string $key key to return value, return '' if not set
  140. * @param string $default value to return
  141. * @return string
  142. */
  143. function getDolGlobalString($key, $default = '')
  144. {
  145. global $conf;
  146. // return $conf->global->$key ?? $default;
  147. return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
  148. }
  149. /**
  150. * Return a Dolibarr global constant int value.
  151. * The constants $conf->global->xxx are loaded by the script master.inc.php included at begin of any PHP page.
  152. *
  153. * @param string $key key to return value, return 0 if not set
  154. * @param int $default value to return
  155. * @return int
  156. */
  157. function getDolGlobalInt($key, $default = 0)
  158. {
  159. global $conf;
  160. // return $conf->global->$key ?? $default;
  161. return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
  162. }
  163. /**
  164. * Return Dolibarr user constant string value
  165. *
  166. * @param string $key key to return value, return '' if not set
  167. * @param string $default value to return
  168. * @param User $tmpuser To get another user than current user
  169. * @return string
  170. */
  171. function getDolUserString($key, $default = '', $tmpuser = null)
  172. {
  173. if (empty($tmpuser)) {
  174. global $user;
  175. $tmpuser = $user;
  176. }
  177. // return $conf->global->$key ?? $default;
  178. return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  179. }
  180. /**
  181. * Return Dolibarr user constant int value
  182. *
  183. * @param string $key key to return value, return 0 if not set
  184. * @param int $default value to return
  185. * @param User $tmpuser To get another user than current user
  186. * @return int
  187. */
  188. function getDolUserInt($key, $default = 0, $tmpuser = null)
  189. {
  190. if (empty($tmpuser)) {
  191. global $user;
  192. $tmpuser = $user;
  193. }
  194. // return $conf->global->$key ?? $default;
  195. return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  196. }
  197. /**
  198. * Is Dolibarr module enabled
  199. *
  200. * @param string $module Module name to check
  201. * @return boolean True if module is enabled
  202. */
  203. function isModEnabled($module)
  204. {
  205. global $conf;
  206. // Fix special cases
  207. $arrayconv = array(
  208. 'bank' => 'banque',
  209. 'category' => 'categorie',
  210. 'contract' => 'contrat',
  211. 'project' => 'projet'
  212. );
  213. if (empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) {
  214. $arrayconv['supplier_order'] = 'fournisseur';
  215. $arrayconv['supplier_invoice'] = 'fournisseur';
  216. }
  217. if (!empty($arrayconv[$module])) {
  218. $module = $arrayconv[$module];
  219. }
  220. return !empty($conf->modules[$module]);
  221. //return !empty($conf->$module->enabled);
  222. }
  223. /**
  224. * Return a DoliDB instance (database handler).
  225. *
  226. * @param string $type Type of database (mysql, pgsql...)
  227. * @param string $host Address of database server
  228. * @param string $user Authorized username
  229. * @param string $pass Password
  230. * @param string $name Name of database
  231. * @param int $port Port of database server
  232. * @return DoliDB A DoliDB instance
  233. */
  234. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  235. {
  236. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  237. $class = 'DoliDB'.ucfirst($type);
  238. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  239. return $dolidb;
  240. }
  241. /**
  242. * Get list of entity id to use.
  243. *
  244. * @param string $element Current element
  245. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  246. * 'product', 'productprice', 'stock', 'bom', 'mo',
  247. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  248. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  249. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  250. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  251. * 'email_template', 'event', 'donation'
  252. * 'c_paiement', 'c_payment_term', ...
  253. * @param int $shared 0=Return id of current entity only,
  254. * 1=Return id of current entity + shared entities (default)
  255. * @param object $currentobject Current object if needed
  256. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  257. */
  258. function getEntity($element, $shared = 1, $currentobject = null)
  259. {
  260. global $conf, $mc, $hookmanager, $object, $action, $db;
  261. if (!is_object($hookmanager)) {
  262. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  263. $hookmanager = new HookManager($db);
  264. }
  265. // fix different element names (France to English)
  266. switch ($element) {
  267. case 'projet':
  268. $element = 'project';
  269. break;
  270. case 'contrat':
  271. $element = 'contract';
  272. break; // "/contrat/class/contrat.class.php"
  273. case 'order_supplier':
  274. $element = 'supplier_order';
  275. break; // "/fourn/class/fournisseur.commande.class.php"
  276. case 'invoice_supplier':
  277. $element = 'supplier_invoice';
  278. break; // "/fourn/class/fournisseur.facture.class.php"
  279. }
  280. if (is_object($mc)) {
  281. $out = $mc->getEntity($element, $shared, $currentobject);
  282. } else {
  283. $out = '';
  284. $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans');
  285. if (in_array($element, $addzero)) {
  286. $out .= '0,';
  287. }
  288. $out .= ((int) $conf->entity);
  289. }
  290. // Manipulate entities to query on the fly
  291. $parameters = array(
  292. 'element' => $element,
  293. 'shared' => $shared,
  294. 'object' => $object,
  295. 'currentobject' => $currentobject,
  296. 'out' => $out
  297. );
  298. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  299. if (is_numeric($reshook)) {
  300. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  301. $out .= ','.$hookmanager->resPrint; // add
  302. } elseif ($reshook == 1) {
  303. $out = $hookmanager->resPrint; // replace
  304. }
  305. }
  306. return $out;
  307. }
  308. /**
  309. * Set entity id to use when to create an object
  310. *
  311. * @param object $currentobject Current object
  312. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  313. */
  314. function setEntity($currentobject)
  315. {
  316. global $conf, $mc;
  317. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  318. return $mc->setEntity($currentobject);
  319. } else {
  320. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  321. }
  322. }
  323. /**
  324. * Return if string has a name dedicated to store a secret
  325. *
  326. * @param string $keyname Name of key to test
  327. * @return boolean True if key is used to store a secret
  328. */
  329. function isASecretKey($keyname)
  330. {
  331. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  332. }
  333. /**
  334. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  335. *
  336. * @param int|string $n Numeric value
  337. * @return string Column in Excel format
  338. */
  339. function num2Alpha($n)
  340. {
  341. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
  342. $r = chr($n % 26 + 0x41) . $r;
  343. return $r;
  344. }
  345. /**
  346. * Return information about user browser
  347. *
  348. * Returns array with the following format:
  349. * array(
  350. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  351. * 'browserversion' => Browser version. Empty if unknown
  352. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  353. * 'layout' => (tablet|phone|classic)
  354. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  355. * 'tablet' => true/false
  356. * )
  357. *
  358. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  359. * @return array Check function documentation
  360. */
  361. function getBrowserInfo($user_agent)
  362. {
  363. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  364. $name = 'unknown';
  365. $version = '';
  366. $os = 'unknown';
  367. $phone = '';
  368. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  369. $detectmobile = new Mobile_Detect(null, $user_agent);
  370. $tablet = $detectmobile->isTablet();
  371. if ($detectmobile->isMobile()) {
  372. $phone = 'unknown';
  373. // If phone/smartphone, we set phone os name.
  374. if ($detectmobile->is('AndroidOS')) {
  375. $os = $phone = 'android';
  376. } elseif ($detectmobile->is('BlackBerryOS')) {
  377. $os = $phone = 'blackberry';
  378. } elseif ($detectmobile->is('iOS')) {
  379. $os = 'ios';
  380. $phone = 'iphone';
  381. } elseif ($detectmobile->is('PalmOS')) {
  382. $os = $phone = 'palm';
  383. } elseif ($detectmobile->is('SymbianOS')) {
  384. $os = 'symbian';
  385. } elseif ($detectmobile->is('webOS')) {
  386. $os = 'webos';
  387. } elseif ($detectmobile->is('MaemoOS')) {
  388. $os = 'maemo';
  389. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  390. $os = 'windows';
  391. }
  392. }
  393. // OS
  394. if (preg_match('/linux/i', $user_agent)) {
  395. $os = 'linux';
  396. } elseif (preg_match('/macintosh/i', $user_agent)) {
  397. $os = 'macintosh';
  398. } elseif (preg_match('/windows/i', $user_agent)) {
  399. $os = 'windows';
  400. }
  401. // Name
  402. $reg = array();
  403. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  404. $name = 'firefox';
  405. $version = empty($reg[2]) ? '' : $reg[2];
  406. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  407. $name = 'edge';
  408. $version = empty($reg[2]) ? '' : $reg[2];
  409. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  410. $name = 'chrome';
  411. $version = empty($reg[2]) ? '' : $reg[2];
  412. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  413. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  414. $name = 'chrome';
  415. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  416. $name = 'iceweasel';
  417. } elseif (preg_match('/epiphany/i', $user_agent)) {
  418. $name = 'epiphany';
  419. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  420. $name = 'safari';
  421. $version = empty($reg[2]) ? '' : $reg[2];
  422. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  423. // Safari is often present in string for mobile but its not.
  424. $name = 'opera';
  425. $version = empty($reg[2]) ? '' : $reg[2];
  426. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  427. $name = 'ie';
  428. $version = end($reg);
  429. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  430. // MS products at end
  431. $name = 'ie';
  432. $version = end($reg);
  433. } elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  434. // MS products at end
  435. $name = 'lynxlinks';
  436. $version = empty($reg[3]) ? '' : $reg[3];
  437. }
  438. if ($tablet) {
  439. $layout = 'tablet';
  440. } elseif ($phone) {
  441. $layout = 'phone';
  442. } else {
  443. $layout = 'classic';
  444. }
  445. return array(
  446. 'browsername' => $name,
  447. 'browserversion' => $version,
  448. 'browseros' => $os,
  449. 'browserua' => $user_agent,
  450. 'layout' => $layout, // tablet, phone, classic
  451. 'phone' => $phone, // deprecated
  452. 'tablet' => $tablet // deprecated
  453. );
  454. }
  455. /**
  456. * Function called at end of web php process
  457. *
  458. * @return void
  459. */
  460. function dol_shutdown()
  461. {
  462. global $db;
  463. $disconnectdone = false;
  464. $depth = 0;
  465. if (is_object($db) && !empty($db->connected)) {
  466. $depth = $db->transaction_opened;
  467. $disconnectdone = $db->close();
  468. }
  469. dol_syslog("--- End access to ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]).(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
  470. }
  471. /**
  472. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  473. * Warning:
  474. * For action=add, use: $var = GETPOST('var'); // No GETPOSTISSET, so GETPOST always called and default value is retreived if not a form POST, and value of form is retreived if it is a form POST.
  475. * For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var;
  476. *
  477. * @param string $paramname Name or parameter to test
  478. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  479. */
  480. function GETPOSTISSET($paramname)
  481. {
  482. $isset = false;
  483. $relativepathstring = $_SERVER["PHP_SELF"];
  484. // Clean $relativepathstring
  485. if (constant('DOL_URL_ROOT')) {
  486. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  487. }
  488. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  489. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  490. //var_dump($relativepathstring);
  491. //var_dump($user->default_values);
  492. // Code for search criteria persistence.
  493. // Retrieve values if restore_lastsearch_values
  494. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  495. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  496. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  497. if (is_array($tmp)) {
  498. foreach ($tmp as $key => $val) {
  499. if ($key == $paramname) { // We are on the requested parameter
  500. $isset = true;
  501. break;
  502. }
  503. }
  504. }
  505. }
  506. // If there is saved contextpage, limit, page or mode
  507. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  508. $isset = true;
  509. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  510. $isset = true;
  511. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  512. $isset = true;
  513. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  514. $isset = true;
  515. }
  516. } else {
  517. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  518. }
  519. return $isset;
  520. }
  521. /**
  522. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  523. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  524. *
  525. * @param string $paramname Name or parameter to test
  526. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  527. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  528. */
  529. function GETPOSTISARRAY($paramname, $method = 0)
  530. {
  531. // for $method test need return the same $val as GETPOST
  532. if (empty($method)) {
  533. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  534. } elseif ($method == 1) {
  535. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  536. } elseif ($method == 2) {
  537. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  538. } elseif ($method == 3) {
  539. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  540. } else {
  541. $val = 'BadFirstParameterForGETPOST';
  542. }
  543. return is_array($val);
  544. }
  545. /**
  546. * Return value of a param into GET or POST supervariable.
  547. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  548. * Note: The property $user->default_values is loaded by main.php when loading the user.
  549. *
  550. * @param string $paramname Name of parameter to found
  551. * @param string $check Type of check
  552. * ''=no check (deprecated)
  553. * 'none'=no check (only for param that should have very rich content like passwords)
  554. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  555. * 'int'=check it's numeric (integer or float)
  556. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  557. * 'alpha'=Same than alphanohtml since v13
  558. * 'alphawithlgt'=alpha with lgt
  559. * 'alphanohtml'=check there is no html content and no " and no ../
  560. * 'aZ'=check it's a-z only
  561. * 'aZ09'=check it's simple alpha string (recommended for keys)
  562. * 'aZ09arobase'=check it's a string for an element type
  563. * 'aZ09comma'=check it's a string for a sortfield or sortorder
  564. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  565. * 'nohtml'=check there is no html content
  566. * 'restricthtml'=check html content is restricted to some tags only
  567. * 'custom'= custom filter specify $filter and $options)
  568. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  569. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  570. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  571. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  572. * @return string|array Value found (string or array), or '' if check fails
  573. */
  574. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  575. {
  576. global $mysoc, $user, $conf;
  577. if (empty($paramname)) {
  578. return 'BadFirstParameterForGETPOST';
  579. }
  580. if (empty($check)) {
  581. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  582. // Enable this line to know who call the GETPOST with '' $check parameter.
  583. //var_dump(debug_backtrace()[0]);
  584. }
  585. if (empty($method)) {
  586. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  587. } elseif ($method == 1) {
  588. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  589. } elseif ($method == 2) {
  590. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  591. } elseif ($method == 3) {
  592. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  593. } else {
  594. return 'BadThirdParameterForGETPOST';
  595. }
  596. if (empty($method) || $method == 3 || $method == 4) {
  597. $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
  598. // Clean $relativepathstring
  599. if (constant('DOL_URL_ROOT')) {
  600. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  601. }
  602. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  603. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  604. //var_dump($relativepathstring);
  605. //var_dump($user->default_values);
  606. // Code for search criteria persistence.
  607. // Retrieve values if restore_lastsearch_values
  608. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  609. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  610. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  611. if (is_array($tmp)) {
  612. foreach ($tmp as $key => $val) {
  613. if ($key == $paramname) { // We are on the requested parameter
  614. $out = $val;
  615. break;
  616. }
  617. }
  618. }
  619. }
  620. // If there is saved contextpage, page or limit
  621. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  622. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  623. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  624. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  625. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  626. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  627. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  628. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  629. }
  630. } elseif (!isset($_GET['sortfield'])) {
  631. // Else, retrieve default values if we are not doing a sort
  632. // 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
  633. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  634. // Search default value from $object->field
  635. global $object;
  636. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  637. $out = $object->fields[$paramname]['default'];
  638. }
  639. }
  640. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  641. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  642. // Now search in setup to overwrite default values
  643. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  644. if (isset($user->default_values[$relativepathstring]['createform'])) {
  645. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  646. $qualified = 0;
  647. if ($defkey != '_noquery_') {
  648. $tmpqueryarraytohave = explode('&', $defkey);
  649. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  650. $foundintru = 0;
  651. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  652. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  653. $foundintru = 1;
  654. }
  655. }
  656. if (!$foundintru) {
  657. $qualified = 1;
  658. }
  659. //var_dump($defkey.'-'.$qualified);
  660. } else {
  661. $qualified = 1;
  662. }
  663. if ($qualified) {
  664. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  665. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  666. break;
  667. }
  668. }
  669. }
  670. }
  671. }
  672. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  673. // Management of default search_filters and sort order
  674. if (!empty($user->default_values)) {
  675. // $user->default_values defined from menu 'Setup - Default values'
  676. //var_dump($user->default_values[$relativepathstring]);
  677. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  678. // Sorted on which fields ? ASC or DESC ?
  679. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  680. // Even if paramname is sortfield, data are stored into ['sortorder...']
  681. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  682. $qualified = 0;
  683. if ($defkey != '_noquery_') {
  684. $tmpqueryarraytohave = explode('&', $defkey);
  685. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  686. $foundintru = 0;
  687. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  688. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  689. $foundintru = 1;
  690. }
  691. }
  692. if (!$foundintru) {
  693. $qualified = 1;
  694. }
  695. //var_dump($defkey.'-'.$qualified);
  696. } else {
  697. $qualified = 1;
  698. }
  699. if ($qualified) {
  700. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  701. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  702. if ($out) {
  703. $out .= ', ';
  704. }
  705. if ($paramname == 'sortfield') {
  706. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  707. }
  708. if ($paramname == 'sortorder') {
  709. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  710. }
  711. }
  712. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  713. }
  714. }
  715. }
  716. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  717. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  718. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  719. continue;
  720. }
  721. $qualified = 0;
  722. if ($defkey != '_noquery_') {
  723. $tmpqueryarraytohave = explode('&', $defkey);
  724. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  725. $foundintru = 0;
  726. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  727. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  728. $foundintru = 1;
  729. }
  730. }
  731. if (!$foundintru) {
  732. $qualified = 1;
  733. }
  734. //var_dump($defkey.'-'.$qualified);
  735. } else {
  736. $qualified = 1;
  737. }
  738. if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
  739. // We must keep $_POST and $_GET here
  740. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  741. // We made a search from quick search menu, do we still use default filter ?
  742. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  743. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  744. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  745. }
  746. } else {
  747. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  748. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  749. }
  750. break;
  751. }
  752. }
  753. }
  754. }
  755. }
  756. }
  757. }
  758. }
  759. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  760. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  761. // 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.
  762. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  763. $reg = array();
  764. $maxloop = 20;
  765. $loopnb = 0; // Protection against infinite loop
  766. 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.
  767. $loopnb++;
  768. $newout = '';
  769. if ($reg[1] == 'DAY') {
  770. $tmp = dol_getdate(dol_now(), true);
  771. $newout = $tmp['mday'];
  772. } elseif ($reg[1] == 'MONTH') {
  773. $tmp = dol_getdate(dol_now(), true);
  774. $newout = $tmp['mon'];
  775. } elseif ($reg[1] == 'YEAR') {
  776. $tmp = dol_getdate(dol_now(), true);
  777. $newout = $tmp['year'];
  778. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  779. $tmp = dol_getdate(dol_now(), true);
  780. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  781. $newout = $tmp2['day'];
  782. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  783. $tmp = dol_getdate(dol_now(), true);
  784. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  785. $newout = $tmp2['month'];
  786. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  787. $tmp = dol_getdate(dol_now(), true);
  788. $newout = ($tmp['year'] - 1);
  789. } elseif ($reg[1] == 'NEXT_DAY') {
  790. $tmp = dol_getdate(dol_now(), true);
  791. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  792. $newout = $tmp2['day'];
  793. } elseif ($reg[1] == 'NEXT_MONTH') {
  794. $tmp = dol_getdate(dol_now(), true);
  795. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  796. $newout = $tmp2['month'];
  797. } elseif ($reg[1] == 'NEXT_YEAR') {
  798. $tmp = dol_getdate(dol_now(), true);
  799. $newout = ($tmp['year'] + 1);
  800. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  801. $newout = $mysoc->country_id;
  802. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  803. $newout = $user->id;
  804. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  805. $newout = $user->fk_user;
  806. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  807. $newout = $conf->entity;
  808. } else {
  809. $newout = ''; // Key not found, we replace with empty string
  810. }
  811. //var_dump('__'.$reg[1].'__ -> '.$newout);
  812. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  813. }
  814. }
  815. // Check rule
  816. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  817. if (!is_array($out) || empty($out)) {
  818. $out = array();
  819. } else {
  820. $tmparray = explode(':', $check);
  821. if (!empty($tmparray[1])) {
  822. $tmpcheck = $tmparray[1];
  823. } else {
  824. $tmpcheck = 'alphanohtml';
  825. }
  826. foreach ($out as $outkey => $outval) {
  827. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  828. }
  829. }
  830. } else {
  831. // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
  832. // we use the < or > to make a search on a numeric value to do higher or lower so we can add a space to break html tags
  833. if (strpos($paramname, 'search_') === 0) {
  834. $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
  835. }
  836. $out = sanitizeVal($out, $check, $filter, $options);
  837. }
  838. // Sanitizing for special parameters.
  839. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  840. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  841. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  842. $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
  843. do {
  844. $oldstringtoclean = $out;
  845. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  846. $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
  847. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  848. } while ($oldstringtoclean != $out);
  849. }
  850. // Code for search criteria persistence.
  851. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  852. if (empty($method) || $method == 3 || $method == 4) {
  853. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  854. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  855. // We save search key only if $out not empty that means:
  856. // - posted value not empty, or
  857. // - 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).
  858. if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
  859. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  860. }
  861. }
  862. }
  863. return $out;
  864. }
  865. /**
  866. * Return value of a param into GET or POST supervariable.
  867. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  868. * Note: The property $user->default_values is loaded by main.php when loading the user.
  869. *
  870. * @param string $paramname Name of parameter to found
  871. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  872. * @return int Value found (int)
  873. */
  874. function GETPOSTINT($paramname, $method = 0)
  875. {
  876. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  877. }
  878. /**
  879. * Return a sanitized or empty value after checking value against a rule.
  880. *
  881. * @deprecated
  882. * @param string|array $out Value to check/clear.
  883. * @param string $check Type of check/sanitizing
  884. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  885. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  886. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  887. */
  888. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  889. {
  890. return sanitizeVal($out, $check, $filter, $options);
  891. }
  892. /**
  893. * Return a sanitized or empty value after checking value against a rule.
  894. *
  895. * @param string|array $out Value to check/clear.
  896. * @param string $check Type of check/sanitizing
  897. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  898. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  899. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  900. */
  901. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  902. {
  903. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  904. // Check is done after replacement
  905. switch ($check) {
  906. case 'none':
  907. break;
  908. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  909. if (!is_numeric($out)) {
  910. $out = '';
  911. }
  912. break;
  913. case 'intcomma':
  914. if (preg_match('/[^0-9,-]+/i', $out)) {
  915. $out = '';
  916. }
  917. break;
  918. case 'san_alpha':
  919. $out = filter_var($out, FILTER_SANITIZE_STRING);
  920. break;
  921. case 'email':
  922. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  923. break;
  924. case 'aZ':
  925. if (!is_array($out)) {
  926. $out = trim($out);
  927. if (preg_match('/[^a-z]+/i', $out)) {
  928. $out = '';
  929. }
  930. }
  931. break;
  932. case 'aZ09':
  933. if (!is_array($out)) {
  934. $out = trim($out);
  935. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  936. $out = '';
  937. }
  938. }
  939. break;
  940. case 'aZ09arobase': // great to sanitize $objecttype parameter
  941. if (!is_array($out)) {
  942. $out = trim($out);
  943. if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
  944. $out = '';
  945. }
  946. }
  947. break;
  948. case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
  949. if (!is_array($out)) {
  950. $out = trim($out);
  951. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  952. $out = '';
  953. }
  954. }
  955. break;
  956. case 'alpha': // No html and no ../ and "
  957. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  958. if (!is_array($out)) {
  959. $out = trim($out);
  960. do {
  961. $oldstringtoclean = $out;
  962. // Remove html tags
  963. $out = dol_string_nohtmltag($out, 0);
  964. // Remove also other dangerous string sequences
  965. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  966. // '../' or '..\' is dangerous because it allows dir transversals
  967. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  968. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  969. } while ($oldstringtoclean != $out);
  970. // keep lines feed
  971. }
  972. break;
  973. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
  974. if (!is_array($out)) {
  975. $out = trim($out);
  976. do {
  977. $oldstringtoclean = $out;
  978. // Remove html tags
  979. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  980. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  981. // '../' or '..\' is dangerous because it allows dir transversals
  982. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  983. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  984. } while ($oldstringtoclean != $out);
  985. }
  986. break;
  987. case 'nohtml': // No html
  988. $out = dol_string_nohtmltag($out, 0);
  989. break;
  990. case 'restricthtmlnolink':
  991. case 'restricthtml': // Recommended for most html textarea
  992. case 'restricthtmlallowclass':
  993. case 'restricthtmlallowunvalid':
  994. $out = dol_htmlwithnojs($out, 1, $check);
  995. break;
  996. case 'custom':
  997. if (!empty($out)) {
  998. if (empty($filter)) {
  999. return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
  1000. }
  1001. /*if (empty($options)) {
  1002. return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
  1003. }*/
  1004. $out = filter_var($out, $filter, $options);
  1005. }
  1006. break;
  1007. }
  1008. return $out;
  1009. }
  1010. if (!function_exists('dol_getprefix')) {
  1011. /**
  1012. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  1013. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  1014. * or two instances in same virtual servers.
  1015. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  1016. *
  1017. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  1018. * @return string A calculated prefix
  1019. */
  1020. function dol_getprefix($mode = '')
  1021. {
  1022. // If prefix is for email (we need to have $conf already loaded for this case)
  1023. if ($mode == 'email') {
  1024. global $conf;
  1025. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  1026. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  1027. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  1028. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  1029. return $_SERVER["SERVER_NAME"];
  1030. }
  1031. }
  1032. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  1033. if (!empty($conf->file->instance_unique_id)) {
  1034. return sha1('dolibarr'.$conf->file->instance_unique_id);
  1035. }
  1036. // For backward compatibility when instance_unique_id is not set
  1037. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1038. }
  1039. // If prefix is for session (no need to have $conf loaded)
  1040. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  1041. $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
  1042. // The recommended value (may be not defined for old versions)
  1043. if (!empty($tmp_instance_unique_id)) {
  1044. return sha1('dolibarr'.$tmp_instance_unique_id);
  1045. }
  1046. // For backward compatibility when instance_unique_id is not set
  1047. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  1048. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1049. } else {
  1050. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1051. }
  1052. }
  1053. }
  1054. /**
  1055. * Make an include_once using default root and alternate root if it fails.
  1056. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  1057. * To link to a module file from a module file, use include './mymodulefile';
  1058. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  1059. *
  1060. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  1061. * @param string $classname Class name (deprecated)
  1062. * @return bool True if load is a success, False if it fails
  1063. */
  1064. function dol_include_once($relpath, $classname = '')
  1065. {
  1066. 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']
  1067. $fullpath = dol_buildpath($relpath);
  1068. if (!file_exists($fullpath)) {
  1069. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  1070. return false;
  1071. }
  1072. if (!empty($classname) && !class_exists($classname)) {
  1073. return include $fullpath;
  1074. } else {
  1075. return include_once $fullpath;
  1076. }
  1077. }
  1078. /**
  1079. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  1080. *
  1081. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  1082. * @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)
  1083. * @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)
  1084. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  1085. * 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
  1086. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  1087. */
  1088. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  1089. {
  1090. global $conf;
  1091. $path = preg_replace('/^\//', '', $path);
  1092. if (empty($type)) { // For a filesystem path
  1093. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  1094. if (is_array($conf->file->dol_document_root)) {
  1095. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  1096. if ($key == 'main') {
  1097. continue;
  1098. }
  1099. // if (@file_exists($dirroot.'/'.$path)) {
  1100. if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn]
  1101. $res = $dirroot.'/'.$path;
  1102. return $res;
  1103. }
  1104. }
  1105. }
  1106. if ($returnemptyifnotfound) {
  1107. // Not found into alternate dir
  1108. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  1109. return '';
  1110. }
  1111. }
  1112. } else {
  1113. // For an url path
  1114. // We try to get local path of file on filesystem from url
  1115. // Note that trying to know if a file on disk exist by forging path on disk from url
  1116. // works only for some web server and some setup. This is bugged when
  1117. // using proxy, rewriting, virtual path, etc...
  1118. $res = '';
  1119. if ($type == 1) {
  1120. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  1121. }
  1122. if ($type == 2) {
  1123. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  1124. }
  1125. if ($type == 3) {
  1126. $res = DOL_URL_ROOT.'/'.$path;
  1127. }
  1128. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  1129. if ($key == 'main') {
  1130. if ($type == 3) {
  1131. global $dolibarr_main_url_root;
  1132. // Define $urlwithroot
  1133. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1134. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1135. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1136. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  1137. }
  1138. continue;
  1139. }
  1140. $regs = array();
  1141. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  1142. if (!empty($regs[1])) {
  1143. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1144. //if (file_exists($dirroot.'/'.$regs[1])) {
  1145. if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn]
  1146. if ($type == 1) {
  1147. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1148. }
  1149. if ($type == 2) {
  1150. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1151. }
  1152. if ($type == 3) {
  1153. global $dolibarr_main_url_root;
  1154. // Define $urlwithroot
  1155. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1156. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1157. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1158. $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
  1159. }
  1160. break;
  1161. }
  1162. }
  1163. }
  1164. }
  1165. return $res;
  1166. }
  1167. /**
  1168. * Create a clone of instance of object (new instance with same value for each properties)
  1169. * With native = 0: Property that are reference are different memory area in the new object (full isolation clone). This means $this->db of new object may not be valid.
  1170. * 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.
  1171. * With native = 2: Property that are reference are different memory area in the new object (full isolation clone). Only scalar and array values are cloned. This means $this->db of new object is not valid.
  1172. *
  1173. * @param object $object Object to clone
  1174. * @param int $native 0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended)
  1175. * @return object Clone object
  1176. * @see https://php.net/manual/language.oop5.cloning.php
  1177. */
  1178. function dol_clone($object, $native = 0)
  1179. {
  1180. if ($native == 0) {
  1181. // deprecated method, use the method with native = 2 instead
  1182. $tmpsavdb = null;
  1183. if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
  1184. $tmpsavdb = $object->db;
  1185. unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
  1186. }
  1187. $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
  1188. if (!empty($tmpsavdb)) {
  1189. $object->db = $tmpsavdb;
  1190. }
  1191. } elseif ($native == 2) {
  1192. // recommended method to have a full isolated cloned object
  1193. $myclone = new stdClass();
  1194. $tmparray = get_object_vars($object); // return only public properties
  1195. if (is_array($tmparray)) {
  1196. foreach ($tmparray as $propertykey => $propertyval) {
  1197. if (is_scalar($propertyval) || is_array($propertyval)) {
  1198. $myclone->$propertykey = $propertyval;
  1199. }
  1200. }
  1201. }
  1202. } else {
  1203. $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)
  1204. }
  1205. return $myclone;
  1206. }
  1207. /**
  1208. * Optimize a size for some browsers (phone, smarphone, ...)
  1209. *
  1210. * @param int $size Size we want
  1211. * @param string $type Type of optimizing:
  1212. * '' = function used to define a size for truncation
  1213. * 'width' = function is used to define a width
  1214. * @return int New size after optimizing
  1215. */
  1216. function dol_size($size, $type = '')
  1217. {
  1218. global $conf;
  1219. if (empty($conf->dol_optimize_smallscreen)) {
  1220. return $size;
  1221. }
  1222. if ($type == 'width' && $size > 250) {
  1223. return 250;
  1224. } else {
  1225. return 10;
  1226. }
  1227. }
  1228. /**
  1229. * Clean a string to use it as a file name.
  1230. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1231. *
  1232. * @param string $str String to clean
  1233. * @param string $newstr String to replace bad chars with.
  1234. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1235. * @return string String cleaned (a-zA-Z_)
  1236. *
  1237. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1238. */
  1239. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1240. {
  1241. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1242. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1243. // Char '/' and '\' are file delimiters.
  1244. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1245. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
  1246. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1247. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1248. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1249. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1250. $tmp = str_replace('..', '', $tmp);
  1251. return $tmp;
  1252. }
  1253. /**
  1254. * Clean a string to use it as a path name.
  1255. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1256. *
  1257. * @param string $str String to clean
  1258. * @param string $newstr String to replace bad chars with
  1259. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1260. * @return string String cleaned (a-zA-Z_)
  1261. *
  1262. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1263. */
  1264. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1265. {
  1266. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1267. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1268. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1269. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
  1270. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1271. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1272. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1273. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1274. $tmp = str_replace('..', '', $tmp);
  1275. return $tmp;
  1276. }
  1277. /**
  1278. * Clean a string to use it as an URL (into a href or src attribute)
  1279. *
  1280. * @param string $stringtoclean String to clean
  1281. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1282. * @return string Escaped string.
  1283. */
  1284. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1285. {
  1286. // 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)
  1287. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1288. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1289. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1290. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1291. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1292. if ($type == 1) {
  1293. // removing : should disable links to external url like http:aaa)
  1294. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1295. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1296. }
  1297. do {
  1298. $oldstringtoclean = $stringtoclean;
  1299. // removing '&colon' should disable links to external url like http:aaa)
  1300. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1301. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1302. } while ($oldstringtoclean != $stringtoclean);
  1303. if ($type == 1) {
  1304. // removing '//' should disable links to external url like //aaa or http//)
  1305. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1306. }
  1307. return $stringtoclean;
  1308. }
  1309. /**
  1310. * Clean a string to use it as an Email.
  1311. *
  1312. * @param string $stringtoclean String to clean. Example 'abc@mycompany.com <My name>'
  1313. * @return string Escaped string.
  1314. */
  1315. function dol_sanitizeEmail($stringtoclean)
  1316. {
  1317. do {
  1318. $oldstringtoclean = $stringtoclean;
  1319. $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
  1320. } while ($oldstringtoclean != $stringtoclean);
  1321. return $stringtoclean;
  1322. }
  1323. /**
  1324. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1325. *
  1326. * @param string $str String to clean
  1327. * @return string Cleaned string
  1328. *
  1329. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1330. */
  1331. function dol_string_unaccent($str)
  1332. {
  1333. global $conf;
  1334. if (is_null($str)) {
  1335. return '';
  1336. }
  1337. if (utf8_check($str)) {
  1338. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1339. $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
  1340. return $transliterator->transliterate($str);
  1341. }
  1342. // See http://www.utf8-chartable.de/
  1343. $string = rawurlencode($str);
  1344. $replacements = array(
  1345. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1346. '%C3%87' => 'C',
  1347. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1348. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1349. '%C3%91' => 'N',
  1350. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1351. '%C5%A0' => 'S',
  1352. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1353. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1354. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1355. '%C3%A7' => 'c',
  1356. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1357. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1358. '%C3%B1' => 'n',
  1359. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1360. '%C5%A1' => 's',
  1361. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1362. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1363. );
  1364. $string = strtr($string, $replacements);
  1365. return rawurldecode($string);
  1366. } else {
  1367. // See http://www.ascii-code.com/
  1368. $string = strtr(
  1369. $str,
  1370. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1371. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1372. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1373. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1374. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1375. \xF9\xFA\xFB\xFC\xFD\xFF",
  1376. "AAAAAAC
  1377. EEEEIIIIDN
  1378. OOOOOUUUY
  1379. aaaaaaceeee
  1380. iiiidnooooo
  1381. uuuuyy"
  1382. );
  1383. $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"));
  1384. return $string;
  1385. }
  1386. }
  1387. /**
  1388. * Clean a string from all punctuation characters to use it as a ref or login.
  1389. * This is a more complete function than dol_sanitizeFileName().
  1390. *
  1391. * @param string $str String to clean
  1392. * @param string $newstr String to replace forbidden chars with
  1393. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1394. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1395. * @param int $keepspaces 1=Do not treat space as a special char to replace or remove
  1396. * @return string Cleaned string
  1397. *
  1398. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1399. */
  1400. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
  1401. {
  1402. $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
  1403. if (empty($keepspaces)) {
  1404. $forbidden_chars_to_replace[] = " ";
  1405. }
  1406. $forbidden_chars_to_remove = array();
  1407. //$forbidden_chars_to_remove=array("(",")");
  1408. if (is_array($badcharstoreplace)) {
  1409. $forbidden_chars_to_replace = $badcharstoreplace;
  1410. }
  1411. if (is_array($badcharstoremove)) {
  1412. $forbidden_chars_to_remove = $badcharstoremove;
  1413. }
  1414. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1415. }
  1416. /**
  1417. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1418. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1419. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1420. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1421. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1422. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1423. * @param string $str String to clean
  1424. * @param int $removetabcrlf Remove also CR-LF
  1425. * @return string Cleaned string
  1426. *
  1427. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1428. */
  1429. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1430. {
  1431. if ($removetabcrlf) {
  1432. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1433. } else {
  1434. 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
  1435. }
  1436. }
  1437. /**
  1438. * Returns text escaped for inclusion into javascript code
  1439. *
  1440. * @param string $stringtoescape String to escape
  1441. * @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 \
  1442. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1443. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1444. */
  1445. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1446. {
  1447. if (is_null($stringtoescape)) {
  1448. return '';
  1449. }
  1450. // escape quotes and backslashes, newlines, etc.
  1451. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1452. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1453. if (empty($noescapebackslashn)) {
  1454. $substitjs["\n"] = '\\n';
  1455. $substitjs['\\'] = '\\\\';
  1456. }
  1457. if (empty($mode)) {
  1458. $substitjs["'"] = "\\'";
  1459. $substitjs['"'] = "\\'";
  1460. } elseif ($mode == 1) {
  1461. $substitjs["'"] = "\\'";
  1462. } elseif ($mode == 2) {
  1463. $substitjs['"'] = '\\"';
  1464. } elseif ($mode == 3) {
  1465. $substitjs["'"] = "\\'";
  1466. $substitjs['"'] = "\\\"";
  1467. }
  1468. return strtr($stringtoescape, $substitjs);
  1469. }
  1470. /**
  1471. * Returns text escaped for inclusion into javascript code
  1472. *
  1473. * @param string $stringtoescape String to escape
  1474. * @return string Escaped string for json content.
  1475. */
  1476. function dol_escape_json($stringtoescape)
  1477. {
  1478. return str_replace('"', '\"', $stringtoescape);
  1479. }
  1480. /**
  1481. * Returns text escaped for inclusion into a php string, build with double quotes " or '
  1482. *
  1483. * @param string $stringtoescape String to escape
  1484. * @param string $stringforquotes 2=String for doublequotes, 1=String for simple quotes
  1485. * @return string Escaped string for json content.
  1486. */
  1487. function dol_escape_php($stringtoescape, $stringforquotes = 2)
  1488. {
  1489. if (is_null($stringtoescape)) {
  1490. return '';
  1491. }
  1492. if ($stringforquotes == 2) {
  1493. return str_replace('"', "'", $stringtoescape);
  1494. }
  1495. if ($stringforquotes == 1) {
  1496. return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
  1497. }
  1498. return 'Bad parameter for stringforquotes in dol_escape_php';
  1499. }
  1500. /**
  1501. * Return a string label ready to be output on HTML content
  1502. * To use text inside an attribute, use can simply only dol_escape_htmltag()
  1503. *
  1504. * @param string $s String to print
  1505. * @return string String ready for HTML output
  1506. */
  1507. function dolPrintLabel($s)
  1508. {
  1509. return dol_escape_htmltag(dol_htmlentitiesbr($s));
  1510. }
  1511. /**
  1512. * Return a string ready to be output on HTML page
  1513. * To use text inside an attribute, you can simply use dol_escape_htmltag()
  1514. *
  1515. * @param string $s String to print
  1516. * @param int $allowiframe Allow iframe tags
  1517. * @return string String ready for HTML output
  1518. */
  1519. function dolPrintHTML($s, $allowiframe = 0)
  1520. {
  1521. return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, 'common', 0, 1);
  1522. }
  1523. /**
  1524. * Return a string ready to be output on an HTML attribute (alt, title, ...)
  1525. *
  1526. * @param string $s String to print
  1527. * @return string String ready for HTML output
  1528. */
  1529. function dolPrintHTMLForAttribute($s)
  1530. {
  1531. // The dol_htmlentitiesbr will convert simple text into html
  1532. // The dol_escape_htmltag will escape html chars.
  1533. return dol_escape_htmltag(dol_htmlentitiesbr($s), 1, -1);
  1534. }
  1535. /**
  1536. * Return a string ready to be output on input textarea
  1537. * To use text inside an attribute, use can use only dol_escape_htmltag()
  1538. *
  1539. * @param string $s String to print
  1540. * @param int $allowiframe Allow iframe tags
  1541. * @return string String ready for HTML output into a textarea
  1542. */
  1543. function dolPrintHTMLForTextArea($s, $allowiframe = 0)
  1544. {
  1545. return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1);
  1546. }
  1547. /**
  1548. * Return a string ready to be output on an HTML attribute (alt, title, ...)
  1549. *
  1550. * @param string $s String to print
  1551. * @return string String ready for HTML output
  1552. */
  1553. function dolPrintPassword($s)
  1554. {
  1555. return htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  1556. }
  1557. /**
  1558. * Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields.
  1559. * When we need to output strings on pages, we should use:
  1560. * - dolPrintHTML... that is dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1)), 1, 1) for notes or descriptions into textarea, add 'common' if into a html content
  1561. * - dolPrintLabel... that is dol_escape_htmltag(dol_htmlentitiesbr()) for simple labels.
  1562. * - dolPrintPassword that is abelhtmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords.
  1563. *
  1564. * @param string $stringtoescape String to escape
  1565. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1566. * @param int $keepn 1=Preserve \r\n strings, 0=Replace them with escaped value, -1=Remove them. Set to 1 when escaping for a <textarea>.
  1567. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes into tag.
  1568. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1569. * @param int $cleanalsojavascript Clean also javascript. @TODO switch this option to 1 by default.
  1570. * @return string Escaped string
  1571. * @see dol_string_nohtmltag(), dol_string_onlythesehtmltags(), dol_string_nospecial(), dol_string_unaccent(), dol_htmlentitiesbr()
  1572. */
  1573. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
  1574. {
  1575. if ($noescapetags == 'common') {
  1576. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1577. }
  1578. if ($cleanalsojavascript) {
  1579. $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
  1580. }
  1581. // escape quotes and backslashes, newlines, etc.
  1582. if ($escapeonlyhtmltags) {
  1583. $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
  1584. } else {
  1585. $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
  1586. }
  1587. if (!$keepb) {
  1588. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>'', '<strong>'=>'', '</strong>'=>''));
  1589. }
  1590. if (!$keepn) {
  1591. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1592. } elseif ($keepn == -1) {
  1593. $tmp = strtr($tmp, array("\r"=>'', "\n"=>''));
  1594. }
  1595. if ($escapeonlyhtmltags) {
  1596. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1597. } else {
  1598. // Escape tags to keep
  1599. $tmparrayoftags = array();
  1600. if ($noescapetags) {
  1601. $tmparrayoftags = explode(',', $noescapetags);
  1602. }
  1603. if (count($tmparrayoftags)) {
  1604. // TODO Does not works yet when there is attributes into tag
  1605. foreach ($tmparrayoftags as $tagtoreplace) {
  1606. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1607. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1608. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1609. }
  1610. }
  1611. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1612. if (count($tmparrayoftags)) {
  1613. foreach ($tmparrayoftags as $tagtoreplace) {
  1614. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1615. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1616. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1617. }
  1618. }
  1619. return $result;
  1620. }
  1621. }
  1622. /**
  1623. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1624. *
  1625. * @param string $string String to encode
  1626. * @param string $encoding Character set encoding
  1627. * @return string String converted
  1628. */
  1629. function dol_strtolower($string, $encoding = "UTF-8")
  1630. {
  1631. if (function_exists('mb_strtolower')) {
  1632. return mb_strtolower($string, $encoding);
  1633. } else {
  1634. return strtolower($string);
  1635. }
  1636. }
  1637. /**
  1638. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1639. *
  1640. * @param string $string String to encode
  1641. * @param string $encoding Character set encoding
  1642. * @return string String converted
  1643. * @see dol_ucfirst(), dol_ucwords()
  1644. */
  1645. function dol_strtoupper($string, $encoding = "UTF-8")
  1646. {
  1647. if (function_exists('mb_strtoupper')) {
  1648. return mb_strtoupper($string, $encoding);
  1649. } else {
  1650. return strtoupper($string);
  1651. }
  1652. }
  1653. /**
  1654. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1655. *
  1656. * @param string $string String to encode
  1657. * @param string $encoding Character set encodign
  1658. * @return string String converted
  1659. * @see dol_strtoupper(), dol_ucwords()
  1660. */
  1661. function dol_ucfirst($string, $encoding = "UTF-8")
  1662. {
  1663. if (function_exists('mb_substr')) {
  1664. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1665. } else {
  1666. return ucfirst($string);
  1667. }
  1668. }
  1669. /**
  1670. * Convert first character of all the words of a string to upper.
  1671. *
  1672. * @param string $string String to encode
  1673. * @param string $encoding Character set encodign
  1674. * @return string String converted
  1675. * @see dol_strtoupper(), dol_ucfirst()
  1676. */
  1677. function dol_ucwords($string, $encoding = "UTF-8")
  1678. {
  1679. if (function_exists('mb_convert_case')) {
  1680. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1681. } else {
  1682. return ucwords($string);
  1683. }
  1684. }
  1685. /**
  1686. * Write log message into outputs. Possible outputs can be:
  1687. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1688. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1689. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1690. * this, use logging to files instead of syslog (see setup of module).
  1691. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1692. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1693. * This function works only if syslog module is enabled.
  1694. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1695. *
  1696. * @param string $message Line to log. ''=Show nothing
  1697. * @param int $level Log level
  1698. * 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
  1699. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1700. * @param int $ident 1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log)
  1701. * @param string $suffixinfilename When output is a file, append this suffix into default log filename. Example '_stripe', '_mail'
  1702. * @param string $restricttologhandler Force output of log only to this log handler
  1703. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1704. * @return void
  1705. */
  1706. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1707. {
  1708. global $conf, $user, $debugbar;
  1709. // If syslog module enabled
  1710. if (!isModEnabled('syslog')) {
  1711. return;
  1712. }
  1713. // Check if we are into execution of code of a website
  1714. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1715. global $website, $websitekey;
  1716. if (is_object($website) && !empty($website->ref)) {
  1717. $suffixinfilename .= '_website_'.$website->ref;
  1718. } elseif (!empty($websitekey)) {
  1719. $suffixinfilename .= '_website_'.$websitekey;
  1720. }
  1721. }
  1722. // Check if we have a forced suffix
  1723. if (defined('USESUFFIXINLOG')) {
  1724. $suffixinfilename .= constant('USESUFFIXINLOG');
  1725. }
  1726. if ($ident < 0) {
  1727. foreach ($conf->loghandlers as $loghandlerinstance) {
  1728. $loghandlerinstance->setIdent($ident);
  1729. }
  1730. }
  1731. if (!empty($message)) {
  1732. // Test log level
  1733. $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');
  1734. if (!array_key_exists($level, $logLevels)) {
  1735. throw new Exception('Incorrect log level');
  1736. }
  1737. if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
  1738. return;
  1739. }
  1740. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1741. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1742. }
  1743. // If adding log inside HTML page is required
  1744. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1745. || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))) {
  1746. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1747. }
  1748. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1749. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1750. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1751. print "\n\n<!-- Log start\n";
  1752. print dol_escape_htmltag($message)."\n";
  1753. print "Log end -->\n";
  1754. }
  1755. $data = array(
  1756. 'message' => $message,
  1757. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1758. 'level' => $level,
  1759. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1760. 'ip' => false
  1761. );
  1762. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1763. if (!empty($remoteip)) {
  1764. $data['ip'] = $remoteip;
  1765. // This is when server run behind a reverse proxy
  1766. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1767. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1768. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1769. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1770. }
  1771. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1772. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1773. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1774. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1775. // 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).
  1776. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1777. } elseif (!empty($_SERVER['LOGNAME'])) {
  1778. // 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).
  1779. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1780. }
  1781. // Loop on each log handler and send output
  1782. foreach ($conf->loghandlers as $loghandlerinstance) {
  1783. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1784. continue;
  1785. }
  1786. $loghandlerinstance->export($data, $suffixinfilename);
  1787. }
  1788. unset($data);
  1789. }
  1790. if ($ident > 0) {
  1791. foreach ($conf->loghandlers as $loghandlerinstance) {
  1792. $loghandlerinstance->setIdent($ident);
  1793. }
  1794. }
  1795. }
  1796. /**
  1797. * Return HTML code to output a button to open a dialog popup box.
  1798. * Such buttons must be included inside a HTML form.
  1799. *
  1800. * @param string $name A name for the html component
  1801. * @param string $label Label shown in Popup title top bar
  1802. * @param string $buttonstring button string (HTML text we can click on)
  1803. * @param string $url Relative Url to open. For example '/project/card.php'
  1804. * @param string $disabled Disabled text
  1805. * @param string $morecss More CSS
  1806. * @param string $jsonopen Some JS code to execute on click/open of popup
  1807. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1808. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1809. * @param string $accesskey A key to use shortcut
  1810. * @return string HTML component with button
  1811. */
  1812. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
  1813. {
  1814. global $conf;
  1815. if (strpos($url, '?') > 0) {
  1816. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1817. } else {
  1818. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1819. }
  1820. $out = '';
  1821. $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
  1822. if ($backtopagejsfields) {
  1823. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1824. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1825. $backtopagejsfields = $name.":".$backtopagejsfields;
  1826. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1827. } else {
  1828. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1829. }
  1830. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1831. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1832. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1833. }
  1834. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1835. $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
  1836. $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
  1837. if (empty($conf->use_javascript_ajax)) {
  1838. $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
  1839. } elseif ($jsonopen) {
  1840. $out .= ' href="#" onclick="'.$jsonopen.'"';
  1841. } else {
  1842. $out .= ' href="#"';
  1843. }
  1844. $out .= '>'.$buttonstring.'</a>';
  1845. if (!empty($conf->use_javascript_ajax)) {
  1846. // Add code to open url using the popup. Add also hidden field to retreive the returned variables
  1847. $out .= '<!-- code to open popup and variables to retreive returned variables -->';
  1848. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1849. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1850. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1851. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1852. $out .= '<script nonce="'.getNonce().'" type="text/javascript">
  1853. jQuery(document).ready(function () {
  1854. jQuery(".button_'.$name.'").click(function () {
  1855. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1856. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1857. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1858. $tmpdialog.dialog({
  1859. autoOpen: false,
  1860. modal: true,
  1861. height: (window.innerHeight - 150),
  1862. width: \'80%\',
  1863. title: \''.dol_escape_js($label).'\',
  1864. open: function (event, ui) {
  1865. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1866. },
  1867. close: function (event, ui) {
  1868. var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1869. var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1870. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1871. if (returnedid != "" && returnedid != "div for returned id") {
  1872. jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
  1873. }
  1874. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1875. jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
  1876. }
  1877. }
  1878. });
  1879. $tmpdialog.dialog(\'open\');
  1880. return false;
  1881. });
  1882. });
  1883. </script>';
  1884. }
  1885. return $out;
  1886. }
  1887. /**
  1888. * Show tab header of a card
  1889. *
  1890. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1891. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1892. * @param string $title Title
  1893. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no sepaaration under tab (to start a tab just after), -3=Add tab header but no footer separation
  1894. * @param string $picto Add a picto on tab title
  1895. * @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.
  1896. * @param string $morehtmlright Add more html content on right of tabs title
  1897. * @param string $morecss More Css
  1898. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1899. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1900. * @return void
  1901. * @deprecated Use print dol_get_fiche_head() instead
  1902. */
  1903. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1904. {
  1905. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1906. }
  1907. /**
  1908. * Show tabs of a record
  1909. *
  1910. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1911. * @param string $active Active tab name
  1912. * @param string $title Title
  1913. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after), -3=-2+'noborderbottom'
  1914. * @param string $picto Add a picto on tab title
  1915. * @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.
  1916. * @param string $morehtmlright Add more html content on right of tabs title
  1917. * @param string $morecss More CSS on the link <a>
  1918. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1919. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1920. * @param int $dragdropfile 0 (default) or 1. 1 enable a drop zone for file to be upload, 0 disable it
  1921. * @return string
  1922. */
  1923. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
  1924. {
  1925. global $conf, $langs, $hookmanager;
  1926. // Show title
  1927. $showtitle = 1;
  1928. if (!empty($conf->dol_optimize_smallscreen)) {
  1929. $showtitle = 0;
  1930. }
  1931. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1932. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1933. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1934. }
  1935. // Show right part
  1936. if ($morehtmlright) {
  1937. $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.
  1938. }
  1939. // Show title
  1940. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1941. $limittitle = 30;
  1942. $out .= '<a class="tabTitle">';
  1943. if ($picto) {
  1944. $noprefix = $pictoisfullpath;
  1945. if (strpos($picto, 'fontawesome_') !== false) {
  1946. $noprefix = 1;
  1947. }
  1948. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1949. }
  1950. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1951. $out .= '</a>';
  1952. }
  1953. // Show tabs
  1954. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1955. $maxkey = -1;
  1956. if (is_array($links) && !empty($links)) {
  1957. $keys = array_keys($links);
  1958. if (count($keys)) {
  1959. $maxkey = max($keys);
  1960. }
  1961. }
  1962. // Show tabs
  1963. // if =0 we don't use the feature
  1964. if (empty($limittoshow)) {
  1965. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1966. }
  1967. if (!empty($conf->dol_optimize_smallscreen)) {
  1968. $limittoshow = 2;
  1969. }
  1970. $displaytab = 0;
  1971. $nbintab = 0;
  1972. $popuptab = 0;
  1973. $outmore = '';
  1974. for ($i = 0; $i <= $maxkey; $i++) {
  1975. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1976. // If active tab is already present
  1977. if ($i >= $limittoshow) {
  1978. $limittoshow--;
  1979. }
  1980. }
  1981. }
  1982. for ($i = 0; $i <= $maxkey; $i++) {
  1983. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1984. $isactive = true;
  1985. } else {
  1986. $isactive = false;
  1987. }
  1988. if ($i < $limittoshow || $isactive) {
  1989. // Output entry with a visible tab
  1990. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
  1991. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1992. if (!empty($links[$i][0])) {
  1993. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1994. } else {
  1995. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1996. }
  1997. } elseif (!empty($links[$i][1])) {
  1998. //print "x $i $active ".$links[$i][2]." z";
  1999. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  2000. if (!empty($links[$i][0])) {
  2001. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  2002. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').(!empty($links[$i][5]) ? ' '.$links[$i][5] : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  2003. }
  2004. $out .= $links[$i][1];
  2005. if (!empty($links[$i][0])) {
  2006. $out .= '</a>'."\n";
  2007. }
  2008. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  2009. $out .= '</div>';
  2010. }
  2011. $out .= '</div>';
  2012. } else {
  2013. // Add entry into the combo popup with the other tabs
  2014. if (!$popuptab) {
  2015. $popuptab = 1;
  2016. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  2017. }
  2018. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  2019. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  2020. if (!empty($links[$i][0])) {
  2021. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  2022. } else {
  2023. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  2024. }
  2025. } elseif (!empty($links[$i][1])) {
  2026. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  2027. $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.
  2028. $outmore .= '</a>'."\n";
  2029. }
  2030. $outmore .= '</div>';
  2031. $nbintab++;
  2032. }
  2033. $displaytab = $i;
  2034. }
  2035. if ($popuptab) {
  2036. $outmore .= '</div>';
  2037. }
  2038. if ($popuptab) { // If there is some tabs not shown
  2039. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  2040. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  2041. $widthofpopup = 200;
  2042. $tabsname = $moretabssuffix;
  2043. if (empty($tabsname)) {
  2044. $tabsname = str_replace("@", "", $picto);
  2045. }
  2046. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  2047. $out .= '<div class="tab"><a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
  2048. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  2049. $out .= $outmore;
  2050. $out .= '</div>';
  2051. $out .= '<div></div>';
  2052. $out .= "</div>\n";
  2053. $out .= '<script nonce="'.getNonce().'">';
  2054. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  2055. var x = this.offsetLeft, y = this.offsetTop;
  2056. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  2057. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  2058. $('#moretabsList".$tabsname."').css('".$right."','8px');
  2059. }
  2060. $('#moretabsList".$tabsname."').css('".$left."','auto');
  2061. });
  2062. ";
  2063. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  2064. $out .= "</script>";
  2065. }
  2066. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  2067. $out .= "</div>\n";
  2068. }
  2069. if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
  2070. $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
  2071. }
  2072. if (!empty($dragdropfile)) {
  2073. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2074. $out .= dragAndDropFileUpload("dragDropAreaTabBar");
  2075. }
  2076. $parameters = array('tabname' => $active, 'out' => $out);
  2077. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  2078. if ($reshook > 0) {
  2079. $out = $hookmanager->resPrint;
  2080. }
  2081. return $out;
  2082. }
  2083. /**
  2084. * Show tab footer of a card
  2085. *
  2086. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  2087. * @return void
  2088. * @deprecated Use print dol_get_fiche_end() instead
  2089. */
  2090. function dol_fiche_end($notab = 0)
  2091. {
  2092. print dol_get_fiche_end($notab);
  2093. }
  2094. /**
  2095. * Return tab footer of a card
  2096. *
  2097. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  2098. * @return string
  2099. */
  2100. function dol_get_fiche_end($notab = 0)
  2101. {
  2102. if (!$notab || $notab == -1) {
  2103. return "\n</div>\n";
  2104. } else {
  2105. return '';
  2106. }
  2107. }
  2108. /**
  2109. * Show tab footer of a card.
  2110. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  2111. *
  2112. * @param Object $object Object to show
  2113. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  2114. * @param string $morehtml More html content to output just before the nav bar
  2115. * @param int $shownav Show Condition (navigation is shown if value is 1)
  2116. * @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.
  2117. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  2118. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  2119. * @param string $moreparam More param to add in nav link url.
  2120. * @param int $nodbprefix Do not include DB prefix to forge table name
  2121. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  2122. * @param string $morehtmlstatus More html code to show under navigation arrows
  2123. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  2124. * @param string $morehtmlright More html code to show before navigation arrows
  2125. * @return void
  2126. */
  2127. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  2128. {
  2129. global $conf, $form, $user, $langs, $hookmanager, $action;
  2130. $error = 0;
  2131. $maxvisiblephotos = 1;
  2132. $showimage = 1;
  2133. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  2134. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  2135. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !$user->hasRight('barcode', 'lire_advance')) {
  2136. $showbarcode = 0;
  2137. }
  2138. $modulepart = 'unknown';
  2139. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  2140. $modulepart = $object->element;
  2141. } elseif ($object->element == 'member') {
  2142. $modulepart = 'memberphoto';
  2143. } elseif ($object->element == 'user') {
  2144. $modulepart = 'userphoto';
  2145. }
  2146. if (class_exists("Imagick")) {
  2147. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  2148. $modulepart = $object->element;
  2149. } elseif ($object->element == 'fichinter') {
  2150. $modulepart = 'ficheinter';
  2151. } elseif ($object->element == 'contrat') {
  2152. $modulepart = 'contract';
  2153. } elseif ($object->element == 'order_supplier') {
  2154. $modulepart = 'supplier_order';
  2155. } elseif ($object->element == 'invoice_supplier') {
  2156. $modulepart = 'supplier_invoice';
  2157. }
  2158. }
  2159. if ($object->element == 'product') {
  2160. $width = 80;
  2161. $cssclass = 'photowithmargin photoref';
  2162. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  2163. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  2164. if ($conf->browser->layout == 'phone') {
  2165. $maxvisiblephotos = 1;
  2166. }
  2167. if ($showimage) {
  2168. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
  2169. } else {
  2170. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  2171. $nophoto = '';
  2172. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2173. } else { // Show no photo link
  2174. $nophoto = '/public/theme/common/nophoto.png';
  2175. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" title="'.dol_escape_htmltag($langs->trans("UploadAnImageToSeeAPhotoHere", $langs->transnoentitiesnoconv("Documents"))).'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  2176. }
  2177. }
  2178. } elseif ($object->element == 'ticket') {
  2179. $width = 80;
  2180. $cssclass = 'photoref';
  2181. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  2182. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  2183. if ($conf->browser->layout == 'phone') {
  2184. $maxvisiblephotos = 1;
  2185. }
  2186. if ($showimage) {
  2187. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  2188. if ($object->nbphoto > 0) {
  2189. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  2190. } else {
  2191. $showimage = 0;
  2192. }
  2193. }
  2194. if (!$showimage) {
  2195. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  2196. $nophoto = '';
  2197. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2198. } else { // Show no photo link
  2199. $nophoto = img_picto('No photo', 'object_ticket');
  2200. $morehtmlleft .= '<!-- No photo to show -->';
  2201. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2202. $morehtmlleft .= $nophoto;
  2203. $morehtmlleft .= '</div></div>';
  2204. }
  2205. }
  2206. } else {
  2207. if ($showimage) {
  2208. if ($modulepart != 'unknown') {
  2209. $phototoshow = '';
  2210. // Check if a preview file is available
  2211. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  2212. $objectref = dol_sanitizeFileName($object->ref);
  2213. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  2214. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  2215. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  2216. $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
  2217. } else {
  2218. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  2219. }
  2220. if (empty($subdir)) {
  2221. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  2222. }
  2223. $filepath = $dir_output.$subdir."/";
  2224. $filepdf = $filepath.$objectref.".pdf";
  2225. $relativepath = $subdir.'/'.$objectref.'.pdf';
  2226. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  2227. $fileimage = $filepdf.'_preview.png';
  2228. $relativepathimage = $relativepath.'_preview.png';
  2229. $pdfexists = file_exists($filepdf);
  2230. // If PDF file exists
  2231. if ($pdfexists) {
  2232. // Conversion du PDF en image png si fichier png non existant
  2233. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  2234. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  2235. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2236. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  2237. if ($ret < 0) {
  2238. $error++;
  2239. }
  2240. }
  2241. }
  2242. }
  2243. if ($pdfexists && !$error) {
  2244. $heightforphotref = 80;
  2245. if (!empty($conf->dol_optimize_smallscreen)) {
  2246. $heightforphotref = 60;
  2247. }
  2248. // If the preview file is found
  2249. if (file_exists($fileimage)) {
  2250. $phototoshow = '<div class="photoref">';
  2251. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  2252. $phototoshow .= '</div>';
  2253. }
  2254. }
  2255. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  2256. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  2257. }
  2258. if ($phototoshow) {
  2259. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  2260. $morehtmlleft .= $phototoshow;
  2261. $morehtmlleft .= '</div>';
  2262. }
  2263. }
  2264. if (empty($phototoshow)) { // Show No photo link (picto of object)
  2265. if ($object->element == 'action') {
  2266. $width = 80;
  2267. $cssclass = 'photorefcenter';
  2268. $nophoto = img_picto('No photo', 'title_agenda');
  2269. } else {
  2270. $width = 14;
  2271. $cssclass = 'photorefcenter';
  2272. $picto = $object->picto;
  2273. $prefix = 'object_';
  2274. if ($object->element == 'project' && !$object->public) {
  2275. $picto = 'project'; // instead of projectpub
  2276. }
  2277. if (strpos($picto, 'fontawesome_') !== false) {
  2278. $prefix = '';
  2279. }
  2280. $nophoto = img_picto('No photo', $prefix.$picto);
  2281. }
  2282. $morehtmlleft .= '<!-- No photo to show -->';
  2283. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2284. $morehtmlleft .= $nophoto;
  2285. $morehtmlleft .= '</div></div>';
  2286. }
  2287. }
  2288. }
  2289. // Show barcode
  2290. if ($showbarcode) {
  2291. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
  2292. }
  2293. if ($object->element == 'societe') {
  2294. if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2295. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  2296. } else {
  2297. $morehtmlstatus .= $object->getLibStatut(6);
  2298. }
  2299. } elseif ($object->element == 'product') {
  2300. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  2301. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2302. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  2303. } else {
  2304. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  2305. }
  2306. $morehtmlstatus .= ' &nbsp; ';
  2307. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2308. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2309. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2310. } else {
  2311. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2312. }
  2313. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  2314. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2315. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2316. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2317. }
  2318. $morehtmlstatus .= $tmptxt;
  2319. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2320. if ($object->statut == 0) {
  2321. $morehtmlstatus .= $object->getLibStatut(5);
  2322. } else {
  2323. $morehtmlstatus .= $object->getLibStatut(4);
  2324. }
  2325. } elseif ($object->element == 'facturerec') {
  2326. if ($object->frequency == 0) {
  2327. $morehtmlstatus .= $object->getLibStatut(2);
  2328. } else {
  2329. $morehtmlstatus .= $object->getLibStatut(5);
  2330. }
  2331. } elseif ($object->element == 'project_task') {
  2332. $object->fk_statut = 1;
  2333. if ($object->progress > 0) {
  2334. $object->fk_statut = 2;
  2335. }
  2336. if ($object->progress >= 100) {
  2337. $object->fk_statut = 3;
  2338. }
  2339. $tmptxt = $object->getLibStatut(5);
  2340. $morehtmlstatus .= $tmptxt; // No status on task
  2341. } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
  2342. $tmptxt = $object->getLibStatut(6);
  2343. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2344. $tmptxt = $object->getLibStatut(5);
  2345. }
  2346. $morehtmlstatus .= $tmptxt;
  2347. }
  2348. // Add if object was dispatched "into accountancy"
  2349. if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2350. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2351. if (method_exists($object, 'getVentilExportCompta')) {
  2352. $accounted = $object->getVentilExportCompta();
  2353. $langs->load("accountancy");
  2354. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2355. }
  2356. }
  2357. // Add alias for thirdparty
  2358. if (!empty($object->name_alias)) {
  2359. $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
  2360. }
  2361. // Add label
  2362. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2363. if (!empty($object->label)) {
  2364. $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
  2365. }
  2366. }
  2367. // Show address and email
  2368. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2369. $moreaddress = $object->getBannerAddress('refaddress', $object);
  2370. if ($moreaddress) {
  2371. $morehtmlref .= '<div class="refidno refaddress">';
  2372. $morehtmlref .= $moreaddress;
  2373. $morehtmlref .= '</div>';
  2374. }
  2375. }
  2376. if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) {
  2377. $morehtmlref .= '<div style="clear: both;"></div>';
  2378. $morehtmlref .= '<div class="refidno opacitymedium">';
  2379. $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
  2380. $morehtmlref .= '</div>';
  2381. }
  2382. $parameters=array('morehtmlref'=>$morehtmlref);
  2383. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2384. if ($reshook < 0) {
  2385. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2386. } elseif (empty($reshook)) {
  2387. $morehtmlref .= $hookmanager->resPrint;
  2388. } elseif ($reshook > 0) {
  2389. $morehtmlref = $hookmanager->resPrint;
  2390. }
  2391. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2392. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2393. print '</div>';
  2394. print '<div class="underrefbanner clearboth"></div>';
  2395. }
  2396. /**
  2397. * Show a string with the label tag dedicated to the HTML edit field.
  2398. *
  2399. * @param string $langkey Translation key
  2400. * @param string $fieldkey Key of the html select field the text refers to
  2401. * @param int $fieldrequired 1=Field is mandatory
  2402. * @return string
  2403. * @deprecated Form::editfieldkey
  2404. */
  2405. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2406. {
  2407. global $langs;
  2408. $ret = '';
  2409. if ($fieldrequired) {
  2410. $ret .= '<span class="fieldrequired">';
  2411. }
  2412. $ret .= '<label for="'.$fieldkey.'">';
  2413. $ret .= $langs->trans($langkey);
  2414. $ret .= '</label>';
  2415. if ($fieldrequired) {
  2416. $ret .= '</span>';
  2417. }
  2418. return $ret;
  2419. }
  2420. /**
  2421. * Return string to add class property on html element with pair/impair.
  2422. *
  2423. * @param string $var 0 or 1
  2424. * @param string $moreclass More class to add
  2425. * @return string String to add class onto HTML element
  2426. */
  2427. function dol_bc($var, $moreclass = '')
  2428. {
  2429. global $bc;
  2430. $ret = ' '.$bc[$var];
  2431. if ($moreclass) {
  2432. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2433. }
  2434. return $ret;
  2435. }
  2436. /**
  2437. * Return a formated address (part address/zip/town/state) according to country rules.
  2438. * See https://en.wikipedia.org/wiki/Address
  2439. *
  2440. * @param Object $object A company or contact object
  2441. * @param int $withcountry 1=Add country into address string
  2442. * @param string $sep Separator to use to separate info when building string
  2443. * @param Translate $outputlangs Object lang that contains language for text translation.
  2444. * @param int $mode 0=Standard output, 1=Remove address
  2445. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2446. * @return string Formated string
  2447. * @see dol_print_address()
  2448. */
  2449. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2450. {
  2451. global $conf, $langs, $hookmanager;
  2452. $ret = '';
  2453. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2454. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2455. // Address
  2456. if (empty($mode)) {
  2457. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : preg_replace('/(\r\n|\r|\n)+/', $sep, $object->address)));
  2458. }
  2459. // Zip/Town/State
  2460. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2461. // US: title firstname name \n address lines \n town, state, zip \n country
  2462. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2463. $ret .= (($ret && $town) ? $sep : '').$town;
  2464. if (!empty($object->state)) {
  2465. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2466. }
  2467. if (!empty($object->zip)) {
  2468. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2469. }
  2470. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2471. // UK: title firstname name \n address lines \n town state \n zip \n country
  2472. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2473. $ret .= ($ret ? $sep : '').$town;
  2474. if (!empty($object->state)) {
  2475. $ret .= ($ret ? ", " : '').$object->state;
  2476. }
  2477. if (!empty($object->zip)) {
  2478. $ret .= ($ret ? $sep : '').$object->zip;
  2479. }
  2480. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2481. // ES: title firstname name \n address lines \n zip town \n state \n country
  2482. $ret .= ($ret ? $sep : '').$object->zip;
  2483. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2484. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2485. if (!empty($object->state)) {
  2486. $ret .= $sep.$object->state;
  2487. }
  2488. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2489. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2490. // See https://www.sljfaq.org/afaq/addresses.html
  2491. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2492. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2493. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2494. // IT: title firstname name\n address lines \n zip town state_code \n country
  2495. $ret .= ($ret ? $sep : '').$object->zip;
  2496. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2497. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2498. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2499. } else {
  2500. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2501. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2502. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2503. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2504. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2505. $ret .= ($ret ? ", " : '').$object->state;
  2506. }
  2507. }
  2508. if (!is_object($outputlangs)) {
  2509. $outputlangs = $langs;
  2510. }
  2511. if ($withcountry) {
  2512. $langs->load("dict");
  2513. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2514. }
  2515. if ($hookmanager) {
  2516. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2517. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2518. if ($reshook > 0) {
  2519. $ret = '';
  2520. }
  2521. $ret .= $hookmanager->resPrint;
  2522. }
  2523. return $ret;
  2524. }
  2525. /**
  2526. * Format a string.
  2527. *
  2528. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2529. * @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)
  2530. * @param int $is_gmt See comment of timestamp parameter
  2531. * @return string A formatted string
  2532. */
  2533. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2534. {
  2535. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2536. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2537. } else {
  2538. return 'Error date into a not supported range';
  2539. }
  2540. }
  2541. /**
  2542. * Output date in a string format according to outputlangs (or langs if not defined).
  2543. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2544. *
  2545. * @param int $time GM Timestamps date
  2546. * @param string $format Output date format (tag of strftime function)
  2547. * "%d %b %Y",
  2548. * "%d/%m/%Y %H:%M",
  2549. * "%d/%m/%Y %H:%M:%S",
  2550. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2551. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2552. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2553. * false or 'tzserver' => output string is for local PHP server TZ usage
  2554. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2555. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2556. * @param Translate $outputlangs Object lang that contains language for text translation.
  2557. * @param boolean $encodetooutput false=no convert into output pagecode
  2558. * @return string Formated date or '' if time is null
  2559. *
  2560. * @see dol_mktime(), dol_stringtotime(), dol_getdate(), selectDate()
  2561. */
  2562. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2563. {
  2564. global $conf, $langs;
  2565. // If date undefined or "", we return ""
  2566. if (dol_strlen($time) == 0) {
  2567. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2568. }
  2569. if ($tzoutput === 'auto') {
  2570. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2571. }
  2572. // Clean parameters
  2573. $to_gmt = false;
  2574. $offsettz = $offsetdst = 0;
  2575. if ($tzoutput) {
  2576. $to_gmt = true; // For backward compatibility
  2577. if (is_string($tzoutput)) {
  2578. if ($tzoutput == 'tzserver') {
  2579. $to_gmt = false;
  2580. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2581. $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
  2582. $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
  2583. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2584. $to_gmt = true;
  2585. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2586. if (class_exists('DateTimeZone')) {
  2587. $user_date_tz = new DateTimeZone($offsettzstring);
  2588. $user_dt = new DateTime();
  2589. $user_dt->setTimezone($user_date_tz);
  2590. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2591. $offsettz = $user_dt->getOffset(); // should include dst ?
  2592. } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
  2593. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2594. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2595. }
  2596. }
  2597. }
  2598. }
  2599. if (!is_object($outputlangs)) {
  2600. $outputlangs = $langs;
  2601. }
  2602. if (!$format) {
  2603. $format = 'daytextshort';
  2604. }
  2605. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2606. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2607. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
  2608. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2609. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2610. if ($formatwithoutreduce != $format) {
  2611. $format = $formatwithoutreduce;
  2612. $reduceformat = 1;
  2613. } // so format 'dayreduceformat' is processed like day
  2614. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2615. // TODO Add format daysmallyear and dayhoursmallyear
  2616. if ($format == 'day') {
  2617. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2618. } elseif ($format == 'hour') {
  2619. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2620. } elseif ($format == 'hourduration') {
  2621. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2622. } elseif ($format == 'daytext') {
  2623. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2624. } elseif ($format == 'daytextshort') {
  2625. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2626. } elseif ($format == 'dayhour') {
  2627. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2628. } elseif ($format == 'dayhoursec') {
  2629. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2630. } elseif ($format == 'dayhourtext') {
  2631. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2632. } elseif ($format == 'dayhourtextshort') {
  2633. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2634. } elseif ($format == 'dayhourlog') {
  2635. // Format not sensitive to language
  2636. $format = '%Y%m%d%H%M%S';
  2637. } elseif ($format == 'dayhourlogsmall') {
  2638. // Format not sensitive to language
  2639. $format = '%y%m%d%H%M';
  2640. } elseif ($format == 'dayhourldap') {
  2641. $format = '%Y%m%d%H%M%SZ';
  2642. } elseif ($format == 'dayhourxcard') {
  2643. $format = '%Y%m%dT%H%M%SZ';
  2644. } elseif ($format == 'dayxcard') {
  2645. $format = '%Y%m%d';
  2646. } elseif ($format == 'dayrfc') {
  2647. $format = '%Y-%m-%d'; // DATE_RFC3339
  2648. } elseif ($format == 'dayhourrfc') {
  2649. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2650. } elseif ($format == 'standard') {
  2651. $format = '%Y-%m-%d %H:%M:%S';
  2652. }
  2653. if ($reduceformat) {
  2654. $format = str_replace('%Y', '%y', $format);
  2655. $format = str_replace('yyyy', 'yy', $format);
  2656. }
  2657. // Clean format
  2658. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2659. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2660. $format = str_replace('%b', '__b__', $format);
  2661. $format = str_replace('%B', '__B__', $format);
  2662. }
  2663. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2664. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2665. $format = str_replace('%a', '__a__', $format);
  2666. $format = str_replace('%A', '__A__', $format);
  2667. }
  2668. // Analyze date
  2669. $reg = array();
  2670. 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
  2671. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]));
  2672. return '';
  2673. } 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
  2674. // This part of code should not be used anymore.
  2675. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]), LOG_WARNING);
  2676. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2677. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2678. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2679. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2680. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2681. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2682. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2683. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2684. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2685. if ($to_gmt) {
  2686. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2687. } else {
  2688. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2689. }
  2690. $dtts = new DateTime();
  2691. $dtts->setTimestamp($time);
  2692. $dtts->setTimezone($tzo);
  2693. $newformat = str_replace(
  2694. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2695. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2696. $format);
  2697. $ret = $dtts->format($newformat);
  2698. $ret = str_replace(
  2699. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2700. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2701. $ret
  2702. );
  2703. } else {
  2704. // Date is a timestamps
  2705. if ($time < 100000000000) { // Protection against bad date values
  2706. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2707. if ($to_gmt) {
  2708. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2709. } else {
  2710. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2711. }
  2712. $dtts = new DateTime();
  2713. $dtts->setTimestamp($timetouse);
  2714. $dtts->setTimezone($tzo);
  2715. $newformat = str_replace(
  2716. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2717. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2718. $format);
  2719. $ret = $dtts->format($newformat);
  2720. $ret = str_replace(
  2721. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2722. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2723. $ret
  2724. );
  2725. //var_dump($ret);exit;
  2726. } else {
  2727. $ret = 'Bad value '.$time.' for date';
  2728. }
  2729. }
  2730. if (preg_match('/__b__/i', $format)) {
  2731. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2732. if ($to_gmt) {
  2733. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2734. } else {
  2735. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2736. }
  2737. $dtts = new DateTime();
  2738. $dtts->setTimestamp($timetouse);
  2739. $dtts->setTimezone($tzo);
  2740. $month = $dtts->format("m");
  2741. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2742. if ($encodetooutput) {
  2743. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2744. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2745. } else {
  2746. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2747. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2748. }
  2749. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2750. $ret = str_replace('__b__', $monthtextshort, $ret);
  2751. $ret = str_replace('__B__', $monthtext, $ret);
  2752. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2753. //return $ret;
  2754. }
  2755. if (preg_match('/__a__/i', $format)) {
  2756. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2757. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2758. if ($to_gmt) {
  2759. $tzo = new DateTimeZone('UTC');
  2760. } else {
  2761. $tzo = new DateTimeZone(date_default_timezone_get());
  2762. }
  2763. $dtts = new DateTime();
  2764. $dtts->setTimestamp($timetouse);
  2765. $dtts->setTimezone($tzo);
  2766. $w = $dtts->format("w");
  2767. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2768. $ret = str_replace('__A__', $dayweek, $ret);
  2769. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2770. }
  2771. return $ret;
  2772. }
  2773. /**
  2774. * Return an array with locale date info.
  2775. * WARNING: This function use PHP server timezone by default to return locale informations.
  2776. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2777. *
  2778. * @param int $timestamp Timestamp
  2779. * @param boolean $fast Fast mode. deprecated.
  2780. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2781. * @return array Array of informations
  2782. * 'seconds' => $secs,
  2783. * 'minutes' => $min,
  2784. * 'hours' => $hour,
  2785. * 'mday' => $day,
  2786. * 'wday' => $dow, 0=sunday, 6=saturday
  2787. * 'mon' => $month,
  2788. * 'year' => $year,
  2789. * 'yday' => floor($secsInYear/$_day_power)
  2790. * '0' => original timestamp
  2791. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2792. */
  2793. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2794. {
  2795. if ($timestamp === '') {
  2796. return array();
  2797. }
  2798. $datetimeobj = new DateTime();
  2799. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2800. if ($forcetimezone) {
  2801. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2802. }
  2803. $arrayinfo = array(
  2804. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2805. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2806. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2807. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2808. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2809. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2810. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2811. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2812. '0'=>$timestamp
  2813. );
  2814. return $arrayinfo;
  2815. }
  2816. /**
  2817. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2818. * Replace function mktime not available under Windows if year < 1970
  2819. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2820. *
  2821. * @param int $hour Hour (can be -1 for undefined)
  2822. * @param int $minute Minute (can be -1 for undefined)
  2823. * @param int $second Second (can be -1 for undefined)
  2824. * @param int $month Month (1 to 12)
  2825. * @param int $day Day (1 to 31)
  2826. * @param int $year Year
  2827. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2828. * False or 0 or 'tzserver' = local to server TZ
  2829. * 'auto'
  2830. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2831. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user into a GMT date.
  2832. * 'tz,TimeZone' = use specified timezone
  2833. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2834. * @return int|string Date as a timestamp, '' or false if error
  2835. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2836. */
  2837. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2838. {
  2839. global $conf;
  2840. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2841. if ($gm === 'auto') {
  2842. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2843. }
  2844. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2845. // Clean parameters
  2846. if ($hour == -1 || empty($hour)) {
  2847. $hour = 0;
  2848. }
  2849. if ($minute == -1 || empty($minute)) {
  2850. $minute = 0;
  2851. }
  2852. if ($second == -1 || empty($second)) {
  2853. $second = 0;
  2854. }
  2855. // Check parameters
  2856. if ($check) {
  2857. if (!$month || !$day) {
  2858. return '';
  2859. }
  2860. if ($day > 31) {
  2861. return '';
  2862. }
  2863. if ($month > 12) {
  2864. return '';
  2865. }
  2866. if ($hour < 0 || $hour > 24) {
  2867. return '';
  2868. }
  2869. if ($minute < 0 || $minute > 60) {
  2870. return '';
  2871. }
  2872. if ($second < 0 || $second > 60) {
  2873. return '';
  2874. }
  2875. }
  2876. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2877. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2878. $localtz = new DateTimeZone($default_timezone);
  2879. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2880. // We use dol_tz_string first because it is more reliable.
  2881. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2882. try {
  2883. $localtz = new DateTimeZone($default_timezone);
  2884. } catch (Exception $e) {
  2885. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2886. $default_timezone = @date_default_timezone_get();
  2887. }
  2888. } elseif (strrpos($gm, "tz,") !== false) {
  2889. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2890. try {
  2891. $localtz = new DateTimeZone($timezone);
  2892. } catch (Exception $e) {
  2893. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2894. }
  2895. }
  2896. if (empty($localtz)) {
  2897. $localtz = new DateTimeZone('UTC');
  2898. }
  2899. //var_dump($localtz);
  2900. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2901. $dt = new DateTime('now', $localtz);
  2902. $dt->setDate((int) $year, (int) $month, (int) $day);
  2903. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2904. $date = $dt->getTimestamp(); // should include daylight saving time
  2905. //var_dump($date);
  2906. return $date;
  2907. }
  2908. /**
  2909. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2910. *
  2911. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2912. * 'gmt' => we return GMT timestamp,
  2913. * 'tzserver' => we add the PHP server timezone
  2914. * 'tzref' => we add the company timezone. Not implemented.
  2915. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2916. * @return int $date Timestamp
  2917. */
  2918. function dol_now($mode = 'auto')
  2919. {
  2920. $ret = 0;
  2921. if ($mode === 'auto') {
  2922. $mode = 'gmt';
  2923. }
  2924. if ($mode == 'gmt') {
  2925. $ret = time(); // Time for now at greenwich.
  2926. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2927. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2928. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2929. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2930. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2931. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2932. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2933. // $ret=dol_now('gmt')+($tzsecond*3600);
  2934. //}
  2935. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2936. // Time for now with user timezone added
  2937. //print 'time: '.time();
  2938. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2939. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2940. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2941. }
  2942. return $ret;
  2943. }
  2944. /**
  2945. * Return string with formated size
  2946. *
  2947. * @param int $size Size to print
  2948. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2949. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2950. * @return string Link
  2951. */
  2952. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2953. {
  2954. global $conf, $langs;
  2955. $level = 1024;
  2956. if (!empty($conf->dol_optimize_smallscreen)) {
  2957. $shortunit = 1;
  2958. }
  2959. // Set value text
  2960. if (empty($shortvalue) || $size < ($level * 10)) {
  2961. $ret = $size;
  2962. $textunitshort = $langs->trans("b");
  2963. $textunitlong = $langs->trans("Bytes");
  2964. } else {
  2965. $ret = round($size / $level, 0);
  2966. $textunitshort = $langs->trans("Kb");
  2967. $textunitlong = $langs->trans("KiloBytes");
  2968. }
  2969. // Use long or short text unit
  2970. if (empty($shortunit)) {
  2971. $ret .= ' '.$textunitlong;
  2972. } else {
  2973. $ret .= ' '.$textunitshort;
  2974. }
  2975. return $ret;
  2976. }
  2977. /**
  2978. * Show Url link
  2979. *
  2980. * @param string $url Url to show
  2981. * @param string $target Target for link
  2982. * @param int $max Max number of characters to show
  2983. * @param int $withpicto With picto
  2984. * @param string $morecss More CSS
  2985. * @return string HTML Link
  2986. */
  2987. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
  2988. {
  2989. global $langs;
  2990. if (empty($url)) {
  2991. return '';
  2992. }
  2993. $linkstart = '<a href="';
  2994. if (!preg_match('/^http/i', $url)) {
  2995. $linkstart .= 'http://';
  2996. }
  2997. $linkstart .= $url;
  2998. $linkstart .= '"';
  2999. if ($target) {
  3000. $linkstart .= ' target="'.$target.'"';
  3001. }
  3002. $linkstart .= ' title="'.$langs->trans("URL").': '.$url.'"';
  3003. $linkstart .= '>';
  3004. $link = '';
  3005. if (!preg_match('/^http/i', $url)) {
  3006. $link .= 'http://';
  3007. }
  3008. $link .= dol_trunc($url, $max);
  3009. $linkend = '</a>';
  3010. if ($morecss == 'float') { // deprecated
  3011. return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  3012. } else {
  3013. return $linkstart.'<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto('', 'globe').' ' : '').$link.'</span>'.$linkend;
  3014. }
  3015. }
  3016. /**
  3017. * Show EMail link formatted for HTML output.
  3018. *
  3019. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  3020. * @param int $cid Id of contact if known
  3021. * @param int $socid Id of third party if known
  3022. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  3023. * @param int $max Max number of characters to show
  3024. * @param int $showinvalid 1=Show warning if syntax email is wrong
  3025. * @param int|string $withpicto Show picto
  3026. * @return string HTML Link
  3027. */
  3028. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  3029. {
  3030. global $conf, $user, $langs, $hookmanager;
  3031. $newemail = dol_escape_htmltag($email);
  3032. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  3033. $withpicto = 0;
  3034. }
  3035. if (empty($email)) {
  3036. return '&nbsp;';
  3037. }
  3038. if (!empty($addlink)) {
  3039. $newemail = '<a style="text-overflow: ellipsis;" href="';
  3040. if (!preg_match('/^mailto:/i', $email)) {
  3041. $newemail .= 'mailto:';
  3042. }
  3043. $newemail .= $email;
  3044. $newemail .= '">';
  3045. $newemail .= dol_trunc($email, $max);
  3046. $newemail .= '</a>';
  3047. if ($showinvalid && !isValidEmail($email)) {
  3048. $langs->load("errors");
  3049. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  3050. }
  3051. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3052. $type = 'AC_EMAIL';
  3053. $link = '';
  3054. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  3055. $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>';
  3056. }
  3057. if ($link) {
  3058. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  3059. }
  3060. }
  3061. } else {
  3062. if ($showinvalid && !isValidEmail($email)) {
  3063. $langs->load("errors");
  3064. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  3065. }
  3066. }
  3067. //$rep = '<div class="nospan" style="margin-right: 10px">';
  3068. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  3069. //$rep .= '</div>';
  3070. if ($hookmanager) {
  3071. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  3072. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  3073. if ($reshook > 0) {
  3074. $rep = '';
  3075. }
  3076. $rep .= $hookmanager->resPrint;
  3077. }
  3078. return $rep;
  3079. }
  3080. /**
  3081. * Get array of social network dictionary
  3082. *
  3083. * @return array Array of Social Networks Dictionary
  3084. */
  3085. function getArrayOfSocialNetworks()
  3086. {
  3087. global $conf, $db;
  3088. $socialnetworks = array();
  3089. // Enable caching of array
  3090. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  3091. $cachekey = 'socialnetworks_' . $conf->entity;
  3092. $dataretrieved = dol_getcache($cachekey);
  3093. if (!is_null($dataretrieved)) {
  3094. $socialnetworks = $dataretrieved;
  3095. } else {
  3096. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  3097. $sql .= " WHERE entity=".$conf->entity;
  3098. $resql = $db->query($sql);
  3099. if ($resql) {
  3100. while ($obj = $db->fetch_object($resql)) {
  3101. $socialnetworks[$obj->code] = array(
  3102. 'rowid' => $obj->rowid,
  3103. 'label' => $obj->label,
  3104. 'url' => $obj->url,
  3105. 'icon' => $obj->icon,
  3106. 'active' => $obj->active,
  3107. );
  3108. }
  3109. }
  3110. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  3111. }
  3112. return $socialnetworks;
  3113. }
  3114. /**
  3115. * Show social network link
  3116. *
  3117. * @param string $value Social network ID to show (only skype, without 'Name of recipient' before)
  3118. * @param int $cid Id of contact if known
  3119. * @param int $socid Id of third party if known
  3120. * @param string $type 'skype','facebook',...
  3121. * @param array $dictsocialnetworks List of socialnetworks availables
  3122. * @return string HTML Link
  3123. */
  3124. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  3125. {
  3126. global $conf, $user, $langs;
  3127. $htmllink = $value;
  3128. if (empty($value)) {
  3129. return '&nbsp;';
  3130. }
  3131. if (!empty($type)) {
  3132. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  3133. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  3134. $htmllink .= '<span class="fab pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  3135. if ($type == 'skype') {
  3136. $htmllink .= dol_escape_htmltag($value);
  3137. $htmllink .= '&nbsp; <a href="skype:';
  3138. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3139. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  3140. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  3141. $htmllink .= '</a><a href="skype:';
  3142. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3143. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  3144. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  3145. $htmllink .= '</a>';
  3146. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
  3147. $addlink = 'AC_SKYPE';
  3148. $link = '';
  3149. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  3150. $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>';
  3151. }
  3152. $htmllink .= ($link ? ' '.$link : '');
  3153. }
  3154. } else {
  3155. if (!empty($dictsocialnetworks[$type]['url'])) {
  3156. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  3157. if ($tmpvirginurl) {
  3158. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3159. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3160. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  3161. if ($tmpvirginurl3) {
  3162. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3163. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3164. }
  3165. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  3166. if ($tmpvirginurl2) {
  3167. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3168. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3169. }
  3170. }
  3171. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  3172. if (preg_match('/^https?:\/\//i', $link)) {
  3173. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3174. } else {
  3175. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3176. }
  3177. } else {
  3178. $htmllink .= dol_escape_htmltag($value);
  3179. }
  3180. }
  3181. $htmllink .= '</div>';
  3182. } else {
  3183. $langs->load("errors");
  3184. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  3185. }
  3186. return $htmllink;
  3187. }
  3188. /**
  3189. * Format professional IDs according to their country
  3190. *
  3191. * @param string $profID Value of profID to format
  3192. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  3193. * @param string $countrycode Country code to use for formatting
  3194. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  3195. * @return string Formated profID
  3196. */
  3197. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
  3198. {
  3199. global $mysoc;
  3200. if (empty($profID) || empty($profIDtype)) {
  3201. return '';
  3202. }
  3203. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  3204. $newProfID = $profID;
  3205. $id = substr($profIDtype, -1);
  3206. $ret = '';
  3207. if (strtoupper($countrycode) == 'FR') {
  3208. // France
  3209. // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
  3210. if ($id == 1 && dol_strlen($newProfID) == 9) {
  3211. // SIREN (ex: 123 123 123)
  3212. $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3);
  3213. }
  3214. if ($id == 2 && dol_strlen($newProfID) == 14) {
  3215. // SIRET (ex: 123 123 123 12345)
  3216. $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3).' '.substr($newProfID, 9, 5);
  3217. }
  3218. if ($id == 3 && dol_strlen($newProfID) == 5) {
  3219. // NAF/APE (ex: 69.20Z)
  3220. $newProfID = substr($newProfID, 0, 2).'.'.substr($newProfID, 2, 3);
  3221. }
  3222. if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
  3223. // TVA intracommunautaire (ex: FR12 123 123 123)
  3224. $newProfID = substr($newProfID, 0, 4).' '.substr($newProfID, 4, 3).' '.substr($newProfID, 7, 3).' '.substr($newProfID, 10, 3);
  3225. }
  3226. }
  3227. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  3228. else $ret = $newProfID;
  3229. return $ret;
  3230. }
  3231. /**
  3232. * Format phone numbers according to country
  3233. *
  3234. * @param string $phone Phone number to format
  3235. * @param string $countrycode Country code to use for formatting
  3236. * @param int $cid Id of contact if known
  3237. * @param int $socid Id of third party if known
  3238. * @param string $addlink ''=no link to create action, 'AC_TEL'=add link to clicktodial (if module enabled) and add link to create event (if conf->global->AGENDA_ADDACTIONFORPHONE set), 'tel'=Force "tel:..." link
  3239. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx. You can also use 'hidenum' to hide the number, keep only the picto.
  3240. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  3241. * @param string $titlealt Text to show on alt
  3242. * @param int $adddivfloat Add div float around phone.
  3243. * @return string Formated phone number
  3244. */
  3245. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  3246. {
  3247. global $conf, $user, $langs, $mysoc, $hookmanager;
  3248. // Clean phone parameter
  3249. $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
  3250. if (empty($phone)) {
  3251. return '';
  3252. }
  3253. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  3254. $separ = $conf->global->MAIN_PHONE_SEPAR;
  3255. }
  3256. if (empty($countrycode) && is_object($mysoc)) {
  3257. $countrycode = $mysoc->country_code;
  3258. }
  3259. // Short format for small screens
  3260. if ($conf->dol_optimize_smallscreen) {
  3261. $separ = '';
  3262. }
  3263. $newphone = $phone;
  3264. if (strtoupper($countrycode) == "FR") {
  3265. // France
  3266. if (dol_strlen($phone) == 10) {
  3267. $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);
  3268. } elseif (dol_strlen($phone) == 7) {
  3269. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  3270. } elseif (dol_strlen($phone) == 9) {
  3271. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  3272. } elseif (dol_strlen($phone) == 11) {
  3273. $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);
  3274. } elseif (dol_strlen($phone) == 12) {
  3275. $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);
  3276. } elseif (dol_strlen($phone) == 13) {
  3277. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  3278. }
  3279. } elseif (strtoupper($countrycode) == "CA") {
  3280. if (dol_strlen($phone) == 10) {
  3281. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  3282. }
  3283. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  3284. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  3285. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3286. }
  3287. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  3288. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  3289. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  3290. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  3291. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  3292. }
  3293. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  3294. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  3295. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  3296. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  3297. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  3298. }
  3299. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  3300. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  3301. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3302. }
  3303. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  3304. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  3305. $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);
  3306. }
  3307. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  3308. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  3309. $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);
  3310. }
  3311. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  3312. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  3313. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3314. }
  3315. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  3316. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  3317. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3318. }
  3319. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  3320. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  3321. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3322. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  3323. $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);
  3324. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  3325. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3326. }
  3327. } elseif (strtoupper($countrycode) == "ML") {//Mali
  3328. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  3329. $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);
  3330. }
  3331. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  3332. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  3333. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3334. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  3335. $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);
  3336. }
  3337. } elseif (strtoupper($countrycode) == "MU") {
  3338. //Maurice
  3339. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  3340. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  3341. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  3342. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  3343. }
  3344. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  3345. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  3346. $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);
  3347. }
  3348. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  3349. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  3350. $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);
  3351. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  3352. $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);
  3353. }
  3354. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  3355. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  3356. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3357. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  3358. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3359. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  3360. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  3361. }
  3362. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  3363. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  3364. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3365. }
  3366. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  3367. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  3368. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3369. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  3370. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3371. }
  3372. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  3373. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  3374. $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);
  3375. }
  3376. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  3377. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  3378. $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);
  3379. }
  3380. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3381. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3382. $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);
  3383. }
  3384. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3385. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3386. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3387. }
  3388. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3389. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
  3390. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  3391. }
  3392. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3393. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3394. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3395. }
  3396. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3397. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3398. $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);
  3399. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3400. $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);
  3401. }
  3402. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3403. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3404. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3405. }
  3406. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3407. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3408. $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);
  3409. }
  3410. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3411. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3412. $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);
  3413. }
  3414. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3415. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3416. $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);
  3417. }
  3418. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3419. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3420. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3421. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3422. $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);
  3423. }
  3424. } elseif (strtoupper($countrycode) == "AU") {
  3425. //Australie
  3426. if (dol_strlen($phone) == 12) {
  3427. //ex: +61_A_BCDE_FGHI
  3428. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3429. }
  3430. } elseif (strtoupper($countrycode) == "LU") {
  3431. // Luxembourg
  3432. if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
  3433. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
  3434. } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
  3435. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 1);
  3436. } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
  3437. $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);
  3438. } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
  3439. $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);
  3440. }
  3441. }
  3442. $newphoneastart = $newphoneaend = '';
  3443. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3444. if ($addlink == 'tel' || $conf->browser->layout == 'phone' || (isModEnabled('clicktodial') && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) { // If phone or option for, we use link of phone
  3445. $newphoneastart = '<a href="tel:'.$phone.'">';
  3446. $newphoneaend .= '</a>';
  3447. } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3448. if (empty($user->clicktodial_loaded)) {
  3449. $user->fetch_clicktodial();
  3450. }
  3451. // Define urlmask
  3452. $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
  3453. if (!empty($user->clicktodial_url)) {
  3454. $urlmask = $user->clicktodial_url;
  3455. }
  3456. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  3457. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  3458. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  3459. // This line is for backward compatibility
  3460. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3461. // Thoose lines are for substitution
  3462. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3463. '__PHONETO__'=>urlencode($phone),
  3464. '__LOGIN__'=>$clicktodial_login,
  3465. '__PASS__'=>$clicktodial_password);
  3466. $url = make_substitutions($url, $substitarray);
  3467. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  3468. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3469. $newphoneastart = '<a href="'.$url.'" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3470. $newphoneaend = '</a>';
  3471. } else {
  3472. // Old method
  3473. $newphoneastart = '<a href="'.$url.'"';
  3474. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  3475. $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
  3476. }
  3477. $newphoneastart .= '>';
  3478. $newphoneaend .= '</a>';
  3479. }
  3480. }
  3481. //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
  3482. if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3483. $type = 'AC_TEL';
  3484. $addlinktoagenda = '';
  3485. if ($addlink == 'AC_FAX') {
  3486. $type = 'AC_FAX';
  3487. }
  3488. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  3489. $addlinktoagenda = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage='. urlencode($_SERVER['REQUEST_URI']) .'&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  3490. }
  3491. if ($addlinktoagenda) {
  3492. $newphone = '<span>'.$newphone.' '.$addlinktoagenda.'</span>';
  3493. }
  3494. }
  3495. }
  3496. if (empty($titlealt)) {
  3497. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3498. }
  3499. $rep = '';
  3500. if ($hookmanager) {
  3501. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3502. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3503. $rep .= $hookmanager->resPrint;
  3504. }
  3505. if (empty($reshook)) {
  3506. $picto = '';
  3507. if ($withpicto) {
  3508. if ($withpicto == 'fax') {
  3509. $picto = 'phoning_fax';
  3510. } elseif ($withpicto == 'phone') {
  3511. $picto = 'phoning';
  3512. } elseif ($withpicto == 'mobile') {
  3513. $picto = 'phoning_mobile';
  3514. } else {
  3515. $picto = '';
  3516. }
  3517. }
  3518. if ($adddivfloat == 1) {
  3519. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3520. } elseif (empty($adddivfloat)) {
  3521. $rep .= '<span style="margin-right: 10px;">';
  3522. }
  3523. $rep .= $newphoneastart;
  3524. $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png') : '');
  3525. if ($separ != 'hidenum') {
  3526. $rep .= ($withpicto ? ' ' : '').$newphone;
  3527. }
  3528. $rep .= $newphoneaend;
  3529. if ($adddivfloat == 1) {
  3530. $rep .= '</div>';
  3531. } elseif (empty($adddivfloat)) {
  3532. $rep .= '</span>';
  3533. }
  3534. }
  3535. return $rep;
  3536. }
  3537. /**
  3538. * Return an IP formated to be shown on screen
  3539. *
  3540. * @param string $ip IP
  3541. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3542. * @return string Formated IP, with country if GeoIP module is enabled
  3543. */
  3544. function dol_print_ip($ip, $mode = 0)
  3545. {
  3546. global $langs;
  3547. $ret = '';
  3548. if (empty($mode)) {
  3549. $ret .= $ip;
  3550. }
  3551. if ($mode != 2) {
  3552. $countrycode = dolGetCountryCodeFromIp($ip);
  3553. if ($countrycode) { // If success, countrycode is us, fr, ...
  3554. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3555. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3556. } else {
  3557. $ret .= ' ('.$countrycode.')';
  3558. }
  3559. } else {
  3560. // Nothing
  3561. }
  3562. }
  3563. return $ret;
  3564. }
  3565. /**
  3566. * Return the IP of remote user.
  3567. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3568. * Then HTTP_CLIENT_IP if defined (rare)
  3569. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3570. *
  3571. * @return string Ip of remote user.
  3572. */
  3573. function getUserRemoteIP()
  3574. {
  3575. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3576. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3577. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3578. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3579. } else {
  3580. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3581. }
  3582. } else {
  3583. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3584. }
  3585. } else {
  3586. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3587. }
  3588. return $ip;
  3589. }
  3590. /**
  3591. * Return if we are using a HTTPS connexion
  3592. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3593. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3594. * Then HTTP_X_FORWARDED_SSL
  3595. *
  3596. * @return boolean True if user is using HTTPS
  3597. */
  3598. function isHTTPS()
  3599. {
  3600. $isSecure = false;
  3601. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3602. $isSecure = true;
  3603. } 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') {
  3604. $isSecure = true;
  3605. }
  3606. return $isSecure;
  3607. }
  3608. /**
  3609. * Return a country code from IP. Empty string if not found.
  3610. *
  3611. * @param string $ip IP
  3612. * @return string Country code ('us', 'fr', ...)
  3613. */
  3614. function dolGetCountryCodeFromIp($ip)
  3615. {
  3616. global $conf;
  3617. $countrycode = '';
  3618. if (!empty($conf->geoipmaxmind->enabled)) {
  3619. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3620. //$ip='24.24.24.24';
  3621. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3622. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3623. $geoip = new DolGeoIP('country', $datafile);
  3624. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3625. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3626. }
  3627. return $countrycode;
  3628. }
  3629. /**
  3630. * Return country code for current user.
  3631. * If software is used inside a local network, detection may fails (we need a public ip)
  3632. *
  3633. * @return string Country code (fr, es, it, us, ...)
  3634. */
  3635. function dol_user_country()
  3636. {
  3637. global $conf, $langs, $user;
  3638. //$ret=$user->xxx;
  3639. $ret = '';
  3640. if (!empty($conf->geoipmaxmind->enabled)) {
  3641. $ip = getUserRemoteIP();
  3642. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3643. //$ip='24.24.24.24';
  3644. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3645. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3646. $geoip = new DolGeoIP('country', $datafile);
  3647. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3648. $ret = $countrycode;
  3649. }
  3650. return $ret;
  3651. }
  3652. /**
  3653. * Format address string
  3654. *
  3655. * @param string $address Address string, already formatted with dol_format_address()
  3656. * @param int $htmlid Html ID (for example 'gmap')
  3657. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3658. * @param int $id Id of object
  3659. * @param int $noprint No output. Result is the function return
  3660. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3661. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3662. * @see dol_format_address()
  3663. */
  3664. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3665. {
  3666. global $conf, $user, $langs, $hookmanager;
  3667. $out = '';
  3668. if ($address) {
  3669. if ($hookmanager) {
  3670. $parameters = array('element' => $element, 'id' => $id);
  3671. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3672. $out .= $hookmanager->resPrint;
  3673. }
  3674. if (empty($reshook)) {
  3675. if (empty($charfornl)) {
  3676. $out .= nl2br($address);
  3677. } else {
  3678. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3679. }
  3680. // TODO Remove this block, we can add this using the hook now
  3681. $showgmap = $showomap = 0;
  3682. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3683. $showgmap = 1;
  3684. }
  3685. if ($element == 'contact' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3686. $showgmap = 1;
  3687. }
  3688. if ($element == 'member' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3689. $showgmap = 1;
  3690. }
  3691. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3692. $showomap = 1;
  3693. }
  3694. if ($element == 'contact' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3695. $showomap = 1;
  3696. }
  3697. if ($element == 'member' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3698. $showomap = 1;
  3699. }
  3700. if ($showgmap) {
  3701. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3702. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3703. }
  3704. if ($showomap) {
  3705. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3706. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3707. }
  3708. }
  3709. }
  3710. if ($noprint) {
  3711. return $out;
  3712. } else {
  3713. print $out;
  3714. }
  3715. }
  3716. /**
  3717. * Return true if email syntax is ok.
  3718. *
  3719. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3720. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3721. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3722. * @return boolean true if email syntax is OK, false if KO or empty string
  3723. * @see isValidMXRecord()
  3724. */
  3725. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3726. {
  3727. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3728. return true;
  3729. }
  3730. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3731. return true;
  3732. }
  3733. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3734. return true;
  3735. }
  3736. return false;
  3737. }
  3738. /**
  3739. * Return if the domain name has a valid MX record.
  3740. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3741. *
  3742. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3743. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3744. * @see isValidEmail()
  3745. */
  3746. function isValidMXRecord($domain)
  3747. {
  3748. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3749. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3750. return 0;
  3751. }
  3752. if (function_exists('getmxrr')) {
  3753. $mxhosts = array();
  3754. $weight = array();
  3755. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3756. if (count($mxhosts) > 1) {
  3757. return 1;
  3758. }
  3759. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3760. return 1;
  3761. }
  3762. return 0;
  3763. }
  3764. }
  3765. // function idn_to_ascii or checkdnsrr or getmxrr does not exists
  3766. return -1;
  3767. }
  3768. /**
  3769. * Return true if phone number syntax is ok
  3770. * TODO Decide what to do with this
  3771. *
  3772. * @param string $phone phone (Ex: "0601010101")
  3773. * @return boolean true if phone syntax is OK, false if KO or empty string
  3774. */
  3775. function isValidPhone($phone)
  3776. {
  3777. return true;
  3778. }
  3779. /**
  3780. * Return first letters of a strings.
  3781. * Example with nbofchar=1: 'ghi' will return 'g' but 'abc def' will return 'ad'
  3782. * Example with nbofchar=2: 'ghi' will return 'gh' but 'abc def' will return 'abde'
  3783. *
  3784. * @param string $s String to truncate
  3785. * @param int $nbofchar Nb of characters to keep
  3786. * @return string Return first chars.
  3787. */
  3788. function dolGetFirstLetters($s, $nbofchar = 1)
  3789. {
  3790. $ret = '';
  3791. $tmparray = explode(' ', $s);
  3792. foreach ($tmparray as $tmps) {
  3793. $ret .= dol_substr($tmps, 0, $nbofchar);
  3794. }
  3795. return $ret;
  3796. }
  3797. /**
  3798. * Make a strlen call. Works even if mbstring module not enabled
  3799. *
  3800. * @param string $string String to calculate length
  3801. * @param string $stringencoding Encoding of string
  3802. * @return int Length of string
  3803. */
  3804. function dol_strlen($string, $stringencoding = 'UTF-8')
  3805. {
  3806. if (is_null($string)) {
  3807. return 0;
  3808. }
  3809. if (function_exists('mb_strlen')) {
  3810. return mb_strlen($string, $stringencoding);
  3811. } else {
  3812. return strlen($string);
  3813. }
  3814. }
  3815. /**
  3816. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3817. *
  3818. * @param string $string String to scan
  3819. * @param string $start Start position
  3820. * @param int|null $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3821. * @param string $stringencoding Page code used for input string encoding
  3822. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3823. * @return string substring
  3824. */
  3825. function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
  3826. {
  3827. global $langs;
  3828. if (empty($stringencoding)) {
  3829. $stringencoding = $langs->charset_output;
  3830. }
  3831. $ret = '';
  3832. if (empty($trunconbytes)) {
  3833. if (function_exists('mb_substr')) {
  3834. $ret = mb_substr($string, $start, $length, $stringencoding);
  3835. } else {
  3836. $ret = substr($string, $start, $length);
  3837. }
  3838. } else {
  3839. if (function_exists('mb_strcut')) {
  3840. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3841. } else {
  3842. $ret = substr($string, $start, $length);
  3843. }
  3844. }
  3845. return $ret;
  3846. }
  3847. /**
  3848. * Truncate a string to a particular length adding '…' if string larger than length.
  3849. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3850. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3851. *
  3852. * @param string $string String to truncate
  3853. * @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 ...)
  3854. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3855. * @param string $stringencoding Tell what is source string encoding
  3856. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3857. * @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)
  3858. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3859. */
  3860. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3861. {
  3862. global $conf;
  3863. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3864. return $string;
  3865. }
  3866. if (empty($stringencoding)) {
  3867. $stringencoding = 'UTF-8';
  3868. }
  3869. // reduce for small screen
  3870. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3871. $size = round($size / 3);
  3872. }
  3873. // We go always here
  3874. if ($trunc == 'right') {
  3875. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3876. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3877. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3878. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3879. } else {
  3880. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3881. return $string;
  3882. }
  3883. } elseif ($trunc == 'middle') {
  3884. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3885. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3886. $size1 = round($size / 2);
  3887. $size2 = round($size / 2);
  3888. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3889. } else {
  3890. return $string;
  3891. }
  3892. } elseif ($trunc == 'left') {
  3893. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3894. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3895. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3896. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3897. } else {
  3898. return $string;
  3899. }
  3900. } elseif ($trunc == 'wrap') {
  3901. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3902. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3903. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3904. } else {
  3905. return $string;
  3906. }
  3907. } else {
  3908. return 'BadParam3CallingDolTrunc';
  3909. }
  3910. }
  3911. /**
  3912. * Return the picto for a data type
  3913. *
  3914. * @param string $key Key
  3915. * @return string Pïcto for the key
  3916. */
  3917. function getPictoForType($key)
  3918. {
  3919. // Set array with type -> picto
  3920. $type2picto = array(
  3921. 'varchar'=>'font',
  3922. 'text'=>'font',
  3923. 'html'=>'code',
  3924. 'int'=>'sort-numeric-down',
  3925. 'double'=>'sort-numeric-down',
  3926. 'price'=>'currency',
  3927. 'pricecy'=>'multicurrency',
  3928. 'password' => 'key',
  3929. 'boolean'=>'check-square',
  3930. 'date'=>'calendar',
  3931. 'datetime'=>'calendar',
  3932. 'phone'=> 'phone',
  3933. 'mail'=> 'email',
  3934. 'url'=> 'url',
  3935. 'ip'=> 'country',
  3936. 'select' => 'list',
  3937. 'sellist' => 'list',
  3938. 'radio' => 'check-circle',
  3939. 'checkbox' => 'check-square',
  3940. 'chkbxlst' => 'check-square',
  3941. 'link' => 'link',
  3942. 'separate'=> 'minus'
  3943. );
  3944. if (!empty($type2picto[$key])) {
  3945. return img_picto('', $type2picto[$key], 'class="pictofixedwidth"');
  3946. }
  3947. return img_picto('', 'generic', 'class="pictofixedwidth"');
  3948. }
  3949. /**
  3950. * Show picto whatever it's its name (generic function)
  3951. *
  3952. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3953. * @param string $picto Name of image file to show ('filenew', ...).
  3954. * For font awesome icon (example 'user'), you can use picto_nocolor to not have the color of picto forced.
  3955. * If no extension provided and it is not a font awesome icon, we use '.png'. Image must be stored into theme/xxx/img directory.
  3956. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3957. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3958. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3959. * Example: fontawesome_envelope-open-text_fas_red_1em if you want to use fontaweseome icons: fontawesome_<icon-name>_<style>_<color>_<size> (only icon-name is mandatory)
  3960. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3961. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3962. * @param int $srconly Return only content of the src attribute of img.
  3963. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3964. * @param string $alt Force alt for bind people
  3965. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3966. * @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.
  3967. * @return string Return img tag
  3968. * @see img_object(), img_picto_common()
  3969. */
  3970. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3971. {
  3972. global $conf, $langs;
  3973. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3974. $url = DOL_URL_ROOT;
  3975. $theme = isset($conf->theme) ? $conf->theme : null;
  3976. $path = 'theme/'.$theme;
  3977. if (empty($picto)) {
  3978. $picto = 'generic';
  3979. }
  3980. // Define fullpathpicto to use into src
  3981. if ($pictoisfullpath) {
  3982. // Clean parameters
  3983. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3984. $picto .= '.png';
  3985. }
  3986. $fullpathpicto = $picto;
  3987. $reg = array();
  3988. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3989. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3990. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3991. }
  3992. } else {
  3993. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', (is_null($picto) ? '' : $picto));
  3994. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3995. $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
  3996. if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
  3997. // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
  3998. $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
  3999. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  4000. // Compatibility with old fontawesome versions
  4001. if ($pictowithouttext == 'file-o') {
  4002. $pictowithouttext = 'file';
  4003. }
  4004. $pictowithouttextarray = explode('_', $pictowithouttext);
  4005. $marginleftonlyshort = 0;
  4006. if (!empty($pictowithouttextarray[1])) {
  4007. // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
  4008. $fakey = 'fa-'.$pictowithouttextarray[0];
  4009. $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
  4010. $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
  4011. $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  4012. } else {
  4013. $fakey = 'fa-'.$pictowithouttext;
  4014. $faprefix = 'fas';
  4015. $facolor = '';
  4016. $fasize = '';
  4017. }
  4018. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  4019. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  4020. $morestyle = '';
  4021. $reg = array();
  4022. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4023. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4024. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4025. }
  4026. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  4027. $morestyle = $reg[1];
  4028. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  4029. }
  4030. $moreatt = trim($moreatt);
  4031. $enabledisablehtml = '<span class="'.$faprefix.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  4032. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  4033. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4034. $enabledisablehtml .= $titlealt;
  4035. }*/
  4036. $enabledisablehtml .= '</span>';
  4037. return $enabledisablehtml;
  4038. }
  4039. if (empty($srconly) && in_array($pictowithouttext, array(
  4040. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  4041. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  4042. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  4043. 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  4044. 'cash-register', 'category', 'chart', 'check', 'clock', 'clone', 'close_title', 'code', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
  4045. 'check-circle', 'check-square', 'currency', 'multicurrency',
  4046. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  4047. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  4048. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
  4049. 'filter', 'file', 'file-o', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus', 'font',
  4050. 'gears', 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  4051. 'hands-helping', 'help', 'holiday',
  4052. 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
  4053. 'key', 'knowledgemanagement',
  4054. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
  4055. 'margin', 'map-marker-alt', 'member', 'meeting', 'minus', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  4056. 'off', 'on', 'order',
  4057. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
  4058. 'stock', 'resize', 'service', 'stats', 'trip',
  4059. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_warning', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
  4060. 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  4061. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  4062. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  4063. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  4064. 'technic', 'ticket',
  4065. 'error', 'warning',
  4066. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
  4067. 'shapes', 'skill', 'square', 'sort-numeric-down', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  4068. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  4069. 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
  4070. 'conferenceorbooth', 'eventorganization',
  4071. 'stamp', 'signature'
  4072. ))) {
  4073. $fakey = $pictowithouttext;
  4074. $facolor = '';
  4075. $fasize = '';
  4076. $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
  4077. if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'file', 'file-o', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  4078. $fa = 'far';
  4079. }
  4080. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  4081. $fa = 'fab';
  4082. }
  4083. $arrayconvpictotofa = array(
  4084. 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  4085. 'bank_account'=>'university',
  4086. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  4087. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  4088. 'bom'=>'shapes',
  4089. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time', 'cross'=>'times',
  4090. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  4091. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  4092. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  4093. 'file-o'=>'file', 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  4094. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  4095. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  4096. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  4097. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  4098. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'jobprofile'=>'cogs',
  4099. 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  4100. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  4101. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  4102. 'sign-out'=>'sign-out-alt',
  4103. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_warning'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  4104. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  4105. 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  4106. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'order'=>'file-invoice',
  4107. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  4108. 'other'=>'square',
  4109. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'proposal'=>'file-signature',
  4110. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'pictoconfirm'=>'check-square', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
  4111. 'recent' => 'check-square', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  4112. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  4113. 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
  4114. 'service'=>'concierge-bell',
  4115. 'skill'=>'shapes', 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  4116. 'supplier'=>'building', 'technic'=>'cogs',
  4117. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  4118. 'title_agenda'=>'calendar-alt',
  4119. 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'arrow-alt-circle-down',
  4120. 'jabber'=>'comment-o',
  4121. 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
  4122. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  4123. );
  4124. if ($conf->currency == 'EUR') {
  4125. $arrayconvpictotofa['currency'] = 'euro-sign';
  4126. $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
  4127. } else {
  4128. $arrayconvpictotofa['currency'] = 'dollar-sign';
  4129. $arrayconvpictotofa['multicurrency'] = 'euro-sign';
  4130. }
  4131. if ($pictowithouttext == 'off') {
  4132. $fakey = 'fa-square';
  4133. $fasize = '1.3em';
  4134. } elseif ($pictowithouttext == 'on') {
  4135. $fakey = 'fa-check-square';
  4136. $fasize = '1.3em';
  4137. } elseif ($pictowithouttext == 'listlight') {
  4138. $fakey = 'fa-download';
  4139. $marginleftonlyshort = 1;
  4140. } elseif ($pictowithouttext == 'printer') {
  4141. $fakey = 'fa-print';
  4142. $fasize = '1.2em';
  4143. } elseif ($pictowithouttext == 'note') {
  4144. $fakey = 'fa-sticky-note';
  4145. $marginleftonlyshort = 1;
  4146. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  4147. $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');
  4148. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  4149. if (preg_match('/selected/', $pictowithouttext)) {
  4150. $facolor = '#888';
  4151. }
  4152. $marginleftonlyshort = 1;
  4153. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  4154. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  4155. } else {
  4156. $fakey = 'fa-'.$pictowithouttext;
  4157. }
  4158. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  4159. $morecss .= ' em092';
  4160. }
  4161. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  4162. $morecss .= ' em088';
  4163. }
  4164. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  4165. $morecss .= ' em080';
  4166. }
  4167. // Define $marginleftonlyshort
  4168. $arrayconvpictotomarginleftonly = array(
  4169. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  4170. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  4171. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  4172. );
  4173. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  4174. $marginleftonlyshort = 0;
  4175. }
  4176. // Add CSS
  4177. $arrayconvpictotomorcess = array(
  4178. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  4179. 'bank_account'=>'infobox-bank_account',
  4180. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  4181. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  4182. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  4183. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  4184. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  4185. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  4186. 'incoterm'=>'infobox-supplier_proposal',
  4187. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  4188. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  4189. 'order'=>'infobox-commande',
  4190. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  4191. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_warning'=>'font-status4 warning', 'switch_on_red'=>'font-status8',
  4192. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  4193. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  4194. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  4195. 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
  4196. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  4197. 'resource'=>'infobox-action',
  4198. 'salary'=>'infobox-bank_account', 'shapes'=>'infobox-adherent', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  4199. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  4200. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  4201. 'vat'=>'infobox-bank_account',
  4202. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  4203. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  4204. );
  4205. if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4206. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  4207. }
  4208. // Define $color
  4209. $arrayconvpictotocolor = array(
  4210. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  4211. 'clone'=>'#999', 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  4212. 'dynamicprice'=>'#a69944',
  4213. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  4214. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  4215. 'lock'=>'#ddd', 'lot'=>'#a69944',
  4216. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  4217. 'other'=>'#ddd', 'world'=>'#986c6a',
  4218. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  4219. //'shipment'=>'#a69944',
  4220. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  4221. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  4222. 'website'=>'#304', 'workstation'=>'#a69944'
  4223. );
  4224. if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4225. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  4226. }
  4227. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  4228. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  4229. $morestyle = '';
  4230. $reg = array();
  4231. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4232. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4233. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4234. }
  4235. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  4236. $morestyle = $reg[1];
  4237. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  4238. }
  4239. $moreatt = trim($moreatt);
  4240. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  4241. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  4242. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4243. $enabledisablehtml .= $titlealt;
  4244. }*/
  4245. $enabledisablehtml .= '</span>';
  4246. return $enabledisablehtml;
  4247. }
  4248. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  4249. $path = getDolGlobalString('MAIN_OVERWRITE_THEME_PATH') . '/theme/'.$theme; // If the theme does not have the same name as the module
  4250. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  4251. $path = getDolGlobalString('MAIN_OVERWRITE_THEME_RES') . '/theme/' . getDolGlobalString('MAIN_OVERWRITE_THEME_RES'); // To allow an external module to overwrite image resources whatever is activated theme
  4252. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  4253. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  4254. }
  4255. // If we ask an image into $url/$mymodule/img (instead of default path)
  4256. $regs = array();
  4257. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  4258. $picto = $regs[1];
  4259. $path = $regs[2]; // $path is $mymodule
  4260. }
  4261. // Clean parameters
  4262. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  4263. $picto .= '.png';
  4264. }
  4265. // If alt path are defined, define url where img file is, according to physical path
  4266. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  4267. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  4268. if ($type == 'main') {
  4269. continue;
  4270. }
  4271. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  4272. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  4273. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  4274. break;
  4275. }
  4276. }
  4277. // $url is '' or '/custom', $path is current theme or
  4278. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  4279. }
  4280. if ($srconly) {
  4281. return $fullpathpicto;
  4282. }
  4283. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  4284. return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dol_escape_htmltag($alt).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
  4285. }
  4286. /**
  4287. * Show a picto called object_picto (generic function)
  4288. *
  4289. * @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.
  4290. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  4291. * For external modules use imagename@mymodule to search into directory "img" of module.
  4292. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  4293. * @param int $pictoisfullpath If 1, image path is a full path
  4294. * @param int $srconly Return only content of the src attribute of img.
  4295. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4296. * @return string Return img tag
  4297. * @see img_picto(), img_picto_common()
  4298. */
  4299. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  4300. {
  4301. if (strpos($picto, '^') === 0) {
  4302. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  4303. } else {
  4304. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  4305. }
  4306. }
  4307. /**
  4308. * Show weather picto
  4309. *
  4310. * @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.
  4311. * @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).
  4312. * @param string $moreatt Add more attribute on img tag
  4313. * @param int $pictoisfullpath If 1, image path is a full path
  4314. * @param string $morecss More CSS
  4315. * @return string Return img tag
  4316. * @see img_object(), img_picto()
  4317. */
  4318. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  4319. {
  4320. global $conf;
  4321. if (is_numeric($picto)) {
  4322. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  4323. //$picto = $leveltopicto[$picto];
  4324. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  4325. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4326. $picto .= '.png';
  4327. }
  4328. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  4329. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  4330. }
  4331. /**
  4332. * Show picto (generic function)
  4333. *
  4334. * @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.
  4335. * @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.
  4336. * @param string $moreatt Add more attribute on img tag
  4337. * @param int $pictoisfullpath If 1, image path is a full path
  4338. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4339. * @return string Return img tag
  4340. * @see img_object(), img_picto()
  4341. */
  4342. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  4343. {
  4344. global $conf;
  4345. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4346. $picto .= '.png';
  4347. }
  4348. if ($pictoisfullpath) {
  4349. $path = $picto;
  4350. } else {
  4351. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  4352. if (getDolGlobalInt('MAIN_MODULE_CAN_OVERWRITE_COMMONICONS')) {
  4353. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  4354. if (file_exists($themepath)) {
  4355. $path = $themepath;
  4356. }
  4357. }
  4358. }
  4359. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  4360. }
  4361. /**
  4362. * Show logo action
  4363. *
  4364. * @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.
  4365. * @param string $numaction Action id or code to show
  4366. * @param string $picto Name of image file to show ('filenew', ...)
  4367. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  4368. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4369. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4370. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4371. * @param string $moreatt More attributes
  4372. * @return string Return an img tag
  4373. */
  4374. function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
  4375. {
  4376. global $langs;
  4377. if (empty($titlealt) || $titlealt == 'default') {
  4378. if ($numaction == '-1' || $numaction == 'ST_NO') {
  4379. $numaction = -1;
  4380. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  4381. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  4382. $numaction = 0;
  4383. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  4384. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  4385. $numaction = 1;
  4386. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  4387. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  4388. $numaction = 2;
  4389. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  4390. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  4391. $numaction = 3;
  4392. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  4393. } else {
  4394. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  4395. $numaction = 0;
  4396. }
  4397. }
  4398. if (!is_numeric($numaction)) {
  4399. $numaction = 0;
  4400. }
  4401. return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
  4402. }
  4403. /**
  4404. * Show pdf logo
  4405. *
  4406. * @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.
  4407. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  4408. * @return string Retourne tag img
  4409. */
  4410. function img_pdf($titlealt = 'default', $size = 3)
  4411. {
  4412. global $langs;
  4413. if ($titlealt == 'default') {
  4414. $titlealt = $langs->trans('Show');
  4415. }
  4416. return img_picto($titlealt, 'pdf'.$size.'.png');
  4417. }
  4418. /**
  4419. * Show logo +
  4420. *
  4421. * @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.
  4422. * @param string $other Add more attributes on img
  4423. * @return string Return tag img
  4424. */
  4425. function img_edit_add($titlealt = 'default', $other = '')
  4426. {
  4427. global $langs;
  4428. if ($titlealt == 'default') {
  4429. $titlealt = $langs->trans('Add');
  4430. }
  4431. return img_picto($titlealt, 'edit_add.png', $other);
  4432. }
  4433. /**
  4434. * Show logo -
  4435. *
  4436. * @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.
  4437. * @param string $other Add more attributes on img
  4438. * @return string Return tag img
  4439. */
  4440. function img_edit_remove($titlealt = 'default', $other = '')
  4441. {
  4442. global $langs;
  4443. if ($titlealt == 'default') {
  4444. $titlealt = $langs->trans('Remove');
  4445. }
  4446. return img_picto($titlealt, 'edit_remove.png', $other);
  4447. }
  4448. /**
  4449. * Show logo editer/modifier fiche
  4450. *
  4451. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  4452. * @param integer $float If you have to put the style "float: right"
  4453. * @param string $other Add more attributes on img
  4454. * @return string Return tag img
  4455. */
  4456. function img_edit($titlealt = 'default', $float = 0, $other = '')
  4457. {
  4458. global $langs;
  4459. if ($titlealt == 'default') {
  4460. $titlealt = $langs->trans('Modify');
  4461. }
  4462. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  4463. }
  4464. /**
  4465. * Show logo view card
  4466. *
  4467. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  4468. * @param integer $float If you have to put the style "float: right"
  4469. * @param string $other Add more attributes on img
  4470. * @return string Return tag img
  4471. */
  4472. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  4473. {
  4474. global $langs;
  4475. if ($titlealt == 'default') {
  4476. $titlealt = $langs->trans('View');
  4477. }
  4478. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4479. return img_picto($titlealt, 'eye', $moreatt);
  4480. }
  4481. /**
  4482. * Show delete logo
  4483. *
  4484. * @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.
  4485. * @param string $other Add more attributes on img
  4486. * @param string $morecss More CSS
  4487. * @return string Retourne tag img
  4488. */
  4489. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4490. {
  4491. global $langs;
  4492. if ($titlealt == 'default') {
  4493. $titlealt = $langs->trans('Delete');
  4494. }
  4495. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4496. }
  4497. /**
  4498. * Show printer logo
  4499. *
  4500. * @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.
  4501. * @param string $other Add more attributes on img
  4502. * @return string Retourne tag img
  4503. */
  4504. function img_printer($titlealt = "default", $other = '')
  4505. {
  4506. global $langs;
  4507. if ($titlealt == "default") {
  4508. $titlealt = $langs->trans("Print");
  4509. }
  4510. return img_picto($titlealt, 'printer.png', $other);
  4511. }
  4512. /**
  4513. * Show split logo
  4514. *
  4515. * @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.
  4516. * @param string $other Add more attributes on img
  4517. * @return string Retourne tag img
  4518. */
  4519. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4520. {
  4521. global $langs;
  4522. if ($titlealt == 'default') {
  4523. $titlealt = $langs->trans('Split');
  4524. }
  4525. return img_picto($titlealt, 'split.png', $other);
  4526. }
  4527. /**
  4528. * Show help logo with cursor "?"
  4529. *
  4530. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4531. * @param int|string $usealttitle Text to use as alt title
  4532. * @return string Return tag img
  4533. */
  4534. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4535. {
  4536. global $langs;
  4537. if ($usealttitle) {
  4538. if (is_string($usealttitle)) {
  4539. $usealttitle = dol_escape_htmltag($usealttitle);
  4540. } else {
  4541. $usealttitle = $langs->trans('Info');
  4542. }
  4543. }
  4544. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4545. }
  4546. /**
  4547. * Show info logo
  4548. *
  4549. * @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.
  4550. * @return string Return img tag
  4551. */
  4552. function img_info($titlealt = 'default')
  4553. {
  4554. global $langs;
  4555. if ($titlealt == 'default') {
  4556. $titlealt = $langs->trans('Informations');
  4557. }
  4558. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4559. }
  4560. /**
  4561. * Show warning logo
  4562. *
  4563. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  4564. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4565. * @param string $morecss Add more CSS
  4566. * @return string Return img tag
  4567. */
  4568. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4569. {
  4570. global $langs;
  4571. if ($titlealt == 'default') {
  4572. $titlealt = $langs->trans('Warning');
  4573. }
  4574. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4575. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4576. }
  4577. /**
  4578. * Show error logo
  4579. *
  4580. * @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.
  4581. * @return string Return img tag
  4582. */
  4583. function img_error($titlealt = 'default')
  4584. {
  4585. global $langs;
  4586. if ($titlealt == 'default') {
  4587. $titlealt = $langs->trans('Error');
  4588. }
  4589. return img_picto($titlealt, 'error.png');
  4590. }
  4591. /**
  4592. * Show next logo
  4593. *
  4594. * @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.
  4595. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4596. * @return string Return img tag
  4597. */
  4598. function img_next($titlealt = 'default', $moreatt = '')
  4599. {
  4600. global $langs;
  4601. if ($titlealt == 'default') {
  4602. $titlealt = $langs->trans('Next');
  4603. }
  4604. //return img_picto($titlealt, 'next.png', $moreatt);
  4605. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4606. }
  4607. /**
  4608. * Show previous logo
  4609. *
  4610. * @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.
  4611. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4612. * @return string Return img tag
  4613. */
  4614. function img_previous($titlealt = 'default', $moreatt = '')
  4615. {
  4616. global $langs;
  4617. if ($titlealt == 'default') {
  4618. $titlealt = $langs->trans('Previous');
  4619. }
  4620. //return img_picto($titlealt, 'previous.png', $moreatt);
  4621. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4622. }
  4623. /**
  4624. * Show down arrow logo
  4625. *
  4626. * @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.
  4627. * @param int $selected Selected
  4628. * @param string $moreclass Add more CSS classes
  4629. * @return string Return img tag
  4630. */
  4631. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4632. {
  4633. global $langs;
  4634. if ($titlealt == 'default') {
  4635. $titlealt = $langs->trans('Down');
  4636. }
  4637. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4638. }
  4639. /**
  4640. * Show top arrow logo
  4641. *
  4642. * @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.
  4643. * @param int $selected Selected
  4644. * @param string $moreclass Add more CSS classes
  4645. * @return string Return img tag
  4646. */
  4647. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4648. {
  4649. global $langs;
  4650. if ($titlealt == 'default') {
  4651. $titlealt = $langs->trans('Up');
  4652. }
  4653. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4654. }
  4655. /**
  4656. * Show left arrow logo
  4657. *
  4658. * @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.
  4659. * @param int $selected Selected
  4660. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4661. * @return string Return img tag
  4662. */
  4663. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4664. {
  4665. global $langs;
  4666. if ($titlealt == 'default') {
  4667. $titlealt = $langs->trans('Left');
  4668. }
  4669. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4670. }
  4671. /**
  4672. * Show right arrow logo
  4673. *
  4674. * @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.
  4675. * @param int $selected Selected
  4676. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4677. * @return string Return img tag
  4678. */
  4679. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4680. {
  4681. global $langs;
  4682. if ($titlealt == 'default') {
  4683. $titlealt = $langs->trans('Right');
  4684. }
  4685. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4686. }
  4687. /**
  4688. * Show tick logo if allowed
  4689. *
  4690. * @param string $allow Allow
  4691. * @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.
  4692. * @return string Return img tag
  4693. */
  4694. function img_allow($allow, $titlealt = 'default')
  4695. {
  4696. global $langs;
  4697. if ($titlealt == 'default') {
  4698. $titlealt = $langs->trans('Active');
  4699. }
  4700. if ($allow == 1) {
  4701. return img_picto($titlealt, 'tick.png');
  4702. }
  4703. return '-';
  4704. }
  4705. /**
  4706. * Return image of a credit card according to its brand name
  4707. *
  4708. * @param string $brand Brand name of credit card
  4709. * @param string $morecss More CSS
  4710. * @return string Return img tag
  4711. */
  4712. function img_credit_card($brand, $morecss = null)
  4713. {
  4714. if (is_null($morecss)) {
  4715. $morecss = 'fa-2x';
  4716. }
  4717. if ($brand == 'visa' || $brand == 'Visa') {
  4718. $brand = 'cc-visa';
  4719. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4720. $brand = 'cc-mastercard';
  4721. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4722. $brand = 'cc-amex';
  4723. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4724. $brand = 'cc-discover';
  4725. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4726. $brand = 'cc-jcb';
  4727. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4728. $brand = 'cc-diners-club';
  4729. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4730. $brand = 'credit-card';
  4731. }
  4732. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4733. }
  4734. /**
  4735. * Show MIME img of a file
  4736. *
  4737. * @param string $file Filename
  4738. * @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.
  4739. * @param string $morecss More css
  4740. * @return string Return img tag
  4741. */
  4742. function img_mime($file, $titlealt = '', $morecss = '')
  4743. {
  4744. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4745. $mimetype = dol_mimetype($file, '', 1);
  4746. $mimeimg = dol_mimetype($file, '', 2);
  4747. $mimefa = dol_mimetype($file, '', 4);
  4748. if (empty($titlealt)) {
  4749. $titlealt = 'Mime type: '.$mimetype;
  4750. }
  4751. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4752. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4753. }
  4754. /**
  4755. * Show search logo
  4756. *
  4757. * @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.
  4758. * @param string $other Add more attributes on img
  4759. * @return string Retourne tag img
  4760. */
  4761. function img_search($titlealt = 'default', $other = '')
  4762. {
  4763. global $conf, $langs;
  4764. if ($titlealt == 'default') {
  4765. $titlealt = $langs->trans('Search');
  4766. }
  4767. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4768. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4769. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4770. return $input;
  4771. }
  4772. /**
  4773. * Show search logo
  4774. *
  4775. * @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.
  4776. * @param string $other Add more attributes on img
  4777. * @return string Retourne tag img
  4778. */
  4779. function img_searchclear($titlealt = 'default', $other = '')
  4780. {
  4781. global $conf, $langs;
  4782. if ($titlealt == 'default') {
  4783. $titlealt = $langs->trans('Search');
  4784. }
  4785. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4786. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4787. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4788. return $input;
  4789. }
  4790. /**
  4791. * Show information for admin users or standard users
  4792. *
  4793. * @param string $text Text info
  4794. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4795. * @param int $nodiv No div
  4796. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4797. * @param string $morecss More CSS ('', 'warning', 'error')
  4798. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4799. * @return string String with info text
  4800. */
  4801. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4802. {
  4803. global $conf, $langs;
  4804. if ($infoonimgalt) {
  4805. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4806. } else {
  4807. if (empty($conf->use_javascript_ajax)) {
  4808. $textfordropdown = '';
  4809. }
  4810. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4811. $result = ($nodiv ? '' : '<div class="'.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  4812. if ($textfordropdown) {
  4813. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4814. $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
  4815. jQuery(document).ready(function() {
  4816. jQuery(".'.$class.'text").click(function() {
  4817. console.log("toggle text");
  4818. jQuery(".'.$class.'").toggle();
  4819. });
  4820. });
  4821. </script>';
  4822. $result = $tmpresult.$result;
  4823. }
  4824. }
  4825. return $result;
  4826. }
  4827. /**
  4828. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4829. * This function must be called when a blocking technical error is encountered.
  4830. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4831. *
  4832. * @param DoliDB|string $db Database handler
  4833. * @param string|string[] $error String or array of errors strings to show
  4834. * @param array $errors Array of errors
  4835. * @return void
  4836. * @see dol_htmloutput_errors()
  4837. */
  4838. function dol_print_error($db = '', $error = '', $errors = null)
  4839. {
  4840. global $conf, $langs, $argv;
  4841. global $dolibarr_main_prod;
  4842. $out = '';
  4843. $syslog = '';
  4844. // If error occurs before the $lang object was loaded
  4845. if (!$langs) {
  4846. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4847. $langs = new Translate('', $conf);
  4848. $langs->load("main");
  4849. }
  4850. // Load translation files required by the error messages
  4851. $langs->loadLangs(array('main', 'errors'));
  4852. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4853. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4854. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4855. $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";
  4856. }
  4857. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4858. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4859. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4860. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4861. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4862. }
  4863. if (function_exists("phpversion")) {
  4864. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4865. }
  4866. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4867. if (function_exists("php_uname")) {
  4868. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4869. }
  4870. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4871. $out .= "<br>\n";
  4872. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4873. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4874. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4875. $out .= "<br>\n";
  4876. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4877. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4878. } else { // Mode CLI
  4879. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4880. $syslog .= "pid=".dol_getmypid();
  4881. }
  4882. if (!empty($conf->modules)) {
  4883. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4884. }
  4885. if (is_object($db)) {
  4886. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4887. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4888. $lastqueryerror = $db->lastqueryerror();
  4889. if (!utf8_check($lastqueryerror)) {
  4890. $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
  4891. }
  4892. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4893. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4894. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4895. $out .= "<br>\n";
  4896. } else { // Mode CLI
  4897. // No dol_escape_htmltag for output, we are in CLI mode
  4898. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4899. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4900. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4901. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4902. }
  4903. $syslog .= ", sql=".$db->lastquery();
  4904. $syslog .= ", db_error=".$db->lasterror();
  4905. }
  4906. if ($error || $errors) {
  4907. $langs->load("errors");
  4908. // Merge all into $errors array
  4909. if (is_array($error) && is_array($errors)) {
  4910. $errors = array_merge($error, $errors);
  4911. } elseif (is_array($error)) {
  4912. $errors = $error;
  4913. } elseif (is_array($errors)) {
  4914. $errors = array_merge(array($error), $errors);
  4915. } else {
  4916. $errors = array_merge(array($error), array($errors));
  4917. }
  4918. foreach ($errors as $msg) {
  4919. if (empty($msg)) {
  4920. continue;
  4921. }
  4922. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4923. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4924. } else // Mode CLI
  4925. {
  4926. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4927. }
  4928. $syslog .= ", msg=".$msg;
  4929. }
  4930. }
  4931. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4932. xdebug_print_function_stack();
  4933. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4934. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4935. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4936. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4937. $out .= "<br>\n";
  4938. }
  4939. // Return a http header with error code if possible
  4940. if (!headers_sent()) {
  4941. if (function_exists('top_httphead')) { // In CLI context, the method does not exists
  4942. top_httphead();
  4943. }
  4944. //http_response_code(500); // If we use 500, message is not ouput with some command line tools
  4945. http_response_code(202); // If we use 202, this is not really an error message, but this allow to ouput message on command line tools
  4946. }
  4947. if (empty($dolibarr_main_prod)) {
  4948. print $out;
  4949. } else {
  4950. if (empty($langs->defaultlang)) {
  4951. $langs->setDefaultLang();
  4952. }
  4953. $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.
  4954. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4955. 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";
  4956. print $langs->trans("DolibarrHasDetectedError").'. ';
  4957. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4958. if (!defined("MAIN_CORE_ERROR")) {
  4959. define("MAIN_CORE_ERROR", 1);
  4960. }
  4961. }
  4962. dol_syslog("Error ".$syslog, LOG_ERR);
  4963. }
  4964. /**
  4965. * Show a public email and error code to contact if technical error
  4966. *
  4967. * @param string $prefixcode Prefix of public error code
  4968. * @param string $errormessage Complete error message
  4969. * @param array $errormessages Array of error messages
  4970. * @param string $morecss More css
  4971. * @param string $email Email
  4972. * @return void
  4973. */
  4974. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4975. {
  4976. global $langs, $conf;
  4977. if (empty($email)) {
  4978. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4979. }
  4980. $langs->load("errors");
  4981. $now = dol_now();
  4982. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4983. print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
  4984. if ($errormessage) {
  4985. print '<br><br>'.$errormessage;
  4986. }
  4987. if (is_array($errormessages) && count($errormessages)) {
  4988. foreach ($errormessages as $mesgtoshow) {
  4989. print '<br><br>'.$mesgtoshow;
  4990. }
  4991. }
  4992. print '</div></div>';
  4993. }
  4994. /**
  4995. * Show title line of an array
  4996. *
  4997. * @param string $name Label of field
  4998. * @param string $file Url used when we click on sort picto
  4999. * @param string $field Field to use for new sorting
  5000. * @param string $begin ("" by defaut)
  5001. * @param string $moreparam Add more parameters on sort url links ("" by default)
  5002. * @param string $moreattrib Options of attribute td ("" by defaut)
  5003. * @param string $sortfield Current field used to sort
  5004. * @param string $sortorder Current sort order
  5005. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  5006. * @param string $tooltip Tooltip
  5007. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  5008. * @return void
  5009. */
  5010. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  5011. {
  5012. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  5013. }
  5014. /**
  5015. * Get title line of an array
  5016. *
  5017. * @param string $name Translation key of field to show or complete HTML string to show
  5018. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  5019. * @param string $file Url used when we click on sort picto
  5020. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  5021. * @param string $begin ("" by defaut)
  5022. * @param string $moreparam Add more parameters on sort url links ("" by default)
  5023. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  5024. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  5025. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  5026. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  5027. * @param string $disablesortlink 1=Disable sort link
  5028. * @param string $tooltip Tooltip
  5029. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  5030. * @return string
  5031. */
  5032. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  5033. {
  5034. global $conf, $langs, $form;
  5035. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  5036. if ($moreattrib == 'class="right"') {
  5037. $prefix .= 'right '; // For backward compatibility
  5038. }
  5039. $sortorder = strtoupper($sortorder);
  5040. $out = '';
  5041. $sortimg = '';
  5042. $tag = 'th';
  5043. if ($thead == 2) {
  5044. $tag = 'div';
  5045. }
  5046. $tmpsortfield = explode(',', $sortfield);
  5047. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  5048. $tmpfield = explode(',', $field);
  5049. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  5050. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  5051. $prefix = 'wrapcolumntitle '.$prefix;
  5052. }
  5053. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  5054. // If field is used as sort criteria we use a specific css class liste_titre_sel
  5055. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  5056. $liste_titre = 'liste_titre';
  5057. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  5058. $liste_titre = 'liste_titre_sel';
  5059. }
  5060. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  5061. //$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)).'"' : '');
  5062. $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  5063. $tagstart .= '>';
  5064. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  5065. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  5066. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  5067. $options = preg_replace('/&+/i', '&', $options);
  5068. if (!preg_match('/^&/', $options)) {
  5069. $options = '&'.$options;
  5070. }
  5071. $sortordertouseinlink = '';
  5072. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  5073. if (preg_match('/^DESC/i', $sortorder)) {
  5074. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  5075. } else { // We reverse the var $sortordertouseinlink
  5076. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  5077. }
  5078. } else { // We are on field that is the first current sorting criteria
  5079. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  5080. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  5081. } else {
  5082. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  5083. }
  5084. }
  5085. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  5086. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  5087. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  5088. $out .= '>';
  5089. }
  5090. if ($tooltip) {
  5091. // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
  5092. if (preg_match('/:\w+$/', $tooltip)) {
  5093. $tmptooltip = explode(':', $tooltip);
  5094. } else {
  5095. $tmptooltip = array($tooltip);
  5096. }
  5097. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  5098. } else {
  5099. $out .= $langs->trans($name);
  5100. }
  5101. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  5102. $out .= '</a>';
  5103. }
  5104. if (empty($thead) && $field) { // If this is a sort field
  5105. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  5106. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  5107. $options = preg_replace('/&+/i', '&', $options);
  5108. if (!preg_match('/^&/', $options)) {
  5109. $options = '&'.$options;
  5110. }
  5111. if (!$sortorder || ($field1 != $sortfield1)) {
  5112. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  5113. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  5114. } else {
  5115. if (preg_match('/^DESC/', $sortorder)) {
  5116. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  5117. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  5118. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  5119. }
  5120. if (preg_match('/^ASC/', $sortorder)) {
  5121. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  5122. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  5123. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  5124. }
  5125. }
  5126. }
  5127. $tagend = '</'.$tag.'>';
  5128. $out = $tagstart.$sortimg.$out.$tagend;
  5129. return $out;
  5130. }
  5131. /**
  5132. * Show a title.
  5133. *
  5134. * @param string $title Title to show
  5135. * @return void
  5136. * @deprecated Use load_fiche_titre instead
  5137. * @see load_fiche_titre()
  5138. */
  5139. function print_titre($title)
  5140. {
  5141. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  5142. print '<div class="titre">'.$title.'</div>';
  5143. }
  5144. /**
  5145. * Show a title with picto
  5146. *
  5147. * @param string $title Title to show
  5148. * @param string $mesg Added message to show on right
  5149. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5150. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5151. * @param int $id To force an id on html objects
  5152. * @return void
  5153. * @deprecated Use print load_fiche_titre instead
  5154. */
  5155. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  5156. {
  5157. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  5158. }
  5159. /**
  5160. * Load a title with picto
  5161. *
  5162. * @param string $titre Title to show
  5163. * @param string $morehtmlright Added message to show on right
  5164. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5165. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5166. * @param string $id To force an id on html objects
  5167. * @param string $morecssontable More css on table
  5168. * @param string $morehtmlcenter Added message to show on center
  5169. * @return string
  5170. * @see print_barre_liste()
  5171. */
  5172. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  5173. {
  5174. global $conf;
  5175. $return = '';
  5176. if ($picto == 'setup') {
  5177. $picto = 'generic';
  5178. }
  5179. $return .= "\n";
  5180. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  5181. $return .= '<tr class="titre">';
  5182. if ($picto) {
  5183. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  5184. }
  5185. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  5186. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  5187. $return .= '</td>';
  5188. if (dol_strlen($morehtmlcenter)) {
  5189. $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5190. }
  5191. if (dol_strlen($morehtmlright)) {
  5192. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
  5193. }
  5194. $return .= '</tr></table>'."\n";
  5195. return $return;
  5196. }
  5197. /**
  5198. * Print a title with navigation controls for pagination
  5199. *
  5200. * @param string $titre Title to show (required)
  5201. * @param int|null $page Numero of page to show in navigation links (required)
  5202. * @param string $file Url of page (required)
  5203. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  5204. * @param string $sortfield Field to sort on ('' by default)
  5205. * @param string $sortorder Order to sort ('' by default)
  5206. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  5207. * @param int $num Number of records found by select with limit+1
  5208. * @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.
  5209. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5210. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5211. * @param string $morehtmlright More html to show (after arrows)
  5212. * @param string $morecss More css to the table
  5213. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  5214. * @param int $hideselectlimit Force to hide select limit
  5215. * @param int $hidenavigation Force to hide the arrows and page for navigation
  5216. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  5217. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  5218. * @return void
  5219. */
  5220. 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 = '')
  5221. {
  5222. global $conf;
  5223. $savlimit = $limit;
  5224. $savtotalnboflines = $totalnboflines;
  5225. $totalnboflines = abs((int) $totalnboflines);
  5226. $page = (int) $page;
  5227. if ($picto == 'setup') {
  5228. $picto = 'title_setup.png';
  5229. }
  5230. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  5231. $picto = 'title.gif';
  5232. }
  5233. if ($limit < 0) {
  5234. $limit = $conf->liste_limit;
  5235. }
  5236. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  5237. $nextpage = 1;
  5238. } else {
  5239. $nextpage = 0;
  5240. }
  5241. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
  5242. print "\n";
  5243. print "<!-- Begin title -->\n";
  5244. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  5245. // Left
  5246. if ($picto && $titre) {
  5247. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  5248. }
  5249. print '<td class="nobordernopadding valignmiddle col-title">';
  5250. print '<div class="titre inline-block">'.$titre;
  5251. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  5252. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  5253. }
  5254. print '</div></td>';
  5255. // Center
  5256. if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
  5257. print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5258. }
  5259. // Right
  5260. print '<td class="nobordernopadding valignmiddle right col-right">';
  5261. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  5262. if ($sortfield) {
  5263. $options .= "&sortfield=".urlencode($sortfield);
  5264. }
  5265. if ($sortorder) {
  5266. $options .= "&sortorder=".urlencode($sortorder);
  5267. }
  5268. // Show navigation bar
  5269. $pagelist = '';
  5270. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  5271. if ($totalnboflines) { // If we know total nb of lines
  5272. // Define nb of extra page links before and after selected page + ... + first or last
  5273. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  5274. if ($limit > 0) {
  5275. $nbpages = ceil($totalnboflines / $limit);
  5276. } else {
  5277. $nbpages = 1;
  5278. }
  5279. $cpt = ($page - $maxnbofpage);
  5280. if ($cpt < 0) {
  5281. $cpt = 0;
  5282. }
  5283. if ($cpt >= 1) {
  5284. if (empty($pagenavastextinput)) {
  5285. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  5286. if ($cpt > 2) {
  5287. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5288. } elseif ($cpt == 2) {
  5289. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  5290. }
  5291. }
  5292. }
  5293. do {
  5294. if ($pagenavastextinput) {
  5295. if ($cpt == $page) {
  5296. $pagelist .= '<li class="pagination"><input type="text" class="'.($totalnboflines > 100 ? 'width40' : 'width25').' center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  5297. $pagelist .= '/';
  5298. }
  5299. } else {
  5300. if ($cpt == $page) {
  5301. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  5302. } else {
  5303. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  5304. }
  5305. }
  5306. $cpt++;
  5307. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  5308. if (empty($pagenavastextinput)) {
  5309. if ($cpt < $nbpages) {
  5310. if ($cpt < $nbpages - 2) {
  5311. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5312. } elseif ($cpt == $nbpages - 2) {
  5313. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  5314. }
  5315. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5316. }
  5317. } else {
  5318. //var_dump($page.' '.$cpt.' '.$nbpages);
  5319. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5320. }
  5321. } else {
  5322. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  5323. }
  5324. }
  5325. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  5326. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow, $hidenavigation); // output the div and ul for previous/last completed with page numbers into $pagelist
  5327. }
  5328. // js to autoselect page field on focus
  5329. if ($pagenavastextinput) {
  5330. print ajax_autoselect('.pageplusone');
  5331. }
  5332. print '</td>';
  5333. print '</tr>';
  5334. print '</table>'."\n";
  5335. // Center
  5336. if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
  5337. print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
  5338. }
  5339. print "<!-- End title -->\n\n";
  5340. }
  5341. /**
  5342. * Function to show navigation arrows into lists
  5343. *
  5344. * @param int $page Number of page
  5345. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  5346. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  5347. * @param integer $nextpage Do we show a next page button
  5348. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  5349. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  5350. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  5351. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  5352. * @param int $hideselectlimit Force to hide select limit
  5353. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  5354. * @param int $hidenavigation Force to hide the switch mode view and the navigation tool (select limit, arrows $betweenarrows and $afterarrows but not $beforearrows)
  5355. * @return void
  5356. */
  5357. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '', $hidenavigation = 0)
  5358. {
  5359. global $conf, $langs;
  5360. print '<div class="pagination"><ul>';
  5361. if ($beforearrows) {
  5362. print '<li class="paginationbeforearrows">';
  5363. print $beforearrows;
  5364. print '</li>';
  5365. }
  5366. if (empty($hidenavigation)) {
  5367. if ((int) $limit > 0 && empty($hideselectlimit)) {
  5368. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
  5369. $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
  5370. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  5371. //$pagesizechoices.=',2:2';
  5372. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  5373. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  5374. }
  5375. print '<li class="pagination">';
  5376. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  5377. $tmpchoice = explode(',', $pagesizechoices);
  5378. $tmpkey = $limit.':'.$limit;
  5379. if (!in_array($tmpkey, $tmpchoice)) {
  5380. $tmpchoice[] = $tmpkey;
  5381. }
  5382. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  5383. if (!in_array($tmpkey, $tmpchoice)) {
  5384. $tmpchoice[] = $tmpkey;
  5385. }
  5386. asort($tmpchoice, SORT_NUMERIC);
  5387. foreach ($tmpchoice as $val) {
  5388. $selected = '';
  5389. $tmp = explode(':', $val);
  5390. $key = $tmp[0];
  5391. $val = $tmp[1];
  5392. if ($key != '' && $val != '') {
  5393. if ((int) $key == (int) $limit) {
  5394. $selected = ' selected="selected"';
  5395. }
  5396. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  5397. }
  5398. }
  5399. print '</select>';
  5400. if ($conf->use_javascript_ajax) {
  5401. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  5402. <script>
  5403. jQuery(document).ready(function () {
  5404. jQuery(".selectlimit").change(function() {
  5405. console.log("Change limit. Send submit");
  5406. $(this).parents(\'form:first\').submit();
  5407. });
  5408. });
  5409. </script>
  5410. ';
  5411. }
  5412. print '</li>';
  5413. }
  5414. if ($page > 0) {
  5415. 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>';
  5416. }
  5417. if ($betweenarrows) {
  5418. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  5419. print $betweenarrows;
  5420. print '<!--</div>-->';
  5421. }
  5422. if ($nextpage > 0) {
  5423. 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>';
  5424. }
  5425. if ($afterarrows) {
  5426. print '<li class="paginationafterarrows">';
  5427. print $afterarrows;
  5428. print '</li>';
  5429. }
  5430. }
  5431. print '</ul></div>'."\n";
  5432. }
  5433. /**
  5434. * Return a string with VAT rate label formated for view output
  5435. * Used into pdf and HTML pages
  5436. *
  5437. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  5438. * @param boolean $addpercent Add a percent % sign in output
  5439. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  5440. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  5441. * @param int $html Used for html output
  5442. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  5443. */
  5444. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
  5445. {
  5446. $morelabel = '';
  5447. if (preg_match('/%/', $rate)) {
  5448. $rate = str_replace('%', '', $rate);
  5449. $addpercent = true;
  5450. }
  5451. $reg = array();
  5452. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  5453. $morelabel = ' ('.$reg[1].')';
  5454. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  5455. $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
  5456. }
  5457. if (preg_match('/\*/', $rate)) {
  5458. $rate = str_replace('*', '', $rate);
  5459. $info_bits |= 1;
  5460. }
  5461. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  5462. if (!preg_match('/\//', $rate)) {
  5463. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  5464. } else {
  5465. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  5466. $ret = $rate.($addpercent ? '%' : '');
  5467. }
  5468. if (($info_bits & 1) && $usestarfornpr >= 0) {
  5469. $ret .= ' *';
  5470. }
  5471. $ret .= $morelabel;
  5472. return $ret;
  5473. }
  5474. /**
  5475. * Function to format a value into an amount for visual output
  5476. * Function used into PDF and HTML pages
  5477. *
  5478. * @param float $amount Amount to format
  5479. * @param integer $form Type of format, HTML or not (not by default)
  5480. * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators.
  5481. * @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.
  5482. * @param int $rounding MINIMUM number of decimal to show: 0=no change, -1=we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  5483. * @param int|string $forcerounding MAXIMUM number of decimal to forcerounding decimal: -1=no change, 'MU' or 'MT' or numeric to round to MU or MT or to a given number of decimal
  5484. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  5485. * @return string String with formated amount
  5486. *
  5487. * @see price2num() Revert function of price
  5488. */
  5489. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  5490. {
  5491. global $langs, $conf;
  5492. // Clean parameters
  5493. if (empty($amount)) {
  5494. $amount = 0; // To have a numeric value if amount not defined or = ''
  5495. }
  5496. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  5497. if ($rounding == -1) {
  5498. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  5499. }
  5500. $nbdecimal = $rounding;
  5501. if ($outlangs === 'none') {
  5502. // Use international separators
  5503. $dec = '.';
  5504. $thousand = '';
  5505. } else {
  5506. // Output separators by default (french)
  5507. $dec = ',';
  5508. $thousand = ' ';
  5509. // If $outlangs not forced, we use use language
  5510. if (!is_object($outlangs)) {
  5511. $outlangs = $langs;
  5512. }
  5513. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5514. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5515. }
  5516. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5517. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5518. }
  5519. if ($thousand == 'None') {
  5520. $thousand = '';
  5521. } elseif ($thousand == 'Space') {
  5522. $thousand = ' ';
  5523. }
  5524. }
  5525. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5526. //print "amount=".$amount."-";
  5527. $amount = str_replace(',', '.', $amount); // should be useless
  5528. //print $amount."-";
  5529. $datas = explode('.', $amount);
  5530. $decpart = isset($datas[1]) ? $datas[1] : '';
  5531. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5532. //print "decpart=".$decpart."<br>";
  5533. $end = '';
  5534. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5535. if (dol_strlen($decpart) > $nbdecimal) {
  5536. $nbdecimal = dol_strlen($decpart);
  5537. }
  5538. // Si on depasse max
  5539. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5540. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5541. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5542. // Si un affichage est tronque, on montre des ...
  5543. $end = '...';
  5544. }
  5545. }
  5546. // If force rounding
  5547. if ((string) $forcerounding != '-1') {
  5548. if ($forcerounding === 'MU') {
  5549. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5550. } elseif ($forcerounding === 'MT') {
  5551. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5552. } elseif ($forcerounding >= 0) {
  5553. $nbdecimal = $forcerounding;
  5554. }
  5555. }
  5556. // Format number
  5557. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5558. if ($form) {
  5559. $output = preg_replace('/\s/', '&nbsp;', $output);
  5560. $output = preg_replace('/\'/', '&#039;', $output);
  5561. }
  5562. // Add symbol of currency if requested
  5563. $cursymbolbefore = $cursymbolafter = '';
  5564. if ($currency_code && is_object($outlangs)) {
  5565. if ($currency_code == 'auto') {
  5566. $currency_code = $conf->currency;
  5567. }
  5568. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC');
  5569. $listoflanguagesbefore = array('nl_NL');
  5570. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5571. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5572. } else {
  5573. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5574. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5575. }
  5576. }
  5577. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5578. return $output;
  5579. }
  5580. /**
  5581. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5582. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5583. * should be roundtext2num().
  5584. *
  5585. * @param string|float $amount Amount to convert/clean or round
  5586. * @param string|int $rounding ''=No rounding
  5587. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5588. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5589. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5590. * 'CU'=Round to Max unit price of foreign currency accuracy
  5591. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5592. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5593. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5594. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5595. * @return string Amount with universal numeric format (Example: '99.99999').
  5596. * If conversion fails to return a numeric, it returns:
  5597. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5598. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5599. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5600. * If amount is null or '', it returns '' if $rounding = '', it returns '0' if $rounding is defined.
  5601. *
  5602. * @see price() Opposite function of price2num
  5603. */
  5604. function price2num($amount, $rounding = '', $option = 0)
  5605. {
  5606. global $langs, $conf;
  5607. // Clean parameters
  5608. if (is_null($amount)) {
  5609. $amount = '';
  5610. }
  5611. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5612. // Numbers must be '1234.56'
  5613. // Decimal delimiter for PHP and database SQL requests must be '.'
  5614. $dec = ',';
  5615. $thousand = ' ';
  5616. if (is_null($langs)) { // $langs is not defined, we use english values.
  5617. $dec = '.';
  5618. $thousand = ',';
  5619. } else {
  5620. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5621. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5622. }
  5623. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5624. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5625. }
  5626. }
  5627. if ($thousand == 'None') {
  5628. $thousand = '';
  5629. } elseif ($thousand == 'Space') {
  5630. $thousand = ' ';
  5631. }
  5632. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5633. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5634. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5635. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5636. if (!is_numeric($amount)) {
  5637. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5638. }
  5639. 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
  5640. $amount = str_replace($thousand, '', $amount);
  5641. }
  5642. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5643. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5644. // So if number was already a good number, it is converted into local Dolibarr setup.
  5645. if (is_numeric($amount)) {
  5646. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5647. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5648. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5649. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5650. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5651. }
  5652. //print "QQ".$amount."<br>\n";
  5653. // Now make replace (the main goal of function)
  5654. if ($thousand != ',' && $thousand != '.') {
  5655. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5656. }
  5657. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5658. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5659. $amount = str_replace($dec, '.', $amount);
  5660. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5661. }
  5662. //print ' XX'.$amount.' '.$rounding;
  5663. // Now, $amount is a real PHP float number. We make a rounding if required.
  5664. if ($rounding) {
  5665. $nbofdectoround = '';
  5666. if ($rounding == 'MU') {
  5667. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5668. } elseif ($rounding == 'MT') {
  5669. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5670. } elseif ($rounding == 'MS') {
  5671. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5672. } elseif ($rounding == 'CU') {
  5673. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5674. } elseif ($rounding == 'CT') {
  5675. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5676. } elseif (is_numeric($rounding)) {
  5677. $nbofdectoround = (int) $rounding;
  5678. }
  5679. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5680. if (dol_strlen($nbofdectoround)) {
  5681. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5682. } else {
  5683. return 'ErrorBadParameterProvidedToFunction';
  5684. }
  5685. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5686. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5687. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5688. if (is_numeric($amount)) {
  5689. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5690. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5691. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5692. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5693. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5694. }
  5695. //print "TT".$amount.'<br>';
  5696. // Always make replace because each math function (like round) replace
  5697. // with local values and we want a number that has a SQL string format x.y
  5698. if ($thousand != ',' && $thousand != '.') {
  5699. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5700. }
  5701. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5702. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5703. $amount = str_replace($dec, '.', $amount);
  5704. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5705. }
  5706. return $amount;
  5707. }
  5708. /**
  5709. * Output a dimension with best unit
  5710. *
  5711. * @param float $dimension Dimension
  5712. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5713. * @param string $type 'weight', 'volume', ...
  5714. * @param Translate $outputlangs Translate language object
  5715. * @param int $round -1 = non rounding, x = number of decimal
  5716. * @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)
  5717. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5718. * @return string String to show dimensions
  5719. */
  5720. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5721. {
  5722. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5723. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5724. $dimension = $dimension * 1000000;
  5725. $unit = $unit - 6;
  5726. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5727. $dimension = $dimension * 1000;
  5728. $unit = $unit - 3;
  5729. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5730. $dimension = $dimension / 1000000;
  5731. $unit = $unit + 6;
  5732. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5733. $dimension = $dimension / 1000;
  5734. $unit = $unit + 3;
  5735. }
  5736. // Special case when we want output unit into pound or ounce
  5737. /* TODO
  5738. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5739. {
  5740. $dimension = // convert dimension from standard unit into ounce or pound
  5741. $unit = $forceunitoutput;
  5742. }
  5743. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5744. {
  5745. $dimension = // convert dimension from standard unit into ounce or pound
  5746. $unit = $forceunitoutput;
  5747. }*/
  5748. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5749. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5750. return $ret;
  5751. }
  5752. /**
  5753. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5754. * Note: This function applies same rules than get_default_tva
  5755. *
  5756. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5757. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5758. * @param Societe $thirdparty_buyer Object of buying third party
  5759. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5760. * @param int $vatnpr If vat rate is NPR or not
  5761. * @return mixed 0 if not found, localtax rate if found
  5762. * @see get_default_tva()
  5763. */
  5764. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5765. {
  5766. global $db, $conf, $mysoc;
  5767. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5768. $thirdparty_seller = $mysoc;
  5769. }
  5770. 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);
  5771. $vatratecleaned = $vatrate;
  5772. $reg = array();
  5773. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5774. $vatratecleaned = trim($reg[1]);
  5775. $vatratecode = $reg[2];
  5776. }
  5777. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5778. {
  5779. return 0;
  5780. }*/
  5781. // Some test to guess with no need to make database access
  5782. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5783. if ($local == 1) {
  5784. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5785. return 0;
  5786. }
  5787. if ($thirdparty_seller->id == $mysoc->id) {
  5788. if (!$thirdparty_buyer->localtax1_assuj) {
  5789. return 0;
  5790. }
  5791. } else {
  5792. if (!$thirdparty_seller->localtax1_assuj) {
  5793. return 0;
  5794. }
  5795. }
  5796. }
  5797. if ($local == 2) {
  5798. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5799. if (!$mysoc->localtax2_assuj) {
  5800. return 0; // If main vat is 0, IRPF may be different than 0.
  5801. }
  5802. if ($thirdparty_seller->id == $mysoc->id) {
  5803. if (!$thirdparty_buyer->localtax2_assuj) {
  5804. return 0;
  5805. }
  5806. } else {
  5807. if (!$thirdparty_seller->localtax2_assuj) {
  5808. return 0;
  5809. }
  5810. }
  5811. }
  5812. } else {
  5813. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5814. return 0;
  5815. }
  5816. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5817. return 0;
  5818. }
  5819. }
  5820. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5821. if (in_array($mysoc->country_code, array('ES'))) {
  5822. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5823. }
  5824. // Search local taxes
  5825. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5826. if ($local == 1) {
  5827. if ($thirdparty_seller != $mysoc) {
  5828. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5829. return $thirdparty_seller->localtax1_value;
  5830. }
  5831. } else { // i am the seller
  5832. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5833. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5834. }
  5835. }
  5836. }
  5837. if ($local == 2) {
  5838. if ($thirdparty_seller != $mysoc) {
  5839. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5840. // TODO We should also return value defined on thirdparty only if defined
  5841. return $thirdparty_seller->localtax2_value;
  5842. }
  5843. } else { // i am the seller
  5844. if (in_array($mysoc->country_code, array('ES'))) {
  5845. return $thirdparty_buyer->localtax2_value;
  5846. } else {
  5847. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5848. }
  5849. }
  5850. }
  5851. }
  5852. // By default, search value of local tax on line of common tax
  5853. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5854. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5855. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5856. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5857. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5858. if (!empty($vatratecode)) {
  5859. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5860. } else {
  5861. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5862. }
  5863. $resql = $db->query($sql);
  5864. if ($resql) {
  5865. $obj = $db->fetch_object($resql);
  5866. if ($obj) {
  5867. if ($local == 1) {
  5868. return $obj->localtax1;
  5869. } elseif ($local == 2) {
  5870. return $obj->localtax2;
  5871. }
  5872. }
  5873. }
  5874. return 0;
  5875. }
  5876. /**
  5877. * Return true if LocalTax (1 or 2) is unique.
  5878. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5879. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5880. *
  5881. * @param int $local Local tax to test (1 or 2)
  5882. * @return boolean True if LocalTax have multiple values, False if not
  5883. */
  5884. function isOnlyOneLocalTax($local)
  5885. {
  5886. $tax = get_localtax_by_third($local);
  5887. $valors = explode(":", $tax);
  5888. if (count($valors) > 1) {
  5889. return false;
  5890. } else {
  5891. return true;
  5892. }
  5893. }
  5894. /**
  5895. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5896. *
  5897. * @param int $local LocalTax to get
  5898. * @return string Values of localtax (Can be '20', '-19:-15:-9') or 'Error'
  5899. */
  5900. function get_localtax_by_third($local)
  5901. {
  5902. global $db, $mysoc;
  5903. $sql = " SELECT t.localtax".$local." as localtax";
  5904. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
  5905. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.entity IN (".getEntity('c_tva').") AND t.taux = (";
  5906. $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";
  5907. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.entity IN (".getEntity('c_tva').") AND tt.active = 1)";
  5908. $sql .= " AND t.localtax".$local."_type <> '0'";
  5909. $sql .= " ORDER BY t.rowid DESC";
  5910. $resql = $db->query($sql);
  5911. if ($resql) {
  5912. $obj = $db->fetch_object($resql);
  5913. if ($obj) {
  5914. return $obj->localtax;
  5915. } else {
  5916. return '0';
  5917. }
  5918. }
  5919. return 'Error';
  5920. }
  5921. /**
  5922. * Get tax (VAT) main information from Id.
  5923. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5924. *
  5925. * @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.
  5926. * @param Societe $buyer Company object
  5927. * @param Societe $seller Company object
  5928. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5929. * @return array array('rowid'=> , 'code'=> ...)
  5930. * @see getLocalTaxesFromRate()
  5931. */
  5932. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5933. {
  5934. global $db, $mysoc;
  5935. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5936. // Search local taxes
  5937. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5938. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5939. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5940. if ($firstparamisid) {
  5941. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5942. } else {
  5943. $vatratecleaned = $vatrate;
  5944. $vatratecode = '';
  5945. $reg = array();
  5946. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5947. $vatratecleaned = $reg[1];
  5948. $vatratecode = $reg[2];
  5949. }
  5950. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5951. /*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 ??
  5952. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5953. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5954. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5955. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5956. if ($vatratecode) {
  5957. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5958. }
  5959. }
  5960. $resql = $db->query($sql);
  5961. if ($resql) {
  5962. $obj = $db->fetch_object($resql);
  5963. if ($obj) {
  5964. return array(
  5965. 'rowid'=>$obj->rowid,
  5966. 'code'=>$obj->code,
  5967. 'rate'=>$obj->rate,
  5968. 'localtax1'=>$obj->localtax1,
  5969. 'localtax1_type'=>$obj->localtax1_type,
  5970. 'localtax2'=>$obj->localtax2,
  5971. 'localtax2_type'=>$obj->localtax2_type,
  5972. 'npr'=>$obj->npr,
  5973. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5974. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5975. );
  5976. } else {
  5977. return array();
  5978. }
  5979. } else {
  5980. dol_print_error($db);
  5981. }
  5982. return array();
  5983. }
  5984. /**
  5985. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5986. * This does not take into account the seller setup if subject to vat or not, only country.
  5987. *
  5988. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5989. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5990. * provide the selected value to the function calcul_price_total.
  5991. *
  5992. * @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.
  5993. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5994. * @param Societe $buyer Company object
  5995. * @param Societe $seller Company object
  5996. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5997. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5998. * @see getTaxesFromId()
  5999. */
  6000. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  6001. {
  6002. global $db, $mysoc;
  6003. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  6004. // Search local taxes
  6005. $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";
  6006. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  6007. if ($firstparamisid) {
  6008. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  6009. } else {
  6010. $vatratecleaned = $vatrate;
  6011. $vatratecode = '';
  6012. $reg = array();
  6013. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  6014. $vatratecleaned = $reg[1];
  6015. $vatratecode = $reg[2];
  6016. }
  6017. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  6018. if (!empty($mysoc) && $mysoc->country_code == 'ES') {
  6019. $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
  6020. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'"; // local tax in spain use the buyer country ??
  6021. } else {
  6022. $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
  6023. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'";
  6024. }
  6025. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  6026. if ($vatratecode) {
  6027. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  6028. }
  6029. }
  6030. $resql = $db->query($sql);
  6031. if ($resql) {
  6032. $obj = $db->fetch_object($resql);
  6033. if ($obj) {
  6034. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  6035. if ($local == 1) {
  6036. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  6037. } elseif ($local == 2) {
  6038. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  6039. } else {
  6040. 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);
  6041. }
  6042. }
  6043. }
  6044. return array();
  6045. }
  6046. /**
  6047. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  6048. * Function called by get_default_tva().
  6049. *
  6050. * @param int $idprod Id of product or 0 if not a predefined product
  6051. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  6052. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  6053. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  6054. * @see get_product_localtax_for_country()
  6055. */
  6056. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  6057. {
  6058. global $db, $conf, $mysoc;
  6059. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6060. $ret = 0;
  6061. $found = 0;
  6062. if ($idprod > 0) {
  6063. // Load product
  6064. $product = new Product($db);
  6065. $product->fetch($idprod);
  6066. if ($mysoc->country_code == $thirdpartytouse->country_code) {
  6067. // If country to consider is ours
  6068. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  6069. $result = $product->get_buyprice($idprodfournprice, 0, 0, 0);
  6070. if ($result > 0) {
  6071. $ret = $product->vatrate_supplier;
  6072. if ($product->default_vat_code_supplier) {
  6073. $ret .= ' ('.$product->default_vat_code_supplier.')';
  6074. }
  6075. $found = 1;
  6076. }
  6077. }
  6078. if (!$found) {
  6079. $ret = $product->tva_tx; // Default sales vat of product
  6080. if ($product->default_vat_code) {
  6081. $ret .= ' ('.$product->default_vat_code.')';
  6082. }
  6083. $found = 1;
  6084. }
  6085. } else {
  6086. // TODO Read default product vat according to product and another countrycode.
  6087. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  6088. }
  6089. }
  6090. if (!$found) {
  6091. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  6092. // If vat of product for the country not found or not defined, we return the first rate found (sorting on use_default, then on higher vat of country).
  6093. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  6094. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  6095. $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
  6096. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  6097. $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
  6098. $sql .= $db->plimit(1);
  6099. $resql = $db->query($sql);
  6100. if ($resql) {
  6101. $obj = $db->fetch_object($resql);
  6102. if ($obj) {
  6103. $ret = $obj->vat_rate;
  6104. if ($obj->default_vat_code) {
  6105. $ret .= ' ('.$obj->default_vat_code.')';
  6106. }
  6107. }
  6108. $db->free($resql);
  6109. } else {
  6110. dol_print_error($db);
  6111. }
  6112. } else {
  6113. // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
  6114. // '1.23'
  6115. // or '1.23 (CODE)'
  6116. $defaulttx = '';
  6117. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  6118. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  6119. }
  6120. /*if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  6121. $defaultcode = $reg[1];
  6122. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  6123. }*/
  6124. $ret = $defaulttx;
  6125. }
  6126. }
  6127. dol_syslog("get_product_vat_for_country: ret=".$ret);
  6128. return $ret;
  6129. }
  6130. /**
  6131. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  6132. *
  6133. * @param int $idprod Id of product
  6134. * @param int $local 1 for localtax1, 2 for localtax 2
  6135. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  6136. * @return int <0 if KO, Vat rate if OK
  6137. * @see get_product_vat_for_country()
  6138. */
  6139. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  6140. {
  6141. global $db, $mysoc;
  6142. if (!class_exists('Product')) {
  6143. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6144. }
  6145. $ret = 0;
  6146. $found = 0;
  6147. if ($idprod > 0) {
  6148. // Load product
  6149. $product = new Product($db);
  6150. $result = $product->fetch($idprod);
  6151. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  6152. /* Not defined yet, so we don't use this
  6153. if ($local==1) $ret=$product->localtax1_tx;
  6154. elseif ($local==2) $ret=$product->localtax2_tx;
  6155. $found=1;
  6156. */
  6157. } else {
  6158. // TODO Read default product vat according to product and another countrycode.
  6159. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  6160. }
  6161. }
  6162. if (!$found) {
  6163. // If vat of product for the country not found or not defined, we return higher vat of country.
  6164. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  6165. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  6166. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  6167. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  6168. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  6169. $sql .= $db->plimit(1);
  6170. $resql = $db->query($sql);
  6171. if ($resql) {
  6172. $obj = $db->fetch_object($resql);
  6173. if ($obj) {
  6174. if ($local == 1) {
  6175. $ret = $obj->localtax1;
  6176. } elseif ($local == 2) {
  6177. $ret = $obj->localtax2;
  6178. }
  6179. }
  6180. } else {
  6181. dol_print_error($db);
  6182. }
  6183. }
  6184. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  6185. return $ret;
  6186. }
  6187. /**
  6188. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  6189. * VATRULE 1: If seller does not use VAT, default VAT is 0. End of rule.
  6190. * VATRULE 2: If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6191. * VATRULE 3: If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  6192. * VATRULE 4: If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6193. * VATRULE 5: If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6194. * VATRULE 6: Otherwise the VAT proposed by default=0. End of rule.
  6195. *
  6196. * @param Societe $thirdparty_seller Objet societe vendeuse
  6197. * @param Societe $thirdparty_buyer Objet societe acheteuse
  6198. * @param int $idprod Id product
  6199. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  6200. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  6201. * @see get_default_npr(), get_default_localtax()
  6202. */
  6203. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6204. {
  6205. global $conf;
  6206. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  6207. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  6208. $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;
  6209. $seller_country_code = $thirdparty_seller->country_code;
  6210. $seller_in_cee = isInEEC($thirdparty_seller);
  6211. $buyer_country_code = $thirdparty_buyer->country_code;
  6212. $buyer_in_cee = isInEEC($thirdparty_buyer);
  6213. 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 : ''));
  6214. // 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)
  6215. // we use the buyer VAT.
  6216. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  6217. if ($seller_in_cee && $buyer_in_cee) {
  6218. $isacompany = $thirdparty_buyer->isACompany();
  6219. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6220. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6221. if (!isValidVATID($thirdparty_buyer)) {
  6222. $isacompany = 0;
  6223. }
  6224. }
  6225. if (!$isacompany) {
  6226. //print 'VATRULE 0';
  6227. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  6228. }
  6229. }
  6230. }
  6231. // If seller does not use VAT, default VAT is 0. End of rule.
  6232. if (!$seller_use_vat) {
  6233. //print 'VATRULE 1';
  6234. return 0;
  6235. }
  6236. // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6237. if (($seller_country_code == $buyer_country_code)
  6238. || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  6239. //print 'VATRULE 2';
  6240. $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6241. if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
  6242. // Special case for india.
  6243. //print 'VATRULE 2b';
  6244. $reg = array();
  6245. if (preg_match('/C+S-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
  6246. // we must revert the C+S into I
  6247. $tmpvat = str_replace("C+S", "I", $tmpvat);
  6248. } elseif (preg_match('/I-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
  6249. // we must revert the I into C+S
  6250. $tmpvat = str_replace("I", "C+S", $tmpvat);
  6251. }
  6252. }
  6253. return $tmpvat;
  6254. }
  6255. // If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  6256. // 'VATRULE 3' - Not supported
  6257. // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6258. // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6259. if (($seller_in_cee && $buyer_in_cee)) {
  6260. $isacompany = $thirdparty_buyer->isACompany();
  6261. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6262. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6263. if (!isValidVATID($thirdparty_buyer)) {
  6264. $isacompany = 0;
  6265. }
  6266. }
  6267. if (!$isacompany) {
  6268. //print 'VATRULE 4';
  6269. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6270. } else {
  6271. //print 'VATRULE 5';
  6272. return 0;
  6273. }
  6274. }
  6275. // If (seller in the European Community and buyer outside the European Community and private buyer) then VAT by default = VAT of the product sold. End of rule
  6276. // I don't see any use case that need this rule.
  6277. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  6278. $isacompany = $thirdparty_buyer->isACompany();
  6279. if (!$isacompany) {
  6280. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6281. //print 'VATRULE extra';
  6282. }
  6283. }
  6284. // Otherwise the VAT proposed by default=0. End of rule.
  6285. // Rem: This means that at least one of the 2 is outside the European Community and the country differs
  6286. //print 'VATRULE 6';
  6287. return 0;
  6288. }
  6289. /**
  6290. * Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
  6291. *
  6292. * @param Societe $thirdparty_seller Thirdparty seller
  6293. * @param Societe $thirdparty_buyer Thirdparty buyer
  6294. * @param int $idprod Id product
  6295. * @param int $idprodfournprice Id supplier price for product
  6296. * @return float 0 or 1
  6297. * @see get_default_tva(), get_default_localtax()
  6298. */
  6299. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6300. {
  6301. global $db;
  6302. if ($idprodfournprice > 0) {
  6303. if (!class_exists('ProductFournisseur')) {
  6304. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6305. }
  6306. $prodprice = new ProductFournisseur($db);
  6307. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  6308. return $prodprice->fourn_tva_npr;
  6309. } elseif ($idprod > 0) {
  6310. if (!class_exists('Product')) {
  6311. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6312. }
  6313. $prod = new Product($db);
  6314. $prod->fetch($idprod);
  6315. return $prod->tva_npr;
  6316. }
  6317. return 0;
  6318. }
  6319. /**
  6320. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  6321. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  6322. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  6323. * Sinon TVA proposee par defaut=0. Fin de regle.
  6324. *
  6325. * @param Societe $thirdparty_seller Thirdparty seller
  6326. * @param Societe $thirdparty_buyer Thirdparty buyer
  6327. * @param int $local Localtax to process (1 or 2)
  6328. * @param int $idprod Id product
  6329. * @return integer localtax, -1 si ne peut etre determine
  6330. * @see get_default_tva(), get_default_npr()
  6331. */
  6332. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  6333. {
  6334. global $mysoc;
  6335. if (!is_object($thirdparty_seller)) {
  6336. return -1;
  6337. }
  6338. if (!is_object($thirdparty_buyer)) {
  6339. return -1;
  6340. }
  6341. if ($local == 1) { // Localtax 1
  6342. if ($mysoc->country_code == 'ES') {
  6343. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  6344. return 0;
  6345. }
  6346. } else {
  6347. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  6348. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  6349. return 0;
  6350. }
  6351. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  6352. return 0;
  6353. }
  6354. }
  6355. } elseif ($local == 2) { //I Localtax 2
  6356. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  6357. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  6358. return 0;
  6359. }
  6360. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  6361. return 0;
  6362. }
  6363. }
  6364. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  6365. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  6366. }
  6367. return 0;
  6368. }
  6369. /**
  6370. * Return yes or no in current language
  6371. *
  6372. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  6373. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  6374. * @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.
  6375. * @return string HTML string
  6376. */
  6377. function yn($yesno, $case = 1, $color = 0)
  6378. {
  6379. global $langs;
  6380. $result = 'unknown';
  6381. $classname = '';
  6382. if ($yesno == 1 || (isset($yesno) && (strtolower($yesno) == 'yes' || strtolower($yesno) == 'true'))) { // A mettre avant test sur no a cause du == 0
  6383. $result = $langs->trans('yes');
  6384. if ($case == 1 || $case == 3) {
  6385. $result = $langs->trans("Yes");
  6386. }
  6387. if ($case == 2) {
  6388. $result = '<input type="checkbox" value="1" checked disabled>';
  6389. }
  6390. if ($case == 3) {
  6391. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  6392. }
  6393. $classname = 'ok';
  6394. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  6395. $result = $langs->trans("no");
  6396. if ($case == 1 || $case == 3) {
  6397. $result = $langs->trans("No");
  6398. }
  6399. if ($case == 2) {
  6400. $result = '<input type="checkbox" value="0" disabled>';
  6401. }
  6402. if ($case == 3) {
  6403. $result = '<input type="checkbox" value="0" disabled> '.$result;
  6404. }
  6405. if ($color == 2) {
  6406. $classname = 'ok';
  6407. } else {
  6408. $classname = 'error';
  6409. }
  6410. }
  6411. if ($color) {
  6412. return '<span class="'.$classname.'">'.$result.'</span>';
  6413. }
  6414. return $result;
  6415. }
  6416. /**
  6417. * Return a path to have a the directory according to object where files are stored.
  6418. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  6419. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  6420. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  6421. * 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/"
  6422. *
  6423. * @param string|int $num Id of object (deprecated, $object will be used in future)
  6424. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  6425. * @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)
  6426. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  6427. * @param Object $object Object to use to get ref to forge the path.
  6428. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  6429. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  6430. */
  6431. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  6432. {
  6433. global $conf;
  6434. if (empty($modulepart) && !empty($object->module)) {
  6435. $modulepart = $object->module;
  6436. }
  6437. $path = '';
  6438. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  6439. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  6440. $arrayforoldpath[] = 'product';
  6441. }
  6442. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  6443. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  6444. if (empty($alpha)) {
  6445. $num = preg_replace('/([^0-9])/i', '', $num);
  6446. } else {
  6447. $num = preg_replace('/^.*\-/i', '', $num);
  6448. }
  6449. $num = substr("000".$num, -$level);
  6450. if ($level == 1) {
  6451. $path = substr($num, 0, 1);
  6452. }
  6453. if ($level == 2) {
  6454. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  6455. }
  6456. if ($level == 3) {
  6457. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  6458. }
  6459. } else {
  6460. // We will enhance here a common way of forging path for document storage.
  6461. // In a future, we may distribute directories on several levels depending on setup and object.
  6462. // Here, $object->id, $object->ref and $modulepart are required.
  6463. //var_dump($modulepart);
  6464. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  6465. }
  6466. if (empty($withoutslash) && !empty($path)) {
  6467. $path .= '/';
  6468. }
  6469. return $path;
  6470. }
  6471. /**
  6472. * Creation of a directory (this can create recursive subdir)
  6473. *
  6474. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  6475. * @param string $dataroot Data root directory (To avoid having the data root in the loop. Using this will also lost the warning, on first dir, saying PHP has no permission when open_basedir is used)
  6476. * @param string $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  6477. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  6478. */
  6479. function dol_mkdir($dir, $dataroot = '', $newmask = '')
  6480. {
  6481. global $conf;
  6482. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  6483. $dir_osencoded = dol_osencode($dir);
  6484. if (@is_dir($dir_osencoded)) {
  6485. return 0;
  6486. }
  6487. $nberr = 0;
  6488. $nbcreated = 0;
  6489. $ccdir = '';
  6490. if (!empty($dataroot)) {
  6491. // Remove data root from loop
  6492. $dir = str_replace($dataroot.'/', '', $dir);
  6493. $ccdir = $dataroot.'/';
  6494. }
  6495. $cdir = explode("/", $dir);
  6496. $num = count($cdir);
  6497. for ($i = 0; $i < $num; $i++) {
  6498. if ($i > 0) {
  6499. $ccdir .= '/'.$cdir[$i];
  6500. } else {
  6501. $ccdir .= $cdir[$i];
  6502. }
  6503. $regs = array();
  6504. if (preg_match("/^.:$/", $ccdir, $regs)) {
  6505. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  6506. }
  6507. // Attention, le is_dir() peut echouer bien que le rep existe.
  6508. // (ex selon config de open_basedir)
  6509. if ($ccdir) {
  6510. $ccdir_osencoded = dol_osencode($ccdir);
  6511. if (!@is_dir($ccdir_osencoded)) {
  6512. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  6513. umask(0);
  6514. $dirmaskdec = octdec((string) $newmask);
  6515. if (empty($newmask)) {
  6516. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  6517. }
  6518. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  6519. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  6520. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  6521. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  6522. $nberr++;
  6523. } else {
  6524. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  6525. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  6526. $nbcreated++;
  6527. }
  6528. } else {
  6529. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  6530. }
  6531. }
  6532. }
  6533. return ($nberr ? -$nberr : $nbcreated);
  6534. }
  6535. /**
  6536. * Change mod of a file
  6537. *
  6538. * @param string $filepath Full file path
  6539. * @param string $newmask Force new mask. For example '0644'
  6540. * @return void
  6541. */
  6542. function dolChmod($filepath, $newmask = '')
  6543. {
  6544. global $conf;
  6545. if (!empty($newmask)) {
  6546. @chmod($filepath, octdec($newmask));
  6547. } elseif (!empty($conf->global->MAIN_UMASK)) {
  6548. @chmod($filepath, octdec($conf->global->MAIN_UMASK));
  6549. }
  6550. }
  6551. /**
  6552. * Return picto saying a field is required
  6553. *
  6554. * @return string Chaine avec picto obligatoire
  6555. */
  6556. function picto_required()
  6557. {
  6558. return '<span class="fieldrequired">*</span>';
  6559. }
  6560. /**
  6561. * Clean a string from all HTML tags and entities.
  6562. * This function differs from strip_tags because:
  6563. * - <br> are replaced with \n if removelinefeed=0 or 1
  6564. * - if entities are found, they are decoded BEFORE the strip
  6565. * - you can decide to convert line feed into a space
  6566. *
  6567. * @param string $stringtoclean String to clean
  6568. * @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..."
  6569. * @param string $pagecodeto Encoding of input/output string
  6570. * @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')
  6571. * @param integer $removedoublespaces Replace double space into one space
  6572. * @return string String cleaned
  6573. *
  6574. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6575. */
  6576. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6577. {
  6578. if (is_null($stringtoclean)) {
  6579. return '';
  6580. }
  6581. if ($removelinefeed == 2) {
  6582. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6583. }
  6584. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6585. // 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)
  6586. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6587. $temp = str_replace('< ', '__ltspace__', $temp);
  6588. if ($strip_tags) {
  6589. $temp = strip_tags($temp);
  6590. } else {
  6591. // 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).
  6592. $pattern = "/<[^<>]+>/";
  6593. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6594. // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6595. // pass 2 - $temp after pass 2: 0000-021
  6596. $tempbis = $temp;
  6597. do {
  6598. $temp = $tempbis;
  6599. $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6600. $tempbis = preg_replace($pattern, '', $tempbis);
  6601. //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
  6602. } while ($tempbis != $temp);
  6603. $temp = $tempbis;
  6604. // Remove '<' into remaining, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
  6605. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6606. }
  6607. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6608. // Remove also carriage returns
  6609. if ($removelinefeed == 1) {
  6610. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6611. }
  6612. // And double quotes
  6613. if ($removedoublespaces) {
  6614. while (strpos($temp, " ")) {
  6615. $temp = str_replace(" ", " ", $temp);
  6616. }
  6617. }
  6618. $temp = str_replace('__ltspace__', '< ', $temp);
  6619. return trim($temp);
  6620. }
  6621. /**
  6622. * Clean a string to keep only desirable HTML tags.
  6623. * WARNING: This also clean HTML comments (because they can be used to obfuscate tag name).
  6624. *
  6625. * @param string $stringtoclean String to clean
  6626. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6627. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6628. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6629. * @param int $allowiframe Allow iframe tags.
  6630. * @param array $allowed_tags List of allowed tags to replace the default list
  6631. * @param int $allowlink Allow "link" tags.
  6632. * @return string String cleaned
  6633. *
  6634. * @see dol_htmlwithnojs() dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6635. */
  6636. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0)
  6637. {
  6638. if (empty($allowed_tags)) {
  6639. $allowed_tags = array(
  6640. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li",
  6641. "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"
  6642. );
  6643. }
  6644. $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6645. if ($allowiframe) {
  6646. if (!in_array('iframe', $allowed_tags)) {
  6647. $allowed_tags[] = "iframe";
  6648. }
  6649. }
  6650. if ($allowlink) {
  6651. if (!in_array('link', $allowed_tags)) {
  6652. $allowed_tags[] = "link";
  6653. }
  6654. }
  6655. $allowed_tags_string = join("><", $allowed_tags);
  6656. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6657. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6658. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6659. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6660. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6661. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6662. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6663. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </>, so may changes string obfuscated with </> that pass the injection detection into a harmfull string
  6664. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6665. $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
  6666. }
  6667. if ($removeclassattribute) { // Clean for remaining html tags
  6668. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6669. }
  6670. // Remove 'javascript:' that we should not find into a text with
  6671. // 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)).
  6672. if ($cleanalsojavascript) {
  6673. $temp = preg_replace('/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t\s*:/i', '', $temp);
  6674. }
  6675. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6676. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6677. return $temp;
  6678. }
  6679. /**
  6680. * Clean a string from some undesirable HTML tags.
  6681. * Note: Complementary to dol_string_onlythesehtmltags().
  6682. * This method is used for example by dol_htmlwithnojs() when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6683. *
  6684. * @param string $stringtoclean String to clean
  6685. * @param array $allowed_attributes Array of tags not allowed
  6686. * @return string String cleaned
  6687. *
  6688. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6689. */
  6690. 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"))
  6691. {
  6692. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6693. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6694. $dom = new DOMDocument(null, 'UTF-8');
  6695. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6696. if (is_object($dom)) {
  6697. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6698. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6699. //var_dump($attrs->item($ii));
  6700. if (!empty($attrs->item($ii)->name)) {
  6701. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6702. // Delete attribute if not into allowed_attributes
  6703. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6704. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6705. // If attribute is 'style'
  6706. $valuetoclean = $attrs->item($ii)->value;
  6707. if (isset($valuetoclean)) {
  6708. do {
  6709. $oldvaluetoclean = $valuetoclean;
  6710. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6711. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6712. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6713. $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
  6714. $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
  6715. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
  6716. }
  6717. // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
  6718. $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
  6719. $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
  6720. } while ($oldvaluetoclean != $valuetoclean);
  6721. }
  6722. $attrs->item($ii)->value = $valuetoclean;
  6723. }
  6724. }
  6725. }
  6726. }
  6727. }
  6728. $return = $dom->saveHTML(); // This may add a LF at end of lines, so we will trim later
  6729. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6730. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6731. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6732. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6733. return trim($return);
  6734. } else {
  6735. return $stringtoclean;
  6736. }
  6737. }
  6738. /**
  6739. * Clean a string from some undesirable HTML tags.
  6740. * Note: You should use instead dol_string_onlythesehtmltags() that is more secured if you can.
  6741. *
  6742. * @param string $stringtoclean String to clean
  6743. * @param array $disallowed_tags Array of tags not allowed
  6744. * @param string $cleanalsosomestyles Clean also some tags
  6745. * @return string String cleaned
  6746. *
  6747. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6748. */
  6749. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6750. {
  6751. $temp = $stringtoclean;
  6752. foreach ($disallowed_tags as $tagtoremove) {
  6753. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6754. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6755. }
  6756. if ($cleanalsosomestyles) {
  6757. $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
  6758. }
  6759. return $temp;
  6760. }
  6761. /**
  6762. * Return first line of text. Cut will depends if content is HTML or not.
  6763. *
  6764. * @param string $text Input text
  6765. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6766. * @param string $charset Charset of $text string (UTF-8 by default)
  6767. * @return string Output text
  6768. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6769. */
  6770. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6771. {
  6772. if ($nboflines == 1) {
  6773. if (dol_textishtml($text)) {
  6774. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6775. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6776. } else {
  6777. if (isset($text)) {
  6778. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6779. } else {
  6780. $firstline = '';
  6781. }
  6782. }
  6783. return $firstline.(isset($firstline) && isset($text) && (strlen($firstline) != strlen($text)) ? '...' : '');
  6784. } else {
  6785. $ishtml = 0;
  6786. if (dol_textishtml($text)) {
  6787. $text = preg_replace('/\n/', '', $text);
  6788. $ishtml = 1;
  6789. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6790. } else {
  6791. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6792. }
  6793. $text = strtr($text, $repTable);
  6794. if ($charset == 'UTF-8') {
  6795. $pattern = '/(<br[^>]*>)/Uu';
  6796. } else {
  6797. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6798. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6799. }
  6800. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6801. $firstline = '';
  6802. $i = 0; $countline = 0; $lastaddediscontent = 1;
  6803. while ($countline < $nboflines && isset($a[$i])) {
  6804. if (preg_match('/<br[^>]*>/', $a[$i])) {
  6805. if (array_key_exists($i+1, $a) && !empty($a[$i+1])) {
  6806. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6807. // Is it a br for a new line of after a printed line ?
  6808. if (!$lastaddediscontent) {
  6809. $countline++;
  6810. }
  6811. $lastaddediscontent = 0;
  6812. }
  6813. } else {
  6814. $firstline .= $a[$i];
  6815. $lastaddediscontent = 1;
  6816. $countline++;
  6817. }
  6818. $i++;
  6819. }
  6820. $adddots = (isset($a[$i]) && (!preg_match('/<br[^>]*>/', $a[$i]) || (array_key_exists($i+1, $a) && !empty($a[$i+1]))));
  6821. //unset($a);
  6822. $ret = $firstline.($adddots ? '...' : '');
  6823. //exit;
  6824. return $ret;
  6825. }
  6826. }
  6827. /**
  6828. * Replace CRLF in string with a HTML BR tag.
  6829. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have
  6830. * encoded the special chars of stringtoencode into HTML before with dol_htmlentitiesbr().
  6831. *
  6832. * @param string $stringtoencode String to encode
  6833. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6834. * @param bool $forxml false=Use <br>, true=Use <br />
  6835. * @return string String encoded
  6836. * @see dol_htmlentitiesbr(), dol_nboflines(), dolGetFirstLineOfText()
  6837. */
  6838. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6839. {
  6840. if (is_null($stringtoencode)) {
  6841. return '';
  6842. }
  6843. if (!$nl2brmode) {
  6844. return nl2br($stringtoencode, $forxml);
  6845. } else {
  6846. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6847. return $ret;
  6848. }
  6849. }
  6850. /**
  6851. * Sanitize a HTML to remove js and dangerous content
  6852. *
  6853. * @param string $stringtoencode String to encode
  6854. * @param int $nouseofiframesandbox 0=Default, 1=Allow use of option MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS for html sanitizing (not yet working)
  6855. * @param string $check 'restricthtmlnolink' or 'restricthtml' or 'restricthtmlallowclass' or 'restricthtmlallowunvalid'
  6856. * @return string HTML sanitized
  6857. */
  6858. function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
  6859. {
  6860. global $conf;
  6861. if (empty($nouseofiframesandbox) && !empty($conf->global->MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS)) {
  6862. // TODO using sandbox on inline html content is not possible yet with current browsers
  6863. //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
  6864. //$s .= $stringtoencode;
  6865. //$s .= '</body></html></iframe>';
  6866. return $stringtoencode;
  6867. } else {
  6868. $out = $stringtoencode;
  6869. do {
  6870. $oldstringtoclean = $out;
  6871. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  6872. try {
  6873. libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
  6874. $dom = new DOMDocument;
  6875. // Add a trick to solve pb with text without parent tag
  6876. // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
  6877. // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
  6878. $out = '<div class="tricktoremove">'.$out.'</div>';
  6879. $dom->loadHTML($out, LIBXML_HTML_NODEFDTD|LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6880. $out = trim($dom->saveHTML());
  6881. // Remove the trick added to solve pb with text without parent tag
  6882. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  6883. $out = preg_replace('/<\/div>$/', '', $out);
  6884. } catch (Exception $e) {
  6885. // If error, invalid HTML string with no way to clean it
  6886. //print $e->getMessage();
  6887. $out = 'InvalidHTMLStringCantBeCleaned';
  6888. }
  6889. }
  6890. // Clean some html entities that are useless so text is cleaner
  6891. $out = preg_replace('/&(tab|newline);/i', ' ', $out);
  6892. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  6893. // encoded using text entities) so we can then exclude all numeric entities.
  6894. $out = preg_replace('/&#39;/i', '&apos;', $out);
  6895. // We replace chars from a/A to z/Z encoded with numeric HTML entities with the real char so we won't loose the chars at the next step (preg_replace).
  6896. // 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
  6897. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  6898. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  6899. return realCharForNumericEntities($m); }, $out);
  6900. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  6901. $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'.
  6902. // Keep only some html tags and remove also some 'javascript:' strings
  6903. $out = dol_string_onlythesehtmltags($out, 0, ($check == 'restricthtmlallowclass' ? 0 : 1), 1);
  6904. // Keep only some html attributes and exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
  6905. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  6906. $out = dol_string_onlythesehtmlattributes($out);
  6907. }
  6908. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  6909. $out = preg_replace('/&apos;/i', "&#39;", $out);
  6910. } while ($oldstringtoclean != $out);
  6911. // Check the limit of external links that are automatically executed in a Rich text content. We count:
  6912. // '<img' to avoid <img src="http...">
  6913. // 'url(' to avoid inline style like background: url(http...
  6914. // '<link' to avoid <link href="http...">
  6915. $reg = array();
  6916. preg_match_all('/(<img|url\(|<link)/i', $out, $reg);
  6917. $nbextlink = count($reg[0]);
  6918. if ($nbextlink > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
  6919. $out = 'TooManyLinksIntoHTMLString';
  6920. }
  6921. //
  6922. if (!empty($conf->global->MAIN_DISALLOW_EXT_URL_INTO_DESCRIPTIONS) || $check == 'restricthtmlnolink') {
  6923. if ($nbextlink > 0) {
  6924. $out = 'ExternalLinksNotAllowed';
  6925. }
  6926. }
  6927. return $out;
  6928. }
  6929. }
  6930. /**
  6931. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6932. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6933. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6934. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6935. * For PDF usage, you can show text by 2 ways:
  6936. * - writeHTMLCell -> param must be encoded into HTML.
  6937. * - MultiCell -> param must not be encoded into HTML.
  6938. * Because writeHTMLCell convert also \n into <br>, if function is used to build PDF, nl2brmode must be 1.
  6939. * Note: When we output string on pages, we should use
  6940. * - dolPrintHTML... that is dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1), 1, 1) for notes or descriptions,
  6941. * - dolPrintLabel... that is dol_escape_htmltag(dol_htmlentitiesbr()) for simple labels.
  6942. * - dolPrintPassword that is abelhtmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords.
  6943. *
  6944. * @param string $stringtoencode String to encode
  6945. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6946. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6947. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6948. * @return string String encoded
  6949. * @see dol_escape_htmltag(), dolGetFirstLineOfText(), dol_string_onlythesehtmltags()
  6950. */
  6951. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6952. {
  6953. if (is_null($stringtoencode)) {
  6954. return '';
  6955. }
  6956. $newstring = $stringtoencode;
  6957. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6958. $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.
  6959. if ($removelasteolbr) {
  6960. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6961. }
  6962. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6963. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6964. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6965. } else {
  6966. if ($removelasteolbr) {
  6967. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6968. }
  6969. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6970. }
  6971. // Other substitutions that htmlentities does not do
  6972. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6973. return $newstring;
  6974. }
  6975. /**
  6976. * This function is called to decode a HTML string (it decodes entities and br tags)
  6977. *
  6978. * @param string $stringtodecode String to decode
  6979. * @param string $pagecodeto Page code for result
  6980. * @return string String decoded
  6981. */
  6982. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6983. {
  6984. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6985. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6986. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6987. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6988. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6989. return $ret;
  6990. }
  6991. /**
  6992. * This function remove all ending \n and br at end
  6993. *
  6994. * @param string $stringtodecode String to decode
  6995. * @return string String decoded
  6996. */
  6997. function dol_htmlcleanlastbr($stringtodecode)
  6998. {
  6999. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  7000. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  7001. return $ret;
  7002. }
  7003. /**
  7004. * Replace html_entity_decode functions to manage errors
  7005. *
  7006. * @param string $a Operand a
  7007. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  7008. * @param string $c Operand c
  7009. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  7010. * @return string String decoded
  7011. */
  7012. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  7013. {
  7014. $newstring = $a;
  7015. if ($keepsomeentities) {
  7016. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  7017. }
  7018. $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
  7019. if ($keepsomeentities) {
  7020. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  7021. }
  7022. return $newstring;
  7023. }
  7024. /**
  7025. * Replace htmlentities functions.
  7026. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  7027. *
  7028. * @param string $string The input string to encode
  7029. * @param int $flags Flags (see PHP doc above)
  7030. * @param string $encoding Encoding page code
  7031. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  7032. * @return string $ret Encoded string
  7033. * @see dol_htmlentitiesbr()
  7034. */
  7035. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  7036. {
  7037. return htmlentities($string, $flags, $encoding, $double_encode);
  7038. }
  7039. /**
  7040. * Check if a string is a correct iso string
  7041. * If not, it will we considered not HTML encoded even if it is by FPDF.
  7042. * Example, if string contains euro symbol that has ascii code 128
  7043. *
  7044. * @param string $s String to check
  7045. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  7046. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  7047. */
  7048. function dol_string_is_good_iso($s, $clean = 0)
  7049. {
  7050. $len = dol_strlen($s);
  7051. $out = '';
  7052. $ok = 1;
  7053. for ($scursor = 0; $scursor < $len; $scursor++) {
  7054. $ordchar = ord($s[$scursor]);
  7055. //print $scursor.'-'.$ordchar.'<br>';
  7056. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  7057. $ok = 0;
  7058. break;
  7059. } elseif ($ordchar > 126 && $ordchar < 160) {
  7060. $ok = 0;
  7061. break;
  7062. } elseif ($clean) {
  7063. $out .= $s[$scursor];
  7064. }
  7065. }
  7066. if ($clean) {
  7067. return $out;
  7068. }
  7069. return $ok;
  7070. }
  7071. /**
  7072. * Return nb of lines of a clear text
  7073. *
  7074. * @param string $s String to check
  7075. * @param int $maxchar Not yet used
  7076. * @return int Number of lines
  7077. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  7078. */
  7079. function dol_nboflines($s, $maxchar = 0)
  7080. {
  7081. if ($s == '') {
  7082. return 0;
  7083. }
  7084. $arraystring = explode("\n", $s);
  7085. $nb = count($arraystring);
  7086. return $nb;
  7087. }
  7088. /**
  7089. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  7090. *
  7091. * @param string $text Text
  7092. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  7093. * @param string $charset Give the charset used to encode the $text variable in memory.
  7094. * @return int Number of lines
  7095. * @see dol_nboflines(), dolGetFirstLineOfText()
  7096. */
  7097. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  7098. {
  7099. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  7100. if (dol_textishtml($text)) {
  7101. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  7102. }
  7103. $text = strtr($text, $repTable);
  7104. if ($charset == 'UTF-8') {
  7105. $pattern = '/(<br[^>]*>)/Uu';
  7106. } else {
  7107. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  7108. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  7109. }
  7110. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  7111. $nblines = (int) floor((count($a) + 1) / 2);
  7112. // count possible auto line breaks
  7113. if ($maxlinesize) {
  7114. foreach ($a as $line) {
  7115. if (dol_strlen($line) > $maxlinesize) {
  7116. //$line_dec = html_entity_decode(strip_tags($line));
  7117. $line_dec = html_entity_decode($line);
  7118. if (dol_strlen($line_dec) > $maxlinesize) {
  7119. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  7120. $nblines += substr_count($line_dec, '\n');
  7121. }
  7122. }
  7123. }
  7124. }
  7125. unset($a);
  7126. return $nblines;
  7127. }
  7128. /**
  7129. * Return if a text is a html content
  7130. *
  7131. * @param string $msg Content to check
  7132. * @param int $option 0=Full detection, 1=Fast check
  7133. * @return boolean true/false
  7134. * @see dol_concatdesc()
  7135. */
  7136. function dol_textishtml($msg, $option = 0)
  7137. {
  7138. if (is_null($msg)) {
  7139. return false;
  7140. }
  7141. if ($option == 1) {
  7142. if (preg_match('/<html/i', $msg)) {
  7143. return true;
  7144. } elseif (preg_match('/<body/i', $msg)) {
  7145. return true;
  7146. } elseif (preg_match('/<\/textarea/i', $msg)) {
  7147. return true;
  7148. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  7149. return true;
  7150. } elseif (preg_match('/<br/i', $msg)) {
  7151. return true;
  7152. }
  7153. return false;
  7154. } else {
  7155. // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
  7156. $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
  7157. if (preg_match('/<html/i', $msg)) {
  7158. return true;
  7159. } elseif (preg_match('/<body/i', $msg)) {
  7160. return true;
  7161. } elseif (preg_match('/<\/textarea/i', $msg)) {
  7162. return true;
  7163. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  7164. return true;
  7165. } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
  7166. return true;
  7167. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
  7168. return true;
  7169. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  7170. return true;
  7171. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  7172. return true; // must accept <img src="http://example.com/aaa.png" />
  7173. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  7174. return true; // must accept <a href="http://example.com/aaa.png" />
  7175. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  7176. return true;
  7177. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  7178. // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
  7179. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  7180. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  7181. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  7182. }
  7183. return false;
  7184. }
  7185. }
  7186. /**
  7187. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  7188. * text1 html + text2 html => text1 + '<br>' + text2
  7189. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  7190. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  7191. * text1 txt + text2 txt => text1 + '\n' + text2
  7192. *
  7193. * @param string $text1 Text 1
  7194. * @param string $text2 Text 2
  7195. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  7196. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  7197. * @return string Text 1 + new line + Text2
  7198. * @see dol_textishtml()
  7199. */
  7200. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  7201. {
  7202. if (!empty($invert)) {
  7203. $tmp = $text1;
  7204. $text1 = $text2;
  7205. $text2 = $tmp;
  7206. }
  7207. $ret = '';
  7208. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  7209. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  7210. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  7211. return $ret;
  7212. }
  7213. /**
  7214. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  7215. *
  7216. * @param Translate $outputlangs Output language
  7217. * @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)
  7218. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7219. * @param Object $object Object for keys on object
  7220. * @param array $include Array of family keys we want to include. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7221. * @return array Array of substitutions
  7222. * @see setSubstitFromObject()
  7223. */
  7224. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
  7225. {
  7226. global $db, $conf, $mysoc, $user, $extrafields;
  7227. $substitutionarray = array();
  7228. if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include))) {
  7229. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  7230. // this will include signature content first and then replace var found into content of signature
  7231. //var_dump($onlykey);
  7232. $emailsendersignature = $user->signature; // dy default, we use the signature of current user. We must complete substitution with signature in c_email_senderprofile of array after calling getCommonSubstitutionArray()
  7233. $usersignature = $user->signature;
  7234. $substitutionarray = array_merge($substitutionarray, array(
  7235. '__SENDEREMAIL_SIGNATURE__' => (string) ((empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
  7236. '__USER_SIGNATURE__' => (string) (($usersignature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
  7237. ));
  7238. if (is_object($user)) {
  7239. $substitutionarray = array_merge($substitutionarray, array(
  7240. '__USER_ID__' => (string) $user->id,
  7241. '__USER_LOGIN__' => (string) $user->login,
  7242. '__USER_EMAIL__' => (string) $user->email,
  7243. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
  7244. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
  7245. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
  7246. '__USER_FAX__' => (string) $user->office_fax,
  7247. '__USER_LASTNAME__' => (string) $user->lastname,
  7248. '__USER_FIRSTNAME__' => (string) $user->firstname,
  7249. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  7250. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  7251. '__USER_JOB__' => (string) $user->job,
  7252. '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
  7253. '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
  7254. ));
  7255. }
  7256. }
  7257. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
  7258. $substitutionarray = array_merge($substitutionarray, array(
  7259. '__MYCOMPANY_NAME__' => $mysoc->name,
  7260. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  7261. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone, '', 0, 0, '', " ", '', '', -1),
  7262. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax, '', 0, 0, '', " ", '', '', -1),
  7263. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  7264. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  7265. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  7266. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  7267. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  7268. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  7269. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  7270. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  7271. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  7272. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  7273. '__MYCOMPANY_TOWN__' => $mysoc->town,
  7274. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  7275. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  7276. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  7277. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  7278. ));
  7279. }
  7280. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
  7281. if ($onlykey) {
  7282. $substitutionarray['__ID__'] = '__ID__';
  7283. $substitutionarray['__REF__'] = '__REF__';
  7284. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  7285. $substitutionarray['__LABEL__'] = '__LABEL__';
  7286. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  7287. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  7288. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  7289. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  7290. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  7291. if (isModEnabled("societe")) { // Most objects are concerned
  7292. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  7293. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  7294. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  7295. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  7296. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  7297. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  7298. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  7299. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  7300. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  7301. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  7302. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  7303. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  7304. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  7305. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  7306. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  7307. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  7308. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  7309. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  7310. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  7311. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  7312. }
  7313. if (isModEnabled('adherent') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
  7314. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  7315. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  7316. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  7317. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  7318. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  7319. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  7320. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  7321. }
  7322. // add variables subtitutions ticket
  7323. if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
  7324. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  7325. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  7326. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  7327. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  7328. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  7329. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  7330. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  7331. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  7332. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  7333. }
  7334. if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
  7335. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  7336. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  7337. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  7338. }
  7339. if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
  7340. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  7341. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  7342. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  7343. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  7344. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  7345. }
  7346. if (isModEnabled('contrat') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
  7347. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  7348. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  7349. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  7350. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  7351. }
  7352. if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
  7353. $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
  7354. }
  7355. if (isModEnabled("ficheinter") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
  7356. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
  7357. }
  7358. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  7359. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  7360. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  7361. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  7362. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  7363. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  7364. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  7365. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  7366. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  7367. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  7368. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  7369. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  7370. if (isModEnabled("expedition") && (!is_object($object) || $object->element == 'shipping')) {
  7371. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  7372. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  7373. $substitutionarray['__SHIPPINGMETHOD__'] = 'Shipping method';
  7374. }
  7375. if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
  7376. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  7377. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  7378. }
  7379. } else {
  7380. $substitutionarray['__ID__'] = $object->id;
  7381. $substitutionarray['__REF__'] = $object->ref;
  7382. $substitutionarray['__NEWREF__'] = $object->newref;
  7383. $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
  7384. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7385. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7386. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  7387. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  7388. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, 'day', 0, $outputlangs) : '');
  7389. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%d") : '');
  7390. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%A") : '');
  7391. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%m") : '');
  7392. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%b") : '');
  7393. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%Y") : '');
  7394. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%H") : '');
  7395. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%M") : '');
  7396. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%S") : '');
  7397. // For backward compatibility (deprecated)
  7398. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7399. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7400. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->delivery_date) ? dol_print_date($object->delivery_date, 'day', 0, $outputlangs) : '');
  7401. $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 : '')) : '');
  7402. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  7403. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  7404. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  7405. if (method_exists($object, 'getCivilityLabel')) {
  7406. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  7407. }
  7408. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  7409. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  7410. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  7411. if (method_exists($object, 'getFullName')) {
  7412. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  7413. }
  7414. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  7415. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  7416. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  7417. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  7418. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  7419. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  7420. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  7421. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  7422. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  7423. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  7424. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  7425. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  7426. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  7427. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  7428. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  7429. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
  7430. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
  7431. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  7432. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  7433. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  7434. }
  7435. if (is_object($object) && $object->element == 'societe') {
  7436. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  7437. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  7438. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  7439. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  7440. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  7441. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  7442. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  7443. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  7444. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  7445. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  7446. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  7447. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  7448. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  7449. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  7450. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  7451. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  7452. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  7453. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  7454. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  7455. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  7456. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  7457. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  7458. } elseif (is_object($object->thirdparty)) {
  7459. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  7460. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  7461. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  7462. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  7463. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  7464. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  7465. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  7466. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  7467. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  7468. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  7469. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  7470. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  7471. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  7472. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  7473. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  7474. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  7475. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  7476. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  7477. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  7478. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  7479. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  7480. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  7481. }
  7482. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  7483. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  7484. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7485. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7486. }
  7487. if (is_object($object) && $object->element == 'conferenceorboothattendee') {
  7488. $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
  7489. $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7490. $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7491. }
  7492. if (is_object($object->project)) {
  7493. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  7494. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  7495. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  7496. }
  7497. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  7498. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  7499. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  7500. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  7501. }
  7502. if (is_object($object) && $object->element == 'project') {
  7503. $substitutionarray['__PROJECT_NAME__'] = $object->title;
  7504. }
  7505. if (is_object($object) && $object->element == 'shipping') {
  7506. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  7507. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  7508. $substitutionarray['__SHIPPINGMETHOD__'] = $object->shipping_method;
  7509. }
  7510. if (is_object($object) && $object->element == 'reception') {
  7511. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  7512. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  7513. }
  7514. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  7515. $dateplannedstart = '';
  7516. $datenextexpiration = '';
  7517. foreach ($object->lines as $line) {
  7518. if ($line->date_start > $dateplannedstart) {
  7519. $dateplannedstart = $line->date_start;
  7520. }
  7521. if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
  7522. $datenextexpiration = $line->date_end;
  7523. }
  7524. }
  7525. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  7526. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  7527. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  7528. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  7529. }
  7530. // add substition variable for ticket
  7531. if (is_object($object) && $object->element == 'ticket') {
  7532. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  7533. $substitutionarray['__REF__'] = $object->ref;
  7534. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  7535. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  7536. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  7537. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  7538. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  7539. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  7540. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  7541. $userstat = new User($db);
  7542. if ($object->fk_user_assign > 0) {
  7543. $userstat->fetch($object->fk_user_assign);
  7544. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7545. }
  7546. if ($object->fk_user_create > 0) {
  7547. $userstat->fetch($object->fk_user_create);
  7548. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7549. }
  7550. }
  7551. // Create dynamic tags for __EXTRAFIELD_FIELD__
  7552. if ($object->table_element && $object->id > 0) {
  7553. if (!is_object($extrafields)) {
  7554. $extrafields = new ExtraFields($db);
  7555. }
  7556. $extrafields->fetch_name_optionals_label($object->table_element, true);
  7557. if ($object->fetch_optionals() > 0) {
  7558. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  7559. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  7560. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  7561. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  7562. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  7563. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  7564. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  7565. $datetime = $object->array_options['options_'.$key];
  7566. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  7567. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  7568. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  7569. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  7570. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  7571. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  7572. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  7573. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7574. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  7575. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
  7576. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = !empty($object->array_options['options_'.$key]) ? $object->array_options['options_'.$key] :'';
  7577. }
  7578. }
  7579. }
  7580. }
  7581. }
  7582. // Complete substitution array with the url to make online payment
  7583. $paymenturl = '';
  7584. if (empty($substitutionarray['__REF__'])) {
  7585. $paymenturl = '';
  7586. } else {
  7587. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  7588. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  7589. $outputlangs->loadLangs(array('paypal', 'other'));
  7590. $amounttouse = 0;
  7591. $typeforonlinepayment = 'free';
  7592. if (is_object($object) && $object->element == 'commande') {
  7593. $typeforonlinepayment = 'order';
  7594. }
  7595. if (is_object($object) && $object->element == 'facture') {
  7596. $typeforonlinepayment = 'invoice';
  7597. }
  7598. if (is_object($object) && $object->element == 'member') {
  7599. $typeforonlinepayment = 'member';
  7600. if (!empty($object->last_subscription_amount)) {
  7601. $amounttouse = $object->last_subscription_amount;
  7602. }
  7603. }
  7604. if (is_object($object) && $object->element == 'contrat') {
  7605. $typeforonlinepayment = 'contract';
  7606. }
  7607. if (is_object($object) && $object->element == 'fichinter') {
  7608. $typeforonlinepayment = 'ficheinter';
  7609. }
  7610. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], $amounttouse);
  7611. $paymenturl = $url;
  7612. }
  7613. if ($object->id > 0) {
  7614. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  7615. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  7616. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  7617. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7618. } else {
  7619. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  7620. }
  7621. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  7622. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  7623. } else {
  7624. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  7625. }
  7626. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  7627. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  7628. } else {
  7629. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  7630. }
  7631. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  7632. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  7633. } else {
  7634. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  7635. }
  7636. if (!empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'fichinter') {
  7637. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
  7638. } else {
  7639. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
  7640. }
  7641. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  7642. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7643. } else {
  7644. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  7645. }
  7646. if (is_object($object) && $object->element == 'propal') {
  7647. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  7648. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7649. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  7650. }
  7651. if (is_object($object) && $object->element == 'commande') {
  7652. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  7653. }
  7654. if (is_object($object) && $object->element == 'facture') {
  7655. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  7656. }
  7657. if (is_object($object) && $object->element == 'contrat') {
  7658. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  7659. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7660. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', $object->ref);
  7661. }
  7662. if (is_object($object) && $object->element == 'fichinter') {
  7663. $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT."/fichinter/card.php?id=".$object->id;
  7664. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7665. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', $object->ref);
  7666. }
  7667. if (is_object($object) && $object->element == 'supplier_proposal') {
  7668. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  7669. }
  7670. if (is_object($object) && $object->element == 'shipping') {
  7671. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  7672. }
  7673. }
  7674. if (is_object($object) && $object->element == 'action') {
  7675. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  7676. $substitutionarray['__EVENT_TYPE__'] = $outputlangs->trans("Action".$object->type_code);
  7677. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, 'day', 'auto', $outputlangs);
  7678. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, 'hour', 'auto', $outputlangs);
  7679. }
  7680. }
  7681. }
  7682. if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
  7683. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  7684. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  7685. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  7686. $already_payed_all = 0;
  7687. if (is_object($object) && ($object instanceof Facture)) {
  7688. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  7689. }
  7690. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  7691. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  7692. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  7693. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  7694. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
  7695. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7696. $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)) : '';
  7697. $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)) : '';
  7698. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7699. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  7700. }
  7701. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7702. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  7703. }
  7704. // Amount keys formated in a currency
  7705. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7706. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7707. $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc - $already_payed_all, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7708. $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)) : '';
  7709. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7710. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7711. }
  7712. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7713. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7714. }
  7715. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  7716. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  7717. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  7718. // TODO Add other keys for foreign multicurrency
  7719. // For backward compatibility
  7720. if ($onlykey != 2) {
  7721. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  7722. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  7723. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7724. }
  7725. }
  7726. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  7727. if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
  7728. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  7729. $now = dol_now();
  7730. $tmp = dol_getdate($now, true);
  7731. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7732. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  7733. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7734. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  7735. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  7736. $substitutionarray = array_merge($substitutionarray, array(
  7737. '__NOW_TMS__' => (int) $now,
  7738. '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 'auto', $outputlangs),
  7739. '__DAY__' => (string) $tmp['mday'],
  7740. '__DAY_TEXT__' => $daytext, // Monday
  7741. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  7742. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  7743. '__MONTH__' => (string) $tmp['mon'],
  7744. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  7745. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  7746. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  7747. '__YEAR__' => (string) $tmp['year'],
  7748. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  7749. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  7750. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  7751. '__NEXT_DAY__' => (string) $tmp4['day'],
  7752. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7753. '__NEXT_MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp5['month'])),
  7754. '__NEXT_MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp5['month'])),
  7755. '__NEXT_MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp5['month'])),
  7756. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7757. ));
  7758. }
  7759. if (isModEnabled('multicompany')) {
  7760. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7761. }
  7762. if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
  7763. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7764. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7765. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7766. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7767. }
  7768. // Note: The lazyload variables are replaced only during the call by make_substitutions, and only if necessary
  7769. return $substitutionarray;
  7770. }
  7771. /**
  7772. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7773. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7774. * Example of usage:
  7775. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7776. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7777. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7778. *
  7779. * @param string $text Source string in which we must do substitution
  7780. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7781. * @param Translate $outputlangs Output language
  7782. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7783. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7784. * @return string Output string after substitutions
  7785. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7786. */
  7787. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7788. {
  7789. global $conf, $langs;
  7790. if (!is_array($substitutionarray)) {
  7791. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7792. }
  7793. if (empty($outputlangs)) {
  7794. $outputlangs = $langs;
  7795. }
  7796. // Is initial text HTML or simple text ?
  7797. $msgishtml = 0;
  7798. if (dol_textishtml($text, 1)) {
  7799. $msgishtml = 1;
  7800. }
  7801. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7802. if (is_object($outputlangs)) {
  7803. $reg = array();
  7804. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7805. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7806. $tmp = explode('|', $reg[1]);
  7807. if (!empty($tmp[1])) {
  7808. $outputlangs->load($tmp[1]);
  7809. }
  7810. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7811. if (empty($converttextinhtmlifnecessary)) {
  7812. // convert $newval into HTML is necessary
  7813. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7814. } else {
  7815. if (! $msgishtml) {
  7816. $valueishtml = dol_textishtml($value, 1);
  7817. //var_dump("valueishtml=".$valueishtml);
  7818. if ($valueishtml) {
  7819. $text = dol_htmlentitiesbr($text);
  7820. $msgishtml = 1;
  7821. }
  7822. } else {
  7823. $value = dol_nl2br("$value");
  7824. }
  7825. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7826. }
  7827. }
  7828. }
  7829. // Make substitution for constant keys.
  7830. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7831. $reg = array();
  7832. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7833. $keyfound = $reg[1];
  7834. if (isASecretKey($keyfound)) {
  7835. $value = '*****forbidden*****';
  7836. } else {
  7837. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7838. }
  7839. if (empty($converttextinhtmlifnecessary)) {
  7840. // convert $newval into HTML is necessary
  7841. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7842. } else {
  7843. if (! $msgishtml) {
  7844. $valueishtml = dol_textishtml($value, 1);
  7845. if ($valueishtml) {
  7846. $text = dol_htmlentitiesbr($text);
  7847. $msgishtml = 1;
  7848. }
  7849. } else {
  7850. $value = dol_nl2br("$value");
  7851. }
  7852. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7853. }
  7854. }
  7855. // Make substitution for array $substitutionarray
  7856. foreach ($substitutionarray as $key => $value) {
  7857. if (!isset($value)) {
  7858. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7859. }
  7860. if (($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__') && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  7861. $value = ''; // Protection
  7862. }
  7863. if (empty($converttextinhtmlifnecessary)) {
  7864. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7865. } else {
  7866. if (! $msgishtml) {
  7867. $valueishtml = dol_textishtml($value, 1);
  7868. if ($valueishtml) {
  7869. $text = dol_htmlentitiesbr($text);
  7870. $msgishtml = 1;
  7871. }
  7872. } else {
  7873. $value = dol_nl2br("$value");
  7874. }
  7875. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7876. }
  7877. }
  7878. // TODO Implement the lazyload substitution
  7879. /*
  7880. add a loop to scan $substitutionarray:
  7881. For each key ending with '@lazyload', we extract the substitution key 'XXX' and we check inside the $text (the 1st parameter of make_substitutions), if the string XXX exists.
  7882. If no, we don't need to make replacement, so we do nothing.
  7883. If yes, we can make the substitution:
  7884. include_once $path;
  7885. $tmpobj = new $class($db);
  7886. $valuetouseforsubstitution = $tmpobj->$method($id, '__XXX__');
  7887. And make the replacement of "__XXX__@lazyload" with $valuetouseforsubstitution
  7888. */
  7889. return $text;
  7890. }
  7891. /**
  7892. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  7893. * In this case, method completesubstitutionarray provided by module is called.
  7894. *
  7895. * @param array $substitutionarray Array substitution old value => new value value
  7896. * @param Translate $outputlangs Output language
  7897. * @param Object $object Source object
  7898. * @param mixed $parameters Add more parameters (useful to pass product lines)
  7899. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  7900. * @return void
  7901. * @see make_substitutions()
  7902. */
  7903. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  7904. {
  7905. global $conf, $user;
  7906. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7907. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7908. // Check if there is external substitution to do, requested by plugins
  7909. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7910. foreach ($dirsubstitutions as $reldir) {
  7911. $dir = dol_buildpath($reldir, 0);
  7912. // Check if directory exists
  7913. if (!dol_is_dir($dir)) {
  7914. continue;
  7915. }
  7916. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7917. foreach ($substitfiles as $substitfile) {
  7918. $reg = array();
  7919. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7920. $module = $reg[1];
  7921. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7922. // Include the user's functions file
  7923. require_once $dir.$substitfile['name'];
  7924. // Call the user's function, and only if it is defined
  7925. $function_name = $module."_".$callfunc;
  7926. if (function_exists($function_name)) {
  7927. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7928. }
  7929. }
  7930. }
  7931. }
  7932. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7933. // to list all tags in odt template
  7934. $tags = '';
  7935. foreach ($substitutionarray as $key => $value) {
  7936. $tags .= '{'.$key.'} => '.$value."\n";
  7937. }
  7938. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7939. }
  7940. }
  7941. /**
  7942. * Format output for start and end date
  7943. *
  7944. * @param int $date_start Start date
  7945. * @param int $date_end End date
  7946. * @param string $format Output format
  7947. * @param Translate $outputlangs Output language
  7948. * @return void
  7949. */
  7950. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7951. {
  7952. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7953. }
  7954. /**
  7955. * Format output for start and end date
  7956. *
  7957. * @param int $date_start Start date
  7958. * @param int $date_end End date
  7959. * @param string $format Output date format ('day', 'dayhour', ...)
  7960. * @param Translate $outputlangs Output language
  7961. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7962. * @return string String
  7963. */
  7964. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7965. {
  7966. global $langs;
  7967. $out = '';
  7968. if (!is_object($outputlangs)) {
  7969. $outputlangs = $langs;
  7970. }
  7971. if ($date_start && $date_end) {
  7972. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7973. }
  7974. if ($date_start && !$date_end) {
  7975. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7976. }
  7977. if (!$date_start && $date_end) {
  7978. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7979. }
  7980. return $out;
  7981. }
  7982. /**
  7983. * Return firstname and lastname in correct order
  7984. *
  7985. * @param string $firstname Firstname
  7986. * @param string $lastname Lastname
  7987. * @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
  7988. * @return string Firstname + lastname or Lastname + firstname
  7989. */
  7990. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7991. {
  7992. global $conf;
  7993. $ret = '';
  7994. // If order not defined, we use the setup
  7995. if ($nameorder < 0) {
  7996. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7997. }
  7998. if ($nameorder == 1) {
  7999. $ret .= $firstname;
  8000. if ($firstname && $lastname) {
  8001. $ret .= ' ';
  8002. }
  8003. $ret .= $lastname;
  8004. } elseif ($nameorder == 2 || $nameorder == 3) {
  8005. $ret .= $firstname;
  8006. if (empty($ret) && $nameorder == 3) {
  8007. $ret .= $lastname;
  8008. }
  8009. } else { // 0, 4 or 5
  8010. $ret .= $lastname;
  8011. if (empty($ret) && $nameorder == 5) {
  8012. $ret .= $firstname;
  8013. }
  8014. if ($nameorder == 0) {
  8015. if ($firstname && $lastname) {
  8016. $ret .= ' ';
  8017. }
  8018. $ret .= $firstname;
  8019. }
  8020. }
  8021. return $ret;
  8022. }
  8023. /**
  8024. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  8025. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  8026. * Note: Prefer to use setEventMessages instead.
  8027. *
  8028. * @param string|string[] $mesgs Message string or array
  8029. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  8030. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  8031. * @return void
  8032. * @see dol_htmloutput_events()
  8033. */
  8034. function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0)
  8035. {
  8036. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  8037. if (!is_array($mesgs)) {
  8038. // If mesgs is a string
  8039. if ($mesgs) {
  8040. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
  8041. return;
  8042. }
  8043. $_SESSION['dol_events'][$style][] = $mesgs;
  8044. }
  8045. } else {
  8046. // If mesgs is an array
  8047. foreach ($mesgs as $mesg) {
  8048. if ($mesg) {
  8049. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
  8050. return;
  8051. }
  8052. $_SESSION['dol_events'][$style][] = $mesg;
  8053. }
  8054. }
  8055. }
  8056. }
  8057. /**
  8058. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  8059. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  8060. *
  8061. * @param string $mesg Message string
  8062. * @param array|null $mesgs Message array
  8063. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  8064. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  8065. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  8066. * @return void
  8067. * @see dol_htmloutput_events()
  8068. */
  8069. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0)
  8070. {
  8071. if (empty($mesg) && empty($mesgs)) {
  8072. dol_syslog("Try to add a message in stack, but value to add is empty message", LOG_WARNING);
  8073. } else {
  8074. if ($messagekey) {
  8075. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  8076. // TODO
  8077. $mesg .= '';
  8078. }
  8079. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  8080. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  8081. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  8082. }
  8083. if (empty($mesgs)) {
  8084. setEventMessage($mesg, $style, $noduplicate);
  8085. } else {
  8086. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  8087. setEventMessage($mesg, $style, $noduplicate); // Add message string if not already into array
  8088. }
  8089. setEventMessage($mesgs, $style, $noduplicate);
  8090. }
  8091. }
  8092. }
  8093. }
  8094. /**
  8095. * Print formated messages to output (Used to show messages on html output).
  8096. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  8097. * no need to call it explicitely.
  8098. *
  8099. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  8100. * @return void
  8101. * @see dol_htmloutput_mesg()
  8102. */
  8103. function dol_htmloutput_events($disabledoutputofmessages = 0)
  8104. {
  8105. // Show mesgs
  8106. if (isset($_SESSION['dol_events']['mesgs'])) {
  8107. if (empty($disabledoutputofmessages)) {
  8108. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  8109. }
  8110. unset($_SESSION['dol_events']['mesgs']);
  8111. }
  8112. // Show errors
  8113. if (isset($_SESSION['dol_events']['errors'])) {
  8114. if (empty($disabledoutputofmessages)) {
  8115. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  8116. }
  8117. unset($_SESSION['dol_events']['errors']);
  8118. }
  8119. // Show warnings
  8120. if (isset($_SESSION['dol_events']['warnings'])) {
  8121. if (empty($disabledoutputofmessages)) {
  8122. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  8123. }
  8124. unset($_SESSION['dol_events']['warnings']);
  8125. }
  8126. }
  8127. /**
  8128. * Get formated messages to output (Used to show messages on html output).
  8129. * This include also the translation of the message key.
  8130. *
  8131. * @param string $mesgstring Message string or message key
  8132. * @param string[] $mesgarray Array of message strings or message keys
  8133. * @param string $style Style of message output ('ok' or 'error')
  8134. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8135. * @return string Return html output
  8136. *
  8137. * @see dol_print_error()
  8138. * @see dol_htmloutput_errors()
  8139. * @see setEventMessages()
  8140. */
  8141. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  8142. {
  8143. global $conf, $langs;
  8144. $ret = 0;
  8145. $return = '';
  8146. $out = '';
  8147. $divstart = $divend = '';
  8148. // If inline message with no format, we add it.
  8149. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  8150. $divstart = '<div class="'.$style.' clearboth">';
  8151. $divend = '</div>';
  8152. }
  8153. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  8154. $langs->load("errors");
  8155. $out .= $divstart;
  8156. if (is_array($mesgarray) && count($mesgarray)) {
  8157. foreach ($mesgarray as $message) {
  8158. $ret++;
  8159. $out .= $langs->trans($message);
  8160. if ($ret < count($mesgarray)) {
  8161. $out .= "<br>\n";
  8162. }
  8163. }
  8164. }
  8165. if ($mesgstring) {
  8166. $ret++;
  8167. $out .= $langs->trans($mesgstring);
  8168. }
  8169. $out .= $divend;
  8170. }
  8171. if ($out) {
  8172. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  8173. $return = '<script nonce="'.getNonce().'">
  8174. $(document).ready(function() {
  8175. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  8176. if (block) {
  8177. $.dolEventValid("","'.dol_escape_js($out).'");
  8178. } else {
  8179. /* jnotify(message, preset of message type, keepmessage) */
  8180. $.jnotify("'.dol_escape_js($out).'",
  8181. "'.($style == "ok" ? 3000 : $style).'",
  8182. '.($style == "ok" ? "false" : "true").',
  8183. { remove: function (){} } );
  8184. }
  8185. });
  8186. </script>';
  8187. } else {
  8188. $return = $out;
  8189. }
  8190. }
  8191. return $return;
  8192. }
  8193. /**
  8194. * Get formated error messages to output (Used to show messages on html output).
  8195. *
  8196. * @param string $mesgstring Error message
  8197. * @param array $mesgarray Error messages array
  8198. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8199. * @return string Return html output
  8200. *
  8201. * @see dol_print_error()
  8202. * @see dol_htmloutput_mesg()
  8203. */
  8204. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8205. {
  8206. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8207. }
  8208. /**
  8209. * Print formated messages to output (Used to show messages on html output).
  8210. *
  8211. * @param string $mesgstring Message string or message key
  8212. * @param string[] $mesgarray Array of message strings or message keys
  8213. * @param string $style Which style to use ('ok', 'warning', 'error')
  8214. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  8215. * @return void
  8216. *
  8217. * @see dol_print_error()
  8218. * @see dol_htmloutput_errors()
  8219. * @see setEventMessages()
  8220. */
  8221. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  8222. {
  8223. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  8224. return;
  8225. }
  8226. $iserror = 0;
  8227. $iswarning = 0;
  8228. if (is_array($mesgarray)) {
  8229. foreach ($mesgarray as $val) {
  8230. if ($val && preg_match('/class="error"/i', $val)) {
  8231. $iserror++;
  8232. break;
  8233. }
  8234. if ($val && preg_match('/class="warning"/i', $val)) {
  8235. $iswarning++;
  8236. break;
  8237. }
  8238. }
  8239. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  8240. $iserror++;
  8241. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  8242. $iswarning++;
  8243. }
  8244. if ($style == 'error') {
  8245. $iserror++;
  8246. }
  8247. if ($style == 'warning') {
  8248. $iswarning++;
  8249. }
  8250. if ($iserror || $iswarning) {
  8251. // Remove div from texts
  8252. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  8253. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  8254. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  8255. // Remove div from texts array
  8256. if (is_array($mesgarray)) {
  8257. $newmesgarray = array();
  8258. foreach ($mesgarray as $val) {
  8259. if (is_string($val)) {
  8260. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  8261. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  8262. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  8263. $newmesgarray[] = $tmpmesgstring;
  8264. } else {
  8265. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  8266. }
  8267. }
  8268. $mesgarray = $newmesgarray;
  8269. }
  8270. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  8271. } else {
  8272. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  8273. }
  8274. }
  8275. /**
  8276. * Print formated error messages to output (Used to show messages on html output).
  8277. *
  8278. * @param string $mesgstring Error message
  8279. * @param array $mesgarray Error messages array
  8280. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8281. * @return void
  8282. *
  8283. * @see dol_print_error()
  8284. * @see dol_htmloutput_mesg()
  8285. */
  8286. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8287. {
  8288. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8289. }
  8290. /**
  8291. * Advanced sort array by second index function, which produces ascending (default)
  8292. * or descending output and uses optionally natural case insensitive sorting (which
  8293. * can be optionally case sensitive as well).
  8294. *
  8295. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  8296. * @param string $index Key in array to use for sorting criteria
  8297. * @param int $order Sort order ('asc' or 'desc')
  8298. * @param int $natsort If values are strings (I said value not type): 0=Use alphabetical order, 1=use "natural" sort (natsort)
  8299. * If values are numeric (I said value not type): 0=Use numeric order (even if type is string) so use a "natural" sort, 1=use "natural" sort too (same than 0), -1=Force alphabetical order
  8300. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  8301. * @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.
  8302. * @return array Sorted array
  8303. */
  8304. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  8305. {
  8306. // Clean parameters
  8307. $order = strtolower($order);
  8308. if (is_array($array)) {
  8309. $sizearray = count($array);
  8310. if ($sizearray > 0) {
  8311. $temp = array();
  8312. foreach (array_keys($array) as $key) {
  8313. if (is_object($array[$key])) {
  8314. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  8315. } else {
  8316. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  8317. }
  8318. if ($natsort == -1) {
  8319. $temp[$key] = '___'.$temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
  8320. }
  8321. }
  8322. if (empty($natsort) || $natsort == -1) {
  8323. if ($order == 'asc') {
  8324. asort($temp);
  8325. } else {
  8326. arsort($temp);
  8327. }
  8328. } else {
  8329. if ($case_sensitive) {
  8330. natsort($temp);
  8331. } else {
  8332. natcasesort($temp); // natecasesort is not sensible to case
  8333. }
  8334. if ($order != 'asc') {
  8335. $temp = array_reverse($temp, true);
  8336. }
  8337. }
  8338. $sorted = array();
  8339. foreach (array_keys($temp) as $key) {
  8340. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  8341. }
  8342. return $sorted;
  8343. }
  8344. }
  8345. return $array;
  8346. }
  8347. /**
  8348. * Check if a string is in UTF8
  8349. *
  8350. * @param string $str String to check
  8351. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  8352. * @see utf8_valid()
  8353. */
  8354. function utf8_check($str)
  8355. {
  8356. $str = (string) $str; // Sometimes string is an int.
  8357. // We must use here a binary strlen function (so not dol_strlen)
  8358. $strLength = dol_strlen($str);
  8359. for ($i = 0; $i < $strLength; $i++) {
  8360. if (ord($str[$i]) < 0x80) {
  8361. continue; // 0bbbbbbb
  8362. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  8363. $n = 1; // 110bbbbb
  8364. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  8365. $n = 2; // 1110bbbb
  8366. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  8367. $n = 3; // 11110bbb
  8368. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  8369. $n = 4; // 111110bb
  8370. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  8371. $n = 5; // 1111110b
  8372. } else {
  8373. return false; // Does not match any model
  8374. }
  8375. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  8376. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  8377. return false;
  8378. }
  8379. }
  8380. }
  8381. return true;
  8382. }
  8383. /**
  8384. * Check if a string is in UTF8
  8385. *
  8386. * @param string $str String to check
  8387. * @return boolean True if string is valid UTF8 string, false if corrupted
  8388. * @see utf8_check()
  8389. */
  8390. function utf8_valid($str)
  8391. {
  8392. /* 2 other methods to test if string is utf8
  8393. $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
  8394. $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
  8395. */
  8396. return preg_match('//u', $str) ? true : false;
  8397. }
  8398. /**
  8399. * Check if a string is in ASCII
  8400. *
  8401. * @param string $str String to check
  8402. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  8403. */
  8404. function ascii_check($str)
  8405. {
  8406. if (function_exists('mb_check_encoding')) {
  8407. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  8408. if (!mb_check_encoding($str, 'ASCII')) {
  8409. return false;
  8410. }
  8411. } else {
  8412. if (preg_match('/[^\x00-\x7f]/', $str)) {
  8413. return false; // Contains a byte > 7f
  8414. }
  8415. }
  8416. return true;
  8417. }
  8418. /**
  8419. * Return a string encoded into OS filesystem encoding. This function is used to define
  8420. * value to pass to filesystem PHP functions.
  8421. *
  8422. * @param string $str String to encode (UTF-8)
  8423. * @return string Encoded string (UTF-8, ISO-8859-1)
  8424. */
  8425. function dol_osencode($str)
  8426. {
  8427. global $conf;
  8428. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  8429. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  8430. $tmp = 'iso-8859-1'; // By default for windows
  8431. }
  8432. if (empty($tmp)) {
  8433. $tmp = 'utf-8'; // By default for other
  8434. }
  8435. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  8436. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  8437. }
  8438. if ($tmp == 'iso-8859-1') {
  8439. return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
  8440. }
  8441. return $str;
  8442. }
  8443. /**
  8444. * Return an id or code from a code or id.
  8445. * Store also Code-Id into a cache to speed up next request on same key.
  8446. *
  8447. * @param DoliDB $db Database handler
  8448. * @param string $key Code or Id to get Id or Code
  8449. * @param string $tablename Table name without prefix
  8450. * @param string $fieldkey Field to search the key into
  8451. * @param string $fieldid Field to get
  8452. * @param int $entityfilter Filter by entity
  8453. * @param string $filters Filters to add. WARNING: string must be escaped for SQL and not coming from user input.
  8454. * @return int <0 if KO, Id of code if OK
  8455. * @see $langs->getLabelFromKey
  8456. */
  8457. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '')
  8458. {
  8459. global $cache_codes;
  8460. // If key empty
  8461. if ($key == '') {
  8462. return '';
  8463. }
  8464. // Check in cache
  8465. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  8466. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  8467. }
  8468. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  8469. $sql = "SELECT ".$fieldid." as valuetoget";
  8470. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  8471. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  8472. if (!empty($entityfilter)) {
  8473. $sql .= " AND entity IN (".getEntity($tablename).")";
  8474. }
  8475. if ($filters) {
  8476. $sql .= $filters;
  8477. }
  8478. $resql = $db->query($sql);
  8479. if ($resql) {
  8480. $obj = $db->fetch_object($resql);
  8481. if ($obj) {
  8482. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  8483. } else {
  8484. $cache_codes[$tablename][$key][$fieldid] = '';
  8485. }
  8486. $db->free($resql);
  8487. return $cache_codes[$tablename][$key][$fieldid];
  8488. } else {
  8489. return -1;
  8490. }
  8491. }
  8492. /**
  8493. * Check if a variable with name $var start with $text.
  8494. * Can be used to forge dol_eval() conditions.
  8495. *
  8496. * @param $var string Variable
  8497. * @param $regextext string Text that must be a valid regex string
  8498. * @param $matchrule int 1=Test if start with, 0=Test if equal
  8499. * @return boolean|string True or False, text if bad use.
  8500. */
  8501. function isStringVarMatching($var, $regextext, $matchrule = 1)
  8502. {
  8503. if ($matchrule == 1) {
  8504. if ($var == 'mainmenu') {
  8505. global $mainmenu;
  8506. return (preg_match('/^'.$regextext.'/', $mainmenu));
  8507. } elseif ($var == 'leftmenu') {
  8508. global $leftmenu;
  8509. return (preg_match('/^'.$regextext.'/', $leftmenu));
  8510. } else {
  8511. return 'This variable is not accessible with dol_eval';
  8512. }
  8513. } else {
  8514. return 'This value for matchrule is not implemented';
  8515. }
  8516. }
  8517. /**
  8518. * Verify if condition in string is ok or not
  8519. *
  8520. * @param string $strToEvaluate String with condition to check
  8521. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  8522. */
  8523. function verifCond($strToEvaluate)
  8524. {
  8525. //print $strToEvaluate."<br>\n";
  8526. $rights = true;
  8527. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  8528. //var_dump($strToEvaluate);
  8529. //$rep = dol_eval($strToEvaluate, 1, 0, '1'); // to show the error
  8530. $rep = dol_eval($strToEvaluate, 1, 1, '1'); // The dol_eval() must contains all the "global $xxx;" for all variables $xxx found into the string condition
  8531. $rights = $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
  8532. //var_dump($rights);
  8533. }
  8534. return $rights;
  8535. }
  8536. /**
  8537. * Replace eval function to add more security.
  8538. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  8539. *
  8540. * @param string $s String to evaluate
  8541. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  8542. * @param int $hideerrors 1=Hide errors
  8543. * @param string $onlysimplestring '0' (deprecated, used for computed property of extrafields)=Accept all chars,
  8544. * '1' (most common use)=Accept only simple string with char 'a-z0-9\s^$_+-.*>&|=!?():"\',/@';',
  8545. * '2' (rarely used)=Accept also '[]'
  8546. * @return mixed Nothing or return result of eval
  8547. * @see verifCond()
  8548. */
  8549. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  8550. {
  8551. // Only this global variables can be read by eval function and returned to caller
  8552. global $conf; // Read of const is done with getDolGlobalString() but we need $conf->currency for example
  8553. global $db, $langs, $user, $website, $websitepage;
  8554. global $action, $mainmenu, $leftmenu;
  8555. global $mysoc;
  8556. global $objectoffield; // To allow the use of $objectoffield in computed fields
  8557. // Old variables used
  8558. global $object;
  8559. global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
  8560. if (!in_array($onlysimplestring, array('0', '1', '2'))) {
  8561. return "Bad call of dol_eval. Parameter onlysimplestring must be '0' (deprecated), '1' or '2'";
  8562. }
  8563. try {
  8564. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  8565. if ($onlysimplestring == '1') {
  8566. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && getDolGlobalString("MAIN_FEATURES_LEVEL")'
  8567. // We must accept: '$user->hasRight("cabinetmed", "read") && !$object->canvas=="patient@cabinetmed"'
  8568. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@', '/').']/i', $s)) {
  8569. if ($returnvalue) {
  8570. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8571. } else {
  8572. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8573. return '';
  8574. }
  8575. }
  8576. $scheck = preg_replace('/->[a-zA-Z0-9_]+\(/', '->__METHOD__', $s); // accept parenthesis in '...->method(...'
  8577. $scheck = preg_replace('/^\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8578. $scheck = preg_replace('/\s\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '... ('. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8579. $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
  8580. $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
  8581. $scheck = preg_replace('/(\^|\')\(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
  8582. //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
  8583. if (strpos($scheck, '(') !== false) {
  8584. if ($returnvalue) {
  8585. return 'Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s;
  8586. } else {
  8587. dol_syslog('Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s);
  8588. return '';
  8589. }
  8590. }
  8591. // TODO
  8592. // We can exclude $ char that are not: $db, $langs, $leftmenu, $topmenu, $user, $langs, $objectoffield, $object...,
  8593. } elseif ($onlysimplestring == '2') {
  8594. // We must accept: (($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"
  8595. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@[]', '/').']/i', $s)) {
  8596. if ($returnvalue) {
  8597. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8598. } else {
  8599. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8600. return '';
  8601. }
  8602. }
  8603. $scheck = preg_replace('/->[a-zA-Z0-9_]+\(/', '->__METHOD__', $s); // accept parenthesis in '...->method(...'
  8604. $scheck = preg_replace('/^\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8605. $scheck = preg_replace('/\s\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '... ('. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8606. $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
  8607. $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\(/', '$1__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
  8608. $scheck = preg_replace('/(\^|\')\(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
  8609. //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
  8610. if (strpos($scheck, '(') !== false) {
  8611. if ($returnvalue) {
  8612. return 'Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s;
  8613. } else {
  8614. dol_syslog('Bad string syntax to evaluate (found call of a function or method without using direct name): '.$s);
  8615. return '';
  8616. }
  8617. }
  8618. // TODO
  8619. // We can exclude $ char that are not: $db, $leftmenu, $topmenu, $user, $langs, $object...,
  8620. }
  8621. if (is_array($s) || $s === 'Array') {
  8622. return 'Bad string syntax to evaluate (value is Array) '.var_export($s, true);
  8623. }
  8624. if (strpos($s, '::') !== false) {
  8625. if ($returnvalue) {
  8626. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  8627. } else {
  8628. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  8629. return '';
  8630. }
  8631. }
  8632. if (strpos($s, '`') !== false) {
  8633. if ($returnvalue) {
  8634. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  8635. } else {
  8636. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  8637. return '';
  8638. }
  8639. }
  8640. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  8641. if ($returnvalue) {
  8642. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  8643. } else {
  8644. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  8645. return '';
  8646. }
  8647. }
  8648. // We block use of php exec or php file functions
  8649. $forbiddenphpstrings = array('$$');
  8650. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  8651. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen");
  8652. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "executeCLI", "verifCond")); // native dolibarr functions
  8653. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("base64_decode", "rawurldecode", "urldecode")); // decode string functions
  8654. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  8655. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
  8656. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  8657. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
  8658. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  8659. do {
  8660. $oldstringtoclean = $s;
  8661. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  8662. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  8663. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  8664. } while ($oldstringtoclean != $s);
  8665. if (strpos($s, '__forbiddenstring__') !== false) {
  8666. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  8667. if ($returnvalue) {
  8668. return 'Bad string syntax to evaluate: '.$s;
  8669. } else {
  8670. dol_syslog('Bad string syntax to evaluate: '.$s);
  8671. return '';
  8672. }
  8673. }
  8674. //print $s."<br>\n";
  8675. if ($returnvalue) {
  8676. if ($hideerrors) {
  8677. return @eval('return '.$s.';');
  8678. } else {
  8679. return eval('return '.$s.';');
  8680. }
  8681. } else {
  8682. if ($hideerrors) {
  8683. @eval($s);
  8684. } else {
  8685. eval($s);
  8686. }
  8687. }
  8688. } catch (Error $e) {
  8689. $error = 'dol_eval try/catch error : ';
  8690. $error .= $e->getMessage();
  8691. dol_syslog($error, LOG_WARNING);
  8692. }
  8693. }
  8694. /**
  8695. * Return if var element is ok
  8696. *
  8697. * @param string $element Variable to check
  8698. * @return boolean Return true of variable is not empty
  8699. * @see getElementProperties()
  8700. */
  8701. function dol_validElement($element)
  8702. {
  8703. return (trim($element) != '');
  8704. }
  8705. /**
  8706. * Return img flag of country for a language code or country code.
  8707. *
  8708. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  8709. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  8710. * @param int $notitlealt No title alt
  8711. * @return string HTML img string with flag.
  8712. */
  8713. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  8714. {
  8715. if (empty($codelang)) {
  8716. return '';
  8717. }
  8718. if ($codelang == 'auto') {
  8719. return '<span class="fa fa-language"></span>';
  8720. }
  8721. $langtocountryflag = array(
  8722. 'ar_AR' => '',
  8723. 'ca_ES' => 'catalonia',
  8724. 'da_DA' => 'dk',
  8725. 'fr_CA' => 'mq',
  8726. 'sv_SV' => 'se',
  8727. 'sw_SW' => 'unknown',
  8728. 'AQ' => 'unknown',
  8729. 'CW' => 'unknown',
  8730. 'IM' => 'unknown',
  8731. 'JE' => 'unknown',
  8732. 'MF' => 'unknown',
  8733. 'BL' => 'unknown',
  8734. 'SX' => 'unknown'
  8735. );
  8736. if (isset($langtocountryflag[$codelang])) {
  8737. $flagImage = $langtocountryflag[$codelang];
  8738. } else {
  8739. $tmparray = explode('_', $codelang);
  8740. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  8741. }
  8742. // return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  8743. return '<span class="flag-sprite '.strtolower($flagImage).'"'.($moreatt ? ' '.$moreatt : '').(!$notitlealt ? ' title="'.$codelang.'"' : '').'></span>';
  8744. }
  8745. /**
  8746. * Return default language from country code.
  8747. * Return null if not found.
  8748. *
  8749. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  8750. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  8751. */
  8752. function getLanguageCodeFromCountryCode($countrycode)
  8753. {
  8754. global $mysoc;
  8755. if (empty($countrycode)) {
  8756. return null;
  8757. }
  8758. if (strtoupper($countrycode) == 'MQ') {
  8759. return 'fr_CA';
  8760. }
  8761. if (strtoupper($countrycode) == 'SE') {
  8762. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  8763. }
  8764. if (strtoupper($countrycode) == 'CH') {
  8765. if ($mysoc->country_code == 'FR') {
  8766. return 'fr_CH';
  8767. }
  8768. if ($mysoc->country_code == 'DE') {
  8769. return 'de_CH';
  8770. }
  8771. if ($mysoc->country_code == 'IT') {
  8772. return 'it_CH';
  8773. }
  8774. }
  8775. // Locale list taken from:
  8776. // http://stackoverflow.com/questions/3191664/
  8777. // list-of-all-locales-and-their-short-codes
  8778. $locales = array(
  8779. 'af-ZA',
  8780. 'am-ET',
  8781. 'ar-AE',
  8782. 'ar-BH',
  8783. 'ar-DZ',
  8784. 'ar-EG',
  8785. 'ar-IQ',
  8786. 'ar-JO',
  8787. 'ar-KW',
  8788. 'ar-LB',
  8789. 'ar-LY',
  8790. 'ar-MA',
  8791. 'ar-OM',
  8792. 'ar-QA',
  8793. 'ar-SA',
  8794. 'ar-SY',
  8795. 'ar-TN',
  8796. 'ar-YE',
  8797. //'as-IN', // Moved after en-IN
  8798. 'ba-RU',
  8799. 'be-BY',
  8800. 'bg-BG',
  8801. 'bn-BD',
  8802. //'bn-IN', // Moved after en-IN
  8803. 'bo-CN',
  8804. 'br-FR',
  8805. 'ca-ES',
  8806. 'co-FR',
  8807. 'cs-CZ',
  8808. 'cy-GB',
  8809. 'da-DK',
  8810. 'de-AT',
  8811. 'de-CH',
  8812. 'de-DE',
  8813. 'de-LI',
  8814. 'de-LU',
  8815. 'dv-MV',
  8816. 'el-GR',
  8817. 'en-AU',
  8818. 'en-BZ',
  8819. 'en-CA',
  8820. 'en-GB',
  8821. 'en-IE',
  8822. 'en-IN',
  8823. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  8824. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  8825. 'en-JM',
  8826. 'en-MY',
  8827. 'en-NZ',
  8828. 'en-PH',
  8829. 'en-SG',
  8830. 'en-TT',
  8831. 'en-US',
  8832. 'en-ZA',
  8833. 'en-ZW',
  8834. 'es-AR',
  8835. 'es-BO',
  8836. 'es-CL',
  8837. 'es-CO',
  8838. 'es-CR',
  8839. 'es-DO',
  8840. 'es-EC',
  8841. 'es-ES',
  8842. 'es-GT',
  8843. 'es-HN',
  8844. 'es-MX',
  8845. 'es-NI',
  8846. 'es-PA',
  8847. 'es-PE',
  8848. 'es-PR',
  8849. 'es-PY',
  8850. 'es-SV',
  8851. 'es-US',
  8852. 'es-UY',
  8853. 'es-VE',
  8854. 'et-EE',
  8855. 'eu-ES',
  8856. 'fa-IR',
  8857. 'fi-FI',
  8858. 'fo-FO',
  8859. 'fr-BE',
  8860. 'fr-CA',
  8861. 'fr-CH',
  8862. 'fr-FR',
  8863. 'fr-LU',
  8864. 'fr-MC',
  8865. 'fy-NL',
  8866. 'ga-IE',
  8867. 'gd-GB',
  8868. 'gl-ES',
  8869. 'gu-IN',
  8870. 'he-IL',
  8871. 'hi-IN',
  8872. 'hr-BA',
  8873. 'hr-HR',
  8874. 'hu-HU',
  8875. 'hy-AM',
  8876. 'id-ID',
  8877. 'ig-NG',
  8878. 'ii-CN',
  8879. 'is-IS',
  8880. 'it-CH',
  8881. 'it-IT',
  8882. 'ja-JP',
  8883. 'ka-GE',
  8884. 'kk-KZ',
  8885. 'kl-GL',
  8886. 'km-KH',
  8887. 'kn-IN',
  8888. 'ko-KR',
  8889. 'ky-KG',
  8890. 'lb-LU',
  8891. 'lo-LA',
  8892. 'lt-LT',
  8893. 'lv-LV',
  8894. 'mi-NZ',
  8895. 'mk-MK',
  8896. 'ml-IN',
  8897. 'mn-MN',
  8898. 'mr-IN',
  8899. 'ms-BN',
  8900. 'ms-MY',
  8901. 'mt-MT',
  8902. 'nb-NO',
  8903. 'ne-NP',
  8904. 'nl-BE',
  8905. 'nl-NL',
  8906. 'nn-NO',
  8907. 'oc-FR',
  8908. 'or-IN',
  8909. 'pa-IN',
  8910. 'pl-PL',
  8911. 'ps-AF',
  8912. 'pt-BR',
  8913. 'pt-PT',
  8914. 'rm-CH',
  8915. 'ro-MD',
  8916. 'ro-RO',
  8917. 'ru-RU',
  8918. 'rw-RW',
  8919. 'sa-IN',
  8920. 'se-FI',
  8921. 'se-NO',
  8922. 'se-SE',
  8923. 'si-LK',
  8924. 'sk-SK',
  8925. 'sl-SI',
  8926. 'sq-AL',
  8927. 'sv-FI',
  8928. 'sv-SE',
  8929. 'sw-KE',
  8930. 'ta-IN',
  8931. 'te-IN',
  8932. 'th-TH',
  8933. 'tk-TM',
  8934. 'tn-ZA',
  8935. 'tr-TR',
  8936. 'tt-RU',
  8937. 'ug-CN',
  8938. 'uk-UA',
  8939. 'ur-PK',
  8940. 'vi-VN',
  8941. 'wo-SN',
  8942. 'xh-ZA',
  8943. 'yo-NG',
  8944. 'zh-CN',
  8945. 'zh-HK',
  8946. 'zh-MO',
  8947. 'zh-SG',
  8948. 'zh-TW',
  8949. 'zu-ZA',
  8950. );
  8951. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  8952. if (in_array($buildprimarykeytotest, $locales)) {
  8953. return strtolower($countrycode).'_'.strtoupper($countrycode);
  8954. }
  8955. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  8956. foreach ($locales as $locale) {
  8957. $locale_language = locale_get_primary_language($locale);
  8958. $locale_region = locale_get_region($locale);
  8959. if (strtoupper($countrycode) == $locale_region) {
  8960. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  8961. return strtolower($locale_language).'_'.strtoupper($locale_region);
  8962. }
  8963. }
  8964. } else {
  8965. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  8966. }
  8967. return null;
  8968. }
  8969. /**
  8970. * Complete or removed entries into a head array (used to build tabs).
  8971. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  8972. * Or by change using hook completeTabsHead
  8973. *
  8974. * @param Conf $conf Object conf
  8975. * @param Translate $langs Object langs
  8976. * @param object|null $object Object object
  8977. * @param array $head Object head
  8978. * @param int $h New position to fill
  8979. * @param string $type Value for object where objectvalue can be
  8980. * 'thirdparty' to add a tab in third party view
  8981. * 'intervention' to add a tab in intervention view
  8982. * 'supplier_order' to add a tab in purchase order view
  8983. * 'supplier_invoice' to add a tab in purchase invoice view
  8984. * 'invoice' to add a tab in sales invoice view
  8985. * 'order' to add a tab in sales order view
  8986. * 'contract' to add a tabl in contract view
  8987. * 'product' to add a tab in product view
  8988. * 'propal' to add a tab in propal view
  8989. * 'user' to add a tab in user view
  8990. * 'group' to add a tab in group view
  8991. * 'member' to add a tab in fundation member view
  8992. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  8993. * 'ecm' to add a tab for another ecm view
  8994. * 'stock' to add a tab for warehouse view
  8995. * @param string $mode 'add' to complete head, 'remove' to remove entries
  8996. * @param string $filterorigmodule Filter on module origin: 'external' will show only external modules. 'core' only core modules. No filter (default) will add both.
  8997. * @return void
  8998. */
  8999. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
  9000. {
  9001. global $hookmanager, $db;
  9002. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  9003. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  9004. $values = explode(':', $value);
  9005. $reg = array();
  9006. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  9007. $newtab = array();
  9008. $postab = $h;
  9009. // detect if position set in $values[1] ie : +(2)mytab@mymodule (first tab is 0, second is one, ...)
  9010. $str = $values[1];
  9011. $posstart = strpos($str, '(');
  9012. if ($posstart > 0) {
  9013. $posend = strpos($str, ')');
  9014. if ($posstart > 0) {
  9015. $res1 = substr($str, $posstart + 1, $posend - $posstart -1);
  9016. if (is_numeric($res1)) {
  9017. $postab = (int) $res1;
  9018. $values[1] = '+' . substr($str, $posend + 1);
  9019. }
  9020. }
  9021. }
  9022. if (count($values) == 6) {
  9023. // new declaration with permissions:
  9024. // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  9025. // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  9026. if ($values[0] != $type) {
  9027. continue;
  9028. }
  9029. if (verifCond($values[4])) {
  9030. if ($values[3]) {
  9031. if ($filterorigmodule) { // If a filter of module origin has been requested
  9032. if (strpos($values[3], '@')) { // This is an external module
  9033. if ($filterorigmodule != 'external') {
  9034. continue;
  9035. }
  9036. } else { // This looks a core module
  9037. if ($filterorigmodule != 'core') {
  9038. continue;
  9039. }
  9040. }
  9041. }
  9042. $langs->load($values[3]);
  9043. }
  9044. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  9045. // If label is "SUBSTITUION_..."
  9046. $substitutionarray = array();
  9047. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  9048. $label = make_substitutions($reg[1], $substitutionarray);
  9049. } else {
  9050. // If label is "Label,Class,File,Method", we call the method to show content inside the badge
  9051. $labeltemp = explode(',', $values[2]);
  9052. $label = $langs->trans($labeltemp[0]);
  9053. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  9054. dol_include_once($labeltemp[2]);
  9055. $classtoload = $labeltemp[1];
  9056. if (class_exists($classtoload)) {
  9057. $obj = new $classtoload($db);
  9058. $function = $labeltemp[3];
  9059. if ($obj && $function && method_exists($obj, $function)) {
  9060. $nbrec = $obj->$function($object->id, $obj);
  9061. if (!empty($nbrec)) {
  9062. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  9063. }
  9064. }
  9065. }
  9066. }
  9067. }
  9068. $newtab[0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  9069. $newtab[1] = $label;
  9070. $newtab[2] = str_replace('+', '', $values[1]);
  9071. $h++;
  9072. }
  9073. } elseif (count($values) == 5) { // case deprecated
  9074. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  9075. if ($values[0] != $type) {
  9076. continue;
  9077. }
  9078. if ($values[3]) {
  9079. if ($filterorigmodule) { // If a filter of module origin has been requested
  9080. if (strpos($values[3], '@')) { // This is an external module
  9081. if ($filterorigmodule != 'external') {
  9082. continue;
  9083. }
  9084. } else { // This looks a core module
  9085. if ($filterorigmodule != 'core') {
  9086. continue;
  9087. }
  9088. }
  9089. }
  9090. $langs->load($values[3]);
  9091. }
  9092. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  9093. $substitutionarray = array();
  9094. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  9095. $label = make_substitutions($reg[1], $substitutionarray);
  9096. } else {
  9097. $label = $langs->trans($values[2]);
  9098. }
  9099. $newtab[0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  9100. $newtab[1] = $label;
  9101. $newtab[2] = str_replace('+', '', $values[1]);
  9102. $h++;
  9103. }
  9104. // set tab at its position
  9105. $head = array_merge(array_slice($head, 0, $postab), array($newtab), array_slice($head, $postab));
  9106. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  9107. if ($values[0] != $type) {
  9108. continue;
  9109. }
  9110. $tabname = str_replace('-', '', $values[1]);
  9111. foreach ($head as $key => $val) {
  9112. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  9113. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  9114. if ($head[$key][2] == $tabname && $condition) {
  9115. unset($head[$key]);
  9116. break;
  9117. }
  9118. }
  9119. }
  9120. }
  9121. }
  9122. // No need to make a return $head. Var is modified as a reference
  9123. if (!empty($hookmanager)) {
  9124. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
  9125. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters, $object);
  9126. if ($reshook > 0) { // Hook ask to replace completely the array
  9127. $head = $hookmanager->resArray;
  9128. } else { // Hook
  9129. $head = array_merge($head, $hookmanager->resArray);
  9130. }
  9131. $h = count($head);
  9132. }
  9133. }
  9134. /**
  9135. * Print common footer :
  9136. * conf->global->MAIN_HTML_FOOTER
  9137. * js for switch of menu hider
  9138. * js for conf->global->MAIN_GOOGLE_AN_ID
  9139. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  9140. * js for conf->logbuffer
  9141. *
  9142. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  9143. * @return void
  9144. */
  9145. function printCommonFooter($zone = 'private')
  9146. {
  9147. global $conf, $hookmanager, $user, $debugbar;
  9148. global $action;
  9149. global $micro_start_time;
  9150. if ($zone == 'private') {
  9151. print "\n".'<!-- Common footer for private page -->'."\n";
  9152. } else {
  9153. print "\n".'<!-- Common footer for public page -->'."\n";
  9154. }
  9155. // A div to store page_y POST parameter so we can read it using javascript
  9156. print "\n<!-- A div to store page_y POST parameter -->\n";
  9157. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  9158. $parameters = array();
  9159. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  9160. if (empty($reshook)) {
  9161. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  9162. print getDolGlobalString('MAIN_HTML_FOOTER') . "\n";
  9163. }
  9164. print "\n";
  9165. if (!empty($conf->use_javascript_ajax)) {
  9166. print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and madatory fields, tuning info, ... -->\n";
  9167. print '<script>'."\n";
  9168. print 'jQuery(document).ready(function() {'."\n";
  9169. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  9170. print "\n";
  9171. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  9172. print 'jQuery("li.menuhider").click(function(event) {';
  9173. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  9174. print ' console.log("We click on .menuhider");'."\n";
  9175. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  9176. print '});'."\n";
  9177. }
  9178. // Management of focus and mandatory for fields
  9179. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))) || ((empty($action) || $action == 'addline') && (preg_match('/card\.php/', $_SERVER["PHP_SELF"])))) {
  9180. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  9181. $relativepathstring = $_SERVER["PHP_SELF"];
  9182. // Clean $relativepathstring
  9183. if (constant('DOL_URL_ROOT')) {
  9184. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  9185. }
  9186. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  9187. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  9188. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  9189. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  9190. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  9191. $qualified = 0;
  9192. if ($defkey != '_noquery_') {
  9193. $tmpqueryarraytohave = explode('&', $defkey);
  9194. $foundintru = 0;
  9195. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  9196. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  9197. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  9198. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  9199. $foundintru = 1;
  9200. }
  9201. }
  9202. if (!$foundintru) {
  9203. $qualified = 1;
  9204. }
  9205. //var_dump($defkey.'-'.$qualified);
  9206. } else {
  9207. $qualified = 1;
  9208. }
  9209. if ($qualified) {
  9210. foreach ($defval as $paramkey => $paramval) {
  9211. // Set focus on field
  9212. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  9213. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  9214. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  9215. }
  9216. }
  9217. }
  9218. }
  9219. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  9220. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  9221. $qualified = 0;
  9222. if ($defkey != '_noquery_') {
  9223. $tmpqueryarraytohave = explode('&', $defkey);
  9224. $foundintru = 0;
  9225. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  9226. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  9227. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  9228. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  9229. $foundintru = 1;
  9230. }
  9231. }
  9232. if (!$foundintru) {
  9233. $qualified = 1;
  9234. }
  9235. //var_dump($defkey.'-'.$qualified);
  9236. } else {
  9237. $qualified = 1;
  9238. }
  9239. if ($qualified) {
  9240. foreach ($defval as $paramkey => $paramval) {
  9241. // Add property 'required' on input
  9242. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9243. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9244. 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";
  9245. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9246. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  9247. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  9248. // Add 'field required' class on closest td for all input elements : input, textarea and select
  9249. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  9250. }
  9251. // If we submit the cancel button we remove the required attributes
  9252. print 'jQuery("input[name=\'cancel\']").click(function() {
  9253. console.log("We click on cancel button so removed all required attribute");
  9254. jQuery("input, textarea, select").each(function(){this.removeAttribute(\'required\');});
  9255. });'."\n";
  9256. }
  9257. }
  9258. }
  9259. }
  9260. print '});'."\n";
  9261. // End of tuning
  9262. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  9263. print "\n";
  9264. print "/* JS CODE TO ENABLE to add memory info */\n";
  9265. print 'window.console && console.log("';
  9266. if (!empty($conf->global->MEMCACHED_SERVER)) {
  9267. print 'MEMCACHED_SERVER=' . getDolGlobalString('MEMCACHED_SERVER').' - ';
  9268. }
  9269. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  9270. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  9271. $micro_end_time = microtime(true);
  9272. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  9273. }
  9274. if (function_exists("memory_get_usage")) {
  9275. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  9276. }
  9277. if (function_exists("memory_get_peak_usage")) {
  9278. print ' - Real mem peak: '.memory_get_peak_usage(true);
  9279. }
  9280. if (function_exists("zend_loader_file_encoded")) {
  9281. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  9282. }
  9283. print '");'."\n";
  9284. }
  9285. print "\n".'</script>'."\n";
  9286. // Google Analytics
  9287. // TODO Add a hook here
  9288. if (isModEnabled('google') && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  9289. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  9290. foreach ($tmptagarray as $tmptag) {
  9291. print "\n";
  9292. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  9293. print '
  9294. <!-- Global site tag (gtag.js) - Google Analytics -->
  9295. <script nonce="'.getNonce().'" async src="https://www.googletagmanager.com/gtag/js?id='.trim($tmptag).'"></script>
  9296. <script>
  9297. window.dataLayer = window.dataLayer || [];
  9298. function gtag(){dataLayer.push(arguments);}
  9299. gtag(\'js\', new Date());
  9300. gtag(\'config\', \''.trim($tmptag).'\');
  9301. </script>';
  9302. print "\n";
  9303. }
  9304. }
  9305. }
  9306. // Add Xdebug coverage of code
  9307. if (defined('XDEBUGCOVERAGE')) {
  9308. print_r(xdebug_get_code_coverage());
  9309. }
  9310. // Add DebugBar data
  9311. if ($user->hasRight('debugbar', 'read') && is_object($debugbar)) {
  9312. $debugbar['time']->stopMeasure('pageaftermaster');
  9313. print '<!-- Output debugbar data -->'."\n";
  9314. $renderer = $debugbar->getRenderer();
  9315. print $debugbar->getRenderer()->render();
  9316. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  9317. print "\n";
  9318. print "<!-- Start of log output\n";
  9319. //print '<div class="hidden">'."\n";
  9320. foreach ($conf->logbuffer as $logline) {
  9321. print $logline."<br>\n";
  9322. }
  9323. //print '</div>'."\n";
  9324. print "End of log output -->\n";
  9325. }
  9326. }
  9327. }
  9328. /**
  9329. * Split a string with 2 keys into key array.
  9330. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  9331. *
  9332. * @param string|null $string String to explode
  9333. * @param string $delimiter Delimiter between each couple of data. Example: ';' or '[\n;]+' or '(\n\r|\r|\n|;)'
  9334. * @param string $kv Delimiter between key and value
  9335. * @return array Array of data exploded
  9336. */
  9337. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  9338. {
  9339. if (is_null($string)) {
  9340. return array();
  9341. }
  9342. if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\(.*\)$/sm', $delimiter)) {
  9343. // This is a regex string
  9344. $newdelimiter = $delimiter;
  9345. } else {
  9346. // This is a simple string
  9347. $newdelimiter = preg_quote($delimiter, '/');
  9348. }
  9349. if ($a = preg_split('/'.$newdelimiter.'/', $string)) {
  9350. $ka = array();
  9351. foreach ($a as $s) { // each part
  9352. if ($s) {
  9353. if ($pos = strpos($s, $kv)) { // key/value delimiter
  9354. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  9355. } else { // key delimiter not found
  9356. $ka[] = trim($s);
  9357. }
  9358. }
  9359. }
  9360. return $ka;
  9361. }
  9362. return array();
  9363. }
  9364. /**
  9365. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  9366. *
  9367. * @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.
  9368. * @return void
  9369. */
  9370. function dol_set_focus($selector)
  9371. {
  9372. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  9373. print '<script nonce="'.getNonce().'">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  9374. }
  9375. /**
  9376. * Return getmypid() or random PID when function is disabled
  9377. * Some web hosts disable this php function for security reasons
  9378. * and sometimes we can't redeclare function.
  9379. *
  9380. * @return int
  9381. */
  9382. function dol_getmypid()
  9383. {
  9384. if (!function_exists('getmypid')) {
  9385. return mt_rand(99900000, 99965535);
  9386. } else {
  9387. return getmypid(); // May be a number on 64 bits (depending on OS)
  9388. }
  9389. }
  9390. /**
  9391. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  9392. *
  9393. * @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")
  9394. * @param string $value The value to look for.
  9395. * If param $mode is 0, can contains several keywords separated with a space or |
  9396. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  9397. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  9398. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < -1000"
  9399. * If param $mode is 2 or -2, can contains a list of int id separated by comma like "1,3,4"
  9400. * If param $mode is 3 or -3, can contains a list of string separated by comma like "a,b,c".
  9401. * @param integer $mode 0=value is list of keyword strings, 1=value is a numeric test (Example ">5.5 <10"), 2=value is a list of ID separated with comma (Example '1,3,4'), -2 is for exclude list,
  9402. * 3=value is list of string separated with comma (Example 'text 1,text 2'), -3 if for exclude list, 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
  9403. * @param integer $nofirstand 1=Do not output the first 'AND'
  9404. * @return string $res The statement to append to the SQL query
  9405. * @see dolSqlDateFilter()
  9406. */
  9407. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  9408. {
  9409. global $db, $langs;
  9410. $value = trim($value);
  9411. if ($mode == 0) {
  9412. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  9413. }
  9414. if ($mode == 1) {
  9415. $value = preg_replace('/([!<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can then explode on space to get all tests to do
  9416. }
  9417. $value = preg_replace('/\s*\|\s*/', '|', $value);
  9418. $crits = explode(' ', $value);
  9419. $res = '';
  9420. if (!is_array($fields)) {
  9421. $fields = array($fields);
  9422. }
  9423. $i1 = 0; // count the nb of and criteria added (all fields / criterias)
  9424. foreach ($crits as $crit) { // Loop on each AND criteria
  9425. $crit = trim($crit);
  9426. $i2 = 0; // count the nb of valid criteria added for this this first criteria
  9427. $newres = '';
  9428. foreach ($fields as $field) {
  9429. if ($mode == 1) {
  9430. $tmpcrits = explode('|', $crit);
  9431. $i3 = 0; // count the nb of valid criteria added for this current field
  9432. foreach ($tmpcrits as $tmpcrit) {
  9433. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9434. continue;
  9435. }
  9436. $tmpcrit = trim($tmpcrit);
  9437. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9438. $operator = '=';
  9439. $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
  9440. $reg = array();
  9441. preg_match('/([!<>=]+)/', $tmpcrit, $reg);
  9442. if (!empty($reg[1])) {
  9443. $operator = $reg[1];
  9444. }
  9445. if ($newcrit != '') {
  9446. $numnewcrit = price2num($newcrit);
  9447. if (is_numeric($numnewcrit)) {
  9448. $newres .= $field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  9449. } else {
  9450. $newres .= '1 = 2'; // force false, we received a corrupted data
  9451. }
  9452. $i3++; // a criteria was added to string
  9453. }
  9454. }
  9455. $i2++; // a criteria for 1 more field was added to string
  9456. } elseif ($mode == 2 || $mode == -2) {
  9457. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  9458. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  9459. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  9460. if ($mode == -2) {
  9461. $newres .= ' OR '.$field.' IS NULL';
  9462. }
  9463. $i2++; // a criteria for 1 more field was added to string
  9464. } elseif ($mode == 3 || $mode == -3) {
  9465. $tmparray = explode(',', $crit);
  9466. if (count($tmparray)) {
  9467. $listofcodes = '';
  9468. foreach ($tmparray as $val) {
  9469. $val = trim($val);
  9470. if ($val) {
  9471. $listofcodes .= ($listofcodes ? ',' : '');
  9472. $listofcodes .= "'".$db->escape($val)."'";
  9473. }
  9474. }
  9475. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  9476. $i2++; // a criteria for 1 more field was added to string
  9477. }
  9478. if ($mode == -3) {
  9479. $newres .= ' OR '.$field.' IS NULL';
  9480. }
  9481. } elseif ($mode == 4) {
  9482. $tmparray = explode(',', $crit);
  9483. if (count($tmparray)) {
  9484. $listofcodes = '';
  9485. foreach ($tmparray as $val) {
  9486. $val = trim($val);
  9487. if ($val) {
  9488. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  9489. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  9490. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  9491. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  9492. $newres .= ')';
  9493. $i2++; // a criteria for 1 more field was added to string (we can add several citeria for the same field as it is a multiselect search criteria)
  9494. }
  9495. }
  9496. }
  9497. } else { // $mode=0
  9498. $tmpcrits = explode('|', $crit);
  9499. $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
  9500. foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
  9501. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9502. continue;
  9503. }
  9504. $tmpcrit = trim($tmpcrit);
  9505. if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
  9506. $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
  9507. } else {
  9508. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9509. }
  9510. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  9511. $newres .= $field." = ".(is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
  9512. } else {
  9513. $tmpcrit2 = $tmpcrit;
  9514. $tmpbefore = '%';
  9515. $tmpafter = '%';
  9516. $tmps = '';
  9517. if (preg_match('/^!/', $tmpcrit)) {
  9518. $tmps .= $field." NOT LIKE "; // ! as exclude character
  9519. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  9520. } else {
  9521. $tmps .= $field." LIKE ";
  9522. }
  9523. $tmps .= "'";
  9524. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  9525. $tmpbefore = '';
  9526. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  9527. }
  9528. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  9529. $tmpafter = '';
  9530. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  9531. }
  9532. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9533. $tmps = "(".$tmps;
  9534. }
  9535. $newres .= $tmps;
  9536. $newres .= $tmpbefore;
  9537. $newres .= $db->escape($tmpcrit2);
  9538. $newres .= $tmpafter;
  9539. $newres .= "'";
  9540. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9541. $newres .= " OR ".$field." IS NULL)";
  9542. }
  9543. }
  9544. $i3++;
  9545. }
  9546. $i2++; // a criteria for 1 more field was added to string
  9547. }
  9548. }
  9549. if ($newres) {
  9550. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  9551. }
  9552. $i1++;
  9553. }
  9554. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  9555. return $res;
  9556. }
  9557. /**
  9558. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  9559. *
  9560. * @param Object $object Object
  9561. * @return string Url string
  9562. */
  9563. function showDirectDownloadLink($object)
  9564. {
  9565. global $conf, $langs;
  9566. $out = '';
  9567. $url = $object->getLastMainDocLink($object->element);
  9568. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  9569. if ($url) {
  9570. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  9571. $out .= ajax_autoselect("directdownloadlink", 0);
  9572. } else {
  9573. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  9574. }
  9575. return $out;
  9576. }
  9577. /**
  9578. * Return the filename of file to get the thumbs
  9579. *
  9580. * @param string $file Original filename (full or relative path)
  9581. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  9582. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  9583. * @return string New file name (full or relative path, including the thumbs/). May be the original path if no thumb can exists.
  9584. */
  9585. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  9586. {
  9587. $dirName = dirname($file);
  9588. if ($dirName == '.') {
  9589. $dirName = '';
  9590. }
  9591. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  9592. $fileName = basename($fileName);
  9593. if (empty($extImgTarget)) {
  9594. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  9595. }
  9596. if (empty($extImgTarget)) {
  9597. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  9598. }
  9599. if (empty($extImgTarget)) {
  9600. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  9601. }
  9602. if (empty($extImgTarget)) {
  9603. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  9604. }
  9605. if (empty($extImgTarget)) {
  9606. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  9607. }
  9608. if (empty($extImgTarget)) {
  9609. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  9610. }
  9611. if (!$extImgTarget) {
  9612. return $file;
  9613. }
  9614. $subdir = '';
  9615. if ($extName) {
  9616. $subdir = 'thumbs/';
  9617. }
  9618. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  9619. }
  9620. /**
  9621. * Return URL we can use for advanced preview links
  9622. *
  9623. * @param string $modulepart propal, facture, facture_fourn, ...
  9624. * @param string $relativepath Relative path of docs.
  9625. * @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)
  9626. * @param string $param More param on http links
  9627. * @return string|array Output string with href link or array with all components of link
  9628. */
  9629. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  9630. {
  9631. global $conf, $langs;
  9632. if (empty($conf->use_javascript_ajax)) {
  9633. return '';
  9634. }
  9635. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  9636. if ($alldata == 1) {
  9637. if ($isAllowedForPreview) {
  9638. return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart).'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : ''), 'mime'=>dol_mimetype($relativepath));
  9639. } else {
  9640. return array();
  9641. }
  9642. }
  9643. // old behavior, return a string
  9644. if ($isAllowedForPreview) {
  9645. $tmpurl = DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart).'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : '');
  9646. $title = $langs->trans("Preview");
  9647. //$title = '%27-alert(document.domain)-%27';
  9648. //$tmpurl = 'file='.urlencode("'-alert(document.domain)-'_small.jpg");
  9649. // We need to urlencode the parameter after the dol_escape_js($tmpurl) because $tmpurl may contain n url with param file=abc%27def if file has a ' inside.
  9650. // and when we click on href with this javascript string, a urlcode is done by browser, converted the %27 of file param
  9651. return 'javascript:document_preview(\''.urlencode(dol_escape_js($tmpurl)).'\', \''.urlencode(dol_mimetype($relativepath)).'\', \''.urlencode(dol_escape_js($title)).'\')';
  9652. } else {
  9653. return '';
  9654. }
  9655. }
  9656. /**
  9657. * Make content of an input box selected when we click into input field.
  9658. *
  9659. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  9660. * @param string $addlink Add a 'link to' after
  9661. * @param string $textonlink Text to show on link or 'image'
  9662. * @return string
  9663. */
  9664. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  9665. {
  9666. global $langs;
  9667. $out = '<script nonce="'.getNonce().'">
  9668. jQuery(document).ready(function () {
  9669. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  9670. });
  9671. </script>';
  9672. if ($addlink) {
  9673. if ($textonlink === 'image') {
  9674. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  9675. } else {
  9676. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  9677. }
  9678. }
  9679. return $out;
  9680. }
  9681. /**
  9682. * Return if a file is qualified for preview
  9683. *
  9684. * @param string $file Filename we looking for information
  9685. * @return int 1 If allowed, 0 otherwise
  9686. * @see dol_mimetype(), image_format_supported() from images.lib.php
  9687. */
  9688. function dolIsAllowedForPreview($file)
  9689. {
  9690. global $conf;
  9691. // Check .noexe extension in filename
  9692. if (preg_match('/\.noexe$/i', $file)) {
  9693. return 0;
  9694. }
  9695. // Check mime types
  9696. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  9697. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  9698. $mime_preview[] = 'svg+xml';
  9699. }
  9700. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  9701. //$mime_preview[]='archive';
  9702. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  9703. if ($num_mime !== false) {
  9704. return 1;
  9705. }
  9706. // By default, not allowed for preview
  9707. return 0;
  9708. }
  9709. /**
  9710. * Return MIME type of a file from its name with extension.
  9711. *
  9712. * @param string $file Filename we looking for MIME type
  9713. * @param string $default Default mime type if extension not found in known list
  9714. * @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
  9715. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  9716. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  9717. */
  9718. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  9719. {
  9720. $mime = $default;
  9721. $imgmime = 'other.png';
  9722. $famime = 'file-o';
  9723. $srclang = '';
  9724. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  9725. // Plain text files
  9726. if (preg_match('/\.txt$/i', $tmpfile)) {
  9727. $mime = 'text/plain';
  9728. $imgmime = 'text.png';
  9729. $famime = 'file-text-o';
  9730. }
  9731. if (preg_match('/\.rtx$/i', $tmpfile)) {
  9732. $mime = 'text/richtext';
  9733. $imgmime = 'text.png';
  9734. $famime = 'file-text-o';
  9735. }
  9736. if (preg_match('/\.csv$/i', $tmpfile)) {
  9737. $mime = 'text/csv';
  9738. $imgmime = 'text.png';
  9739. $famime = 'file-text-o';
  9740. }
  9741. if (preg_match('/\.tsv$/i', $tmpfile)) {
  9742. $mime = 'text/tab-separated-values';
  9743. $imgmime = 'text.png';
  9744. $famime = 'file-text-o';
  9745. }
  9746. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  9747. $mime = 'text/plain';
  9748. $imgmime = 'text.png';
  9749. $famime = 'file-text-o';
  9750. }
  9751. if (preg_match('/\.ini$/i', $tmpfile)) {
  9752. $mime = 'text/plain';
  9753. $imgmime = 'text.png';
  9754. $srclang = 'ini';
  9755. $famime = 'file-text-o';
  9756. }
  9757. if (preg_match('/\.md$/i', $tmpfile)) {
  9758. $mime = 'text/plain';
  9759. $imgmime = 'text.png';
  9760. $srclang = 'md';
  9761. $famime = 'file-text-o';
  9762. }
  9763. if (preg_match('/\.css$/i', $tmpfile)) {
  9764. $mime = 'text/css';
  9765. $imgmime = 'css.png';
  9766. $srclang = 'css';
  9767. $famime = 'file-text-o';
  9768. }
  9769. if (preg_match('/\.lang$/i', $tmpfile)) {
  9770. $mime = 'text/plain';
  9771. $imgmime = 'text.png';
  9772. $srclang = 'lang';
  9773. $famime = 'file-text-o';
  9774. }
  9775. // Certificate files
  9776. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  9777. $mime = 'text/plain';
  9778. $imgmime = 'text.png';
  9779. $famime = 'file-text-o';
  9780. }
  9781. // XML based (HTML/XML/XAML)
  9782. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  9783. $mime = 'text/html';
  9784. $imgmime = 'html.png';
  9785. $srclang = 'html';
  9786. $famime = 'file-text-o';
  9787. }
  9788. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  9789. $mime = 'text/xml';
  9790. $imgmime = 'other.png';
  9791. $srclang = 'xml';
  9792. $famime = 'file-text-o';
  9793. }
  9794. if (preg_match('/\.xaml$/i', $tmpfile)) {
  9795. $mime = 'text/xml';
  9796. $imgmime = 'other.png';
  9797. $srclang = 'xaml';
  9798. $famime = 'file-text-o';
  9799. }
  9800. // Languages
  9801. if (preg_match('/\.bas$/i', $tmpfile)) {
  9802. $mime = 'text/plain';
  9803. $imgmime = 'text.png';
  9804. $srclang = 'bas';
  9805. $famime = 'file-code-o';
  9806. }
  9807. if (preg_match('/\.(c)$/i', $tmpfile)) {
  9808. $mime = 'text/plain';
  9809. $imgmime = 'text.png';
  9810. $srclang = 'c';
  9811. $famime = 'file-code-o';
  9812. }
  9813. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  9814. $mime = 'text/plain';
  9815. $imgmime = 'text.png';
  9816. $srclang = 'cpp';
  9817. $famime = 'file-code-o';
  9818. }
  9819. if (preg_match('/\.cs$/i', $tmpfile)) {
  9820. $mime = 'text/plain';
  9821. $imgmime = 'text.png';
  9822. $srclang = 'cs';
  9823. $famime = 'file-code-o';
  9824. }
  9825. if (preg_match('/\.(h)$/i', $tmpfile)) {
  9826. $mime = 'text/plain';
  9827. $imgmime = 'text.png';
  9828. $srclang = 'h';
  9829. $famime = 'file-code-o';
  9830. }
  9831. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  9832. $mime = 'text/plain';
  9833. $imgmime = 'text.png';
  9834. $srclang = 'java';
  9835. $famime = 'file-code-o';
  9836. }
  9837. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  9838. $mime = 'text/plain';
  9839. $imgmime = 'php.png';
  9840. $srclang = 'php';
  9841. $famime = 'file-code-o';
  9842. }
  9843. if (preg_match('/\.phtml$/i', $tmpfile)) {
  9844. $mime = 'text/plain';
  9845. $imgmime = 'php.png';
  9846. $srclang = 'php';
  9847. $famime = 'file-code-o';
  9848. }
  9849. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  9850. $mime = 'text/plain';
  9851. $imgmime = 'pl.png';
  9852. $srclang = 'perl';
  9853. $famime = 'file-code-o';
  9854. }
  9855. if (preg_match('/\.sql$/i', $tmpfile)) {
  9856. $mime = 'text/plain';
  9857. $imgmime = 'text.png';
  9858. $srclang = 'sql';
  9859. $famime = 'file-code-o';
  9860. }
  9861. if (preg_match('/\.js$/i', $tmpfile)) {
  9862. $mime = 'text/x-javascript';
  9863. $imgmime = 'jscript.png';
  9864. $srclang = 'js';
  9865. $famime = 'file-code-o';
  9866. }
  9867. // Open office
  9868. if (preg_match('/\.odp$/i', $tmpfile)) {
  9869. $mime = 'application/vnd.oasis.opendocument.presentation';
  9870. $imgmime = 'ooffice.png';
  9871. $famime = 'file-powerpoint-o';
  9872. }
  9873. if (preg_match('/\.ods$/i', $tmpfile)) {
  9874. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  9875. $imgmime = 'ooffice.png';
  9876. $famime = 'file-excel-o';
  9877. }
  9878. if (preg_match('/\.odt$/i', $tmpfile)) {
  9879. $mime = 'application/vnd.oasis.opendocument.text';
  9880. $imgmime = 'ooffice.png';
  9881. $famime = 'file-word-o';
  9882. }
  9883. // MS Office
  9884. if (preg_match('/\.mdb$/i', $tmpfile)) {
  9885. $mime = 'application/msaccess';
  9886. $imgmime = 'mdb.png';
  9887. $famime = 'file-o';
  9888. }
  9889. if (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
  9890. $mime = 'application/msword';
  9891. $imgmime = 'doc.png';
  9892. $famime = 'file-word-o';
  9893. }
  9894. if (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
  9895. $mime = 'application/msword';
  9896. $imgmime = 'doc.png';
  9897. $famime = 'file-word-o';
  9898. }
  9899. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  9900. $mime = 'application/vnd.ms-excel';
  9901. $imgmime = 'xls.png';
  9902. $famime = 'file-excel-o';
  9903. }
  9904. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  9905. $mime = 'application/vnd.ms-excel';
  9906. $imgmime = 'xls.png';
  9907. $famime = 'file-excel-o';
  9908. }
  9909. if (preg_match('/\.xls$/i', $tmpfile)) {
  9910. $mime = 'application/vnd.ms-excel';
  9911. $imgmime = 'xls.png';
  9912. $famime = 'file-excel-o';
  9913. }
  9914. if (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
  9915. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  9916. $imgmime = 'xls.png';
  9917. $famime = 'file-excel-o';
  9918. }
  9919. if (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
  9920. $mime = 'application/vnd.ms-powerpoint';
  9921. $imgmime = 'ppt.png';
  9922. $famime = 'file-powerpoint-o';
  9923. }
  9924. if (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
  9925. $mime = 'application/x-mspowerpoint';
  9926. $imgmime = 'ppt.png';
  9927. $famime = 'file-powerpoint-o';
  9928. }
  9929. // Other
  9930. if (preg_match('/\.pdf$/i', $tmpfile)) {
  9931. $mime = 'application/pdf';
  9932. $imgmime = 'pdf.png';
  9933. $famime = 'file-pdf-o';
  9934. }
  9935. // Scripts
  9936. if (preg_match('/\.bat$/i', $tmpfile)) {
  9937. $mime = 'text/x-bat';
  9938. $imgmime = 'script.png';
  9939. $srclang = 'dos';
  9940. $famime = 'file-code-o';
  9941. }
  9942. if (preg_match('/\.sh$/i', $tmpfile)) {
  9943. $mime = 'text/x-sh';
  9944. $imgmime = 'script.png';
  9945. $srclang = 'bash';
  9946. $famime = 'file-code-o';
  9947. }
  9948. if (preg_match('/\.ksh$/i', $tmpfile)) {
  9949. $mime = 'text/x-ksh';
  9950. $imgmime = 'script.png';
  9951. $srclang = 'bash';
  9952. $famime = 'file-code-o';
  9953. }
  9954. if (preg_match('/\.bash$/i', $tmpfile)) {
  9955. $mime = 'text/x-bash';
  9956. $imgmime = 'script.png';
  9957. $srclang = 'bash';
  9958. $famime = 'file-code-o';
  9959. }
  9960. // Images
  9961. if (preg_match('/\.ico$/i', $tmpfile)) {
  9962. $mime = 'image/x-icon';
  9963. $imgmime = 'image.png';
  9964. $famime = 'file-image-o';
  9965. }
  9966. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  9967. $mime = 'image/jpeg';
  9968. $imgmime = 'image.png';
  9969. $famime = 'file-image-o';
  9970. }
  9971. if (preg_match('/\.png$/i', $tmpfile)) {
  9972. $mime = 'image/png';
  9973. $imgmime = 'image.png';
  9974. $famime = 'file-image-o';
  9975. }
  9976. if (preg_match('/\.gif$/i', $tmpfile)) {
  9977. $mime = 'image/gif';
  9978. $imgmime = 'image.png';
  9979. $famime = 'file-image-o';
  9980. }
  9981. if (preg_match('/\.bmp$/i', $tmpfile)) {
  9982. $mime = 'image/bmp';
  9983. $imgmime = 'image.png';
  9984. $famime = 'file-image-o';
  9985. }
  9986. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  9987. $mime = 'image/tiff';
  9988. $imgmime = 'image.png';
  9989. $famime = 'file-image-o';
  9990. }
  9991. if (preg_match('/\.svg$/i', $tmpfile)) {
  9992. $mime = 'image/svg+xml';
  9993. $imgmime = 'image.png';
  9994. $famime = 'file-image-o';
  9995. }
  9996. if (preg_match('/\.webp$/i', $tmpfile)) {
  9997. $mime = 'image/webp';
  9998. $imgmime = 'image.png';
  9999. $famime = 'file-image-o';
  10000. }
  10001. // Calendar
  10002. if (preg_match('/\.vcs$/i', $tmpfile)) {
  10003. $mime = 'text/calendar';
  10004. $imgmime = 'other.png';
  10005. $famime = 'file-text-o';
  10006. }
  10007. if (preg_match('/\.ics$/i', $tmpfile)) {
  10008. $mime = 'text/calendar';
  10009. $imgmime = 'other.png';
  10010. $famime = 'file-text-o';
  10011. }
  10012. // Other
  10013. if (preg_match('/\.torrent$/i', $tmpfile)) {
  10014. $mime = 'application/x-bittorrent';
  10015. $imgmime = 'other.png';
  10016. $famime = 'file-o';
  10017. }
  10018. // Audio
  10019. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  10020. $mime = 'audio';
  10021. $imgmime = 'audio.png';
  10022. $famime = 'file-audio-o';
  10023. }
  10024. // Video
  10025. if (preg_match('/\.mp4$/i', $tmpfile)) {
  10026. $mime = 'video/mp4';
  10027. $imgmime = 'video.png';
  10028. $famime = 'file-video-o';
  10029. }
  10030. if (preg_match('/\.ogv$/i', $tmpfile)) {
  10031. $mime = 'video/ogg';
  10032. $imgmime = 'video.png';
  10033. $famime = 'file-video-o';
  10034. }
  10035. if (preg_match('/\.webm$/i', $tmpfile)) {
  10036. $mime = 'video/webm';
  10037. $imgmime = 'video.png';
  10038. $famime = 'file-video-o';
  10039. }
  10040. if (preg_match('/\.avi$/i', $tmpfile)) {
  10041. $mime = 'video/x-msvideo';
  10042. $imgmime = 'video.png';
  10043. $famime = 'file-video-o';
  10044. }
  10045. if (preg_match('/\.divx$/i', $tmpfile)) {
  10046. $mime = 'video/divx';
  10047. $imgmime = 'video.png';
  10048. $famime = 'file-video-o';
  10049. }
  10050. if (preg_match('/\.xvid$/i', $tmpfile)) {
  10051. $mime = 'video/xvid';
  10052. $imgmime = 'video.png';
  10053. $famime = 'file-video-o';
  10054. }
  10055. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  10056. $mime = 'video';
  10057. $imgmime = 'video.png';
  10058. $famime = 'file-video-o';
  10059. }
  10060. // Archive
  10061. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  10062. $mime = 'archive';
  10063. $imgmime = 'archive.png';
  10064. $famime = 'file-archive-o';
  10065. } // application/xxx where zzz is zip, ...
  10066. // Exe
  10067. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  10068. $mime = 'application/octet-stream';
  10069. $imgmime = 'other.png';
  10070. $famime = 'file-o';
  10071. }
  10072. // Lib
  10073. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  10074. $mime = 'library';
  10075. $imgmime = 'library.png';
  10076. $famime = 'file-o';
  10077. }
  10078. // Err
  10079. if (preg_match('/\.err$/i', $tmpfile)) {
  10080. $mime = 'error';
  10081. $imgmime = 'error.png';
  10082. $famime = 'file-text-o';
  10083. }
  10084. // Return string
  10085. if ($mode == 1) {
  10086. $tmp = explode('/', $mime);
  10087. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  10088. }
  10089. if ($mode == 2) {
  10090. return $imgmime;
  10091. }
  10092. if ($mode == 3) {
  10093. return $srclang;
  10094. }
  10095. if ($mode == 4) {
  10096. return $famime;
  10097. }
  10098. return $mime;
  10099. }
  10100. /**
  10101. * Return the value of a filed into a dictionary for the record $id.
  10102. * This also set all the values into a cache for a next search.
  10103. *
  10104. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  10105. * @param string $field The name of field where to find the value to return
  10106. * @param int $id Id of line record
  10107. * @param bool $checkentity Add filter on entity
  10108. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  10109. * @return string The value of field $field. This also set $dictvalues cache.
  10110. */
  10111. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  10112. {
  10113. global $conf, $db;
  10114. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  10115. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  10116. if (is_null($dictvalues)) {
  10117. $dictvalues = array();
  10118. $sql = "SELECT * FROM ".MAIN_DB_PREFIX.$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  10119. if ($checkentity) {
  10120. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  10121. }
  10122. $resql = $db->query($sql);
  10123. if ($resql) {
  10124. while ($obj = $db->fetch_object($resql)) {
  10125. $dictvalues[$obj->$rowidfield] = $obj; // $obj is stdClass
  10126. }
  10127. } else {
  10128. dol_print_error($db);
  10129. }
  10130. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  10131. }
  10132. if (!empty($dictvalues[$id])) {
  10133. // Found
  10134. $tmp = $dictvalues[$id];
  10135. return (property_exists($tmp, $field) ? $tmp->$field : '');
  10136. } else {
  10137. // Not found
  10138. return '';
  10139. }
  10140. }
  10141. /**
  10142. * Return true if the color is light
  10143. *
  10144. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  10145. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  10146. */
  10147. function colorIsLight($stringcolor)
  10148. {
  10149. $stringcolor = str_replace('#', '', $stringcolor);
  10150. $res = -1;
  10151. if (!empty($stringcolor)) {
  10152. $res = 0;
  10153. $tmp = explode(',', $stringcolor);
  10154. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  10155. $r = $tmp[0];
  10156. $g = $tmp[1];
  10157. $b = $tmp[2];
  10158. } else {
  10159. $hexr = $stringcolor[0].$stringcolor[1];
  10160. $hexg = $stringcolor[2].$stringcolor[3];
  10161. $hexb = $stringcolor[4].$stringcolor[5];
  10162. $r = hexdec($hexr);
  10163. $g = hexdec($hexg);
  10164. $b = hexdec($hexb);
  10165. }
  10166. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  10167. if ($bright > 0.6) {
  10168. $res = 1;
  10169. }
  10170. }
  10171. return $res;
  10172. }
  10173. /**
  10174. * Function to test if an entry is enabled or not
  10175. *
  10176. * @param string $type_user 0=We test for internal user, 1=We test for external user
  10177. * @param array $menuentry Array for feature entry to test
  10178. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  10179. * @return int 0=Hide, 1=Show, 2=Show gray
  10180. */
  10181. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  10182. {
  10183. global $conf;
  10184. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  10185. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  10186. if (empty($menuentry['enabled'])) {
  10187. return 0; // Entry disabled by condition
  10188. }
  10189. if ($type_user && $menuentry['module']) {
  10190. $tmploops = explode('|', $menuentry['module']);
  10191. $found = 0;
  10192. foreach ($tmploops as $tmploop) {
  10193. if (in_array($tmploop, $listofmodulesforexternal)) {
  10194. $found++;
  10195. break;
  10196. }
  10197. }
  10198. if (!$found) {
  10199. return 0; // Entry is for menus all excluded to external users
  10200. }
  10201. }
  10202. if (!$menuentry['perms'] && $type_user) {
  10203. return 0; // No permissions and user is external
  10204. }
  10205. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  10206. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  10207. }
  10208. if (!$menuentry['perms']) {
  10209. return 2; // No permissions and user is external
  10210. }
  10211. return 1;
  10212. }
  10213. /**
  10214. * Round to next multiple.
  10215. *
  10216. * @param double $n Number to round up
  10217. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  10218. * @return integer Value rounded.
  10219. */
  10220. function roundUpToNextMultiple($n, $x = 5)
  10221. {
  10222. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  10223. }
  10224. /**
  10225. * Function dolGetBadge
  10226. *
  10227. * @param string $label label of badge no html : use in alt attribute for accessibility
  10228. * @param string $html optional : label of badge with html
  10229. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  10230. * @param string $mode default '' , 'pill', 'dot'
  10231. * @param string $url the url for link
  10232. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  10233. * @return string Html badge
  10234. */
  10235. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  10236. {
  10237. $attr = array(
  10238. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  10239. );
  10240. if (empty($html)) {
  10241. $html = $label;
  10242. }
  10243. if (!empty($url)) {
  10244. $attr['href'] = $url;
  10245. }
  10246. if ($mode === 'dot') {
  10247. $attr['class'] .= ' classfortooltip';
  10248. $attr['title'] = $html;
  10249. $attr['aria-label'] = $label;
  10250. $html = '';
  10251. }
  10252. // Override attr
  10253. if (!empty($params['attr']) && is_array($params['attr'])) {
  10254. foreach ($params['attr'] as $key => $value) {
  10255. if ($key == 'class') {
  10256. $attr['class'] .= ' '.$value;
  10257. } elseif ($key == 'classOverride') {
  10258. $attr['class'] = $value;
  10259. } else {
  10260. $attr[$key] = $value;
  10261. }
  10262. }
  10263. }
  10264. // TODO: add hook
  10265. // escape all attribute
  10266. $attr = array_map('dol_escape_htmltag', $attr);
  10267. $TCompiledAttr = array();
  10268. foreach ($attr as $key => $value) {
  10269. $TCompiledAttr[] = $key.'="'.$value.'"';
  10270. }
  10271. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  10272. $tag = !empty($url) ? 'a' : 'span';
  10273. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  10274. }
  10275. /**
  10276. * Output the badge of a status.
  10277. *
  10278. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  10279. * @param string $statusLabelShort Short label of badge no html
  10280. * @param string $html Optional : label of badge with html
  10281. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  10282. * @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
  10283. * @param string $url The url for link
  10284. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  10285. * @return string Html status string
  10286. */
  10287. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  10288. {
  10289. global $conf;
  10290. $return = '';
  10291. $dolGetBadgeParams = array();
  10292. if (!empty($params['badgeParams'])) {
  10293. $dolGetBadgeParams = $params['badgeParams'];
  10294. }
  10295. // TODO : add a hook
  10296. if ($displayMode == 0) {
  10297. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  10298. } elseif ($displayMode == 1) {
  10299. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  10300. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  10301. // Use status with images (for backward compatibility)
  10302. $return = '';
  10303. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  10304. $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>' : '');
  10305. // For small screen, we always use the short label instead of long label.
  10306. if (!empty($conf->dol_optimize_smallscreen)) {
  10307. if ($displayMode == 0) {
  10308. $displayMode = 1;
  10309. } elseif ($displayMode == 4) {
  10310. $displayMode = 2;
  10311. } elseif ($displayMode == 6) {
  10312. $displayMode = 5;
  10313. }
  10314. }
  10315. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  10316. $statusImg = array(
  10317. 'status0' => 'statut0',
  10318. 'status1' => 'statut1',
  10319. 'status2' => 'statut2',
  10320. 'status3' => 'statut3',
  10321. 'status4' => 'statut4',
  10322. 'status5' => 'statut5',
  10323. 'status6' => 'statut6',
  10324. 'status7' => 'statut7',
  10325. 'status8' => 'statut8',
  10326. 'status9' => 'statut9'
  10327. );
  10328. if (!empty($statusImg[$statusType])) {
  10329. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  10330. } else {
  10331. $htmlImg = img_picto($statusLabel, $statusType);
  10332. }
  10333. if ($displayMode === 2) {
  10334. $return = $htmlImg.' '.$htmlLabelShort;
  10335. } elseif ($displayMode === 3) {
  10336. $return = $htmlImg;
  10337. } elseif ($displayMode === 4) {
  10338. $return = $htmlImg.' '.$htmlLabel;
  10339. } elseif ($displayMode === 5) {
  10340. $return = $htmlLabelShort.' '.$htmlImg;
  10341. } else { // $displayMode >= 6
  10342. $return = $htmlLabel.' '.$htmlImg;
  10343. }
  10344. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  10345. // Use new badge
  10346. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  10347. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  10348. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  10349. if ($displayMode == 3) {
  10350. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  10351. } elseif ($displayMode === 5) {
  10352. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  10353. } else {
  10354. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  10355. }
  10356. }
  10357. return $return;
  10358. }
  10359. /**
  10360. * Function dolGetButtonAction
  10361. *
  10362. * @param string $label Label or tooltip of button if $tet is provided. Also used as tooltip in title attribute. Can be escaped HTML content or full simple text.
  10363. * @param string $text Optional : short label on button. Can be escaped HTML content or full simple text.
  10364. * @param string $actionType 'default', 'danger', 'email', 'clone', 'cancel', 'delete', ...
  10365. * @param string|array $url Url for link or array of subbutton description ('label'=>, 'url'=>, 'lang'=>, 'perm'=> )
  10366. * Example when an array is used: $arrayforbutaction = array(
  10367. * 10 => array('lang'=>'propal', 'enabled'=>isModEnabled("propal"), 'perm'=>$user->hasRight('propal', 'creer'), 'label' => 'AddProp', 'url'=>'/comm/propal/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10368. * 20 => array('lang'=>'orders', 'enabled'=>isModEnabled("commande"), 'perm'=>$user->hasRight('commande', 'creer'), 'label' => 'CreateOrder', 'url'=>'/commande/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10369. * 30 => array('lang'=>'bills', 'enabled'=>isModEnabled("facture"), 'perm'=>$user->hasRight('facture', 'creer'), 'label' => 'CreateBill', 'url'=>'/compta/facture/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10370. * );
  10371. * @param string $id Attribute id of button
  10372. * @param int|boolean $userRight User action right
  10373. * // phpcs:disable
  10374. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  10375. * 'attr' => [ // to add or override button attributes
  10376. * 'xxxxx' => '', // your xxxxx attribute you want
  10377. * 'class' => 'reposition', // to add more css class to the button class attribute
  10378. * 'classOverride' => '' // to replace class attribute of the button
  10379. * ],
  10380. * 'confirm' => [
  10381. * 'url' => 'http://', // Overide Url to go when user click on action btn, if empty default url is $url.?confirm=yes, for no js compatibility use $url for fallback confirm.
  10382. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  10383. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  10384. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  10385. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  10386. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  10387. * 'isDropDrown' => false, // true|false to display dialog as a dropdown (with dark background)
  10388. * ],
  10389. * ]
  10390. * // phpcs:enable
  10391. * @return string html button
  10392. */
  10393. function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  10394. {
  10395. global $hookmanager, $action, $object, $langs;
  10396. // If $url is an array, we must build a dropdown button
  10397. if (is_array($url)) {
  10398. $out = '';
  10399. if (count($url) > 1) {
  10400. $out .= '<div class="dropdown inline-block dropdown-holder">';
  10401. $out .= '<a style="margin-right: auto;" class="dropdown-toggle classfortooltip butAction'.($userRight ? '' : 'Refused').'" title="'.dol_escape_htmltag($label).'" data-toggle="dropdown">'.($text ? $text : $label).'</a>';
  10402. $out .= '<div class="dropdown-content">';
  10403. foreach ($url as $subbutton) {
  10404. if (!empty($subbutton['lang'])) {
  10405. $langs->load($subbutton['lang']);
  10406. }
  10407. $tmpurl = DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage']));
  10408. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, '', $subbutton['perm'], array('isDropDown' => true));
  10409. }
  10410. $out .= "</div>";
  10411. $out .= "</div>";
  10412. } else {
  10413. foreach ($url as $subbutton) { // Should loop on 1 record only
  10414. if (!empty($subbutton['lang'])) {
  10415. $langs->load($subbutton['lang']);
  10416. }
  10417. $tmpurl = DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage']));
  10418. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, '', $subbutton['perm']);
  10419. }
  10420. }
  10421. return $out;
  10422. }
  10423. // Here, $url is a simple link
  10424. if (!empty($params['isDropdown']))
  10425. $class = "dropdown-item";
  10426. else {
  10427. $class = 'butAction';
  10428. if ($actionType == 'danger' || $actionType == 'delete') {
  10429. $class = 'butActionDelete';
  10430. if (!empty($url) && strpos($url, 'token=') === false) {
  10431. $url .= '&token='.newToken();
  10432. }
  10433. }
  10434. }
  10435. $attr = array(
  10436. 'class' => $class,
  10437. 'href' => empty($url) ? '' : $url,
  10438. 'title' => $label
  10439. );
  10440. if (empty($text)) {
  10441. $text = $label;
  10442. $attr['title'] = ''; // if html not set, leave label on title is redundant
  10443. } else {
  10444. $attr['title'] = $label;
  10445. $attr['aria-label'] = $label;
  10446. }
  10447. if (empty($userRight)) {
  10448. $attr['class'] = 'butActionRefused';
  10449. $attr['href'] = '';
  10450. $attr['title'] = (($label && $text && $label != $text) ? $label : $langs->trans('NotEnoughPermissions'));
  10451. }
  10452. if (!empty($id)) {
  10453. $attr['id'] = $id;
  10454. }
  10455. // Override attr
  10456. if (!empty($params['attr']) && is_array($params['attr'])) {
  10457. foreach ($params['attr'] as $key => $value) {
  10458. if ($key == 'class') {
  10459. $attr['class'] .= ' '.$value;
  10460. } elseif ($key == 'classOverride') {
  10461. $attr['class'] = $value;
  10462. } else {
  10463. $attr[$key] = $value;
  10464. }
  10465. }
  10466. }
  10467. // automatic add tooltip when title is detected
  10468. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  10469. $attr['class'].= ' classfortooltip';
  10470. }
  10471. // Js Confirm button
  10472. if ($userRight && !empty($params['confirm'])) {
  10473. if (!is_array($params['confirm'])) {
  10474. $params['confirm'] = array();
  10475. }
  10476. if (empty($params['confirm']['url'])) {
  10477. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  10478. }
  10479. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  10480. $attr['data-confirm-url'] = $params['confirm']['url'];
  10481. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  10482. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  10483. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  10484. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  10485. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  10486. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  10487. $attr['class'].= ' butActionConfirm';
  10488. }
  10489. if (isset($attr['href']) && empty($attr['href'])) {
  10490. unset($attr['href']);
  10491. }
  10492. // escape all attribute
  10493. $attr = array_map('dol_escape_htmltag', $attr);
  10494. $TCompiledAttr = array();
  10495. foreach ($attr as $key => $value) {
  10496. $TCompiledAttr[] = $key.'= "'.$value.'"';
  10497. }
  10498. $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
  10499. $tag = !empty($attr['href']) ? 'a' : 'span';
  10500. $parameters = array(
  10501. 'TCompiledAttr' => $TCompiledAttr, // array
  10502. 'compiledAttributes' => $compiledAttributes, // string
  10503. 'attr' => $attr,
  10504. 'tag' => $tag,
  10505. 'label' => $label,
  10506. 'html' => $text,
  10507. 'actionType' => $actionType,
  10508. 'url' => $url,
  10509. 'id' => $id,
  10510. 'userRight' => $userRight,
  10511. 'params' => $params
  10512. );
  10513. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  10514. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  10515. if (empty($reshook)) {
  10516. if (dol_textishtml($text)) { // If content already HTML encoded
  10517. return '<' . $tag . ' ' . $compiledAttributes . '>' . $text . '</' . $tag . '>';
  10518. } else {
  10519. return '<' . $tag . ' ' . $compiledAttributes . '>' . dol_escape_htmltag($text) . '</' . $tag . '>';
  10520. }
  10521. } else {
  10522. return $hookmanager->resPrint;
  10523. }
  10524. }
  10525. /**
  10526. * Add space between dolGetButtonTitle
  10527. *
  10528. * @param string $moreClass more css class label
  10529. * @return string html of title separator
  10530. */
  10531. function dolGetButtonTitleSeparator($moreClass = "")
  10532. {
  10533. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  10534. }
  10535. /**
  10536. * get field error icon
  10537. *
  10538. * @param string $fieldValidationErrorMsg message to add in tooltip
  10539. * @return string html output
  10540. */
  10541. function getFieldErrorIcon($fieldValidationErrorMsg)
  10542. {
  10543. $out = '';
  10544. if (!empty($fieldValidationErrorMsg)) {
  10545. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  10546. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  10547. $out.= '</span>';
  10548. }
  10549. return $out;
  10550. }
  10551. /**
  10552. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  10553. *
  10554. * @param string $label label of button
  10555. * @param string $helpText optional : content for help tooltip
  10556. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  10557. * @param string $url the url for link
  10558. * @param string $id attribute id of button
  10559. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use param $helpText as tooltip help
  10560. * @param array $params various params for future : recommended rather than adding more function arguments
  10561. * @return string html button
  10562. */
  10563. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  10564. {
  10565. global $langs, $conf, $user;
  10566. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  10567. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  10568. return '';
  10569. }
  10570. $class = 'btnTitle';
  10571. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
  10572. $class .= ' btnTitlePlus';
  10573. }
  10574. $useclassfortooltip = 1;
  10575. if (!empty($params['morecss'])) {
  10576. $class .= ' '.$params['morecss'];
  10577. }
  10578. $attr = array(
  10579. 'class' => $class,
  10580. 'href' => empty($url) ? '' : $url
  10581. );
  10582. if (!empty($helpText)) {
  10583. $attr['title'] = dol_escape_htmltag($helpText);
  10584. } elseif (empty($attr['title']) && $label) {
  10585. $attr['title'] = $label;
  10586. $useclassfortooltip = 0;
  10587. }
  10588. if ($status == 2) {
  10589. $attr['class'] .= ' btnTitleSelected';
  10590. } elseif ($status <= 0) {
  10591. $attr['class'] .= ' refused';
  10592. $attr['href'] = '';
  10593. if ($status == -1) { // disable
  10594. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  10595. } elseif ($status == 0) { // Not enough permissions
  10596. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  10597. }
  10598. }
  10599. if (!empty($attr['title']) && $useclassfortooltip) {
  10600. $attr['class'] .= ' classfortooltip';
  10601. }
  10602. if (!empty($id)) {
  10603. $attr['id'] = $id;
  10604. }
  10605. // Override attr
  10606. if (!empty($params['attr']) && is_array($params['attr'])) {
  10607. foreach ($params['attr'] as $key => $value) {
  10608. if ($key == 'class') {
  10609. $attr['class'] .= ' '.$value;
  10610. } elseif ($key == 'classOverride') {
  10611. $attr['class'] = $value;
  10612. } else {
  10613. $attr[$key] = $value;
  10614. }
  10615. }
  10616. }
  10617. if (isset($attr['href']) && empty($attr['href'])) {
  10618. unset($attr['href']);
  10619. }
  10620. // TODO : add a hook
  10621. // escape all attribute
  10622. $attr = array_map('dol_escape_htmltag', $attr);
  10623. $TCompiledAttr = array();
  10624. foreach ($attr as $key => $value) {
  10625. $TCompiledAttr[] = $key.'="'.$value.'"';
  10626. }
  10627. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  10628. $tag = (empty($attr['href']) ? 'span' : 'a');
  10629. $button = '<'.$tag.' '.$compiledAttributes.'>';
  10630. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  10631. if (!empty($params['forcenohideoftext'])) {
  10632. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  10633. }
  10634. $button .= '</'.$tag.'>';
  10635. return $button;
  10636. }
  10637. /**
  10638. * Get an array with properties of an element.
  10639. *
  10640. * @param string $element_type Element type (Value of $object->element). Example:
  10641. * 'action', 'facture', 'project', 'project_task' or
  10642. * 'myobject@mymodule' or
  10643. * 'myobject_mysubobject' (where mymodule = myobject, like 'project_task')
  10644. * @return array array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>)
  10645. * @see fetchObjectByElement()
  10646. */
  10647. function getElementProperties($element_type)
  10648. {
  10649. global $conf;
  10650. $regs = array();
  10651. $classfile = $classname = $classpath = $subdir = $dir_output = '';
  10652. // Parse element/subelement
  10653. $module = $element_type;
  10654. $element = $element_type;
  10655. $subelement = $element_type;
  10656. $table_element = $element_type;
  10657. // If we ask a resource form external module (instead of default path)
  10658. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) { // 'myobject@mymodule'
  10659. $element = $subelement = $regs[1];
  10660. $module = $regs[2];
  10661. }
  10662. // If we ask a resource for a string with an element and a subelement
  10663. // Example 'project_task'
  10664. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
  10665. $module = $element = $regs[1];
  10666. $subelement = $regs[2];
  10667. }
  10668. // For compat and To work with non standard path
  10669. if ($element_type == "action") {
  10670. $classpath = 'comm/action/class';
  10671. $subelement = 'Actioncomm';
  10672. $module = 'agenda';
  10673. $table_element = 'actioncomm';
  10674. } elseif ($element_type == 'cronjob') {
  10675. $classpath = 'cron/class';
  10676. $module = 'cron';
  10677. $table_element = 'cron';
  10678. } elseif ($element_type == 'adherent_type') {
  10679. $classpath = 'adherents/class';
  10680. $classfile = 'adherent_type';
  10681. $module = 'adherent';
  10682. $subelement = 'adherent_type';
  10683. $classname = 'AdherentType';
  10684. $table_element = 'adherent_type';
  10685. } elseif ($element_type == 'bank_account') {
  10686. $classpath = 'compta/bank/class';
  10687. $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
  10688. $classfile = 'account';
  10689. $classname = 'Account';
  10690. } elseif ($element_type == 'category') {
  10691. $classpath = 'categories/class';
  10692. $module = 'categorie';
  10693. $subelement = 'categorie';
  10694. $table_element = 'categorie';
  10695. } elseif ($element_type == 'contact') {
  10696. $classpath = 'contact/class';
  10697. $classfile = 'contact';
  10698. $module = 'societe';
  10699. $subelement = 'contact';
  10700. $table_element = 'socpeople';
  10701. } elseif ($element_type == 'stock') {
  10702. $classpath = 'product/stock/class';
  10703. $classfile = 'entrepot';
  10704. $classname = 'Entrepot';
  10705. $table_element = 'entrepot';
  10706. } elseif ($element_type == 'project') {
  10707. $classpath = 'projet/class';
  10708. $module = 'projet';
  10709. $table_element = 'projet';
  10710. } elseif ($element_type == 'project_task') {
  10711. $classpath = 'projet/class';
  10712. $module = 'projet';
  10713. $subelement = 'task';
  10714. $table_element = 'projet_task';
  10715. } elseif ($element_type == 'facture' || $element_type == 'invoice') {
  10716. $classpath = 'compta/facture/class';
  10717. $module = 'facture';
  10718. $subelement = 'facture';
  10719. $table_element = 'facture';
  10720. } elseif ($element_type == 'commande' || $element_type == 'order') {
  10721. $classpath = 'commande/class';
  10722. $module = 'commande';
  10723. $subelement = 'commande';
  10724. $table_element = 'commande';
  10725. } elseif ($element_type == 'propal') {
  10726. $classpath = 'comm/propal/class';
  10727. $table_element = 'propal';
  10728. } elseif ($element_type == 'shipping') {
  10729. $classpath = 'expedition/class';
  10730. $classfile = 'expedition';
  10731. $classname = 'Expedition';
  10732. $module = 'expedition';
  10733. $table_element = 'expedition';
  10734. } elseif ($element_type == 'supplier_proposal') {
  10735. $classpath = 'supplier_proposal/class';
  10736. $module = 'supplier_proposal';
  10737. $element = 'supplierproposal';
  10738. $classfile = 'supplier_proposal';
  10739. $subelement = 'supplierproposal';
  10740. } elseif ($element_type == 'shipping') {
  10741. $classpath = 'expedition/class';
  10742. $subelement = 'expedition';
  10743. $module = 'expedition_bon';
  10744. } elseif ($element_type == 'delivery') {
  10745. $classpath = 'delivery/class';
  10746. $subelement = 'delivery';
  10747. $module = 'delivery_note';
  10748. } elseif ($element_type == 'contract') {
  10749. $classpath = 'contrat/class';
  10750. $module = 'contrat';
  10751. $subelement = 'contrat';
  10752. $table_element = 'contract';
  10753. } elseif ($element_type == 'mailing') {
  10754. $classpath = 'comm/mailing/class';
  10755. $module = 'mailing';
  10756. $classfile = 'mailing';
  10757. $classname = 'Mailing';
  10758. $subelement = '';
  10759. } elseif ($element_type == 'member') {
  10760. $classpath = 'adherents/class';
  10761. $module = 'adherent';
  10762. $subelement = 'adherent';
  10763. $table_element = 'adherent';
  10764. } elseif ($element_type == 'usergroup') {
  10765. $classpath = 'user/class';
  10766. $module = 'user';
  10767. } elseif ($element_type == 'mo') {
  10768. $classpath = 'mrp/class';
  10769. $classfile = 'mo';
  10770. $classname = 'Mo';
  10771. $module = 'mrp';
  10772. $subelement = '';
  10773. $table_element = 'mrp_mo';
  10774. } elseif ($element_type == 'cabinetmed_cons') {
  10775. $classpath = 'cabinetmed/class';
  10776. $module = 'cabinetmed';
  10777. $subelement = 'cabinetmedcons';
  10778. $table_element = 'cabinetmedcons';
  10779. } elseif ($element_type == 'fichinter') {
  10780. $classpath = 'fichinter/class';
  10781. $module = 'ficheinter';
  10782. $subelement = 'fichinter';
  10783. $table_element = 'fichinter';
  10784. } elseif ($element_type == 'dolresource' || $element_type == 'resource') {
  10785. $classpath = 'resource/class';
  10786. $module = 'resource';
  10787. $subelement = 'dolresource';
  10788. $table_element = 'resource';
  10789. } elseif ($element_type == 'propaldet') {
  10790. $classpath = 'comm/propal/class';
  10791. $module = 'propal';
  10792. $subelement = 'propaleligne';
  10793. } elseif ($element_type == 'opensurvey_sondage') {
  10794. $classpath = 'opensurvey/class';
  10795. $module = 'opensurvey';
  10796. $subelement = 'opensurveysondage';
  10797. } elseif ($element_type == 'order_supplier') {
  10798. $classpath = 'fourn/class';
  10799. $module = 'fournisseur';
  10800. $classfile = 'fournisseur.commande';
  10801. $element = 'order_supplier';
  10802. $subelement = '';
  10803. $classname = 'CommandeFournisseur';
  10804. $table_element = 'commande_fournisseur';
  10805. } elseif ($element_type == 'invoice_supplier') {
  10806. $classpath = 'fourn/class';
  10807. $module = 'fournisseur';
  10808. $classfile = 'fournisseur.facture';
  10809. $element = 'invoice_supplier';
  10810. $subelement = '';
  10811. $classname = 'FactureFournisseur';
  10812. $table_element = 'facture_fourn';
  10813. } elseif ($element_type == "service") {
  10814. $classpath = 'product/class';
  10815. $subelement = 'product';
  10816. $table_element = 'product';
  10817. } elseif ($element_type == 'salary') {
  10818. $classpath = 'salaries/class';
  10819. $module = 'salaries';
  10820. } elseif ($element_type == 'productlot') {
  10821. $module = 'productbatch';
  10822. $classpath = 'product/stock/class';
  10823. $classfile = 'productlot';
  10824. $classname = 'Productlot';
  10825. $element = 'productlot';
  10826. $subelement = '';
  10827. $table_element = 'product_lot';
  10828. } elseif ($element_type == 'websitepage') {
  10829. $classpath = 'website/class';
  10830. $classfile = 'websitepage';
  10831. $classname = 'Websitepage';
  10832. $module = 'website';
  10833. $subelement = 'websitepage';
  10834. $table_element = 'website_page';
  10835. } elseif ($element_type == 'fiscalyear') {
  10836. $classpath = 'core/class';
  10837. $module = 'accounting';
  10838. $subelement = 'fiscalyear';
  10839. } elseif ($element_type == 'chargesociales') {
  10840. $classpath = 'compta/sociales/class';
  10841. $module = 'tax';
  10842. $table_element = 'chargesociales';
  10843. } elseif ($element_type == 'tva') {
  10844. $classpath = 'compta/tva/class';
  10845. $module = 'tax';
  10846. $subdir = '/vat';
  10847. $table_element = 'tva';
  10848. }
  10849. if (empty($classfile)) {
  10850. $classfile = strtolower($subelement);
  10851. }
  10852. if (empty($classname)) {
  10853. $classname = ucfirst($subelement);
  10854. }
  10855. if (empty($classpath)) {
  10856. $classpath = $module.'/class';
  10857. }
  10858. //print 'getElementProperties subdir='.$subdir;
  10859. // Set dir_output
  10860. if ($module && isset($conf->$module)) { // The generic case
  10861. if (!empty($conf->$module->multidir_output[$conf->entity])) {
  10862. $dir_output = $conf->$module->multidir_output[$conf->entity];
  10863. } elseif (!empty($conf->$module->output[$conf->entity])) {
  10864. $dir_output = $conf->$module->output[$conf->entity];
  10865. } elseif (!empty($conf->$module->dir_output)) {
  10866. $dir_output = $conf->$module->dir_output;
  10867. }
  10868. }
  10869. // Overwrite value for special cases
  10870. if ($element == 'order_supplier') {
  10871. $dir_output = $conf->fournisseur->commande->dir_output;
  10872. } elseif ($element == 'invoice_supplier') {
  10873. $dir_output = $conf->fournisseur->facture->dir_output;
  10874. }
  10875. $dir_output .= $subdir;
  10876. $element_properties = array(
  10877. 'module' => $module,
  10878. 'element' => $element,
  10879. 'table_element' => $table_element,
  10880. 'subelement' => $subelement,
  10881. 'classpath' => $classpath,
  10882. 'classfile' => $classfile,
  10883. 'classname' => $classname,
  10884. 'dir_output' => $dir_output
  10885. );
  10886. return $element_properties;
  10887. }
  10888. /**
  10889. * Fetch an object from its id and element_type
  10890. * Inclusion of classes is automatic
  10891. *
  10892. * @param int $element_id Element id
  10893. * @param string $element_type Element type ('module' or 'myobject@mymodule' or 'mymodule_myobject')
  10894. * @param string $element_ref Element ref (Use this or element_id but not both)
  10895. * @return int|object object || 0 || <0 if error
  10896. * @see getElementProperties()
  10897. */
  10898. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  10899. {
  10900. global $db;
  10901. $ret = 0;
  10902. $element_prop = getElementProperties($element_type);
  10903. if (is_array($element_prop) && isModEnabled($element_prop['module'])) {
  10904. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  10905. if (class_exists($element_prop['classname'])) {
  10906. $classname = $element_prop['classname'];
  10907. $objecttmp = new $classname($db);
  10908. $ret = $objecttmp->fetch($element_id, $element_ref);
  10909. if ($ret >= 0) {
  10910. if (empty($objecttmp->module)) {
  10911. $objecttmp->module = $element_prop['module'];
  10912. }
  10913. return $objecttmp;
  10914. }
  10915. } else {
  10916. return -1;
  10917. }
  10918. }
  10919. return $ret;
  10920. }
  10921. /**
  10922. * Return if a file can contains executable content
  10923. *
  10924. * @param string $filename File name to test
  10925. * @return boolean True if yes, False if no
  10926. */
  10927. function isAFileWithExecutableContent($filename)
  10928. {
  10929. 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)) {
  10930. return true;
  10931. }
  10932. return false;
  10933. }
  10934. /**
  10935. * Return the value of token currently saved into session with name 'newtoken'.
  10936. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  10937. *
  10938. * @since Dolibarr v10.0.7
  10939. * @return string
  10940. */
  10941. function newToken()
  10942. {
  10943. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  10944. }
  10945. /**
  10946. * Return the value of token currently saved into session with name 'token'.
  10947. * For ajax call, you must use this token as a parameter of the call into the js calling script (the called ajax php page must also set constant NOTOKENRENEWAL).
  10948. *
  10949. * @since Dolibarr v10.0.7
  10950. * @return string
  10951. */
  10952. function currentToken()
  10953. {
  10954. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  10955. }
  10956. /**
  10957. * Return a random string to be used as a nonce value for js
  10958. *
  10959. * @return string
  10960. */
  10961. function getNonce()
  10962. {
  10963. global $conf;
  10964. if (empty($conf->cache['nonce'])) {
  10965. $conf->cache['nonce'] = dolGetRandomBytes(8);
  10966. }
  10967. return $conf->cache['nonce'];
  10968. }
  10969. /**
  10970. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  10971. *
  10972. * @param string $header The first left header of the table (automatic translated)
  10973. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  10974. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  10975. * @param integer $emptyRows (optional) The count of empty rows after the first header
  10976. * @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"
  10977. * @return void
  10978. *
  10979. * @see finishSimpleTable()
  10980. */
  10981. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  10982. {
  10983. global $langs;
  10984. print '<div class="div-table-responsive-no-min">';
  10985. print '<table class="noborder centpercent">';
  10986. print '<tr class="liste_titre">';
  10987. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  10988. print $langs->trans($header);
  10989. // extra space between the first header and the number
  10990. if ($number > -1) {
  10991. print ' ';
  10992. }
  10993. if (!empty($link)) {
  10994. if (!empty($arguments)) {
  10995. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10996. } else {
  10997. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  10998. }
  10999. }
  11000. if ($number > -1) {
  11001. print '<span class="badge">'.$number.'</span>';
  11002. }
  11003. if (!empty($link)) {
  11004. print '</a>';
  11005. }
  11006. print '</th>';
  11007. if ($number < 0 && !empty($link)) {
  11008. print '<th class="right">';
  11009. if (!empty($arguments)) {
  11010. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  11011. } else {
  11012. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  11013. }
  11014. print $langs->trans("FullList");
  11015. print '</a>';
  11016. print '</th>';
  11017. }
  11018. print '</tr>';
  11019. }
  11020. /**
  11021. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  11022. *
  11023. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  11024. * @return void
  11025. *
  11026. * @see startSimpleTable()
  11027. */
  11028. function finishSimpleTable($addLineBreak = false)
  11029. {
  11030. print '</table>';
  11031. print '</div>';
  11032. if ($addLineBreak) {
  11033. print '<br>';
  11034. }
  11035. }
  11036. /**
  11037. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  11038. *
  11039. * @param integer $tableColumnCount The complete count columns of the table
  11040. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  11041. * @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)
  11042. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  11043. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  11044. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  11045. * @return void
  11046. */
  11047. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  11048. {
  11049. global $langs;
  11050. if ($num === 0) {
  11051. print '<tr class="oddeven">';
  11052. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  11053. print '</tr>';
  11054. return;
  11055. }
  11056. if ($nbofloop === 0) {
  11057. // don't show a summary line
  11058. return;
  11059. }
  11060. if ($num === 0) {
  11061. $colspan = $tableColumnCount;
  11062. } elseif ($num > $nbofloop) {
  11063. $colspan = $tableColumnCount;
  11064. } else {
  11065. $colspan = $tableColumnCount - 1;
  11066. }
  11067. if ($extraRightColumn) {
  11068. $colspan--;
  11069. }
  11070. print '<tr class="liste_total">';
  11071. if ($nbofloop > 0 && $num > $nbofloop) {
  11072. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  11073. } else {
  11074. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  11075. print '<td class="right" width="100">'.price($total).'</td>';
  11076. }
  11077. if ($extraRightColumn) {
  11078. print '<td></td>';
  11079. }
  11080. print '</tr>';
  11081. }
  11082. /**
  11083. * Return a file on output using a low memory. It can return very large files with no need of memory.
  11084. * WARNING: This close output buffers.
  11085. *
  11086. * @param string $fullpath_original_file_osencoded Full path of file to return.
  11087. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  11088. * @return void
  11089. */
  11090. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  11091. {
  11092. global $conf;
  11093. if ($method == -1) {
  11094. $method = 0;
  11095. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  11096. $method = 1;
  11097. }
  11098. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  11099. $method = 2;
  11100. }
  11101. }
  11102. // Be sure we don't have output buffering enabled to have readfile working correctly
  11103. while (ob_get_level()) {
  11104. ob_end_flush();
  11105. }
  11106. // Solution 0
  11107. if ($method == 0) {
  11108. readfile($fullpath_original_file_osencoded);
  11109. } elseif ($method == 1) {
  11110. // Solution 1
  11111. $handle = fopen($fullpath_original_file_osencoded, "rb");
  11112. while (!feof($handle)) {
  11113. print fread($handle, 8192);
  11114. }
  11115. fclose($handle);
  11116. } elseif ($method == 2) {
  11117. // Solution 2
  11118. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  11119. $handle2 = fopen("php://output", "wb");
  11120. stream_copy_to_stream($handle1, $handle2);
  11121. fclose($handle1);
  11122. fclose($handle2);
  11123. }
  11124. }
  11125. /**
  11126. * Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
  11127. * Code that handle the click is inside core/js/lib_foot.js.php.
  11128. *
  11129. * @param string $valuetocopy The value to print
  11130. * @param int $showonlyonhover Show the copy-paste button only on hover
  11131. * @param string $texttoshow Replace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
  11132. * @return string The string to print for the button
  11133. */
  11134. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  11135. {
  11136. /*
  11137. global $conf;
  11138. if (!empty($conf->dol_no_mouse_hover)) {
  11139. $showonlyonhover = 0;
  11140. }*/
  11141. $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
  11142. if ($texttoshow === 'none') {
  11143. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint"></span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  11144. } elseif ($texttoshow) {
  11145. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint">'.dol_escape_htmltag($texttoshow, 1, 1).'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  11146. } else {
  11147. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  11148. }
  11149. return $result;
  11150. }
  11151. /**
  11152. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  11153. *
  11154. * @param string $stringtodecode String to decode (json or serialize coded)
  11155. * @return mixed The decoded object.
  11156. */
  11157. function jsonOrUnserialize($stringtodecode)
  11158. {
  11159. $result = json_decode($stringtodecode);
  11160. if ($result === null) {
  11161. $result = unserialize($stringtodecode);
  11162. }
  11163. return $result;
  11164. }
  11165. /**
  11166. * forgeSQLFromUniversalSearchCriteria
  11167. *
  11168. * @param string $filter String with universal search string. Must be '(aaa:bbb:...) OR (ccc:ddd:...) ...' with
  11169. * aaa is a field name (with alias or not) and
  11170. * bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'.
  11171. * Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
  11172. * @param string $errorstr Error message string
  11173. * @param int $noand 1=Do not add the AND before the condition string.
  11174. * @param int $nopar 1=Do not add the perenthesis around the condition string.
  11175. * @param int $noerror 1=If search criteria is not valid, does not return an error string but invalidate the SQL
  11176. * @return string Return forged SQL string
  11177. */
  11178. function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0)
  11179. {
  11180. if (!preg_match('/^\(.*\)$/', $filter)) { // If $filter does not start and end with ()
  11181. $filter = '(' . $filter . ')';
  11182. }
  11183. $regexstring = '\(([a-zA-Z0-9_\.]+:[<>!=insotlke]+:[^\(\)]+)\)'; // Must be (aaa:bbb:...) with aaa is a field name (with alias or not) and bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'
  11184. if (!dolCheckFilters($filter, $errorstr)) {
  11185. if ($noerror) {
  11186. return '1 = 2';
  11187. } else {
  11188. return 'Filter syntax error - '.$errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
  11189. }
  11190. }
  11191. // Test the filter syntax
  11192. $t = preg_replace_callback('/'.$regexstring.'/i', 'dolForgeDummyCriteriaCallback', $filter);
  11193. $t = str_replace(array('and','or','AND','OR',' '), '', $t); // Remove the only strings allowed between each () criteria
  11194. // If the string result contains something else than '()', the syntax was wrong
  11195. if (preg_match('/[^\(\)]/', $t)) {
  11196. $errorstr = 'Bad syntax of the search string';
  11197. if ($noerror) {
  11198. return '1 = 2';
  11199. } else {
  11200. return 'Filter syntax error - '.$errorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
  11201. }
  11202. }
  11203. return ($noand ? "" : " AND ").($nopar ? "" : '(').preg_replace_callback('/'.$regexstring.'/i', 'dolForgeCriteriaCallback', $filter).($nopar ? "" : ')');
  11204. }
  11205. /**
  11206. * Return if a $sqlfilters parameter has a valid balance of parenthesis
  11207. *
  11208. * @param string $sqlfilters sqlfilter string
  11209. * @param string $error Error message
  11210. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  11211. */
  11212. function dolCheckFilters($sqlfilters, &$error = '')
  11213. {
  11214. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  11215. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  11216. $tmp = $sqlfilters;
  11217. $i = 0; $nb = strlen($tmp);
  11218. $counter = 0;
  11219. while ($i < $nb) {
  11220. if ($tmp[$i] == '(') {
  11221. $counter++;
  11222. }
  11223. if ($tmp[$i] == ')') {
  11224. $counter--;
  11225. }
  11226. if ($counter < 0) {
  11227. $error = "Wrond balance of parenthesis in sqlfilters=".$sqlfilters;
  11228. dol_syslog($error, LOG_WARNING);
  11229. return false;
  11230. }
  11231. $i++;
  11232. }
  11233. return true;
  11234. }
  11235. /**
  11236. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  11237. * This method is called by forgeSQLFromUniversalSearchCriteria()
  11238. *
  11239. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  11240. * @return string Forged criteria. Example: "" or "()"
  11241. */
  11242. function dolForgeDummyCriteriaCallback($matches)
  11243. {
  11244. //dol_syslog("Convert matches ".$matches[1]);
  11245. if (empty($matches[1])) {
  11246. return '';
  11247. }
  11248. $tmp = explode(':', $matches[1]);
  11249. if (count($tmp) < 3) {
  11250. return '';
  11251. }
  11252. return '()'; // An empty criteria
  11253. }
  11254. /**
  11255. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  11256. * This method is called by forgeSQLFromUniversalSearchCriteria()
  11257. *
  11258. * @param array $matches Array of found string by regex search.
  11259. * Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL"
  11260. * @return string Forged criteria. Example: "t.field LIKE 'abc%'"
  11261. */
  11262. function dolForgeCriteriaCallback($matches)
  11263. {
  11264. global $db;
  11265. //dol_syslog("Convert matches ".$matches[1]);
  11266. if (empty($matches[1])) {
  11267. return '';
  11268. }
  11269. $tmp = explode(':', $matches[1]);
  11270. if (count($tmp) < 3) {
  11271. return '';
  11272. }
  11273. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  11274. $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
  11275. if ($operator == 'NOTLIKE') {
  11276. $operator = 'NOT LIKE';
  11277. }
  11278. if ($operator == 'ISNOT') {
  11279. $operator = 'IS NOT';
  11280. }
  11281. if ($operator == '!=') {
  11282. $operator = '<>';
  11283. }
  11284. $tmpescaped = $tmp[2];
  11285. $regbis = array();
  11286. if ($operator == 'IN') { // IN is allowed for list of ID or code only
  11287. //if (!preg_match('/^\(.*\)$/', $tmpescaped)) {
  11288. $tmpescaped = '('.$db->escape($db->sanitize($tmpescaped, 1, 0)).')';
  11289. //} else {
  11290. // $tmpescaped = $db->escape($db->sanitize($tmpescaped, 1));
  11291. //}
  11292. } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
  11293. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  11294. $tmpescaped = $regbis[1];
  11295. }
  11296. //$tmpescaped = "'".$db->escapeforlike($db->escape($regbis[1]))."'";
  11297. $tmpescaped = "'".$db->escape($tmpescaped)."'"; // We do not escape the _ and % so the like will works
  11298. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  11299. $tmpescaped = "'".$db->escape($regbis[1])."'";
  11300. } else {
  11301. if (strtoupper($tmpescaped) == 'NULL') {
  11302. $tmpescaped = 'NULL';
  11303. } elseif (is_int($tmpescaped)) {
  11304. $tmpescaped = (int) $tmpescaped;
  11305. } else {
  11306. $tmpescaped = (float) $tmpescaped;
  11307. }
  11308. }
  11309. return '('.$db->escape($operand).' '.strtoupper($operator).' '.$tmpescaped.')';
  11310. }
  11311. /**
  11312. * Get timeline icon
  11313. *
  11314. * @param ActionComm $actionstatic actioncomm
  11315. * @param array $histo histo
  11316. * @param int $key key
  11317. * @return string String with timeline icon
  11318. * @deprecated Use actioncomm->getPictoType() instead
  11319. */
  11320. function getTimelineIcon($actionstatic, &$histo, $key)
  11321. {
  11322. global $conf, $langs;
  11323. $out = '<!-- timeline icon -->'."\n";
  11324. $iconClass = 'fa fa-comments';
  11325. $img_picto = '';
  11326. $colorClass = '';
  11327. $pictoTitle = '';
  11328. if ($histo[$key]['percent'] == -1) {
  11329. $colorClass = 'timeline-icon-not-applicble';
  11330. $pictoTitle = $langs->trans('StatusNotApplicable');
  11331. } elseif ($histo[$key]['percent'] == 0) {
  11332. $colorClass = 'timeline-icon-todo';
  11333. $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
  11334. } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
  11335. $colorClass = 'timeline-icon-in-progress';
  11336. $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
  11337. } elseif ($histo[$key]['percent'] >= 100) {
  11338. $colorClass = 'timeline-icon-done';
  11339. $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
  11340. }
  11341. if ($actionstatic->code == 'AC_TICKET_CREATE') {
  11342. $iconClass = 'fa fa-ticket';
  11343. } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
  11344. $iconClass = 'fa fa-pencilxxx';
  11345. } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11346. $iconClass = 'fa fa-comments';
  11347. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  11348. $iconClass = 'fa fa-mask';
  11349. } elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  11350. if ($actionstatic->type_picto) {
  11351. $img_picto = img_picto('', $actionstatic->type_picto);
  11352. } else {
  11353. if ($actionstatic->type_code == 'AC_RDV') {
  11354. $iconClass = 'fa fa-handshake';
  11355. } elseif ($actionstatic->type_code == 'AC_TEL') {
  11356. $iconClass = 'fa fa-phone';
  11357. } elseif ($actionstatic->type_code == 'AC_FAX') {
  11358. $iconClass = 'fa fa-fax';
  11359. } elseif ($actionstatic->type_code == 'AC_EMAIL') {
  11360. $iconClass = 'fa fa-envelope';
  11361. } elseif ($actionstatic->type_code == 'AC_INT') {
  11362. $iconClass = 'fa fa-shipping-fast';
  11363. } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
  11364. $iconClass = 'fa fa-robot';
  11365. } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
  11366. $iconClass = 'fa fa-robot';
  11367. }
  11368. }
  11369. }
  11370. $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
  11371. return $out;
  11372. }
  11373. /**
  11374. * getActionCommEcmList
  11375. *
  11376. * @param ActionComm $object Object ActionComm
  11377. * @return array Array of documents in index table
  11378. */
  11379. function getActionCommEcmList($object)
  11380. {
  11381. global $conf, $db;
  11382. $documents = array();
  11383. $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename';
  11384. $sql .= ' FROM '.MAIN_DB_PREFIX.'ecm_files ecm';
  11385. $sql .= " WHERE ecm.filepath = 'agenda/".((int) $object->id)."'";
  11386. //$sql.= " ecm.src_object_type = '".$db->escape($object->element)."' AND ecm.src_object_id = ".((int) $object->id); // Old version didn't add object_type during upload
  11387. $sql .= ' ORDER BY ecm.position ASC';
  11388. $resql = $db->query($sql);
  11389. if ($resql) {
  11390. if ($db->num_rows($resql)) {
  11391. while ($obj = $db->fetch_object($resql)) {
  11392. $documents[$obj->id] = $obj;
  11393. }
  11394. }
  11395. }
  11396. return $documents;
  11397. }
  11398. /**
  11399. * Show html area with actions in messaging format.
  11400. * Note: Global parameter $param must be defined.
  11401. *
  11402. * @param Conf $conf Object conf
  11403. * @param Translate $langs Object langs
  11404. * @param DoliDB $db Object db
  11405. * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object
  11406. * @param Contact $objcon Filter on object contact to filter events on a contact
  11407. * @param int $noprint Return string but does not output it
  11408. * @param string $actioncode Filter on actioncode
  11409. * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all).
  11410. * @param array $filters Filter on other fields
  11411. * @param string $sortfield Sort field
  11412. * @param string $sortorder Sort order
  11413. * @return string|void Return html part or void if noprint is 1
  11414. */
  11415. function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
  11416. {
  11417. global $user, $conf;
  11418. global $form;
  11419. global $param, $massactionbutton;
  11420. dol_include_once('/comm/action/class/actioncomm.class.php');
  11421. // Check parameters
  11422. if (!is_object($filterobj) && !is_object($objcon)) {
  11423. dol_print_error('', 'BadParameter');
  11424. }
  11425. $histo = array();
  11426. $numaction = 0;
  11427. $now = dol_now();
  11428. $sortfield_list = explode(',', $sortfield);
  11429. $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
  11430. $sortfield_new_list = array();
  11431. foreach ($sortfield_list as $sortfield_value) {
  11432. $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
  11433. }
  11434. $sortfield_new = implode(',', $sortfield_new_list);
  11435. if (isModEnabled('agenda')) {
  11436. // Search histo on actioncomm
  11437. if (is_object($objcon) && $objcon->id > 0) {
  11438. $sql = "SELECT DISTINCT a.id, a.label as label,";
  11439. } else {
  11440. $sql = "SELECT a.id, a.label as label,";
  11441. }
  11442. $sql .= " a.datep as dp,";
  11443. $sql .= " a.note as message,";
  11444. $sql .= " a.datep2 as dp2,";
  11445. $sql .= " a.percent as percent, 'action' as type,";
  11446. $sql .= " a.fk_element, a.elementtype,";
  11447. $sql .= " a.fk_contact,";
  11448. $sql .= " a.email_from as msg_from,";
  11449. $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
  11450. $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
  11451. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11452. $sql .= ", sp.lastname, sp.firstname";
  11453. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11454. $sql .= ", m.lastname, m.firstname";
  11455. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11456. $sql .= ", o.ref";
  11457. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11458. $sql .= ", o.ref";
  11459. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11460. $sql .= ", o.ref";
  11461. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11462. $sql .= ", o.ref";
  11463. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11464. $sql .= ", o.ref";
  11465. }
  11466. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  11467. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
  11468. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
  11469. $force_filter_contact = false;
  11470. if (is_object($objcon) && $objcon->id > 0) {
  11471. $force_filter_contact = true;
  11472. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
  11473. $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
  11474. }
  11475. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11476. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
  11477. } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
  11478. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
  11479. $sql .= " ON er.resource_type = 'dolresource'";
  11480. $sql .= " AND er.element_id = a.id";
  11481. $sql .= " AND er.resource_id = ".((int) $filterobj->id);
  11482. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11483. $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
  11484. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11485. $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
  11486. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11487. $sql .= ", ".MAIN_DB_PREFIX."product as o";
  11488. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11489. $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
  11490. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11491. $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
  11492. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11493. $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
  11494. }
  11495. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  11496. if ($force_filter_contact === false) {
  11497. if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
  11498. $sql .= " AND a.fk_soc = ".((int) $filterobj->id);
  11499. } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
  11500. $sql .= " AND a.fk_project = ".((int) $filterobj->id);
  11501. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11502. $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
  11503. if ($filterobj->id) {
  11504. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11505. }
  11506. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11507. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
  11508. if ($filterobj->id) {
  11509. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11510. }
  11511. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11512. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
  11513. if ($filterobj->id) {
  11514. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11515. }
  11516. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11517. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
  11518. if ($filterobj->id) {
  11519. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11520. }
  11521. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11522. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
  11523. if ($filterobj->id) {
  11524. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11525. }
  11526. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11527. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
  11528. if ($filterobj->id) {
  11529. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11530. }
  11531. }
  11532. }
  11533. // Condition on actioncode
  11534. if (!empty($actioncode)) {
  11535. if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  11536. if ($actioncode == 'AC_NON_AUTO') {
  11537. $sql .= " AND c.type != 'systemauto'";
  11538. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11539. $sql .= " AND c.type = 'systemauto'";
  11540. } else {
  11541. if ($actioncode == 'AC_OTH') {
  11542. $sql .= " AND c.type != 'systemauto'";
  11543. } elseif ($actioncode == 'AC_OTH_AUTO') {
  11544. $sql .= " AND c.type = 'systemauto'";
  11545. }
  11546. }
  11547. } else {
  11548. if ($actioncode == 'AC_NON_AUTO') {
  11549. $sql .= " AND c.type != 'systemauto'";
  11550. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11551. $sql .= " AND c.type = 'systemauto'";
  11552. } else {
  11553. $sql .= " AND c.code = '".$db->escape($actioncode)."'";
  11554. }
  11555. }
  11556. }
  11557. if ($donetodo == 'todo') {
  11558. $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11559. } elseif ($donetodo == 'done') {
  11560. $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11561. }
  11562. if (is_array($filters) && $filters['search_agenda_label']) {
  11563. $sql .= natural_search('a.label', $filters['search_agenda_label']);
  11564. }
  11565. }
  11566. // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
  11567. if (isModEnabled('mailing') && !empty($objcon->email)
  11568. && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
  11569. $langs->load("mails");
  11570. $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type";
  11571. $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
  11572. $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
  11573. $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
  11574. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11575. $sql2 .= ", '' as lastname, '' as firstname";
  11576. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11577. $sql2 .= ", '' as lastname, '' as firstname";
  11578. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11579. $sql2 .= ", '' as ref";
  11580. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11581. $sql2 .= ", '' as ref";
  11582. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11583. $sql2 .= ", '' as ref";
  11584. }
  11585. $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
  11586. $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
  11587. $sql2 .= " AND mc.statut = 1";
  11588. $sql2 .= " AND u.rowid = m.fk_user_valid";
  11589. $sql2 .= " AND mc.fk_mailing=m.rowid";
  11590. }
  11591. if (!empty($sql) && !empty($sql2)) {
  11592. $sql = $sql." UNION ".$sql2;
  11593. } elseif (empty($sql) && !empty($sql2)) {
  11594. $sql = $sql2;
  11595. }
  11596. // TODO Add limit in nb of results
  11597. if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too
  11598. $sql .= $db->order($sortfield_new, $sortorder);
  11599. dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
  11600. $resql = $db->query($sql);
  11601. if ($resql) {
  11602. $i = 0;
  11603. $num = $db->num_rows($resql);
  11604. while ($i < $num) {
  11605. $obj = $db->fetch_object($resql);
  11606. if ($obj->type == 'action') {
  11607. $contactaction = new ActionComm($db);
  11608. $contactaction->id = $obj->id;
  11609. $result = $contactaction->fetchResources();
  11610. if ($result < 0) {
  11611. dol_print_error($db);
  11612. setEventMessage("actions.lib::show_actions_messaging Error fetch ressource", 'errors');
  11613. }
  11614. //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11615. //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11616. $tododone = '';
  11617. if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
  11618. $tododone = 'todo';
  11619. }
  11620. $histo[$numaction] = array(
  11621. 'type'=>$obj->type,
  11622. 'tododone'=>$tododone,
  11623. 'id'=>$obj->id,
  11624. 'datestart'=>$db->jdate($obj->dp),
  11625. 'dateend'=>$db->jdate($obj->dp2),
  11626. 'note'=>$obj->label,
  11627. 'message'=>$obj->message,
  11628. 'percent'=>$obj->percent,
  11629. 'userid'=>$obj->user_id,
  11630. 'login'=>$obj->user_login,
  11631. 'userfirstname'=>$obj->user_firstname,
  11632. 'userlastname'=>$obj->user_lastname,
  11633. 'userphoto'=>$obj->user_photo,
  11634. 'msg_from'=>$obj->msg_from,
  11635. 'contact_id'=>$obj->fk_contact,
  11636. 'socpeopleassigned' => $contactaction->socpeopleassigned,
  11637. 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
  11638. 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
  11639. 'fk_element'=>$obj->fk_element,
  11640. 'elementtype'=>$obj->elementtype,
  11641. // Type of event
  11642. 'acode'=>$obj->acode,
  11643. 'alabel'=>$obj->alabel,
  11644. 'libelle'=>$obj->alabel, // deprecated
  11645. 'apicto'=>$obj->apicto
  11646. );
  11647. } else {
  11648. $histo[$numaction] = array(
  11649. 'type'=>$obj->type,
  11650. 'tododone'=>'done',
  11651. 'id'=>$obj->id,
  11652. 'datestart'=>$db->jdate($obj->dp),
  11653. 'dateend'=>$db->jdate($obj->dp2),
  11654. 'note'=>$obj->label,
  11655. 'message'=>$obj->message,
  11656. 'percent'=>$obj->percent,
  11657. 'acode'=>$obj->acode,
  11658. 'userid'=>$obj->user_id,
  11659. 'login'=>$obj->user_login,
  11660. 'userfirstname'=>$obj->user_firstname,
  11661. 'userlastname'=>$obj->user_lastname,
  11662. 'userphoto'=>$obj->user_photo
  11663. );
  11664. }
  11665. $numaction++;
  11666. $i++;
  11667. }
  11668. } else {
  11669. dol_print_error($db);
  11670. }
  11671. }
  11672. // Set $out to show events
  11673. $out = '';
  11674. if (!isModEnabled('agenda')) {
  11675. $langs->loadLangs(array("admin", "errors"));
  11676. $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
  11677. }
  11678. if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
  11679. $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
  11680. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  11681. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  11682. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  11683. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  11684. $formactions = new FormActions($db);
  11685. $actionstatic = new ActionComm($db);
  11686. $userstatic = new User($db);
  11687. $contactstatic = new Contact($db);
  11688. $userGetNomUrlCache = array();
  11689. $contactGetNomUrlCache = array();
  11690. $out .= '<div class="filters-container" >';
  11691. $out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  11692. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  11693. if ($objcon && get_class($objcon) == 'Contact' &&
  11694. (is_null($filterobj) || get_class($filterobj) == 'Societe')) {
  11695. $out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
  11696. } else {
  11697. $out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
  11698. }
  11699. if ($filterobj && get_class($filterobj) == 'Societe') {
  11700. $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
  11701. }
  11702. $out .= "\n";
  11703. $out .= '<div class="div-table-responsive-no-min">';
  11704. $out .= '<table class="noborder borderbottom centpercent">';
  11705. $out .= '<tr class="liste_titre">';
  11706. // Action column
  11707. if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  11708. $out .= '<th class="liste_titre width50 middle">';
  11709. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11710. $out .= $searchpicto;
  11711. $out .= '</th>';
  11712. }
  11713. $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n";
  11714. $out .= '<th class="liste_titre"><strong class="hideonsmartphone">'.$langs->trans("Search").' : </strong></th>';
  11715. if ($donetodo) {
  11716. $out .= '<th class="liste_titre"></th>';
  11717. }
  11718. $out .= '<th class="liste_titre">';
  11719. $out .= '<span class="fas fa-square inline-block fawidth30" style=" color: #ddd;" title="'.$langs->trans("ActionType").'"></span>';
  11720. //$out .= img_picto($langs->trans("Type"), 'type');
  11721. $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1, 'minwidth200imp');
  11722. $out .= '</th>';
  11723. $out .= '<th class="liste_titre maxwidth100onsmartphone">';
  11724. $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'" placeholder="'.$langs->trans("Label").'">';
  11725. $out .= '</th>';
  11726. // Action column
  11727. if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  11728. $out .= '<th class="liste_titre width50 middle">';
  11729. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11730. $out .= $searchpicto;
  11731. $out .= '</th>';
  11732. }
  11733. $out .= '</tr>';
  11734. $out .= '</table>';
  11735. $out .= '</form>';
  11736. $out .= '</div>';
  11737. $out .= "\n";
  11738. $out .= '<ul class="timeline">';
  11739. if ($donetodo) {
  11740. $tmp = '';
  11741. if (get_class($filterobj) == 'Societe') {
  11742. $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
  11743. }
  11744. $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
  11745. $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
  11746. $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
  11747. //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
  11748. if (get_class($filterobj) == 'Societe') {
  11749. $tmp .= '</a>';
  11750. }
  11751. $out .= getTitleFieldOfList($tmp);
  11752. }
  11753. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
  11754. $caction = new CActionComm($db);
  11755. $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1);
  11756. $actualCycleDate = false;
  11757. // Loop on each event to show it
  11758. foreach ($histo as $key => $value) {
  11759. $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
  11760. $actionstatic->type_picto = $histo[$key]['apicto'];
  11761. $actionstatic->type_code = $histo[$key]['acode'];
  11762. $labeltype = $actionstatic->type_code;
  11763. if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) {
  11764. $labeltype = 'AC_OTH';
  11765. }
  11766. if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11767. $labeltype = $langs->trans("Message");
  11768. } else {
  11769. if (!empty($arraylist[$labeltype])) {
  11770. $labeltype = $arraylist[$labeltype];
  11771. }
  11772. if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) {
  11773. $labeltype .= ' - '.$arraylist[$actionstatic->code]; // Use code in priority on type_code
  11774. }
  11775. }
  11776. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
  11777. $tmpa = dol_getdate($histo[$key]['datestart'], false);
  11778. if (isset($tmpa['year']) && isset($tmpa['yday']) && $actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
  11779. $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
  11780. $out .= '<!-- timeline time label -->';
  11781. $out .= '<li class="time-label">';
  11782. $out .= '<span class="timeline-badge-date">';
  11783. $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
  11784. $out .= '</span>';
  11785. $out .= '</li>';
  11786. $out .= '<!-- /.timeline-label -->';
  11787. }
  11788. $out .= '<!-- timeline item -->'."\n";
  11789. $out .= '<li class="timeline-code-'.strtolower($actionstatic->code).'">';
  11790. //$timelineicon = getTimelineIcon($actionstatic, $histo, $key);
  11791. $typeicon = $actionstatic->getTypePicto('pictofixedwidth timeline-icon-not-applicble', $labeltype);
  11792. //$out .= $timelineicon;
  11793. //var_dump($timelineicon);
  11794. $out .= $typeicon;
  11795. $out .= '<div class="timeline-item">'."\n";
  11796. $out .= '<span class="time timeline-header-action2">';
  11797. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
  11798. $out .= '<a class="paddingleft paddingright timeline-btn2 editfielda" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11799. $out .= $histo[$key]['id'];
  11800. $out .= '</a> ';
  11801. } else {
  11802. $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle').' ';
  11803. }
  11804. if ($user->hasRight('agenda', 'allactions', 'create') ||
  11805. (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
  11806. $out .= '<a class="paddingleft paddingright timeline-btn2 editfielda" href="'.DOL_MAIN_URL_ROOT.'/comm/action/card.php?action=edit&token='.newToken().'&id='.$actionstatic->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?'.$param).'">';
  11807. //$out .= '<i class="fa fa-pencil" title="'.$langs->trans("Modify").'" ></i>';
  11808. $out .= img_picto($langs->trans("Modify"), 'edit', 'class="edita"');
  11809. $out .= '</a>';
  11810. }
  11811. $out .= '</span>';
  11812. // Date
  11813. $out .= '<span class="time"><i class="fa fa-clock-o valignmiddle"></i> <span class="valignmiddle">';
  11814. $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
  11815. if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
  11816. $tmpa = dol_getdate($histo[$key]['datestart'], true);
  11817. $tmpb = dol_getdate($histo[$key]['dateend'], true);
  11818. if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
  11819. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
  11820. } else {
  11821. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
  11822. }
  11823. }
  11824. $late = 0;
  11825. if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11826. $late = 1;
  11827. }
  11828. if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11829. $late = 1;
  11830. }
  11831. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
  11832. $late = 1;
  11833. }
  11834. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11835. $late = 1;
  11836. }
  11837. if ($late) {
  11838. $out .= img_warning($langs->trans("Late")).' ';
  11839. }
  11840. $out .= "</span></span>\n";
  11841. // Ref
  11842. $out .= '<h3 class="timeline-header">';
  11843. // Author of event
  11844. $out .= '<div class="messaging-author inline-block tdoverflowmax150 valignmiddle marginrightonly">';
  11845. if ($histo[$key]['userid'] > 0) {
  11846. if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
  11847. $userstatic->fetch($histo[$key]['userid']);
  11848. $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
  11849. }
  11850. $out .= $userGetNomUrlCache[$histo[$key]['userid']];
  11851. } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
  11852. if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
  11853. if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
  11854. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
  11855. } else {
  11856. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
  11857. }
  11858. }
  11859. $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
  11860. }
  11861. $out .= '</div>';
  11862. // Title
  11863. $out .= ' <div class="messaging-title inline-block">';
  11864. //$out .= $actionstatic->getTypePicto();
  11865. if (empty($conf->dol_optimize_smallscreen) && $actionstatic->type_code != 'AC_OTH_AUTO') {
  11866. $out .= $labeltype.' - ';
  11867. }
  11868. $libelle = '';
  11869. if (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11870. $out .= $langs->trans('TicketNewMessage');
  11871. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  11872. $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
  11873. } elseif (isset($histo[$key]['type'])) {
  11874. if ($histo[$key]['type'] == 'action') {
  11875. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11876. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
  11877. $libelle = $histo[$key]['note'];
  11878. $actionstatic->id = $histo[$key]['id'];
  11879. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11880. } elseif ($histo[$key]['type'] == 'mailing') {
  11881. $out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11882. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11883. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
  11884. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11885. } else {
  11886. $libelle .= $histo[$key]['note'];
  11887. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11888. }
  11889. }
  11890. if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) {
  11891. if (isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']]) && isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']])) {
  11892. $link = $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']];
  11893. } else {
  11894. if (!isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']])) {
  11895. $conf->cache['elementlinkcache'][$histo[$key]['elementtype']] = array();
  11896. }
  11897. $link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1);
  11898. $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link;
  11899. }
  11900. if ($link) {
  11901. $out .= ' - '.$link;
  11902. }
  11903. }
  11904. $out .= '</div>';
  11905. $out .= '</h3>';
  11906. // Message
  11907. if (!empty($histo[$key]['message'] && $histo[$key]['message'] != $libelle)
  11908. && $actionstatic->code != 'AC_TICKET_CREATE'
  11909. && $actionstatic->code != 'AC_TICKET_MODIFY'
  11910. ) {
  11911. $out .= '<div class="timeline-body classfortooltip" title="'.dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($histo[$key]['message']), 1, 1, 1)), 1, 1).'">';
  11912. $out .= dolGetFirstLineOfText($histo[$key]['message'], 3);
  11913. $out .= '</div>';
  11914. }
  11915. // Timeline footer
  11916. $footer = '';
  11917. // Contact for this action
  11918. if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
  11919. $contactList = '';
  11920. foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
  11921. if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
  11922. $contact = new Contact($db);
  11923. $contact->fetch($cid);
  11924. $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
  11925. } else {
  11926. $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
  11927. }
  11928. if ($contact) {
  11929. $contactList .= !empty($contactList) ? ', ' : '';
  11930. $contactList .= $contact->getNomUrl(1);
  11931. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11932. if (!empty($contact->phone_pro)) {
  11933. $contactList .= '('.dol_print_phone($contact->phone_pro).')';
  11934. }
  11935. }
  11936. }
  11937. }
  11938. $footer .= $langs->trans('ActionOnContact').' : '.$contactList;
  11939. } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
  11940. if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
  11941. $contact = new Contact($db);
  11942. $result = $contact->fetch($histo[$key]['contact_id']);
  11943. $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
  11944. } else {
  11945. $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
  11946. }
  11947. if ($result > 0) {
  11948. $footer .= $contact->getNomUrl(1);
  11949. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11950. if (!empty($contact->phone_pro)) {
  11951. $footer .= '('.dol_print_phone($contact->phone_pro).')';
  11952. }
  11953. }
  11954. }
  11955. }
  11956. $documents = getActionCommEcmList($actionstatic);
  11957. if (!empty($documents)) {
  11958. $footer .= '<div class="timeline-documents-container">';
  11959. foreach ($documents as $doc) {
  11960. $footer .= '<span id="document_'.$doc->id.'" class="timeline-documents" ';
  11961. $footer .= ' data-id="'.$doc->id.'" ';
  11962. $footer .= ' data-path="'.$doc->filepath.'"';
  11963. $footer .= ' data-filename="'.dol_escape_htmltag($doc->filename).'" ';
  11964. $footer .= '>';
  11965. $filePath = DOL_DATA_ROOT.'/'.$doc->filepath.'/'.$doc->filename;
  11966. $mime = dol_mimetype($filePath);
  11967. $file = $actionstatic->id.'/'.$doc->filename;
  11968. $thumb = $actionstatic->id.'/thumbs/'.substr($doc->filename, 0, strrpos($doc->filename, '.')).'_mini'.substr($doc->filename, strrpos($doc->filename, '.'));
  11969. $doclink = dol_buildpath('document.php', 1).'?modulepart=actions&attachment=0&file='.urlencode($file).'&entity='.$conf->entity;
  11970. $viewlink = dol_buildpath('viewimage.php', 1).'?modulepart=actions&file='.urlencode($thumb).'&entity='.$conf->entity;
  11971. $mimeAttr = ' mime="'.$mime.'" ';
  11972. $class = '';
  11973. if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
  11974. $class .= ' documentpreview';
  11975. }
  11976. $footer .= '<a href="'.$doclink.'" class="btn-link '.$class.'" target="_blank" rel="noopener noreferrer" '.$mimeAttr.' >';
  11977. $footer .= img_mime($filePath).' '.$doc->filename;
  11978. $footer .= '</a>';
  11979. $footer .= '</span>';
  11980. }
  11981. $footer .= '</div>';
  11982. }
  11983. if (!empty($footer)) {
  11984. $out .= '<div class="timeline-footer">'.$footer.'</div>';
  11985. }
  11986. $out .= '</div>'."\n"; // end timeline-item
  11987. $out .= '</li>';
  11988. $out .= '<!-- END timeline item -->';
  11989. $i++;
  11990. }
  11991. $out .= "</ul>\n";
  11992. if (empty($histo)) {
  11993. $out .= '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
  11994. }
  11995. }
  11996. if ($noprint) {
  11997. return $out;
  11998. } else {
  11999. print $out;
  12000. }
  12001. }
  12002. /**
  12003. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  12004. * optionally hour, minute, second) fields to return a timestamp.
  12005. *
  12006. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  12007. * @param string $hourTime 'getpost' to include hour, minute, second values from the HTTP request, 'XX:YY:ZZ' to set
  12008. * hour, minute, second respectively (for instance '23:59:59')
  12009. * @param string $gm Passed to dol_mktime
  12010. * @return int|string Date as a timestamp, '' or false if error
  12011. */
  12012. function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto')
  12013. {
  12014. if ($hourTime === 'getpost') {
  12015. $hour = GETPOSTINT($prefix . 'hour');
  12016. $minute = GETPOSTINT($prefix . 'minute');
  12017. $second = GETPOSTINT($prefix . 'second');
  12018. } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
  12019. $hour = intval($m[1]);
  12020. $minute = intval($m[2]);
  12021. $second = intval($m[3]);
  12022. } else {
  12023. $hour = $minute = $second = 0;
  12024. }
  12025. // normalize out of range values
  12026. $hour = min($hour, 23);
  12027. $minute = min($minute, 59);
  12028. $second = min($second, 59);
  12029. return dol_mktime($hour, $minute, $second, GETPOSTINT($prefix . 'month'), GETPOSTINT($prefix . 'day'), GETPOSTINT($prefix . 'year'), $gm);
  12030. }
  12031. /**
  12032. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  12033. * optionally hour, minute, second) fields to return a a portion of URL reproducing the values from the current HTTP
  12034. * request.
  12035. *
  12036. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  12037. * @param int $timestamp If null, the timestamp will be created from request data
  12038. * @param bool $hourTime If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  12039. * @param bool $gm If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  12040. * @return string Portion of URL with query parameters for the specified date
  12041. */
  12042. function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
  12043. {
  12044. if ($timestamp === null) $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
  12045. $TParam = array(
  12046. $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
  12047. $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
  12048. $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
  12049. );
  12050. if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
  12051. $TParam = array_merge($TParam, array(
  12052. $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
  12053. $prefix . 'minute' => intval(dol_print_date($timestamp, '%M')),
  12054. $prefix . 'second' => intval(dol_print_date($timestamp, '%S'))
  12055. ));
  12056. }
  12057. return '&' . http_build_query($TParam);
  12058. }