functions.lib.php 384 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2017 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-2020 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. * or see https://www.gnu.org/
  33. */
  34. /**
  35. * \file htdocs/core/lib/functions.lib.php
  36. * \brief A set of functions for Dolibarr
  37. * This file contains all frequently used functions.
  38. */
  39. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  40. /**
  41. * Return a DoliDB instance (database handler).
  42. *
  43. * @param string $type Type of database (mysql, pgsql...)
  44. * @param string $host Address of database server
  45. * @param string $user Authorized username
  46. * @param string $pass Password
  47. * @param string $name Name of database
  48. * @param int $port Port of database server
  49. * @return DoliDB A DoliDB instance
  50. */
  51. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  52. {
  53. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  54. $class = 'DoliDB'.ucfirst($type);
  55. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  56. return $dolidb;
  57. }
  58. /**
  59. * Get list of entity id to use.
  60. *
  61. * @param string $element Current element
  62. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  63. * 'product', 'productprice', 'stock', 'bom', 'mo',
  64. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  65. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  66. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  67. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  68. * 'email_template', 'event', 'donation'
  69. * 'c_paiement', 'c_payment_term', ...
  70. * @param int $shared 0=Return id of current entity only,
  71. * 1=Return id of current entity + shared entities (default)
  72. * @param object $currentobject Current object if needed
  73. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  74. */
  75. function getEntity($element, $shared = 1, $currentobject = null)
  76. {
  77. global $conf, $mc;
  78. // fix different element names (France to English)
  79. switch ($element) {
  80. case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php"
  81. case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php"
  82. }
  83. if (is_object($mc))
  84. {
  85. return $mc->getEntity($element, $shared, $currentobject);
  86. } else {
  87. $out = '';
  88. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  89. if (in_array($element, $addzero)) $out .= '0,';
  90. $out .= ((int) $conf->entity);
  91. return $out;
  92. }
  93. }
  94. /**
  95. * Set entity id to use when to create an object
  96. *
  97. * @param object $currentobject Current object
  98. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  99. */
  100. function setEntity($currentobject)
  101. {
  102. global $conf, $mc;
  103. if (is_object($mc) && method_exists($mc, 'setEntity'))
  104. {
  105. return $mc->setEntity($currentobject);
  106. } else {
  107. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  108. }
  109. }
  110. /**
  111. * Return if string has a name dedicated to store a secret
  112. *
  113. * @param string $keyname Name of key to test
  114. * @return boolean True if key is used to store a secret
  115. */
  116. function isASecretKey($keyname)
  117. {
  118. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  119. }
  120. /**
  121. * Return information about user browser
  122. *
  123. * Returns array with the following format:
  124. * array(
  125. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  126. * 'browserversion' => Browser version. Empty if unknown
  127. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  128. * 'layout' => (tablet|phone|classic)
  129. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  130. * 'tablet' => true/false
  131. * )
  132. *
  133. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  134. * @return array Check function documentation
  135. */
  136. function getBrowserInfo($user_agent)
  137. {
  138. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  139. $name = 'unknown';
  140. $version = '';
  141. $os = 'unknown';
  142. $phone = '';
  143. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  144. $detectmobile = new Mobile_Detect(null, $user_agent);
  145. $tablet = $detectmobile->isTablet();
  146. if ($detectmobile->isMobile()) {
  147. $phone = 'unknown';
  148. // If phone/smartphone, we set phone os name.
  149. if ($detectmobile->is('AndroidOS')) {
  150. $os = $phone = 'android';
  151. } elseif ($detectmobile->is('BlackBerryOS')) {
  152. $os = $phone = 'blackberry';
  153. } elseif ($detectmobile->is('iOS')) {
  154. $os = 'ios';
  155. $phone = 'iphone';
  156. } elseif ($detectmobile->is('PalmOS')) {
  157. $os = $phone = 'palm';
  158. } elseif ($detectmobile->is('SymbianOS')) {
  159. $os = 'symbian';
  160. } elseif ($detectmobile->is('webOS')) {
  161. $os = 'webos';
  162. } elseif ($detectmobile->is('MaemoOS')) {
  163. $os = 'maemo';
  164. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  165. $os = 'windows';
  166. }
  167. }
  168. // OS
  169. if (preg_match('/linux/i', $user_agent)) { $os = 'linux'; } elseif (preg_match('/macintosh/i', $user_agent)) { $os = 'macintosh'; } elseif (preg_match('/windows/i', $user_agent)) { $os = 'windows'; }
  170. // Name
  171. $reg = array();
  172. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'firefox'; $version = $reg[2]; } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'edge'; $version = $reg[2]; } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name = 'chrome'; $version = $reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string
  173. elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name = 'chrome'; } elseif (preg_match('/iceweasel/i', $user_agent)) { $name = 'iceweasel'; } elseif (preg_match('/epiphany/i', $user_agent)) { $name = 'epiphany'; } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'safari'; $version = $reg[2]; } // Safari is often present in string for mobile but its not.
  174. elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'opera'; $version = $reg[2]; } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end
  175. elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end
  176. elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name = 'lynxlinks'; $version = $reg[4]; }
  177. if ($tablet) {
  178. $layout = 'tablet';
  179. } elseif ($phone) {
  180. $layout = 'phone';
  181. } else {
  182. $layout = 'classic';
  183. }
  184. return array(
  185. 'browsername' => $name,
  186. 'browserversion' => $version,
  187. 'browseros' => $os,
  188. 'layout' => $layout,
  189. 'phone' => $phone,
  190. 'tablet' => $tablet
  191. );
  192. }
  193. /**
  194. * Function called at end of web php process
  195. *
  196. * @return void
  197. */
  198. function dol_shutdown()
  199. {
  200. global $conf, $user, $langs, $db;
  201. $disconnectdone = false; $depth = 0;
  202. if (is_object($db) && !empty($db->connected)) { $depth = $db->transaction_opened; $disconnectdone = $db->close(); }
  203. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  204. }
  205. /**
  206. * Return true if we are in a context of submitting the parameter $paramname
  207. *
  208. * @param string $paramname Name or parameter to test
  209. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  210. */
  211. function GETPOSTISSET($paramname)
  212. {
  213. $isset = false;
  214. $relativepathstring = $_SERVER["PHP_SELF"];
  215. // Clean $relativepathstring
  216. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  217. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  218. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  219. //var_dump($relativepathstring);
  220. //var_dump($user->default_values);
  221. // Code for search criteria persistence.
  222. // Retrieve values if restore_lastsearch_values
  223. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  224. {
  225. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  226. {
  227. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  228. if (is_array($tmp))
  229. {
  230. foreach ($tmp as $key => $val)
  231. {
  232. if ($key == $paramname) // We are on the requested parameter
  233. {
  234. $isset = true;
  235. break;
  236. }
  237. }
  238. }
  239. }
  240. // If there is saved contextpage, page or limit
  241. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  242. {
  243. $isset = true;
  244. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  245. {
  246. $isset = true;
  247. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  248. {
  249. $isset = true;
  250. }
  251. } else {
  252. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  253. }
  254. return $isset;
  255. }
  256. /**
  257. * Return value of a param into GET or POST supervariable.
  258. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  259. * Note: The property $user->default_values is loaded by main.php when loading the user.
  260. *
  261. * @param string $paramname Name of parameter to found
  262. * @param string $check Type of check
  263. * ''=no check (deprecated)
  264. * 'none'=no check (only for param that should have very rich content)
  265. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  266. * 'int'=check it's numeric (integer or float)
  267. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  268. * 'alpha'=Same than alphanohtml since v13
  269. * 'alphanohtml'=check there is no html content and no " and no ../
  270. * 'aZ'=check it's a-z only
  271. * 'aZ09'=check it's simple alpha string (recommended for keys)
  272. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  273. * 'nohtml'=check there is no html content and no " and no ../
  274. * 'restricthtml'=check html content is restricted to some tags only
  275. * 'custom'= custom filter specify $filter and $options)
  276. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  277. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  278. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  279. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  280. * @return string|array Value found (string or array), or '' if check fails
  281. */
  282. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  283. {
  284. global $mysoc, $user, $conf;
  285. if (empty($paramname)) return 'BadFirstParameterForGETPOST';
  286. if (empty($check))
  287. {
  288. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  289. // Enable this line to know who call the GETPOST with '' $check parameter.
  290. //var_dump(debug_backtrace()[0]);
  291. }
  292. if (empty($method)) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  293. elseif ($method == 1) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  294. elseif ($method == 2) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  295. elseif ($method == 3) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  296. else return 'BadThirdParameterForGETPOST';
  297. if (empty($method) || $method == 3 || $method == 4)
  298. {
  299. $relativepathstring = $_SERVER["PHP_SELF"];
  300. // Clean $relativepathstring
  301. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  302. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  303. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  304. //var_dump($relativepathstring);
  305. //var_dump($user->default_values);
  306. // Code for search criteria persistence.
  307. // Retrieve values if restore_lastsearch_values
  308. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  309. {
  310. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  311. {
  312. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  313. if (is_array($tmp))
  314. {
  315. foreach ($tmp as $key => $val)
  316. {
  317. if ($key == $paramname) // We are on the requested parameter
  318. {
  319. $out = $val;
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. // If there is saved contextpage, page or limit
  326. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  327. {
  328. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  329. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  330. {
  331. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  332. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  333. {
  334. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  335. }
  336. } // Else, retrieve default values if we are not doing a sort
  337. elseif (!isset($_GET['sortfield'])) // 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
  338. {
  339. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  340. {
  341. // Search default value from $object->field
  342. global $object;
  343. if (is_object($object) && isset($object->fields[$paramname]['default']))
  344. {
  345. $out = $object->fields[$paramname]['default'];
  346. }
  347. }
  348. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
  349. {
  350. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  351. {
  352. // Now search in setup to overwrite default values
  353. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  354. {
  355. if (isset($user->default_values[$relativepathstring]['createform']))
  356. {
  357. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval)
  358. {
  359. $qualified = 0;
  360. if ($defkey != '_noquery_')
  361. {
  362. $tmpqueryarraytohave = explode('&', $defkey);
  363. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  364. $foundintru = 0;
  365. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  366. {
  367. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  368. }
  369. if (!$foundintru) $qualified = 1;
  370. //var_dump($defkey.'-'.$qualified);
  371. } else $qualified = 1;
  372. if ($qualified)
  373. {
  374. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname]))
  375. {
  376. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  377. break;
  378. }
  379. }
  380. }
  381. }
  382. }
  383. } // Management of default search_filters and sort order
  384. elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  385. {
  386. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  387. {
  388. //var_dump($user->default_values[$relativepathstring]);
  389. if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ?
  390. {
  391. if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...']
  392. {
  393. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval)
  394. {
  395. $qualified = 0;
  396. if ($defkey != '_noquery_')
  397. {
  398. $tmpqueryarraytohave = explode('&', $defkey);
  399. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  400. $foundintru = 0;
  401. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  402. {
  403. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  404. }
  405. if (!$foundintru) $qualified = 1;
  406. //var_dump($defkey.'-'.$qualified);
  407. } else $qualified = 1;
  408. if ($qualified)
  409. {
  410. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  411. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val)
  412. {
  413. if ($out) $out .= ', ';
  414. if ($paramname == 'sortfield')
  415. {
  416. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  417. }
  418. if ($paramname == 'sortorder')
  419. {
  420. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  421. }
  422. }
  423. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  424. }
  425. }
  426. }
  427. } elseif (isset($user->default_values[$relativepathstring]['filters']))
  428. {
  429. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  430. {
  431. $qualified = 0;
  432. if ($defkey != '_noquery_')
  433. {
  434. $tmpqueryarraytohave = explode('&', $defkey);
  435. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  436. $foundintru = 0;
  437. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  438. {
  439. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  440. }
  441. if (!$foundintru) $qualified = 1;
  442. //var_dump($defkey.'-'.$qualified);
  443. } else $qualified = 1;
  444. if ($qualified)
  445. {
  446. // We must keep $_POST and $_GET here
  447. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all']))
  448. {
  449. // We made a search from quick search menu, do we still use default filter ?
  450. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH))
  451. {
  452. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  453. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  454. }
  455. } else {
  456. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  457. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  458. }
  459. break;
  460. }
  461. }
  462. }
  463. }
  464. }
  465. }
  466. }
  467. }
  468. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  469. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  470. // 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.
  471. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace))
  472. {
  473. $reg = array();
  474. $maxloop = 20; $loopnb = 0; // Protection against infinite loop
  475. 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.
  476. {
  477. $loopnb++; $newout = '';
  478. if ($reg[1] == 'DAY') {
  479. $tmp = dol_getdate(dol_now(), true);
  480. $newout = $tmp['mday'];
  481. } elseif ($reg[1] == 'MONTH') {
  482. $tmp = dol_getdate(dol_now(), true);
  483. $newout = $tmp['mon'];
  484. } elseif ($reg[1] == 'YEAR') {
  485. $tmp = dol_getdate(dol_now(), true);
  486. $newout = $tmp['year'];
  487. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  488. $tmp = dol_getdate(dol_now(), true);
  489. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  490. $newout = $tmp2['day'];
  491. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  492. $tmp = dol_getdate(dol_now(), true);
  493. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  494. $newout = $tmp2['month'];
  495. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  496. $tmp = dol_getdate(dol_now(), true);
  497. $newout = ($tmp['year'] - 1);
  498. } elseif ($reg[1] == 'NEXT_DAY') {
  499. $tmp = dol_getdate(dol_now(), true);
  500. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  501. $newout = $tmp2['day'];
  502. } elseif ($reg[1] == 'NEXT_MONTH') {
  503. $tmp = dol_getdate(dol_now(), true);
  504. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  505. $newout = $tmp2['month'];
  506. } elseif ($reg[1] == 'NEXT_YEAR') {
  507. $tmp = dol_getdate(dol_now(), true);
  508. $newout = ($tmp['year'] + 1);
  509. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  510. $newout = $mysoc->country_id;
  511. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  512. $newout = $user->id;
  513. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  514. $newout = $user->fk_user;
  515. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  516. $newout = $conf->entity;
  517. } else {
  518. $newout = ''; // Key not found, we replace with empty string
  519. }
  520. //var_dump('__'.$reg[1].'__ -> '.$newout);
  521. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  522. }
  523. }
  524. // Check rule
  525. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09'
  526. if (!is_array($out) || empty($out)) {
  527. $out = array();
  528. } else {
  529. $tmparray = explode(':', $check);
  530. if (!empty($tmparray[1])) {
  531. $tmpcheck = $tmparray[1];
  532. } else {
  533. $tmpcheck = 'alphanohtml';
  534. }
  535. foreach ($out as $outkey => $outval) {
  536. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  537. }
  538. }
  539. }
  540. else {
  541. $out = checkVal($out, $check, $filter, $options);
  542. }
  543. // Sanitizing for special parameters. There is no reason to allow the backtopage parameter to contains an external URL.
  544. if ($paramname == 'backtopage') {
  545. $out = str_replace('\\', '/', $out);
  546. $out = preg_replace(array('/^\/\/+/', '/^[a-z]*:/i'), '', $out);
  547. }
  548. // Code for search criteria persistence.
  549. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  550. if (empty($method) || $method == 3 || $method == 4)
  551. {
  552. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield')))
  553. {
  554. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  555. // We save search key only if $out not empty that means:
  556. // - posted value not empty, or
  557. // - 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).
  558. if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep
  559. {
  560. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  561. }
  562. }
  563. }
  564. return $out;
  565. }
  566. /**
  567. * Return value of a param into GET or POST supervariable.
  568. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  569. * Note: The property $user->default_values is loaded by main.php when loading the user.
  570. *
  571. * @param string $paramname Name of parameter to found
  572. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  573. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  574. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  575. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  576. * @return int Value found (int)
  577. */
  578. function GETPOSTINT($paramname, $method = 0, $filter = null, $options = null, $noreplace = 0)
  579. {
  580. return (int) GETPOST($paramname, 'int', $method, $filter, $options, $noreplace);
  581. }
  582. /**
  583. * Return a value after checking on a rule.
  584. *
  585. * @param string $out Value to get/check
  586. * @param string $check Type of check
  587. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  588. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  589. * @return string|array Value found (string or array), or '' if check fails
  590. */
  591. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  592. {
  593. // Check is done after replacement
  594. switch ($check)
  595. {
  596. case 'none':
  597. break;
  598. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  599. if (!is_numeric($out)) { $out = ''; }
  600. break;
  601. case 'intcomma':
  602. if (preg_match('/[^0-9,-]+/i', $out)) $out = '';
  603. break;
  604. case 'san_alpha':
  605. $out = filter_var($out, FILTER_SANITIZE_STRING);
  606. break;
  607. case 'email':
  608. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  609. break;
  610. case 'aZ':
  611. if (!is_array($out))
  612. {
  613. $out = trim($out);
  614. if (preg_match('/[^a-z]+/i', $out)) $out = '';
  615. }
  616. break;
  617. case 'aZ09':
  618. if (!is_array($out))
  619. {
  620. $out = trim($out);
  621. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) $out = '';
  622. }
  623. break;
  624. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  625. if (!is_array($out))
  626. {
  627. $out = trim($out);
  628. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out = '';
  629. }
  630. break;
  631. case 'nohtml':
  632. $out = dol_string_nohtmltag($out, 0);
  633. break;
  634. case 'alpha': // No html and no " and no ../
  635. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  636. if (!is_array($out)) {
  637. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  638. // '../' is dangerous because it allows dir transversals
  639. $out = str_replace(array('&quot;', '"', '../'), '', trim($out));
  640. // keep lines feed
  641. $out = dol_string_nohtmltag($out, 0);
  642. }
  643. break;
  644. case 'restricthtml': // Recommended for most html textarea
  645. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  646. break;
  647. case 'custom':
  648. if (empty($filter)) return 'BadFourthParameterForGETPOST';
  649. $out = filter_var($out, $filter, $options);
  650. break;
  651. }
  652. return $out;
  653. }
  654. if (!function_exists('dol_getprefix'))
  655. {
  656. /**
  657. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  658. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  659. * or two instances in same virtual servers.
  660. *
  661. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  662. * @return string A calculated prefix
  663. */
  664. function dol_getprefix($mode = '')
  665. {
  666. // If prefix is for email (we need to have $conf alreayd loaded for this case)
  667. if ($mode == 'email')
  668. {
  669. global $conf;
  670. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  671. {
  672. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  673. elseif (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"];
  674. }
  675. // The recommended value (may be not defined for old versions)
  676. if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id;
  677. // For backward compatibility
  678. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  679. }
  680. // If prefix is for session (no need to have $conf loaded)
  681. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  682. $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
  683. // The recommended value (may be not defined for old versions)
  684. if (!empty($tmp_instance_unique_id)) {
  685. return $tmp_instance_unique_id;
  686. }
  687. // For backward compatibility
  688. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  689. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  690. }
  691. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  692. }
  693. }
  694. /**
  695. * Make an include_once using default root and alternate root if it fails.
  696. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  697. * To link to a module file from a module file, use include './mymodulefile';
  698. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  699. *
  700. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  701. * @param string $classname Class name (deprecated)
  702. * @return bool True if load is a success, False if it fails
  703. */
  704. function dol_include_once($relpath, $classname = '')
  705. {
  706. 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']
  707. $fullpath = dol_buildpath($relpath);
  708. if (!file_exists($fullpath)) {
  709. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  710. return false;
  711. }
  712. if (!empty($classname) && !class_exists($classname)) {
  713. return include $fullpath;
  714. } else {
  715. return include_once $fullpath;
  716. }
  717. }
  718. /**
  719. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  720. *
  721. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  722. * @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)
  723. * @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)
  724. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  725. * 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
  726. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  727. */
  728. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  729. {
  730. global $conf;
  731. $path = preg_replace('/^\//', '', $path);
  732. if (empty($type)) // For a filesystem path
  733. {
  734. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  735. if (is_array($conf->file->dol_document_root))
  736. {
  737. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  738. {
  739. if ($key == 'main')
  740. {
  741. continue;
  742. }
  743. if (file_exists($dirroot.'/'.$path))
  744. {
  745. $res = $dirroot.'/'.$path;
  746. return $res;
  747. }
  748. }
  749. }
  750. if ($returnemptyifnotfound) // Not found into alternate dir
  751. {
  752. if ($returnemptyifnotfound == 1 || !file_exists($res)) return '';
  753. }
  754. } else // For an url path
  755. {
  756. // We try to get local path of file on filesystem from url
  757. // Note that trying to know if a file on disk exist by forging path on disk from url
  758. // works only for some web server and some setup. This is bugged when
  759. // using proxy, rewriting, virtual path, etc...
  760. $res = '';
  761. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  762. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  763. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  764. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  765. {
  766. if ($key == 'main')
  767. {
  768. if ($type == 3)
  769. {
  770. global $dolibarr_main_url_root;
  771. // Define $urlwithroot
  772. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  773. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  774. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  775. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  776. }
  777. continue;
  778. }
  779. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  780. if (!empty($regs[1]))
  781. {
  782. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  783. if (file_exists($dirroot.'/'.$regs[1]))
  784. {
  785. if ($type == 1)
  786. {
  787. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  788. }
  789. if ($type == 2)
  790. {
  791. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  792. }
  793. if ($type == 3)
  794. {
  795. global $dolibarr_main_url_root;
  796. // Define $urlwithroot
  797. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  798. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  799. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  800. $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
  801. }
  802. break;
  803. }
  804. }
  805. }
  806. }
  807. return $res;
  808. }
  809. /**
  810. * Create a clone of instance of object (new instance with same value for properties)
  811. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  812. * 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.
  813. *
  814. * @param object $object Object to clone
  815. * @param int $native 0=Full isolation method, 1=Native PHP method
  816. * @return object Clone object
  817. * @see https://php.net/manual/language.oop5.cloning.php
  818. */
  819. function dol_clone($object, $native = 0)
  820. {
  821. if (empty($native))
  822. {
  823. $myclone = unserialize(serialize($object));
  824. } else {
  825. $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)
  826. }
  827. return $myclone;
  828. }
  829. /**
  830. * Optimize a size for some browsers (phone, smarphone, ...)
  831. *
  832. * @param int $size Size we want
  833. * @param string $type Type of optimizing:
  834. * '' = function used to define a size for truncation
  835. * 'width' = function is used to define a width
  836. * @return int New size after optimizing
  837. */
  838. function dol_size($size, $type = '')
  839. {
  840. global $conf;
  841. if (empty($conf->dol_optimize_smallscreen)) return $size;
  842. if ($type == 'width' && $size > 250) return 250;
  843. else return 10;
  844. }
  845. /**
  846. * Clean a string to use it as a file name
  847. *
  848. * @param string $str String to clean
  849. * @param string $newstr String to replace bad chars with
  850. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  851. * @return string String cleaned (a-zA-Z_)
  852. *
  853. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  854. */
  855. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  856. {
  857. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  858. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  859. // Char '/' and '\' are file delimiters.
  860. // -- car can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  861. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '--');
  862. return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  863. }
  864. /**
  865. * Clean a string to use it as a path name
  866. *
  867. * @param string $str String to clean
  868. * @param string $newstr String to replace bad chars with
  869. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  870. * @return string String cleaned (a-zA-Z_)
  871. *
  872. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  873. */
  874. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  875. {
  876. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°');
  877. return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  878. }
  879. /**
  880. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  881. *
  882. * @param string $str String to clean
  883. * @return string Cleaned string
  884. *
  885. * @see dol_sanitizeFilename(), dol_string_nospecial()
  886. */
  887. function dol_string_unaccent($str)
  888. {
  889. if (utf8_check($str))
  890. {
  891. // See http://www.utf8-chartable.de/
  892. $string = rawurlencode($str);
  893. $replacements = array(
  894. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  895. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  896. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  897. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  898. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  899. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  900. '%C3%A7' => 'c',
  901. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  902. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  903. '%C3%B1' => 'n',
  904. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  905. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  906. '%C3%BF' => 'y'
  907. );
  908. $string = strtr($string, $replacements);
  909. return rawurldecode($string);
  910. } else {
  911. // See http://www.ascii-code.com/
  912. $string = strtr(
  913. $str,
  914. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  915. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  916. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  917. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  918. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  919. \xF9\xFA\xFB\xFC\xFD\xFF",
  920. "AAAAAAC
  921. EEEEIIIIDN
  922. OOOOOUUUY
  923. aaaaaaceeee
  924. iiiidnooooo
  925. uuuuyy"
  926. );
  927. $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"));
  928. return $string;
  929. }
  930. }
  931. /**
  932. * Clean a string from all punctuation characters to use it as a ref or login.
  933. * This is a more complete function than dol_sanitizeFileName.
  934. *
  935. * @param string $str String to clean
  936. * @param string $newstr String to replace forbidden chars with
  937. * @param array $badcharstoreplace List of forbidden characters
  938. * @return string Cleaned string
  939. *
  940. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  941. */
  942. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
  943. {
  944. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  945. $forbidden_chars_to_remove = array();
  946. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace = $badcharstoreplace;
  947. //$forbidden_chars_to_remove=array("(",")");
  948. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  949. }
  950. /**
  951. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  952. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  953. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  954. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  955. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  956. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  957. * @param string $str String to clean
  958. * @param int $removetabcrlf Remove also CR-LF
  959. * @return string Cleaned string
  960. *
  961. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  962. */
  963. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  964. {
  965. if ($removetabcrlf) {
  966. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  967. } else {
  968. 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
  969. }
  970. }
  971. /**
  972. * Returns text escaped for inclusion into javascript code
  973. *
  974. * @param string $stringtoescape String to escape
  975. * @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 \
  976. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  977. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  978. */
  979. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  980. {
  981. // escape quotes and backslashes, newlines, etc.
  982. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  983. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  984. if (empty($noescapebackslashn)) { $substitjs["\n"] = '\\n'; $substitjs['\\'] = '\\\\'; }
  985. if (empty($mode)) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\'"; } elseif ($mode == 1) $substitjs["'"] = "\\'";
  986. elseif ($mode == 2) { $substitjs['"'] = '\\"'; } elseif ($mode == 3) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\\""; }
  987. return strtr($stringtoescape, $substitjs);
  988. }
  989. /**
  990. * Returns text escaped for inclusion into javascript code
  991. *
  992. * @param string $stringtoescape String to escape
  993. * @return string Escaped string for json content.
  994. */
  995. function dol_escape_json($stringtoescape)
  996. {
  997. return str_replace('"', '\"', $stringtoescape);
  998. }
  999. /**
  1000. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1001. *
  1002. * @param string $stringtoescape String to escape
  1003. * @param int $keepb 1=Keep b tags and escape them, 0=remove them
  1004. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1005. * @param string $keepmoretags '' or 'common' or list of tags
  1006. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1007. * @return string Escaped string
  1008. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1009. */
  1010. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $keepmoretags = '', $escapeonlyhtmltags = 0)
  1011. {
  1012. if ($keepmoretags == 'common') $keepmoretags = 'html,body,a,b,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1013. // TODO Implement $keepmoretags
  1014. // escape quotes and backslashes, newlines, etc.
  1015. if ($escapeonlyhtmltags) {
  1016. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1017. } else {
  1018. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1019. }
  1020. if (!$keepb) $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1021. if (!$keepn) $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1022. if ($escapeonlyhtmltags) {
  1023. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1024. } else {
  1025. return htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1026. }
  1027. }
  1028. /**
  1029. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1030. *
  1031. * @param string $string String to encode
  1032. * @param string $encoding Character set encoding
  1033. * @return string String converted
  1034. */
  1035. function dol_strtolower($string, $encoding = "UTF-8")
  1036. {
  1037. if (function_exists('mb_strtolower')) {
  1038. return mb_strtolower($string, $encoding);
  1039. } else {
  1040. return strtolower($string);
  1041. }
  1042. }
  1043. /**
  1044. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1045. *
  1046. * @param string $string String to encode
  1047. * @param string $encoding Character set encoding
  1048. * @return string String converted
  1049. */
  1050. function dol_strtoupper($string, $encoding = "UTF-8")
  1051. {
  1052. if (function_exists('mb_strtoupper')) {
  1053. return mb_strtoupper($string, $encoding);
  1054. } else {
  1055. return strtoupper($string);
  1056. }
  1057. }
  1058. /**
  1059. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1060. *
  1061. * @param string $string String to encode
  1062. * @param string $encoding Character set encodign
  1063. * @return string String converted
  1064. */
  1065. function dol_ucfirst($string, $encoding = "UTF-8")
  1066. {
  1067. if (function_exists('mb_substr')) {
  1068. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1069. } else {
  1070. return ucfirst($string);
  1071. }
  1072. }
  1073. /**
  1074. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1075. *
  1076. * @param string $string String to encode
  1077. * @param string $encoding Character set encodign
  1078. * @return string String converted
  1079. */
  1080. function dol_ucwords($string, $encoding = "UTF-8")
  1081. {
  1082. if (function_exists('mb_convert_case')) {
  1083. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1084. } else {
  1085. return ucwords($string);
  1086. }
  1087. }
  1088. /**
  1089. * Write log message into outputs. Possible outputs can be:
  1090. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1091. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1092. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1093. * this, use logging to files instead of syslog (see setup of module).
  1094. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1095. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1096. * This function works only if syslog module is enabled.
  1097. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1098. *
  1099. * @param string $message Line to log. ''=Show nothing
  1100. * @param int $level Log level
  1101. * 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
  1102. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  1103. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1104. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1105. * @param string $restricttologhandler Force output of log only to this log handler
  1106. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1107. * @return void
  1108. */
  1109. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1110. {
  1111. global $conf, $user, $debugbar;
  1112. // If syslog module enabled
  1113. if (empty($conf->syslog->enabled)) return;
  1114. // Check if we are into execution of code of a website
  1115. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1116. global $website, $websitekey;
  1117. if (is_object($website) && !empty($website->ref)) $suffixinfilename .= '_website_'.$website->ref;
  1118. elseif (!empty($websitekey)) $suffixinfilename .= '_website_'.$websitekey;
  1119. }
  1120. if ($ident < 0)
  1121. {
  1122. foreach ($conf->loghandlers as $loghandlerinstance)
  1123. {
  1124. $loghandlerinstance->setIdent($ident);
  1125. }
  1126. }
  1127. if (!empty($message))
  1128. {
  1129. // Test log level
  1130. $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');
  1131. if (!array_key_exists($level, $logLevels))
  1132. {
  1133. throw new Exception('Incorrect log level');
  1134. }
  1135. if ($level > $conf->global->SYSLOG_LEVEL) return;
  1136. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1137. // If adding log inside HTML page is required
  1138. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1139. || (!empty($user->rights->debugbar->read) && is_object($debugbar)))
  1140. {
  1141. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1142. }
  1143. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1144. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1145. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"]))
  1146. {
  1147. print "\n\n<!-- Log start\n";
  1148. print $message."\n";
  1149. print "Log end -->\n";
  1150. }
  1151. $data = array(
  1152. 'message' => $message,
  1153. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1154. 'level' => $level,
  1155. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1156. 'ip' => false
  1157. );
  1158. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1159. if (!empty($remoteip)) {
  1160. $data['ip'] = $remoteip;
  1161. // This is when server run behind a reverse proxy
  1162. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1163. elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1164. } // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1165. elseif (!empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  1166. // 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).
  1167. elseif (!empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1168. // 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).
  1169. elseif (!empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1170. // Loop on each log handler and send output
  1171. foreach ($conf->loghandlers as $loghandlerinstance)
  1172. {
  1173. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  1174. $loghandlerinstance->export($data, $suffixinfilename);
  1175. }
  1176. unset($data);
  1177. }
  1178. if ($ident > 0)
  1179. {
  1180. foreach ($conf->loghandlers as $loghandlerinstance)
  1181. {
  1182. $loghandlerinstance->setIdent($ident);
  1183. }
  1184. }
  1185. }
  1186. /**
  1187. * Return HTML code to output a button to open a dialog popup box.
  1188. * Such buttons must be included inside a HTML form.
  1189. *
  1190. * @param string $name A name for the html component
  1191. * @param string $label Label of button
  1192. * @param string $buttonstring button string
  1193. * @param string $url Url to open
  1194. * @param string $disabled Disabled text
  1195. * @return string HTML component with button
  1196. */
  1197. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1198. {
  1199. if (strpos($url, '?') > 0) {
  1200. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1201. } else {
  1202. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1203. }
  1204. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1205. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1206. $out .= '<script language="javascript">
  1207. jQuery(document).ready(function () {
  1208. jQuery(".button_'.$name.'").click(function () {
  1209. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1210. .dialog({
  1211. autoOpen: false,
  1212. modal: true,
  1213. height: (window.innerHeight - 150),
  1214. width: \'80%\',
  1215. title: "'.dol_escape_js($label).'"
  1216. });
  1217. $dialog.dialog(\'open\');
  1218. });
  1219. });
  1220. </script>';
  1221. return $out;
  1222. }
  1223. /**
  1224. * Show tab header of a card
  1225. *
  1226. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1227. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1228. * @param string $title Title
  1229. * @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)
  1230. * @param string $picto Add a picto on tab title
  1231. * @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.
  1232. * @param string $morehtmlright Add more html content on right of tabs title
  1233. * @param string $morecss More Css
  1234. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1235. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1236. * @return void
  1237. * @deprecated Use print dol_get_fiche_head() instead
  1238. */
  1239. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1240. {
  1241. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1242. }
  1243. /**
  1244. * Show tabs of a record
  1245. *
  1246. * @param array $links Array of tabs
  1247. * @param string $active Active tab name
  1248. * @param string $title Title
  1249. * @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)
  1250. * @param string $picto Add a picto on tab title
  1251. * @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.
  1252. * @param string $morehtmlright Add more html content on right of tabs title
  1253. * @param string $morecss More Css
  1254. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1255. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1256. * @return string
  1257. */
  1258. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1259. {
  1260. global $conf, $langs, $hookmanager;
  1261. // Show title
  1262. $showtitle = 1;
  1263. if (!empty($conf->dol_optimize_smallscreen)) $showtitle = 0;
  1264. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1265. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1266. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1267. }
  1268. // Show right part
  1269. if ($morehtmlright) $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.
  1270. // Show title
  1271. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1272. {
  1273. $limittitle = 30;
  1274. $out .= '<a class="tabTitle">';
  1275. if ($picto) $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1276. $out .= '<span class="tabTitleText">'.dol_trunc($title, $limittitle).'</span>';
  1277. $out .= '</a>';
  1278. }
  1279. // Show tabs
  1280. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1281. $maxkey = -1;
  1282. if (is_array($links) && !empty($links))
  1283. {
  1284. $keys = array_keys($links);
  1285. if (count($keys)) $maxkey = max($keys);
  1286. }
  1287. // Show tabs
  1288. // if =0 we don't use the feature
  1289. if (empty($limittoshow)) {
  1290. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1291. }
  1292. if (!empty($conf->dol_optimize_smallscreen)) $limittoshow = 2;
  1293. $displaytab = 0;
  1294. $nbintab = 0;
  1295. $popuptab = 0;
  1296. $outmore = '';
  1297. for ($i = 0; $i <= $maxkey; $i++)
  1298. {
  1299. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1300. // If active tab is already present
  1301. if ($i >= $limittoshow) $limittoshow--;
  1302. }
  1303. }
  1304. for ($i = 0; $i <= $maxkey; $i++)
  1305. {
  1306. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1307. $isactive = true;
  1308. } else {
  1309. $isactive = false;
  1310. }
  1311. if ($i < $limittoshow || $isactive)
  1312. {
  1313. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : $links[$i][2]).' -->';
  1314. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1315. {
  1316. if (!empty($links[$i][0]))
  1317. {
  1318. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1319. } else {
  1320. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1321. }
  1322. } elseif (!empty($links[$i][1]))
  1323. {
  1324. //print "x $i $active ".$links[$i][2]." z";
  1325. if ($isactive)
  1326. {
  1327. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1328. $out .= $links[$i][1];
  1329. $out .= '</a>'."\n";
  1330. } else {
  1331. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabunactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1332. $out .= $links[$i][1];
  1333. $out .= '</a>'."\n";
  1334. }
  1335. }
  1336. $out .= '</div>';
  1337. } else {
  1338. // The popup with the other tabs
  1339. if (!$popuptab)
  1340. {
  1341. $popuptab = 1;
  1342. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1343. }
  1344. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1345. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1346. {
  1347. if (!empty($links[$i][0]))
  1348. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1349. else $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1350. } elseif (!empty($links[$i][1]))
  1351. {
  1352. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1353. $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.
  1354. $outmore .= '</a>'."\n";
  1355. }
  1356. $outmore .= '</div>';
  1357. $nbintab++;
  1358. }
  1359. $displaytab = $i;
  1360. }
  1361. if ($popuptab) $outmore .= '</div>';
  1362. if ($popuptab) // If there is some tabs not shown
  1363. {
  1364. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1365. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1366. $widthofpopup = 200;
  1367. $tabsname = $moretabssuffix;
  1368. if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); }
  1369. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1370. $out .= '<a href="#" class="tab moretab inline-block tabunactive">'.$langs->trans("More").'... ('.$nbintab.')</a>'; // Do not use "reposition" class in the "More".
  1371. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1372. $out .= $outmore;
  1373. $out .= '</div>';
  1374. $out .= '<div></div>';
  1375. $out .= "</div>\n";
  1376. $out .= "<script>";
  1377. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1378. var x = this.offsetLeft, y = this.offsetTop;
  1379. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1380. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1381. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1382. }
  1383. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1384. });
  1385. ";
  1386. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1387. $out .= "</script>";
  1388. }
  1389. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1390. $out .= "</div>\n";
  1391. }
  1392. if (!$notab || $notab == -1 || $notab == -2) $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1393. $parameters = array('tabname' => $active, 'out' => $out);
  1394. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1395. if ($reshook > 0)
  1396. {
  1397. $out = $hookmanager->resPrint;
  1398. }
  1399. return $out;
  1400. }
  1401. /**
  1402. * Show tab footer of a card
  1403. *
  1404. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1405. * @return void
  1406. * @deprecated Use print dol_get_fiche_end() instead
  1407. */
  1408. function dol_fiche_end($notab = 0)
  1409. {
  1410. print dol_get_fiche_end($notab);
  1411. }
  1412. /**
  1413. * Return tab footer of a card
  1414. *
  1415. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1416. * @return string
  1417. */
  1418. function dol_get_fiche_end($notab = 0)
  1419. {
  1420. if (!$notab || $notab == -1) return "\n</div>\n";
  1421. else return '';
  1422. }
  1423. /**
  1424. * Show tab footer of a card.
  1425. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1426. *
  1427. * @param Object $object Object to show
  1428. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1429. * @param string $morehtml More html content to output just before the nav bar
  1430. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1431. * @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.
  1432. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1433. * @param string $morehtmlref More html to show after ref
  1434. * @param string $moreparam More param to add in nav link url.
  1435. * @param int $nodbprefix Do not include DB prefix to forge table name
  1436. * @param string $morehtmlleft More html code to show before ref
  1437. * @param string $morehtmlstatus More html code to show under navigation arrows
  1438. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1439. * @param string $morehtmlright More html code to show before navigation arrows
  1440. * @return void
  1441. */
  1442. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1443. {
  1444. global $conf, $form, $user, $langs;
  1445. $error = 0;
  1446. $maxvisiblephotos = 1;
  1447. $showimage = 1;
  1448. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1449. $showbarcode = empty($conf->barcode->enabled) ? 0 : ($object->barcode ? 1 : 0);
  1450. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0;
  1451. $modulepart = 'unknown';
  1452. if ($object->element == 'societe') $modulepart = 'societe';
  1453. if ($object->element == 'contact') $modulepart = 'contact';
  1454. if ($object->element == 'member') $modulepart = 'memberphoto';
  1455. if ($object->element == 'user') $modulepart = 'userphoto';
  1456. if ($object->element == 'product') $modulepart = 'product';
  1457. if ($object->element == 'ticket') $modulepart = 'ticket';
  1458. if (class_exists("Imagick"))
  1459. {
  1460. if ($object->element == 'propal') $modulepart = 'propal';
  1461. if ($object->element == 'commande') $modulepart = 'commande';
  1462. if ($object->element == 'facture') $modulepart = 'facture';
  1463. if ($object->element == 'fichinter') $modulepart = 'ficheinter';
  1464. if ($object->element == 'contrat') $modulepart = 'contract';
  1465. if ($object->element == 'supplier_proposal') $modulepart = 'supplier_proposal';
  1466. if ($object->element == 'order_supplier') $modulepart = 'supplier_order';
  1467. if ($object->element == 'invoice_supplier') $modulepart = 'supplier_invoice';
  1468. if ($object->element == 'expensereport') $modulepart = 'expensereport';
  1469. }
  1470. if ($object->element == 'product')
  1471. {
  1472. $width = 80; $cssclass = 'photoref';
  1473. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1474. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1475. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1476. if ($showimage) {
  1477. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'</div>';
  1478. } else {
  1479. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1480. $nophoto = '';
  1481. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1482. } else { // Show no photo link
  1483. $nophoto = '/public/theme/common/nophoto.png';
  1484. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1485. }
  1486. }
  1487. } elseif ($object->element == 'ticket') {
  1488. $width = 80; $cssclass = 'photoref';
  1489. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1490. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1491. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1492. if ($showimage)
  1493. {
  1494. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1495. if ($object->nbphoto > 0)
  1496. {
  1497. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1498. } else {
  1499. $showimage = 0;
  1500. }
  1501. }
  1502. if (!$showimage)
  1503. {
  1504. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1505. $nophoto = '';
  1506. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1507. } else { // Show no photo link
  1508. $nophoto = img_picto('No photo', 'object_ticket');
  1509. $morehtmlleft .= '<!-- No photo to show -->';
  1510. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1511. $morehtmlleft .= $nophoto;
  1512. $morehtmlleft .= '</div></div>';
  1513. }
  1514. }
  1515. } else {
  1516. if ($showimage)
  1517. {
  1518. if ($modulepart != 'unknown')
  1519. {
  1520. $phototoshow = '';
  1521. // Check if a preview file is available
  1522. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick"))
  1523. {
  1524. $objectref = dol_sanitizeFileName($object->ref);
  1525. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1526. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1527. {
  1528. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1529. $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
  1530. } else {
  1531. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1532. }
  1533. if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1534. $filepath = $dir_output.$subdir."/";
  1535. $filepdf = $filepath.$objectref.".pdf";
  1536. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1537. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1538. $fileimage = $filepdf.'_preview.png';
  1539. $relativepathimage = $relativepath.'_preview.png';
  1540. $pdfexists = file_exists($filepdf);
  1541. // If PDF file exists
  1542. if ($pdfexists)
  1543. {
  1544. // Conversion du PDF en image png si fichier png non existant
  1545. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
  1546. {
  1547. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1548. {
  1549. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1550. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1551. if ($ret < 0) $error++;
  1552. }
  1553. }
  1554. }
  1555. if ($pdfexists && !$error)
  1556. {
  1557. $heightforphotref = 80;
  1558. if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
  1559. // If the preview file is found
  1560. if (file_exists($fileimage))
  1561. {
  1562. $phototoshow = '<div class="photoref">';
  1563. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1564. $phototoshow .= '</div>';
  1565. }
  1566. }
  1567. } elseif (!$phototoshow) { // example if modulepart = 'photo'
  1568. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1569. }
  1570. if ($phototoshow) {
  1571. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1572. $morehtmlleft .= $phototoshow;
  1573. $morehtmlleft .= '</div>';
  1574. }
  1575. }
  1576. if (!$phototoshow) // Show No photo link (picto of object)
  1577. {
  1578. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1579. if ($object->element == 'action')
  1580. {
  1581. $width = 80;
  1582. $cssclass = 'photorefcenter';
  1583. $nophoto = img_picto('No photo', 'title_agenda');
  1584. } else {
  1585. $width = 14; $cssclass = 'photorefcenter';
  1586. $picto = $object->picto;
  1587. if ($object->element == 'project' && !$object->public) $picto = 'project'; // instead of projectpub
  1588. $nophoto = img_picto('No photo', 'object_'.$picto);
  1589. }
  1590. $morehtmlleft .= '<!-- No photo to show -->';
  1591. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1592. $morehtmlleft .= $nophoto;
  1593. $morehtmlleft .= '</div></div>';
  1594. $morehtmlleft .= '</div>';
  1595. }
  1596. }
  1597. }
  1598. if ($showbarcode) $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1599. if ($object->element == 'societe')
  1600. {
  1601. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1602. {
  1603. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1604. } else {
  1605. $morehtmlstatus .= $object->getLibStatut(6);
  1606. }
  1607. } elseif ($object->element == 'product')
  1608. {
  1609. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1610. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1611. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1612. } else {
  1613. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1614. }
  1615. $morehtmlstatus .= ' &nbsp; ';
  1616. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1617. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1618. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1619. } else {
  1620. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1621. }
  1622. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) {
  1623. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1624. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1625. $morehtmlstatus .= $tmptxt;
  1626. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  1627. if ($object->statut == 0) $morehtmlstatus .= $object->getLibStatut(5);
  1628. else $morehtmlstatus .= $object->getLibStatut(4);
  1629. } elseif ($object->element == 'facturerec') {
  1630. if ($object->frequency == 0) $morehtmlstatus .= $object->getLibStatut(2);
  1631. else $morehtmlstatus .= $object->getLibStatut(5);
  1632. } elseif ($object->element == 'project_task') {
  1633. $object->fk_statut = 1;
  1634. if ($object->progress > 0) $object->fk_statut = 2;
  1635. if ($object->progress >= 100) $object->fk_statut = 3;
  1636. $tmptxt = $object->getLibStatut(5);
  1637. $morehtmlstatus .= $tmptxt; // No status on task
  1638. } else { // Generic case
  1639. $tmptxt = $object->getLibStatut(6);
  1640. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5);
  1641. $morehtmlstatus .= $tmptxt;
  1642. }
  1643. // Add if object was dispatched "into accountancy"
  1644. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various')))
  1645. {
  1646. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  1647. if (method_exists($object, 'getVentilExportCompta'))
  1648. {
  1649. $accounted = $object->getVentilExportCompta();
  1650. $langs->load("accountancy");
  1651. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1652. }
  1653. }
  1654. // Add alias for thirdparty
  1655. if (!empty($object->name_alias)) $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1656. // Add label
  1657. if (in_array($object->element, array('product', 'bank_account', 'project_task')))
  1658. {
  1659. if (!empty($object->label)) $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1660. }
  1661. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files')))
  1662. {
  1663. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1664. if ($moreaddress) {
  1665. $morehtmlref .= '<div class="refidno">';
  1666. $morehtmlref .= $moreaddress;
  1667. $morehtmlref .= '</div>';
  1668. }
  1669. }
  1670. if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && ($conf->global->MAIN_SHOW_TECHNICAL_ID == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id))
  1671. {
  1672. $morehtmlref .= '<div style="clear: both;"></div>';
  1673. $morehtmlref .= '<div class="refidno">';
  1674. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1675. $morehtmlref .= '</div>';
  1676. }
  1677. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1678. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1679. print '</div>';
  1680. print '<div class="underrefbanner clearboth"></div>';
  1681. }
  1682. /**
  1683. * Show a string with the label tag dedicated to the HTML edit field.
  1684. *
  1685. * @param string $langkey Translation key
  1686. * @param string $fieldkey Key of the html select field the text refers to
  1687. * @param int $fieldrequired 1=Field is mandatory
  1688. * @return string
  1689. * @deprecated Form::editfieldkey
  1690. */
  1691. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1692. {
  1693. global $langs;
  1694. $ret = '';
  1695. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  1696. $ret .= '<label for="'.$fieldkey.'">';
  1697. $ret .= $langs->trans($langkey);
  1698. $ret .= '</label>';
  1699. if ($fieldrequired) $ret .= '</span>';
  1700. return $ret;
  1701. }
  1702. /**
  1703. * Return string to add class property on html element with pair/impair.
  1704. *
  1705. * @param string $var 0 or 1
  1706. * @param string $moreclass More class to add
  1707. * @return string String to add class onto HTML element
  1708. */
  1709. function dol_bc($var, $moreclass = '')
  1710. {
  1711. global $bc;
  1712. $ret = ' '.$bc[$var];
  1713. if ($moreclass) $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  1714. return $ret;
  1715. }
  1716. /**
  1717. * Return a formated address (part address/zip/town/state) according to country rules.
  1718. * See https://en.wikipedia.org/wiki/Address
  1719. *
  1720. * @param Object $object A company or contact object
  1721. * @param int $withcountry 1=Add country into address string
  1722. * @param string $sep Separator to use to build string
  1723. * @param Translate $outputlangs Object lang that contains language for text translation.
  1724. * @param int $mode 0=Standard output, 1=Remove address
  1725. * @param string $extralangcode User extralanguage $langcode as values for address, town
  1726. * @return string Formated string
  1727. * @see dol_print_address()
  1728. */
  1729. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  1730. {
  1731. global $conf, $langs;
  1732. $ret = '';
  1733. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1734. // See format of addresses on https://en.wikipedia.org/wiki/Address
  1735. // Address
  1736. if (empty($mode)) {
  1737. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : $object->address);
  1738. }
  1739. // Zip/Town/State
  1740. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) { // US: title firstname name \n address lines \n town, state, zip \n country
  1741. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1742. $ret .= ($ret ? $sep : '').$town;
  1743. if (!empty($object->state)) {
  1744. $ret .= ($ret ? ", " : '').$object->state;
  1745. }
  1746. if ($object->zip) $ret .= ($ret ? ", " : '').$object->zip;
  1747. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country
  1748. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1749. $ret .= ($ret ? $sep : '').$town;
  1750. if (!empty($object->state)) {
  1751. $ret .= ($ret ? ", " : '').$object->state;
  1752. }
  1753. if ($object->zip) $ret .= ($ret ? $sep : '').$object->zip;
  1754. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country
  1755. $ret .= ($ret ? $sep : '').$object->zip;
  1756. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1757. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1758. if (!empty($object->state)) {
  1759. $ret .= "\n".$object->state;
  1760. }
  1761. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) { // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1762. $ret .= ($ret ? $sep : '').$object->zip;
  1763. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1764. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1765. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  1766. } else { // Other: title firstname name \n address lines \n zip town \n country
  1767. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1768. $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : '';
  1769. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  1770. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  1771. $ret .= ($ret ? ", " : '').$object->state;
  1772. }
  1773. }
  1774. if (!is_object($outputlangs)) $outputlangs = $langs;
  1775. if ($withcountry) {
  1776. $langs->load("dict");
  1777. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  1778. }
  1779. return $ret;
  1780. }
  1781. /**
  1782. * Format a string.
  1783. *
  1784. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1785. * @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)
  1786. * @param int $is_gmt See comment of timestamp parameter
  1787. * @return string A formatted string
  1788. */
  1789. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  1790. {
  1791. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1792. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  1793. } else return 'Error date into a not supported range';
  1794. }
  1795. /**
  1796. * Output date in a string format according to outputlangs (or langs if not defined).
  1797. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1798. *
  1799. * @param int $time GM Timestamps date
  1800. * @param string $format Output date format (tag of strftime function)
  1801. * "%d %b %Y",
  1802. * "%d/%m/%Y %H:%M",
  1803. * "%d/%m/%Y %H:%M:%S",
  1804. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1805. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1806. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1807. * false or 'tzserver' => output string is for local PHP server TZ usage
  1808. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  1809. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  1810. * @param Translate $outputlangs Object lang that contains language for text translation.
  1811. * @param boolean $encodetooutput false=no convert into output pagecode
  1812. * @return string Formated date or '' if time is null
  1813. *
  1814. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  1815. */
  1816. function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlangs = '', $encodetooutput = false)
  1817. {
  1818. global $conf, $langs;
  1819. // Clean parameters
  1820. $to_gmt = false;
  1821. $offsettz = $offsetdst = 0;
  1822. if ($tzoutput)
  1823. {
  1824. $to_gmt = true; // For backward compatibility
  1825. if (is_string($tzoutput))
  1826. {
  1827. if ($tzoutput == 'tzserver')
  1828. {
  1829. $to_gmt = false;
  1830. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1831. $offsettz = 0;
  1832. $offsetdst = 0;
  1833. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel')
  1834. {
  1835. $to_gmt = true;
  1836. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1837. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  1838. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  1839. }
  1840. }
  1841. }
  1842. if (!is_object($outputlangs)) $outputlangs = $langs;
  1843. if (!$format) $format = 'daytextshort';
  1844. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0;
  1845. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  1846. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat = 1; } // so format 'dayreduceformat' is processed like day
  1847. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1848. // TODO Add format daysmallyear and dayhoursmallyear
  1849. if ($format == 'day') $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  1850. elseif ($format == 'hour') $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  1851. elseif ($format == 'hourduration') $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  1852. elseif ($format == 'daytext') $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  1853. elseif ($format == 'daytextshort') $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  1854. elseif ($format == 'dayhour') $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  1855. elseif ($format == 'dayhoursec') $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  1856. elseif ($format == 'dayhourtext') $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  1857. elseif ($format == 'dayhourtextshort') $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  1858. // Format not sensitive to language
  1859. elseif ($format == 'dayhourlog') $format = '%Y%m%d%H%M%S';
  1860. elseif ($format == 'dayhourldap') $format = '%Y%m%d%H%M%SZ';
  1861. elseif ($format == 'dayhourxcard') $format = '%Y%m%dT%H%M%SZ';
  1862. elseif ($format == 'dayxcard') $format = '%Y%m%d';
  1863. elseif ($format == 'dayrfc') $format = '%Y-%m-%d'; // DATE_RFC3339
  1864. elseif ($format == 'dayhourrfc') $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1865. elseif ($format == 'standard') $format = '%Y-%m-%d %H:%M:%S';
  1866. if ($reduceformat)
  1867. {
  1868. $format = str_replace('%Y', '%y', $format);
  1869. $format = str_replace('yyyy', 'yy', $format);
  1870. }
  1871. // If date undefined or "", we return ""
  1872. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1873. // Clean format
  1874. if (preg_match('/%b/i', $format)) // There is some text to translate
  1875. {
  1876. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1877. $format = str_replace('%b', '__b__', $format);
  1878. $format = str_replace('%B', '__B__', $format);
  1879. }
  1880. if (preg_match('/%a/i', $format)) // There is some text to translate
  1881. {
  1882. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1883. $format = str_replace('%a', '__a__', $format);
  1884. $format = str_replace('%A', '__A__', $format);
  1885. }
  1886. // Analyze date
  1887. $reg = array();
  1888. 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
  1889. {
  1890. dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  1891. return '';
  1892. } 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
  1893. {
  1894. // This part of code should not be used.
  1895. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  1896. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  1897. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  1898. $syear = (!empty($reg[1]) ? $reg[1] : '');
  1899. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  1900. $sday = (!empty($reg[3]) ? $reg[3] : '');
  1901. $shour = (!empty($reg[4]) ? $reg[4] : '');
  1902. $smin = (!empty($reg[5]) ? $reg[5] : '');
  1903. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  1904. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  1905. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  1906. } else {
  1907. // Date is a timestamps
  1908. if ($time < 100000000000) // Protection against bad date values
  1909. {
  1910. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1911. $ret = adodb_strftime($format, $timetouse, $to_gmt);
  1912. } else $ret = 'Bad value '.$time.' for date';
  1913. }
  1914. if (preg_match('/__b__/i', $format))
  1915. {
  1916. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1917. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1918. $month = adodb_strftime('%m', $timetouse);
  1919. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  1920. if ($encodetooutput)
  1921. {
  1922. $monthtext = $outputlangs->transnoentities('Month'.$month);
  1923. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  1924. } else {
  1925. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  1926. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1927. }
  1928. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1929. $ret = str_replace('__b__', $monthtextshort, $ret);
  1930. $ret = str_replace('__B__', $monthtext, $ret);
  1931. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1932. //return $ret;
  1933. }
  1934. if (preg_match('/__a__/i', $format))
  1935. {
  1936. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1937. $w = adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1938. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  1939. $ret = str_replace('__A__', $dayweek, $ret);
  1940. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  1941. }
  1942. return $ret;
  1943. }
  1944. /**
  1945. * Return an array with locale date info.
  1946. * WARNING: This function use PHP server timezone by default to return locale informations.
  1947. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  1948. *
  1949. * @param int $timestamp Timestamp
  1950. * @param boolean $fast Fast mode. deprecated.
  1951. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'Europe/Paris' or '+0200' to force timezone.
  1952. * @return array Array of informations
  1953. * 'seconds' => $secs,
  1954. * 'minutes' => $min,
  1955. * 'hours' => $hour,
  1956. * 'mday' => $day,
  1957. * 'wday' => $dow, 0=sunday, 6=saturday
  1958. * 'mon' => $month,
  1959. * 'year' => $year,
  1960. * 'yday' => floor($secsInYear/$_day_power)
  1961. * '0' => original timestamp
  1962. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  1963. */
  1964. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  1965. {
  1966. global $conf;
  1967. if (empty($conf->global->MAIN_USE_OLD_FUNCTIONS_FOR_GETDATE)) {
  1968. //$datetimeobj = new DateTime('@'.$timestamp);
  1969. $datetimeobj = new DateTime();
  1970. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  1971. if ($forcetimezone) $datetimeobj->setTimezone(new DateTimeZone($forcetimezone)); // (add timezone relative to the date entered)
  1972. $arrayinfo = array(
  1973. 'year'=>((int) date_format($datetimeobj, 'Y')),
  1974. 'mon'=>((int) date_format($datetimeobj, 'm')),
  1975. 'mday'=>((int) date_format($datetimeobj, 'd')),
  1976. 'wday'=>((int) date_format($datetimeobj, 'w')),
  1977. 'yday'=>((int) date_format($datetimeobj, 'z')),
  1978. 'hours'=>((int) date_format($datetimeobj, 'H')),
  1979. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  1980. 'seconds'=>((int) date_format($datetimeobj, 's')),
  1981. '0'=>$timestamp
  1982. );
  1983. } else {
  1984. // PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1985. $usealternatemethod = false;
  1986. if ($timestamp <= 0) $usealternatemethod = true; // <= 1970
  1987. if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038
  1988. if ($usealternatemethod)
  1989. {
  1990. $arrayinfo = adodb_getdate($timestamp, $fast);
  1991. } else {
  1992. $arrayinfo = getdate($timestamp);
  1993. }
  1994. }
  1995. return $arrayinfo;
  1996. }
  1997. /**
  1998. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  1999. * Replace function mktime not available under Windows if year < 1970
  2000. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2001. *
  2002. * @param int $hour Hour (can be -1 for undefined)
  2003. * @param int $minute Minute (can be -1 for undefined)
  2004. * @param int $second Second (can be -1 for undefined)
  2005. * @param int $month Month (1 to 12)
  2006. * @param int $day Day (1 to 31)
  2007. * @param int $year Year
  2008. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2009. * False or 0 or 'server' = local to server TZ
  2010. * 'user' = local to user TZ
  2011. * 'tz,TimeZone' = use specified timezone
  2012. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2013. * @return int|string Date as a timestamp, '' or false if error
  2014. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2015. */
  2016. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $check = 1)
  2017. {
  2018. global $conf;
  2019. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2020. // Clean parameters
  2021. if ($hour == -1 || empty($hour)) $hour = 0;
  2022. if ($minute == -1 || empty($minute)) $minute = 0;
  2023. if ($second == -1 || empty($second)) $second = 0;
  2024. // Check parameters
  2025. if ($check)
  2026. {
  2027. if (!$month || !$day) return '';
  2028. if ($day > 31) return '';
  2029. if ($month > 12) return '';
  2030. if ($hour < 0 || $hour > 24) return '';
  2031. if ($minute < 0 || $minute > 60) return '';
  2032. if ($second < 0 || $second > 60) return '';
  2033. }
  2034. if (empty($gm) || $gm === 'server')
  2035. {
  2036. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2037. $localtz = new DateTimeZone($default_timezone);
  2038. } elseif ($gm === 'user')
  2039. {
  2040. // We use dol_tz_string first because it is more reliable.
  2041. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2042. try {
  2043. $localtz = new DateTimeZone($default_timezone);
  2044. } catch (Exception $e)
  2045. {
  2046. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2047. $default_timezone = @date_default_timezone_get();
  2048. }
  2049. } elseif (strrpos($gm, "tz,") !== false)
  2050. {
  2051. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2052. try {
  2053. $localtz = new DateTimeZone($timezone);
  2054. } catch (Exception $e)
  2055. {
  2056. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2057. }
  2058. }
  2059. if (empty($localtz)) {
  2060. $localtz = new DateTimeZone('UTC');
  2061. }
  2062. //var_dump($localtz);
  2063. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2064. $dt = new DateTime(null, $localtz);
  2065. $dt->setDate((int) $year, (int) $month, (int) $day);
  2066. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2067. $date = $dt->getTimestamp(); // should include daylight saving time
  2068. //var_dump($date);
  2069. return $date;
  2070. }
  2071. /**
  2072. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2073. *
  2074. * @param string $mode 'gmt' => we return GMT timestamp,
  2075. * 'tzserver' => we add the PHP server timezone
  2076. * 'tzref' => we add the company timezone
  2077. * 'tzuser' => we add the user timezone
  2078. * @return int $date Timestamp
  2079. */
  2080. function dol_now($mode = 'gmt')
  2081. {
  2082. $ret = 0;
  2083. if ($mode == 'gmt') $ret = time(); // Time for now at greenwich.
  2084. elseif ($mode == 'tzserver') // Time for now with PHP server timezone added
  2085. {
  2086. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2087. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2088. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2089. } /*elseif ($mode == 'tzref') // Time for now with parent company timezone is added
  2090. {
  2091. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2092. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2093. $ret=dol_now('gmt')+($tzsecond*3600);
  2094. }*/
  2095. elseif ($mode == 'tzuser') // Time for now with user timezone added
  2096. {
  2097. //print 'time: '.time();
  2098. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2099. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2100. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2101. }
  2102. return $ret;
  2103. }
  2104. /**
  2105. * Return string with formated size
  2106. *
  2107. * @param int $size Size to print
  2108. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2109. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2110. * @return string Link
  2111. */
  2112. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2113. {
  2114. global $conf, $langs;
  2115. $level = 1024;
  2116. if (!empty($conf->dol_optimize_smallscreen)) $shortunit = 1;
  2117. // Set value text
  2118. if (empty($shortvalue) || $size < ($level * 10))
  2119. {
  2120. $ret = $size;
  2121. $textunitshort = $langs->trans("b");
  2122. $textunitlong = $langs->trans("Bytes");
  2123. } else {
  2124. $ret = round($size / $level, 0);
  2125. $textunitshort = $langs->trans("Kb");
  2126. $textunitlong = $langs->trans("KiloBytes");
  2127. }
  2128. // Use long or short text unit
  2129. if (empty($shortunit)) { $ret .= ' '.$textunitlong; } else { $ret .= ' '.$textunitshort; }
  2130. return $ret;
  2131. }
  2132. /**
  2133. * Show Url link
  2134. *
  2135. * @param string $url Url to show
  2136. * @param string $target Target for link
  2137. * @param int $max Max number of characters to show
  2138. * @param int $withpicto With picto
  2139. * @return string HTML Link
  2140. */
  2141. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2142. {
  2143. global $langs;
  2144. if (empty($url)) return '';
  2145. $link = '<a href="';
  2146. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2147. $link .= $url;
  2148. $link .= '"';
  2149. if ($target) $link .= ' target="'.$target.'"';
  2150. $link .= '>';
  2151. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2152. $link .= dol_trunc($url, $max);
  2153. $link .= '</a>';
  2154. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2155. }
  2156. /**
  2157. * Show EMail link formatted for HTML output.
  2158. *
  2159. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2160. * @param int $cid Id of contact if known
  2161. * @param int $socid Id of third party if known
  2162. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2163. * @param int $max Max number of characters to show
  2164. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2165. * @param int $withpicto Show picto
  2166. * @return string HTML Link
  2167. */
  2168. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2169. {
  2170. global $conf, $user, $langs, $hookmanager;
  2171. $newemail = dol_escape_htmltag($email);
  2172. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0;
  2173. if (empty($email)) return '&nbsp;';
  2174. if (!empty($addlink))
  2175. {
  2176. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2177. if (!preg_match('/^mailto:/i', $email)) $newemail .= 'mailto:';
  2178. $newemail .= $email;
  2179. $newemail .= '">';
  2180. $newemail .= dol_trunc($email, $max);
  2181. $newemail .= '</a>';
  2182. if ($showinvalid && !isValidEmail($email))
  2183. {
  2184. $langs->load("errors");
  2185. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2186. }
  2187. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2188. {
  2189. $type = 'AC_EMAIL'; $link = '';
  2190. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $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>';
  2191. if ($link) $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2192. }
  2193. } else {
  2194. if ($showinvalid && !isValidEmail($email))
  2195. {
  2196. $langs->load("errors");
  2197. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2198. }
  2199. }
  2200. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2201. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2202. //$rep .= '</div>';
  2203. if ($hookmanager) {
  2204. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2205. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2206. if ($reshook > 0) {
  2207. $rep = '';
  2208. }
  2209. $rep .= $hookmanager->resPrint;
  2210. }
  2211. return $rep;
  2212. }
  2213. /**
  2214. * Get array of social network dictionary
  2215. *
  2216. * @return array Array of Social Networks Dictionary
  2217. */
  2218. function getArrayOfSocialNetworks()
  2219. {
  2220. global $conf, $db;
  2221. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2222. $sql .= " WHERE entity=".$conf->entity;
  2223. $socialnetworks = array();
  2224. $resql = $db->query($sql);
  2225. if ($resql) {
  2226. while ($obj = $db->fetch_object($resql)) {
  2227. $socialnetworks[$obj->code] = array(
  2228. 'rowid' => $obj->rowid,
  2229. 'label' => $obj->label,
  2230. 'url' => $obj->url,
  2231. 'icon' => $obj->icon,
  2232. 'active' => $obj->active,
  2233. );
  2234. }
  2235. }
  2236. return $socialnetworks;
  2237. }
  2238. /**
  2239. * Show social network link
  2240. *
  2241. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2242. * @param int $cid Id of contact if known
  2243. * @param int $socid Id of third party if known
  2244. * @param string $type 'skype','facebook',...
  2245. * @param array $dictsocialnetworks socialnetworks availables
  2246. * @return string HTML Link
  2247. */
  2248. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2249. {
  2250. global $conf, $user, $langs;
  2251. $htmllink = $value;
  2252. if (empty($value)) return '&nbsp;';
  2253. if (!empty($type)) {
  2254. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2255. // TODO use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2256. $htmllink .= img_picto($langs->trans(dol_ucfirst($type)), $type.'.png', '', false, 0, 0, '', 'paddingright', 0);
  2257. if ($type == 'skype') {
  2258. $htmllink .= $value;
  2259. $htmllink .= '&nbsp;';
  2260. $htmllink .= '<a href="skype:';
  2261. $htmllink .= $value;
  2262. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2263. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2264. $htmllink .= '</a><a href="skype:';
  2265. $htmllink .= $value;
  2266. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2267. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2268. $htmllink .= '</a>';
  2269. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2270. $addlink = 'AC_SKYPE';
  2271. $link = '';
  2272. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $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>';
  2273. $htmllink .= ($link ? ' '.$link : '');
  2274. }
  2275. } else {
  2276. if (!empty($dictsocialnetworks[$type]['url'])) {
  2277. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2278. $htmllink .= '&nbsp;<a href="'.$link.'" target="_blank">'.$value.'</a>';
  2279. } else {
  2280. $htmllink .= $value;
  2281. }
  2282. }
  2283. $htmllink .= '</div>';
  2284. } else {
  2285. $langs->load("errors");
  2286. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2287. }
  2288. return $htmllink;
  2289. }
  2290. /**
  2291. * Format phone numbers according to country
  2292. *
  2293. * @param string $phone Phone number to format
  2294. * @param string $countrycode Country code to use for formatting
  2295. * @param int $cid Id of contact if known
  2296. * @param int $socid Id of third party if known
  2297. * @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)
  2298. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2299. * @param string $withpicto Show picto
  2300. * @param string $titlealt Text to show on alt
  2301. * @param int $adddivfloat Add div float around phone.
  2302. * @return string Formated phone number
  2303. */
  2304. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2305. {
  2306. global $conf, $user, $langs, $mysoc, $hookmanager;
  2307. // Clean phone parameter
  2308. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2309. if (empty($phone)) { return ''; }
  2310. if (!empty($conf->global->MAIN_PHONE_SEPAR)) $separ = $conf->global->MAIN_PHONE_SEPAR;
  2311. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2312. // Short format for small screens
  2313. if ($conf->dol_optimize_smallscreen) $separ = '';
  2314. $newphone = $phone;
  2315. if (strtoupper($countrycode) == "FR")
  2316. {
  2317. // France
  2318. if (dol_strlen($phone) == 10) {
  2319. $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);
  2320. } elseif (dol_strlen($phone) == 7)
  2321. {
  2322. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2323. } elseif (dol_strlen($phone) == 9)
  2324. {
  2325. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2326. } elseif (dol_strlen($phone) == 11)
  2327. {
  2328. $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);
  2329. } elseif (dol_strlen($phone) == 12)
  2330. {
  2331. $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);
  2332. }
  2333. } elseif (strtoupper($countrycode) == "CA")
  2334. {
  2335. if (dol_strlen($phone) == 10) {
  2336. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2337. }
  2338. } elseif (strtoupper($countrycode) == "PT")
  2339. {//Portugal
  2340. if (dol_strlen($phone) == 13)
  2341. {//ex: +351_ABC_DEF_GHI
  2342. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2343. }
  2344. } elseif (strtoupper($countrycode) == "SR")
  2345. {//Suriname
  2346. if (dol_strlen($phone) == 10)
  2347. {//ex: +597_ABC_DEF
  2348. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2349. } elseif (dol_strlen($phone) == 11)
  2350. {//ex: +597_ABC_DEFG
  2351. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2352. }
  2353. } elseif (strtoupper($countrycode) == "DE")
  2354. {//Allemagne
  2355. if (dol_strlen($phone) == 14)
  2356. {//ex: +49_ABCD_EFGH_IJK
  2357. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2358. } elseif (dol_strlen($phone) == 13)
  2359. {//ex: +49_ABC_DEFG_HIJ
  2360. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2361. }
  2362. } elseif (strtoupper($countrycode) == "ES")
  2363. {//Espagne
  2364. if (dol_strlen($phone) == 12)
  2365. {//ex: +34_ABC_DEF_GHI
  2366. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2367. }
  2368. } elseif (strtoupper($countrycode) == "BF")
  2369. {// Burkina Faso
  2370. if (dol_strlen($phone) == 12)
  2371. {//ex : +22 A BC_DE_FG_HI
  2372. $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);
  2373. }
  2374. } elseif (strtoupper($countrycode) == "RO")
  2375. {// Roumanie
  2376. if (dol_strlen($phone) == 12)
  2377. {//ex : +40 AB_CDE_FG_HI
  2378. $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);
  2379. }
  2380. } elseif (strtoupper($countrycode) == "TR")
  2381. {//Turquie
  2382. if (dol_strlen($phone) == 13)
  2383. {//ex : +90 ABC_DEF_GHIJ
  2384. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2385. }
  2386. } elseif (strtoupper($countrycode) == "US")
  2387. {//Etat-Unis
  2388. if (dol_strlen($phone) == 12)
  2389. {//ex: +1 ABC_DEF_GHIJ
  2390. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2391. }
  2392. } elseif (strtoupper($countrycode) == "MX")
  2393. {//Mexique
  2394. if (dol_strlen($phone) == 12)
  2395. {//ex: +52 ABCD_EFG_HI
  2396. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2397. } elseif (dol_strlen($phone) == 11)
  2398. {//ex: +52 AB_CD_EF_GH
  2399. $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);
  2400. } elseif (dol_strlen($phone) == 13)
  2401. {//ex: +52 ABC_DEF_GHIJ
  2402. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2403. }
  2404. } elseif (strtoupper($countrycode) == "ML")
  2405. {//Mali
  2406. if (dol_strlen($phone) == 12)
  2407. {//ex: +223 AB_CD_EF_GH
  2408. $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);
  2409. }
  2410. } elseif (strtoupper($countrycode) == "TH")
  2411. {//Thaïlande
  2412. if (dol_strlen($phone) == 11)
  2413. {//ex: +66_ABC_DE_FGH
  2414. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2415. } elseif (dol_strlen($phone) == 12)
  2416. {//ex: +66_A_BCD_EF_GHI
  2417. $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);
  2418. }
  2419. } elseif (strtoupper($countrycode) == "MU")
  2420. {
  2421. //Maurice
  2422. if (dol_strlen($phone) == 11)
  2423. {//ex: +230_ABC_DE_FG
  2424. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2425. } elseif (dol_strlen($phone) == 12)
  2426. {//ex: +230_ABCD_EF_GH
  2427. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2428. }
  2429. } elseif (strtoupper($countrycode) == "ZA")
  2430. {//Afrique du sud
  2431. if (dol_strlen($phone) == 12)
  2432. {//ex: +27_AB_CDE_FG_HI
  2433. $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);
  2434. }
  2435. } elseif (strtoupper($countrycode) == "SY")
  2436. {//Syrie
  2437. if (dol_strlen($phone) == 12)
  2438. {//ex: +963_AB_CD_EF_GH
  2439. $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);
  2440. } elseif (dol_strlen($phone) == 13)
  2441. {//ex: +963_AB_CD_EF_GHI
  2442. $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);
  2443. }
  2444. } elseif (strtoupper($countrycode) == "AE")
  2445. {//Emirats Arabes Unis
  2446. if (dol_strlen($phone) == 12)
  2447. {//ex: +971_ABC_DEF_GH
  2448. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2449. } elseif (dol_strlen($phone) == 13)
  2450. {//ex: +971_ABC_DEF_GHI
  2451. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2452. } elseif (dol_strlen($phone) == 14)
  2453. {//ex: +971_ABC_DEF_GHIK
  2454. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2455. }
  2456. } elseif (strtoupper($countrycode) == "DZ")
  2457. {//Algérie
  2458. if (dol_strlen($phone) == 13)
  2459. {//ex: +213_ABC_DEF_GHI
  2460. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2461. }
  2462. } elseif (strtoupper($countrycode) == "BE")
  2463. {//Belgique
  2464. if (dol_strlen($phone) == 11)
  2465. {//ex: +32_ABC_DE_FGH
  2466. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2467. } elseif (dol_strlen($phone) == 12)
  2468. {//ex: +32_ABC_DEF_GHI
  2469. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2470. }
  2471. } elseif (strtoupper($countrycode) == "PF")
  2472. {//Polynésie française
  2473. if (dol_strlen($phone) == 12)
  2474. {//ex: +689_AB_CD_EF_GH
  2475. $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);
  2476. }
  2477. } elseif (strtoupper($countrycode) == "CO")
  2478. {//Colombie
  2479. if (dol_strlen($phone) == 13)
  2480. {//ex: +57_ABC_DEF_GH_IJ
  2481. $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);
  2482. }
  2483. } elseif (strtoupper($countrycode) == "JO")
  2484. {//Jordanie
  2485. if (dol_strlen($phone) == 12)
  2486. {//ex: +962_A_BCD_EF_GH
  2487. $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);
  2488. }
  2489. } elseif (strtoupper($countrycode) == "JM")
  2490. {//Jamaïque
  2491. if (dol_strlen($newphone) == 12)
  2492. {//ex: +1867_ABC_DEFG
  2493. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2494. }
  2495. } elseif (strtoupper($countrycode) == "MG")
  2496. {//Madagascar
  2497. if (dol_strlen($phone) == 13)
  2498. {//ex: +261_AB_CD_EF_GHI
  2499. $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);
  2500. }
  2501. } elseif (strtoupper($countrycode) == "GB")
  2502. {//Royaume uni
  2503. if (dol_strlen($phone) == 13)
  2504. {//ex: +44_ABCD_EFG_HIJ
  2505. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2506. }
  2507. } elseif (strtoupper($countrycode) == "CH")
  2508. {//Suisse
  2509. if (dol_strlen($phone) == 12)
  2510. {//ex: +41_AB_CDE_FG_HI
  2511. $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);
  2512. } elseif (dol_strlen($phone) == 15)
  2513. {// +41_AB_CDE_FGH_IJKL
  2514. $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);
  2515. }
  2516. } elseif (strtoupper($countrycode) == "TN")
  2517. {//Tunisie
  2518. if (dol_strlen($phone) == 12)
  2519. {//ex: +216_AB_CDE_FGH
  2520. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2521. }
  2522. } elseif (strtoupper($countrycode) == "GF")
  2523. {//Guyane francaise
  2524. if (dol_strlen($phone) == 13)
  2525. {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2526. $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);
  2527. }
  2528. } elseif (strtoupper($countrycode) == "GP")
  2529. {//Guadeloupe
  2530. if (dol_strlen($phone) == 13)
  2531. {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2532. $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);
  2533. }
  2534. } elseif (strtoupper($countrycode) == "MQ")
  2535. {//Martinique
  2536. if (dol_strlen($phone) == 13)
  2537. {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2538. $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);
  2539. }
  2540. } elseif (strtoupper($countrycode) == "IT")
  2541. {//Italie
  2542. if (dol_strlen($phone) == 12)
  2543. {//ex: +39_ABC_DEF_GHI
  2544. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2545. } elseif (dol_strlen($phone) == 13)
  2546. {//ex: +39_ABC_DEF_GH_IJ
  2547. $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);
  2548. }
  2549. } elseif (strtoupper($countrycode) == "AU")
  2550. {
  2551. //Australie
  2552. if (dol_strlen($phone) == 12)
  2553. {
  2554. //ex: +61_A_BCDE_FGHI
  2555. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2556. }
  2557. }
  2558. if (!empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2559. {
  2560. if ($conf->browser->layout == 'phone' || (!empty($conf->clicktodial->enabled) && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) // If phone or option for, we use link of phone
  2561. {
  2562. $newphoneform = $newphone;
  2563. $newphone = '<a href="tel:'.$phone.'"';
  2564. $newphone .= '>'.$newphoneform.'</a>';
  2565. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  2566. {
  2567. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  2568. // Define urlmask
  2569. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2570. if (!empty($conf->global->CLICKTODIAL_URL)) $urlmask = $conf->global->CLICKTODIAL_URL;
  2571. if (!empty($user->clicktodial_url)) $urlmask = $user->clicktodial_url;
  2572. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2573. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2574. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2575. // This line is for backward compatibility
  2576. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2577. // Thoose lines are for substitution
  2578. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2579. '__PHONETO__'=>urlencode($phone),
  2580. '__LOGIN__'=>$clicktodial_login,
  2581. '__PASS__'=>$clicktodial_password);
  2582. $url = make_substitutions($url, $substitarray);
  2583. $newphonesav = $newphone;
  2584. $newphone = '<a href="'.$url.'"';
  2585. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone .= ' target="_blank"';
  2586. $newphone .= '>'.$newphonesav.'</a>';
  2587. }
  2588. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2589. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2590. {
  2591. $type = 'AC_TEL'; $link = '';
  2592. if ($addlink == 'AC_FAX') $type = 'AC_FAX';
  2593. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  2594. if ($link) $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2595. }
  2596. }
  2597. if (empty($titlealt))
  2598. {
  2599. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2600. }
  2601. $rep = '';
  2602. if ($hookmanager) {
  2603. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2604. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2605. $rep .= $hookmanager->resPrint;
  2606. }
  2607. if (empty($reshook))
  2608. {
  2609. $picto = '';
  2610. if ($withpicto) {
  2611. if ($withpicto == 'fax') {
  2612. $picto = 'phoning_fax';
  2613. } elseif ($withpicto == 'phone') {
  2614. $picto = 'phoning';
  2615. } elseif ($withpicto == 'mobile') {
  2616. $picto = 'phoning_mobile';
  2617. } else {
  2618. $picto = '';
  2619. }
  2620. }
  2621. if ($adddivfloat) $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2622. else $rep .= '<span style="margin-right: 10px;">';
  2623. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2624. if ($adddivfloat) $rep .= '</div>';
  2625. else $rep .= '</span>';
  2626. }
  2627. return $rep;
  2628. }
  2629. /**
  2630. * Return an IP formated to be shown on screen
  2631. *
  2632. * @param string $ip IP
  2633. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2634. * @return string Formated IP, with country if GeoIP module is enabled
  2635. */
  2636. function dol_print_ip($ip, $mode = 0)
  2637. {
  2638. global $conf, $langs;
  2639. $ret = '';
  2640. if (empty($mode)) $ret .= $ip;
  2641. if ($mode != 2)
  2642. {
  2643. $countrycode = dolGetCountryCodeFromIp($ip);
  2644. if ($countrycode) // If success, countrycode is us, fr, ...
  2645. {
  2646. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  2647. {
  2648. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2649. } else $ret .= ' ('.$countrycode.')';
  2650. } else {
  2651. // Nothing
  2652. }
  2653. }
  2654. return $ret;
  2655. }
  2656. /**
  2657. * Return the IP of remote user.
  2658. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2659. * Then HTTP_CLIENT_IP if defined (rare)
  2660. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2661. *
  2662. * @return string Ip of remote user.
  2663. */
  2664. function getUserRemoteIP()
  2665. {
  2666. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  2667. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  2668. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  2669. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been forged by client
  2670. } else {
  2671. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  2672. }
  2673. } else {
  2674. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  2675. }
  2676. } else {
  2677. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  2678. }
  2679. return $ip;
  2680. }
  2681. /**
  2682. * Return if we are using a HTTPS connexion
  2683. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  2684. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  2685. * Then HTTP_X_FORWARDED_SSL
  2686. *
  2687. * @return boolean True if user is using HTTPS
  2688. */
  2689. function isHTTPS()
  2690. {
  2691. $isSecure = false;
  2692. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  2693. $isSecure = true;
  2694. }
  2695. 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') {
  2696. $isSecure = true;
  2697. }
  2698. return $isSecure;
  2699. }
  2700. /**
  2701. * Return a country code from IP. Empty string if not found.
  2702. *
  2703. * @param string $ip IP
  2704. * @return string Country code ('us', 'fr', ...)
  2705. */
  2706. function dolGetCountryCodeFromIp($ip)
  2707. {
  2708. global $conf;
  2709. $countrycode = '';
  2710. if (!empty($conf->geoipmaxmind->enabled))
  2711. {
  2712. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2713. //$ip='24.24.24.24';
  2714. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  2715. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2716. $geoip = new DolGeoIP('country', $datafile);
  2717. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2718. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2719. }
  2720. return $countrycode;
  2721. }
  2722. /**
  2723. * Return country code for current user.
  2724. * If software is used inside a local network, detection may fails (we need a public ip)
  2725. *
  2726. * @return string Country code (fr, es, it, us, ...)
  2727. */
  2728. function dol_user_country()
  2729. {
  2730. global $conf, $langs, $user;
  2731. //$ret=$user->xxx;
  2732. $ret = '';
  2733. if (!empty($conf->geoipmaxmind->enabled))
  2734. {
  2735. $ip = getUserRemoteIP();
  2736. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2737. //$ip='24.24.24.24';
  2738. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2739. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2740. $geoip = new DolGeoIP('country', $datafile);
  2741. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2742. $ret = $countrycode;
  2743. }
  2744. return $ret;
  2745. }
  2746. /**
  2747. * Format address string
  2748. *
  2749. * @param string $address Address string, already formatted with dol_format_address()
  2750. * @param int $htmlid Html ID (for example 'gmap')
  2751. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  2752. * @param int $id Id of object
  2753. * @param int $noprint No output. Result is the function return
  2754. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2755. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2756. * @see dol_format_address()
  2757. */
  2758. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  2759. {
  2760. global $conf, $user, $langs, $hookmanager;
  2761. $out = '';
  2762. if ($address)
  2763. {
  2764. if ($hookmanager) {
  2765. $parameters = array('element' => $element, 'id' => $id);
  2766. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2767. $out .= $hookmanager->resPrint;
  2768. }
  2769. if (empty($reshook))
  2770. {
  2771. if (empty($charfornl)) $out .= nl2br($address);
  2772. else $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  2773. // TODO Remove this block, we can add this using the hook now
  2774. $showgmap = $showomap = 0;
  2775. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap = 1;
  2776. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap = 1;
  2777. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap = 1;
  2778. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap = 1;
  2779. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap = 1;
  2780. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap = 1;
  2781. if ($showgmap)
  2782. {
  2783. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  2784. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2785. }
  2786. if ($showomap)
  2787. {
  2788. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  2789. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2790. }
  2791. }
  2792. }
  2793. if ($noprint) return $out;
  2794. else print $out;
  2795. }
  2796. /**
  2797. * Return true if email syntax is ok.
  2798. *
  2799. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  2800. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2801. * @return boolean true if email syntax is OK, false if KO or empty string
  2802. * @see isValidMXRecord()
  2803. */
  2804. function isValidEmail($address, $acceptsupervisorkey = 0)
  2805. {
  2806. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2807. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2808. return false;
  2809. }
  2810. /**
  2811. * Return if the domain name has a valid MX record.
  2812. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  2813. *
  2814. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  2815. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  2816. * @see isValidEmail()
  2817. */
  2818. function isValidMXRecord($domain)
  2819. {
  2820. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr'))
  2821. {
  2822. if (!checkdnsrr(idn_to_ascii($domain), 'MX'))
  2823. {
  2824. return 0;
  2825. }
  2826. if (function_exists('getmxrr'))
  2827. {
  2828. $mxhosts = array();
  2829. $weight = array();
  2830. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  2831. if (count($mxhosts) > 1) return 1;
  2832. if (count($mxhosts) == 1 && !empty($mxhosts[0])) return 1;
  2833. return 0;
  2834. }
  2835. }
  2836. return -1;
  2837. }
  2838. /**
  2839. * Return true if phone number syntax is ok
  2840. * TODO Decide what to do with this
  2841. *
  2842. * @param string $phone phone (Ex: "0601010101")
  2843. * @return boolean true if phone syntax is OK, false if KO or empty string
  2844. */
  2845. function isValidPhone($phone)
  2846. {
  2847. return true;
  2848. }
  2849. /**
  2850. * Make a strlen call. Works even if mbstring module not enabled
  2851. *
  2852. * @param string $string String to calculate length
  2853. * @param string $stringencoding Encoding of string
  2854. * @return int Length of string
  2855. */
  2856. function dol_strlen($string, $stringencoding = 'UTF-8')
  2857. {
  2858. if (function_exists('mb_strlen')) return mb_strlen($string, $stringencoding);
  2859. else return strlen($string);
  2860. }
  2861. /**
  2862. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  2863. *
  2864. * @param string $string String to scan
  2865. * @param string $start Start position
  2866. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  2867. * @param string $stringencoding Page code used for input string encoding
  2868. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  2869. * @return string substring
  2870. */
  2871. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  2872. {
  2873. global $langs;
  2874. if (empty($stringencoding)) $stringencoding = $langs->charset_output;
  2875. $ret = '';
  2876. if (empty($trunconbytes))
  2877. {
  2878. if (function_exists('mb_substr'))
  2879. {
  2880. $ret = mb_substr($string, $start, $length, $stringencoding);
  2881. } else {
  2882. $ret = substr($string, $start, $length);
  2883. }
  2884. } else {
  2885. if (function_exists('mb_strcut'))
  2886. {
  2887. $ret = mb_strcut($string, $start, $length, $stringencoding);
  2888. } else {
  2889. $ret = substr($string, $start, $length);
  2890. }
  2891. }
  2892. return $ret;
  2893. }
  2894. /**
  2895. * Truncate a string to a particular length adding '...' if string larger than length.
  2896. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2897. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2898. *
  2899. * @param string $string String to truncate
  2900. * @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 or max+2 or max+3 so it does not worse to replace with ...)
  2901. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  2902. * @param string $stringencoding Tell what is source string encoding
  2903. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2904. * @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)
  2905. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  2906. */
  2907. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  2908. {
  2909. global $conf;
  2910. if ($size == 0 || !empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2911. if (empty($stringencoding)) $stringencoding = 'UTF-8';
  2912. // reduce for small screen
  2913. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) $size = round($size / 3);
  2914. // We go always here
  2915. if ($trunc == 'right')
  2916. {
  2917. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2918. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
  2919. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...');
  2920. else //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  2921. return $string;
  2922. } elseif ($trunc == 'middle')
  2923. {
  2924. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2925. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1))
  2926. {
  2927. $size1 = round($size / 2);
  2928. $size2 = round($size / 2);
  2929. return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  2930. } else return $string;
  2931. } elseif ($trunc == 'left')
  2932. {
  2933. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2934. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
  2935. return '...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  2936. else return $string;
  2937. } elseif ($trunc == 'wrap')
  2938. {
  2939. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2940. if (dol_strlen($newstring, $stringencoding) > ($size + 1))
  2941. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  2942. else return $string;
  2943. } else return 'BadParam3CallingDolTrunc';
  2944. }
  2945. /**
  2946. * Show picto whatever it's its name (generic function)
  2947. *
  2948. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  2949. * @param string $picto Name of image file to show ('filenew', ...)
  2950. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2951. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2952. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2953. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2954. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2955. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  2956. * @param int $srconly Return only content of the src attribute of img.
  2957. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2958. * @param string $alt Force alt for bind people
  2959. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  2960. * @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.
  2961. * @return string Return img tag
  2962. * @see img_object(), img_picto_common()
  2963. */
  2964. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  2965. {
  2966. global $conf, $langs;
  2967. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2968. $url = DOL_URL_ROOT;
  2969. $theme = isset($conf->theme) ? $conf->theme : null;
  2970. $path = 'theme/'.$theme;
  2971. // Define fullpathpicto to use into src
  2972. if ($pictoisfullpath) {
  2973. // Clean parameters
  2974. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  2975. $picto .= '.png';
  2976. }
  2977. $fullpathpicto = $picto;
  2978. $reg = array();
  2979. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2980. $morecss .= ($morecss ? ' ' : '').$reg[1];
  2981. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  2982. }
  2983. } else {
  2984. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  2985. if (empty($srconly) && in_array($pictowithouttext, array(
  2986. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  2987. 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'bank_account', 'barcode', 'bank', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'building',
  2988. 'cash-register', 'category', 'check', 'clock', 'close_title', 'company', 'contact', 'contract', 'cron', 'cubes',
  2989. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'edit', 'ellipsis-h', 'email', 'eraser', 'external-link-alt', 'external-link-square-alt',
  2990. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title', 'group',
  2991. 'help', 'holiday',
  2992. 'intervention', 'label', 'language', 'link', 'list', 'listlight', 'lot',
  2993. 'map-marker-alt', 'member', 'money-bill-alt', 'mrp', 'note', 'next',
  2994. 'object_accounting', 'object_account', 'object_accountline', 'object_action', 'object_barcode', 'object_bill', 'object_billa', 'object_billd', 'object_bom',
  2995. 'object_category', 'object_conversation', 'object_bookmark', 'object_bug', 'object_dolly', 'object_dollyrevert', 'object_generic', 'object_folder',
  2996. 'object_list-alt', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser',
  2997. 'object_cash-register', 'object_company', 'object_contact', 'object_contract', 'object_donation', 'object_dynamicprice',
  2998. 'object_globe', 'object_holiday', 'object_hrm', 'object_invoice', 'object_intervention', 'object_label',
  2999. 'object_margin', 'object_money-bill-alt', 'object_multicurrency', 'object_order', 'object_payment',
  3000. 'object_lot', 'object_mrp', 'object_other',
  3001. 'object_payment', 'object_pdf', 'object_product', 'object_propal',
  3002. 'object_paragraph', 'object_poll', 'object_printer', 'object_project', 'object_projectpub', 'object_propal', 'object_resource', 'object_rss', 'object_projecttask',
  3003. 'object_recruitmentjobposition', 'object_recruitmentcandidature',
  3004. 'object_shipment', 'object_share-alt', 'object_supplier_invoice', 'object_supplier_invoicea', 'object_supplier_invoiced', 'object_supplier_order', 'object_supplier_proposal', 'object_service', 'object_stock',
  3005. 'object_technic', 'object_ticket', 'object_trip', 'object_user', 'object_group', 'object_member',
  3006. 'object_phoning', 'object_phoning_mobile', 'object_phoning_fax', 'object_email', 'object_website',
  3007. 'off', 'on', 'order',
  3008. 'paiment', 'play', 'pdf', 'playdisabled', 'previous', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip',
  3009. 'setup', 'share-alt', 'sign-out', 'split', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3010. 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3011. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3012. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3013. 'payment', 'pencil-ruler', 'preview', 'project', 'projectpub', 'refresh', 'supplier_invoice', 'ticket',
  3014. 'error', 'warning',
  3015. 'recruitmentcandidature', 'recruitmentjobposition', 'resource',
  3016. 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3017. 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda'
  3018. )
  3019. )) {
  3020. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3021. $fakey = $pictowithouttext;
  3022. $facolor = ''; $fasize = '';
  3023. $fa = 'fas';
  3024. if (in_array($pictowithouttext, array('clock', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3025. $fa = 'far';
  3026. }
  3027. if (in_array($pictowithouttext, array('black-tie', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3028. $fa = 'fab';
  3029. }
  3030. $arrayconvpictotofa = array(
  3031. 'account'=>'university', 'accountline'=>'receipt', 'accountancy'=>'money-check-alt', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book',
  3032. 'bank_account'=>'university', 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'supplier_invoicea'=>'file-excel', 'billd'=>'file-medical', 'supplier_invoiced'=>'file-medical', 'bom'=>'cubes',
  3033. 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'conversation'=>'comments', 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3034. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3035. 'accounting'=>'chart-line', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3036. 'hrm'=>'user-tie', 'margin'=>'calculator', 'members'=>'users', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3037. 'email'=>'at',
  3038. 'edit'=>'pencil-alt', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3039. 'generic'=>'file', 'holiday'=>'umbrella-beach', 'label'=>'layer-group',
  3040. 'member'=>'users', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3041. 'trip'=>'wallet', 'group'=>'users',
  3042. 'sign-out'=>'sign-out-alt',
  3043. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star',
  3044. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter',
  3045. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3046. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3047. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3048. 'other'=>'square',
  3049. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'preview'=>'binoculars', 'project'=>'sitemap', 'projectpub'=>'sitemap', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3050. 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell',
  3051. 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3052. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3053. 'refresh'=>'redo', 'resource'=>'laptop-house',
  3054. 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt',
  3055. 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3056. 'title_agenda'=>'calendar-alt',
  3057. 'uparrow'=>'mail-forward', 'vcard'=>'address-card',
  3058. 'jabber'=>'comment-o',
  3059. 'website'=>'globe-americas'
  3060. );
  3061. if ($pictowithouttext == 'off') {
  3062. $fakey = 'fa-square';
  3063. $fasize = '1.3em';
  3064. } elseif ($pictowithouttext == 'on') {
  3065. $fakey = 'fa-check-square';
  3066. $fasize = '1.3em';
  3067. } elseif ($pictowithouttext == 'listlight') {
  3068. $fakey = 'fa-download';
  3069. $marginleftonlyshort = 1;
  3070. } elseif ($pictowithouttext == 'printer') {
  3071. $fakey = 'fa-print';
  3072. $fasize = '1.2em';
  3073. } elseif ($pictowithouttext == 'note') {
  3074. $fakey = 'fa-sticky-note';
  3075. $marginleftonlyshort = 1;
  3076. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3077. $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');
  3078. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3079. if (preg_match('/selected/', $pictowithouttext)) $facolor = '#888';
  3080. $marginleftonlyshort = 1;
  3081. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3082. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3083. } else {
  3084. $fakey = 'fa-'.$pictowithouttext;
  3085. }
  3086. // Define $marginleftonlyshort
  3087. $arrayconvpictotomarginleftonly = array(
  3088. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3089. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_off',
  3090. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3091. );
  3092. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3093. $marginleftonlyshort = 0;
  3094. }
  3095. // Add CSS
  3096. $arrayconvpictotomorcess = array(
  3097. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account',
  3098. 'bank_account'=>'bg-infobox-bank_account',
  3099. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billd'=>'infobox-commande',
  3100. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'conversation'=>'infobox-contrat',
  3101. 'donation'=>'infobox-commande', 'dollyrevert'=>'flip', 'ecm'=>'infobox-action',
  3102. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3103. 'multicurrency'=>'infobox-bank_account',
  3104. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3105. 'order'=>'infobox-commande',
  3106. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3107. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4',
  3108. 'holiday'=>'infobox-holiday', 'invoice'=>'infobox-commande',
  3109. 'payment'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  3110. 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3111. 'resource'=>'infobox-action',
  3112. 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3113. 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3114. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3115. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3116. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3117. );
  3118. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3119. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3120. }
  3121. // Define $color
  3122. $arrayconvpictotocolor = array(
  3123. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3124. 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'dynamicprice'=>'#a69944',
  3125. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999',
  3126. 'dolly'=>'#a69944', 'dollyrevert'=>'#a69944', 'lot'=>'#a69944',
  3127. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'stock'=>'#a69944',
  3128. 'other'=>'#ddd',
  3129. 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'resize'=>'#444', 'rss'=>'#cba',
  3130. 'shipment'=>'#a69944', 'stats'=>'#444', 'switch_off'=>'#999', 'uparrow'=>'#555', 'globe-americas'=>'#aaa',
  3131. 'website'=>'#304'
  3132. );
  3133. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3134. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3135. }
  3136. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3137. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3138. $morestyle = '';
  3139. $reg = array();
  3140. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3141. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3142. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3143. }
  3144. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3145. $morestyle = $reg[1];
  3146. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3147. }
  3148. $moreatt = trim($moreatt);
  3149. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3150. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3151. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3152. $enabledisablehtml .= $titlealt;
  3153. }*/
  3154. $enabledisablehtml .= '</span>';
  3155. return $enabledisablehtml;
  3156. }
  3157. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3158. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3159. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3160. $path = $conf->global->MAIN_OVERWRITE_THEME_RES.'/theme/'.$conf->global->MAIN_OVERWRITE_THEME_RES; // To allow an external module to overwrite image resources whatever is activated theme
  3161. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3162. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3163. }
  3164. // If we ask an image into $url/$mymodule/img (instead of default path)
  3165. $regs = array();
  3166. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3167. $picto = $regs[1];
  3168. $path = $regs[2]; // $path is $mymodule
  3169. }
  3170. // Clean parameters
  3171. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3172. $picto .= '.png';
  3173. }
  3174. // If alt path are defined, define url where img file is, according to physical path
  3175. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3176. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3177. if ($type == 'main') {
  3178. continue;
  3179. }
  3180. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3181. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3182. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3183. break;
  3184. }
  3185. }
  3186. // $url is '' or '/custom', $path is current theme or
  3187. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3188. }
  3189. if ($srconly) {
  3190. return $fullpathpicto;
  3191. }
  3192. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3193. return '<img src="'.$fullpathpicto.'" alt="'.dol_escape_htmltag($alt).'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
  3194. }
  3195. /**
  3196. * Show a picto called object_picto (generic function)
  3197. *
  3198. * @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.
  3199. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3200. * For external modules use imagename@mymodule to search into directory "img" of module.
  3201. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3202. * @param int $pictoisfullpath If 1, image path is a full path
  3203. * @param int $srconly Return only content of the src attribute of img.
  3204. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3205. * @return string Return img tag
  3206. * @see img_picto(), img_picto_common()
  3207. */
  3208. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3209. {
  3210. if (strpos($picto, '^') === 0) return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3211. else return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3212. }
  3213. /**
  3214. * Show weather picto
  3215. *
  3216. * @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.
  3217. * @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).
  3218. * @param string $moreatt Add more attribute on img tag
  3219. * @param int $pictoisfullpath If 1, image path is a full path
  3220. * @param string $morecss More CSS
  3221. * @return string Return img tag
  3222. * @see img_object(), img_picto()
  3223. */
  3224. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3225. {
  3226. global $conf;
  3227. if (is_numeric($picto)) {
  3228. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3229. //$picto = $leveltopicto[$picto];
  3230. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3231. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3232. $picto .= '.png';
  3233. }
  3234. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3235. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3236. }
  3237. /**
  3238. * Show picto (generic function)
  3239. *
  3240. * @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.
  3241. * @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.
  3242. * @param string $moreatt Add more attribute on img tag
  3243. * @param int $pictoisfullpath If 1, image path is a full path
  3244. * @return string Return img tag
  3245. * @see img_object(), img_picto()
  3246. */
  3247. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  3248. {
  3249. global $conf;
  3250. if (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  3251. if ($pictoisfullpath) $path = $picto;
  3252. else {
  3253. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3254. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  3255. {
  3256. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3257. if (file_exists($themepath)) $path = $themepath;
  3258. }
  3259. }
  3260. return img_picto($titlealt, $path, $moreatt, 1);
  3261. }
  3262. /**
  3263. * Show logo action
  3264. *
  3265. * @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.
  3266. * @param string $numaction Action id or code to show
  3267. * @param string $picto Name of image file to show ('filenew', ...)
  3268. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3269. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3270. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3271. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3272. * @return string Return an img tag
  3273. */
  3274. function img_action($titlealt, $numaction, $picto = '')
  3275. {
  3276. global $langs;
  3277. if (empty($titlealt) || $titlealt == 'default')
  3278. {
  3279. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3280. $numaction = -1;
  3281. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3282. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3283. $numaction = 0;
  3284. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3285. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3286. $numaction = 1;
  3287. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3288. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3289. $numaction = 2;
  3290. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3291. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3292. $numaction = 3;
  3293. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3294. } else {
  3295. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3296. $numaction = 0;
  3297. }
  3298. }
  3299. if (!is_numeric($numaction)) $numaction = 0;
  3300. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3301. }
  3302. /**
  3303. * Show pdf logo
  3304. *
  3305. * @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.
  3306. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3307. * @return string Retourne tag img
  3308. */
  3309. function img_pdf($titlealt = 'default', $size = 3)
  3310. {
  3311. global $langs;
  3312. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  3313. return img_picto($titlealt, 'pdf'.$size.'.png');
  3314. }
  3315. /**
  3316. * Show logo +
  3317. *
  3318. * @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.
  3319. * @param string $other Add more attributes on img
  3320. * @return string Return tag img
  3321. */
  3322. function img_edit_add($titlealt = 'default', $other = '')
  3323. {
  3324. global $langs;
  3325. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  3326. return img_picto($titlealt, 'edit_add.png', $other);
  3327. }
  3328. /**
  3329. * Show logo -
  3330. *
  3331. * @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.
  3332. * @param string $other Add more attributes on img
  3333. * @return string Return tag img
  3334. */
  3335. function img_edit_remove($titlealt = 'default', $other = '')
  3336. {
  3337. global $langs;
  3338. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  3339. return img_picto($titlealt, 'edit_remove.png', $other);
  3340. }
  3341. /**
  3342. * Show logo editer/modifier fiche
  3343. *
  3344. * @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.
  3345. * @param integer $float If you have to put the style "float: right"
  3346. * @param string $other Add more attributes on img
  3347. * @return string Return tag img
  3348. */
  3349. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3350. {
  3351. global $langs;
  3352. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  3353. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3354. }
  3355. /**
  3356. * Show logo view card
  3357. *
  3358. * @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.
  3359. * @param integer $float If you have to put the style "float: right"
  3360. * @param string $other Add more attributes on img
  3361. * @return string Return tag img
  3362. */
  3363. function img_view($titlealt = 'default', $float = 0, $other = '')
  3364. {
  3365. global $langs;
  3366. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  3367. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3368. return img_picto($titlealt, 'view.png', $moreatt);
  3369. }
  3370. /**
  3371. * Show delete logo
  3372. *
  3373. * @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.
  3374. * @param string $other Add more attributes on img
  3375. * @param string $morecss More CSS
  3376. * @return string Retourne tag img
  3377. */
  3378. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3379. {
  3380. global $langs;
  3381. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  3382. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3383. }
  3384. /**
  3385. * Show printer logo
  3386. *
  3387. * @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.
  3388. * @param string $other Add more attributes on img
  3389. * @return string Retourne tag img
  3390. */
  3391. function img_printer($titlealt = "default", $other = '')
  3392. {
  3393. global $langs;
  3394. if ($titlealt == "default") $titlealt = $langs->trans("Print");
  3395. return img_picto($titlealt, 'printer.png', $other);
  3396. }
  3397. /**
  3398. * Show split logo
  3399. *
  3400. * @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.
  3401. * @param string $other Add more attributes on img
  3402. * @return string Retourne tag img
  3403. */
  3404. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3405. {
  3406. global $langs;
  3407. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  3408. return img_picto($titlealt, 'split.png', $other);
  3409. }
  3410. /**
  3411. * Show help logo with cursor "?"
  3412. *
  3413. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3414. * @param int|string $usealttitle Text to use as alt title
  3415. * @return string Return tag img
  3416. */
  3417. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3418. {
  3419. global $langs;
  3420. if ($usealttitle)
  3421. {
  3422. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  3423. else $usealttitle = $langs->trans('Info');
  3424. }
  3425. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3426. }
  3427. /**
  3428. * Show info logo
  3429. *
  3430. * @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.
  3431. * @return string Return img tag
  3432. */
  3433. function img_info($titlealt = 'default')
  3434. {
  3435. global $langs;
  3436. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  3437. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3438. }
  3439. /**
  3440. * Show warning logo
  3441. *
  3442. * @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.
  3443. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3444. * @param string $morecss Add more CSS
  3445. * @return string Return img tag
  3446. */
  3447. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3448. {
  3449. global $langs;
  3450. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  3451. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3452. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3453. }
  3454. /**
  3455. * Show error logo
  3456. *
  3457. * @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.
  3458. * @return string Return img tag
  3459. */
  3460. function img_error($titlealt = 'default')
  3461. {
  3462. global $langs;
  3463. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  3464. return img_picto($titlealt, 'error.png');
  3465. }
  3466. /**
  3467. * Show next logo
  3468. *
  3469. * @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.
  3470. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3471. * @return string Return img tag
  3472. */
  3473. function img_next($titlealt = 'default', $moreatt = '')
  3474. {
  3475. global $langs;
  3476. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  3477. //return img_picto($titlealt, 'next.png', $moreatt);
  3478. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3479. }
  3480. /**
  3481. * Show previous logo
  3482. *
  3483. * @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.
  3484. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3485. * @return string Return img tag
  3486. */
  3487. function img_previous($titlealt = 'default', $moreatt = '')
  3488. {
  3489. global $langs;
  3490. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  3491. //return img_picto($titlealt, 'previous.png', $moreatt);
  3492. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3493. }
  3494. /**
  3495. * Show down arrow logo
  3496. *
  3497. * @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.
  3498. * @param int $selected Selected
  3499. * @param string $moreclass Add more CSS classes
  3500. * @return string Return img tag
  3501. */
  3502. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3503. {
  3504. global $langs;
  3505. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  3506. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3507. }
  3508. /**
  3509. * Show top arrow logo
  3510. *
  3511. * @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.
  3512. * @param int $selected Selected
  3513. * @param string $moreclass Add more CSS classes
  3514. * @return string Return img tag
  3515. */
  3516. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3517. {
  3518. global $langs;
  3519. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  3520. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3521. }
  3522. /**
  3523. * Show left arrow logo
  3524. *
  3525. * @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.
  3526. * @param int $selected Selected
  3527. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3528. * @return string Return img tag
  3529. */
  3530. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3531. {
  3532. global $langs;
  3533. if ($titlealt == 'default') {
  3534. $titlealt = $langs->trans('Left');
  3535. }
  3536. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3537. }
  3538. /**
  3539. * Show right arrow logo
  3540. *
  3541. * @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.
  3542. * @param int $selected Selected
  3543. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3544. * @return string Return img tag
  3545. */
  3546. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3547. {
  3548. global $langs;
  3549. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  3550. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3551. }
  3552. /**
  3553. * Show tick logo if allowed
  3554. *
  3555. * @param string $allow Allow
  3556. * @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.
  3557. * @return string Return img tag
  3558. */
  3559. function img_allow($allow, $titlealt = 'default')
  3560. {
  3561. global $langs;
  3562. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  3563. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  3564. return '-';
  3565. }
  3566. /**
  3567. * Return image of a credit card according to its brand name
  3568. *
  3569. * @param string $brand Brand name of credit card
  3570. * @param string $morecss More CSS
  3571. * @return string Return img tag
  3572. */
  3573. function img_credit_card($brand, $morecss = null)
  3574. {
  3575. if (is_null($morecss)) $morecss = 'fa-2x';
  3576. if ($brand == 'visa' || $brand == 'Visa') {
  3577. $brand = 'cc-visa';
  3578. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  3579. $brand = 'cc-mastercard';
  3580. } elseif ($brand == 'amex' || $brand == 'American Express') {
  3581. $brand = 'cc-amex';
  3582. } elseif ($brand == 'discover' || $brand == 'Discover') {
  3583. $brand = 'cc-discover';
  3584. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  3585. $brand = 'cc-jcb';
  3586. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  3587. $brand = 'cc-diners-club';
  3588. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  3589. $brand = 'credit-card';
  3590. }
  3591. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  3592. }
  3593. /**
  3594. * Show MIME img of a file
  3595. *
  3596. * @param string $file Filename
  3597. * @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.
  3598. * @param string $morecss More css
  3599. * @return string Return img tag
  3600. */
  3601. function img_mime($file, $titlealt = '', $morecss = '')
  3602. {
  3603. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3604. $mimetype = dol_mimetype($file, '', 1);
  3605. $mimeimg = dol_mimetype($file, '', 2);
  3606. $mimefa = dol_mimetype($file, '', 4);
  3607. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  3608. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3609. return '<i class="fa fa-'.$mimefa.' paddingright"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  3610. }
  3611. /**
  3612. * Show search logo
  3613. *
  3614. * @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.
  3615. * @param string $other Add more attributes on img
  3616. * @return string Retourne tag img
  3617. */
  3618. function img_search($titlealt = 'default', $other = '')
  3619. {
  3620. global $conf, $langs;
  3621. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3622. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3623. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3624. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3625. return $input;
  3626. }
  3627. /**
  3628. * Show search logo
  3629. *
  3630. * @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.
  3631. * @param string $other Add more attributes on img
  3632. * @return string Retourne tag img
  3633. */
  3634. function img_searchclear($titlealt = 'default', $other = '')
  3635. {
  3636. global $conf, $langs;
  3637. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3638. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3639. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3640. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3641. return $input;
  3642. }
  3643. /**
  3644. * Show information for admin users or standard users
  3645. *
  3646. * @param string $text Text info
  3647. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3648. * @param int $nodiv No div
  3649. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error','xxx'=Other
  3650. * @param string $morecss More CSS ('', 'warning', 'error')
  3651. * @param string $textfordropdown Show a text to click to dropdown the info box.
  3652. * @return string String with info text
  3653. */
  3654. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  3655. {
  3656. global $conf, $langs;
  3657. if ($infoonimgalt)
  3658. {
  3659. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  3660. } else {
  3661. if (empty($conf->use_javascript_ajax)) $textfordropdown = '';
  3662. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  3663. $result = ($nodiv ? '' : '<div class="'.$class.' hideonsmartphone'.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  3664. if ($textfordropdown) {
  3665. $tmpresult .= '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  3666. $tmpresult .= '<script type="text/javascript" language="javascript">
  3667. jQuery(document).ready(function() {
  3668. jQuery(".'.$class.'text").click(function() {
  3669. console.log("toggle text");
  3670. jQuery(".'.$class.'").toggle();
  3671. });
  3672. });
  3673. </script>';
  3674. $result = $tmpresult.$result;
  3675. }
  3676. }
  3677. return $result;
  3678. }
  3679. /**
  3680. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  3681. * This function must be called when a blocking technical error is encountered.
  3682. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  3683. *
  3684. * @param DoliDB $db Database handler
  3685. * @param string|string[] $error String or array of errors strings to show
  3686. * @param array $errors Array of errors
  3687. * @return void
  3688. * @see dol_htmloutput_errors()
  3689. */
  3690. function dol_print_error($db = '', $error = '', $errors = null)
  3691. {
  3692. global $conf, $langs, $argv;
  3693. global $dolibarr_main_prod;
  3694. $out = '';
  3695. $syslog = '';
  3696. // If error occurs before the $lang object was loaded
  3697. if (!$langs)
  3698. {
  3699. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  3700. $langs = new Translate('', $conf);
  3701. $langs->load("main");
  3702. }
  3703. // Load translation files required by the error messages
  3704. $langs->loadLangs(array('main', 'errors'));
  3705. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3706. {
  3707. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  3708. if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $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";
  3709. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  3710. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  3711. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  3712. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  3713. if (function_exists("phpversion"))
  3714. {
  3715. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  3716. }
  3717. $out .= "<b>".$langs->trans("Server").":</b> ".dol_htmlentities($_SERVER["SERVER_SOFTWARE"])."<br>\n";
  3718. if (function_exists("php_uname"))
  3719. {
  3720. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  3721. }
  3722. $out .= "<b>".$langs->trans("UserAgent").":</b> ".dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3723. $out .= "<br>\n";
  3724. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3725. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '')."<br>\n";
  3726. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu) : '')."<br>\n";
  3727. $out .= "<br>\n";
  3728. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  3729. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  3730. } else // Mode CLI
  3731. {
  3732. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  3733. $syslog .= "pid=".dol_getmypid();
  3734. }
  3735. if (!empty($conf->modules))
  3736. {
  3737. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  3738. }
  3739. if (is_object($db))
  3740. {
  3741. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3742. {
  3743. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  3744. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3745. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3746. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3747. $out .= "<br>\n";
  3748. } else // Mode CLI
  3749. {
  3750. // No dol_escape_htmltag for output, we are in CLI mode
  3751. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  3752. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3753. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3754. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3755. }
  3756. $syslog .= ", sql=".$db->lastquery();
  3757. $syslog .= ", db_error=".$db->lasterror();
  3758. }
  3759. if ($error || $errors)
  3760. {
  3761. $langs->load("errors");
  3762. // Merge all into $errors array
  3763. if (is_array($error) && is_array($errors)) $errors = array_merge($error, $errors);
  3764. elseif (is_array($error)) $errors = $error;
  3765. elseif (is_array($errors)) $errors = array_merge(array($error), $errors);
  3766. else $errors = array_merge(array($error));
  3767. foreach ($errors as $msg)
  3768. {
  3769. if (empty($msg)) continue;
  3770. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3771. {
  3772. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  3773. } else // Mode CLI
  3774. {
  3775. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  3776. }
  3777. $syslog .= ", msg=".$msg;
  3778. }
  3779. }
  3780. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  3781. {
  3782. xdebug_print_function_stack();
  3783. $out .= '<b>XDebug informations:</b>'."<br>\n";
  3784. $out .= 'File: '.xdebug_call_file()."<br>\n";
  3785. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  3786. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  3787. $out .= "<br>\n";
  3788. }
  3789. // Return a http error code if possible
  3790. if (!headers_sent()) {
  3791. http_response_code(500);
  3792. }
  3793. if (empty($dolibarr_main_prod)) {
  3794. print $out;
  3795. } else {
  3796. if (empty($langs->defaultlang)) $langs->setDefaultLang();
  3797. $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.
  3798. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  3799. 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 are on next line...<br><br>'."\n";
  3800. print $langs->trans("DolibarrHasDetectedError").'. ';
  3801. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  3802. define("MAIN_CORE_ERROR", 1);
  3803. }
  3804. dol_syslog("Error ".$syslog, LOG_ERR);
  3805. }
  3806. /**
  3807. * Show a public email and error code to contact if technical error
  3808. *
  3809. * @param string $prefixcode Prefix of public error code
  3810. * @param string $errormessage Complete error message
  3811. * @param array $errormessages Array of error messages
  3812. * @param string $morecss More css
  3813. * @param string $email Email
  3814. * @return void
  3815. */
  3816. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  3817. {
  3818. global $langs, $conf;
  3819. if (empty($email)) $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  3820. $langs->load("errors");
  3821. $now = dol_now();
  3822. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  3823. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  3824. if ($errormessage) print '<br><br>'.$errormessage;
  3825. if (is_array($errormessages) && count($errormessages))
  3826. {
  3827. foreach ($errormessages as $mesgtoshow)
  3828. {
  3829. print '<br><br>'.$mesgtoshow;
  3830. }
  3831. }
  3832. print '</div></div>';
  3833. }
  3834. /**
  3835. * Show title line of an array
  3836. *
  3837. * @param string $name Label of field
  3838. * @param string $file Url used when we click on sort picto
  3839. * @param string $field Field to use for new sorting
  3840. * @param string $begin ("" by defaut)
  3841. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3842. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  3843. * @param string $sortfield Current field used to sort
  3844. * @param string $sortorder Current sort order
  3845. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  3846. * @param string $tooltip Tooltip
  3847. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  3848. * @return void
  3849. */
  3850. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  3851. {
  3852. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  3853. }
  3854. /**
  3855. * Get title line of an array
  3856. *
  3857. * @param string $name Translation key of field to show or complete HTML string to show
  3858. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  3859. * @param string $file Url used when we click on sort picto
  3860. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  3861. * @param string $begin ("" by defaut)
  3862. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3863. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  3864. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  3865. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  3866. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  3867. * @param string $disablesortlink 1=Disable sort link
  3868. * @param string $tooltip Tooltip
  3869. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  3870. * @return string
  3871. */
  3872. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  3873. {
  3874. global $conf, $langs, $form;
  3875. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  3876. if ($moreattrib == 'class="right"') $prefix .= 'right '; // For backward compatibility
  3877. $sortorder = strtoupper($sortorder);
  3878. $out = '';
  3879. $sortimg = '';
  3880. $tag = 'th';
  3881. if ($thead == 2) $tag = 'div';
  3882. $tmpsortfield = explode(',', $sortfield);
  3883. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  3884. $tmpfield = explode(',', $field);
  3885. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  3886. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  3887. $prefix = 'wrapcolumntitle '.$prefix;
  3888. }
  3889. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  3890. // If field is used as sort criteria we use a specific css class liste_titre_sel
  3891. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  3892. $liste_titre = 'liste_titre';
  3893. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  3894. $liste_titre = 'liste_titre_sel';
  3895. }
  3896. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  3897. //$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)).'"' : '');
  3898. $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  3899. $out .= '>';
  3900. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3901. {
  3902. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  3903. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3904. $options = preg_replace('/&+/i', '&', $options);
  3905. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3906. $sortordertouseinlink = '';
  3907. if ($field1 != $sortfield1) // We are on another field than current sorted field
  3908. {
  3909. if (preg_match('/^DESC/i', $sortorder))
  3910. {
  3911. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3912. } else // We reverse the var $sortordertouseinlink
  3913. {
  3914. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3915. }
  3916. } else // We are on field that is the first current sorting criteria
  3917. {
  3918. if (preg_match('/^ASC/i', $sortorder)) // We reverse the var $sortordertouseinlink
  3919. {
  3920. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3921. } else {
  3922. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3923. }
  3924. }
  3925. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  3926. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  3927. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3928. $out .= '>';
  3929. }
  3930. if ($tooltip) {
  3931. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  3932. $tmptooltip = explode(':', $tooltip);
  3933. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  3934. }
  3935. else $out .= $langs->trans($name);
  3936. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3937. {
  3938. $out .= '</a>';
  3939. }
  3940. if (empty($thead) && $field) // If this is a sort field
  3941. {
  3942. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  3943. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3944. $options = preg_replace('/&+/i', '&', $options);
  3945. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3946. if (!$sortorder || $field1 != $sortfield1)
  3947. {
  3948. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3949. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3950. } else {
  3951. if (preg_match('/^DESC/', $sortorder)) {
  3952. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3953. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3954. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  3955. }
  3956. if (preg_match('/^ASC/', $sortorder)) {
  3957. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3958. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3959. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  3960. }
  3961. }
  3962. }
  3963. $out .= $sortimg;
  3964. $out .= '</'.$tag.'>';
  3965. return $out;
  3966. }
  3967. /**
  3968. * Show a title.
  3969. *
  3970. * @param string $title Title to show
  3971. * @return string Title to show
  3972. * @deprecated Use load_fiche_titre instead
  3973. * @see load_fiche_titre()
  3974. */
  3975. function print_titre($title)
  3976. {
  3977. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  3978. print '<div class="titre">'.$title.'</div>';
  3979. }
  3980. /**
  3981. * Show a title with picto
  3982. *
  3983. * @param string $title Title to show
  3984. * @param string $mesg Added message to show on right
  3985. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3986. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3987. * @param int $id To force an id on html objects
  3988. * @return void
  3989. * @deprecated Use print load_fiche_titre instead
  3990. */
  3991. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  3992. {
  3993. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3994. }
  3995. /**
  3996. * Load a title with picto
  3997. *
  3998. * @param string $titre Title to show
  3999. * @param string $morehtmlright Added message to show on right
  4000. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4001. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4002. * @param string $id To force an id on html objects
  4003. * @param string $morecssontable More css on table
  4004. * @param string $morehtmlcenter Added message to show on center
  4005. * @return string
  4006. * @see print_barre_liste()
  4007. */
  4008. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4009. {
  4010. global $conf;
  4011. $return = '';
  4012. if ($picto == 'setup') $picto = 'generic';
  4013. $return .= "\n";
  4014. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4015. $return .= '<tr class="titre">';
  4016. if ($picto) $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4017. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4018. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4019. $return .= '</td>';
  4020. if (dol_strlen($morehtmlcenter))
  4021. {
  4022. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4023. }
  4024. if (dol_strlen($morehtmlright))
  4025. {
  4026. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4027. }
  4028. $return .= '</tr></table>'."\n";
  4029. return $return;
  4030. }
  4031. /**
  4032. * Print a title with navigation controls for pagination
  4033. *
  4034. * @param string $titre Title to show (required)
  4035. * @param int $page Numero of page to show in navigation links (required)
  4036. * @param string $file Url of page (required)
  4037. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4038. * @param string $sortfield Field to sort on ('' by default)
  4039. * @param string $sortorder Order to sort ('' by default)
  4040. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4041. * @param int $num Number of records found by select with limit+1
  4042. * @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.
  4043. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4044. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4045. * @param string $morehtmlright More html to show (after arrows)
  4046. * @param string $morecss More css to the table
  4047. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4048. * @param int $hideselectlimit Force to hide select limit
  4049. * @param int $hidenavigation Force to hide all navigation tools
  4050. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4051. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4052. * @return void
  4053. */
  4054. 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 = '')
  4055. {
  4056. global $conf, $langs;
  4057. $savlimit = $limit;
  4058. $savtotalnboflines = $totalnboflines;
  4059. $totalnboflines = abs((int) $totalnboflines);
  4060. if ($picto == 'setup') $picto = 'title_setup.png';
  4061. if (($conf->browser->name == 'ie') && $picto == 'generic') $picto = 'title.gif';
  4062. if ($limit < 0) $limit = $conf->liste_limit;
  4063. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  4064. {
  4065. $nextpage = 1;
  4066. } else {
  4067. $nextpage = 0;
  4068. }
  4069. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4070. print "\n";
  4071. print "<!-- Begin title '".$titre."' -->\n";
  4072. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4073. // Left
  4074. if ($picto && $titre) print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4075. print '<td class="nobordernopadding valignmiddle col-title">';
  4076. print '<div class="titre inline-block">'.$titre;
  4077. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4078. print '</div></td>';
  4079. // Center
  4080. if ($morehtmlcenter)
  4081. {
  4082. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4083. }
  4084. // Right
  4085. print '<td class="nobordernopadding valignmiddle right">';
  4086. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4087. if ($sortfield) $options .= "&sortfield=".urlencode($sortfield);
  4088. if ($sortorder) $options .= "&sortorder=".urlencode($sortorder);
  4089. // Show navigation bar
  4090. $pagelist = '';
  4091. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  4092. {
  4093. if ($totalnboflines) // If we know total nb of lines
  4094. {
  4095. // Define nb of extra page links before and after selected page + ... + first or last
  4096. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4097. if ($limit > 0) $nbpages = ceil($totalnboflines / $limit);
  4098. else $nbpages = 1;
  4099. $cpt = ($page - $maxnbofpage);
  4100. if ($cpt < 0) { $cpt = 0; }
  4101. if ($cpt >= 1)
  4102. {
  4103. if (empty($pagenavastextinput)) {
  4104. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4105. if ($cpt > 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4106. elseif ($cpt == 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4107. }
  4108. }
  4109. do {
  4110. if ($pagenavastextinput) {
  4111. if ($cpt == $page)
  4112. {
  4113. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4114. $pagelist .= '/';
  4115. //if (($cpt + 1) < $nbpages) $pagelist .= '/';
  4116. }
  4117. } else {
  4118. if ($cpt == $page)
  4119. {
  4120. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4121. } else {
  4122. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4123. }
  4124. }
  4125. $cpt++;
  4126. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4127. if (empty($pagenavastextinput)) {
  4128. if ($cpt < $nbpages)
  4129. {
  4130. if ($cpt < $nbpages - 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4131. elseif ($cpt == $nbpages - 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4132. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4133. }
  4134. } else {
  4135. //var_dump($page.' '.$cpt.' '.$nbpages);
  4136. //if (($page + 1) < $nbpages) {
  4137. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4138. //}
  4139. }
  4140. } else {
  4141. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4142. }
  4143. }
  4144. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4145. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow); // output the div and ul for previous/last completed with page numbers into $pagelist
  4146. }
  4147. // js to autoselect page field on focus
  4148. if ($pagenavastextinput) {
  4149. print ajax_autoselect('.pageplusone');
  4150. }
  4151. print '</td>';
  4152. print '</tr></table>'."\n";
  4153. print "<!-- End title -->\n\n";
  4154. }
  4155. /**
  4156. * Function to show navigation arrows into lists
  4157. *
  4158. * @param int $page Number of page
  4159. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4160. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4161. * @param integer $nextpage Do we show a next page button
  4162. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4163. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4164. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4165. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4166. * @param int $hideselectlimit Force to hide select limit
  4167. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4168. * @return void
  4169. */
  4170. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4171. {
  4172. global $conf, $langs;
  4173. print '<div class="pagination"><ul>';
  4174. if ($beforearrows)
  4175. {
  4176. print '<li class="paginationbeforearrows">';
  4177. print $beforearrows;
  4178. print '</li>';
  4179. }
  4180. if ((int) $limit > 0 && empty($hideselectlimit))
  4181. {
  4182. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  4183. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4184. //$pagesizechoices.=',2:2';
  4185. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4186. print '<li class="pagination">';
  4187. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4188. $tmpchoice = explode(',', $pagesizechoices);
  4189. $tmpkey = $limit.':'.$limit;
  4190. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4191. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4192. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4193. asort($tmpchoice, SORT_NUMERIC);
  4194. foreach ($tmpchoice as $val)
  4195. {
  4196. $selected = '';
  4197. $tmp = explode(':', $val);
  4198. $key = $tmp[0];
  4199. $val = $tmp[1];
  4200. if ($key != '' && $val != '')
  4201. {
  4202. if ((int) $key == (int) $limit)
  4203. {
  4204. $selected = ' selected="selected"';
  4205. }
  4206. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4207. }
  4208. }
  4209. print '</select>';
  4210. if ($conf->use_javascript_ajax)
  4211. {
  4212. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4213. <script>
  4214. jQuery(document).ready(function () {
  4215. jQuery(".selectlimit").change(function() {
  4216. console.log("Change limit. Send submit");
  4217. $(this).parents(\'form:first\').submit();
  4218. });
  4219. });
  4220. </script>
  4221. ';
  4222. }
  4223. print '</li>';
  4224. }
  4225. if ($page > 0)
  4226. {
  4227. 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>';
  4228. }
  4229. if ($betweenarrows)
  4230. {
  4231. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4232. print $betweenarrows;
  4233. print '<!--</div>-->';
  4234. }
  4235. if ($nextpage > 0)
  4236. {
  4237. 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>';
  4238. }
  4239. if ($afterarrows)
  4240. {
  4241. print '<li class="paginationafterarrows">';
  4242. print $afterarrows;
  4243. print '</li>';
  4244. }
  4245. print '</ul></div>'."\n";
  4246. }
  4247. /**
  4248. * Return a string with VAT rate label formated for view output
  4249. * Used into pdf and HTML pages
  4250. *
  4251. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4252. * @param boolean $addpercent Add a percent % sign in output
  4253. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4254. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4255. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4256. */
  4257. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4258. {
  4259. $morelabel = '';
  4260. if (preg_match('/%/', $rate))
  4261. {
  4262. $rate = str_replace('%', '', $rate);
  4263. $addpercent = true;
  4264. }
  4265. if (preg_match('/\((.*)\)/', $rate, $reg))
  4266. {
  4267. $morelabel = ' ('.$reg[1].')';
  4268. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4269. }
  4270. if (preg_match('/\*/', $rate))
  4271. {
  4272. $rate = str_replace('*', '', $rate);
  4273. $info_bits |= 1;
  4274. }
  4275. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4276. if (!preg_match('/\//', $rate)) $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4277. else {
  4278. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4279. $ret = $rate.($addpercent ? '%' : '');
  4280. }
  4281. if (($info_bits & 1) && $usestarfornpr >= 0) $ret .= ' *';
  4282. $ret .= $morelabel;
  4283. return $ret;
  4284. }
  4285. /**
  4286. * Function to format a value into an amount for visual output
  4287. * Function used into PDF and HTML pages
  4288. *
  4289. * @param float $amount Amount to format
  4290. * @param integer $form Type of format, HTML or not (not by default)
  4291. * @param Translate $outlangs Object langs for output
  4292. * @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.
  4293. * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  4294. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4295. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4296. * @return string Chaine avec montant formate
  4297. *
  4298. * @see price2num() Revert function of price
  4299. */
  4300. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4301. {
  4302. global $langs, $conf;
  4303. // Clean parameters
  4304. if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = ''
  4305. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4306. if ($rounding < 0) $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4307. $nbdecimal = $rounding;
  4308. // Output separators by default (french)
  4309. $dec = ','; $thousand = ' ';
  4310. // If $outlangs not forced, we use use language
  4311. if (!is_object($outlangs)) $outlangs = $langs;
  4312. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4313. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4314. if ($thousand == 'None') $thousand = '';
  4315. elseif ($thousand == 'Space') $thousand = ' ';
  4316. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4317. //print "amount=".$amount."-";
  4318. $amount = str_replace(',', '.', $amount); // should be useless
  4319. //print $amount."-";
  4320. $datas = explode('.', $amount);
  4321. $decpart = isset($datas[1]) ? $datas[1] : '';
  4322. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4323. //print "decpart=".$decpart."<br>";
  4324. $end = '';
  4325. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4326. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal = dol_strlen($decpart);
  4327. // Si on depasse max
  4328. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  4329. {
  4330. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4331. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN))
  4332. {
  4333. // Si un affichage est tronque, on montre des ...
  4334. $end = '...';
  4335. }
  4336. }
  4337. // If force rounding
  4338. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  4339. // Format number
  4340. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4341. if ($form)
  4342. {
  4343. $output = preg_replace('/\s/', '&nbsp;', $output);
  4344. $output = preg_replace('/\'/', '&#039;', $output);
  4345. }
  4346. // Add symbol of currency if requested
  4347. $cursymbolbefore = $cursymbolafter = '';
  4348. if ($currency_code)
  4349. {
  4350. if ($currency_code == 'auto') $currency_code = $conf->currency;
  4351. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4352. $listoflanguagesbefore = array('nl_NL');
  4353. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore))
  4354. {
  4355. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4356. } else {
  4357. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4358. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4359. }
  4360. }
  4361. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4362. return $output;
  4363. }
  4364. /**
  4365. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4366. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4367. * should be roundtext2num().
  4368. *
  4369. * @param string|float $amount Amount to convert/clean or round
  4370. * @param string $rounding ''=No rounding
  4371. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4372. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4373. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4374. * 'CR'=Currency rate
  4375. * Numeric = Nb of digits for rounding
  4376. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4377. * Put 2 if you know that number is a user input (so we know we don't have to fix decimal separator).
  4378. * @return string Amount with universal numeric format (Example: '99.99999').
  4379. * If conversion fails, it return text unchanged if $rounding = '' or '0' if $rounding is defined.
  4380. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined..
  4381. *
  4382. * @see price() Opposite function of price2num
  4383. */
  4384. function price2num($amount, $rounding = '', $option = 0)
  4385. {
  4386. global $langs, $conf;
  4387. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4388. // Numbers must be '1234.56'
  4389. // Decimal delimiter for PHP and database SQL requests must be '.'
  4390. $dec = ','; $thousand = ' ';
  4391. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4392. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4393. if ($thousand == 'None') $thousand = '';
  4394. elseif ($thousand == 'Space') $thousand = ' ';
  4395. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4396. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4397. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4398. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4399. if (!is_numeric($amount)) {
  4400. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>]/', '', $amount);
  4401. }
  4402. if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come frominput data, so 1.123 is 1123
  4403. $amount = str_replace($thousand, '', $amount);
  4404. }
  4405. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4406. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4407. // So if number was already a good number, it is converted into local Dolibarr setup.
  4408. if (is_numeric($amount))
  4409. {
  4410. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4411. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4412. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4413. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4414. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4415. }
  4416. //print "QQ".$amount."<br>\n";
  4417. // Now make replace (the main goal of function)
  4418. if ($thousand != ',' && $thousand != '.') {
  4419. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4420. }
  4421. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4422. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4423. $amount = str_replace($dec, '.', $amount);
  4424. }
  4425. // Now, make a rounding if required
  4426. if ($rounding)
  4427. {
  4428. $nbofdectoround = '';
  4429. if ($rounding == 'MU') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4430. elseif ($rounding == 'MT') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4431. elseif ($rounding == 'MS') $nbofdectoround = empty($conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : $conf->global->MAIN_MAX_DECIMALS_STOCK;
  4432. elseif ($rounding == 'CR') $nbofdectoround = 8;
  4433. elseif (is_numeric($rounding)) $nbofdectoround = $rounding;
  4434. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  4435. if (dol_strlen($nbofdectoround)) $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  4436. else return 'ErrorBadParameterProvidedToFunction';
  4437. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4438. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4439. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4440. if (is_numeric($amount))
  4441. {
  4442. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4443. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4444. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4445. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4446. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4447. }
  4448. //print "TT".$amount.'<br>';
  4449. // Always make replace because each math function (like round) replace
  4450. // with local values and we want a number that has a SQL string format x.y
  4451. if ($thousand != ',' && $thousand != '.') $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4452. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4453. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4454. $amount = str_replace($dec, '.', $amount);
  4455. }
  4456. return $amount;
  4457. }
  4458. /**
  4459. * Output a dimension with best unit
  4460. *
  4461. * @param float $dimension Dimension
  4462. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4463. * @param string $type 'weight', 'volume', ...
  4464. * @param Translate $outputlangs Translate language object
  4465. * @param int $round -1 = non rounding, x = number of decimal
  4466. * @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)
  4467. * @return string String to show dimensions
  4468. */
  4469. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
  4470. {
  4471. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4472. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  4473. {
  4474. $dimension = $dimension * 1000000;
  4475. $unit = $unit - 6;
  4476. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  4477. {
  4478. $dimension = $dimension * 1000;
  4479. $unit = $unit - 3;
  4480. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  4481. {
  4482. $dimension = $dimension / 1000000;
  4483. $unit = $unit + 6;
  4484. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  4485. {
  4486. $dimension = $dimension / 1000;
  4487. $unit = $unit + 3;
  4488. }
  4489. // Special case when we want output unit into pound or ounce
  4490. /* TODO
  4491. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4492. {
  4493. $dimension = // convert dimension from standard unit into ounce or pound
  4494. $unit = $forceunitoutput;
  4495. }
  4496. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4497. {
  4498. $dimension = // convert dimension from standard unit into ounce or pound
  4499. $unit = $forceunitoutput;
  4500. }*/
  4501. $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuringUnitString(0, $type, $unit);
  4502. return $ret;
  4503. }
  4504. /**
  4505. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4506. * Note: This function applies same rules than get_default_tva
  4507. *
  4508. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4509. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4510. * @param Societe $thirdparty_buyer Object of buying third party
  4511. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4512. * @param int $vatnpr If vat rate is NPR or not
  4513. * @return mixed 0 if not found, localtax rate if found
  4514. * @see get_default_tva()
  4515. */
  4516. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  4517. {
  4518. global $db, $conf, $mysoc;
  4519. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) $thirdparty_seller = $mysoc;
  4520. 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);
  4521. $vatratecleaned = $vatrate;
  4522. $reg = array();
  4523. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  4524. $vatratecleaned = trim($reg[1]);
  4525. $vatratecode = $reg[2];
  4526. }
  4527. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4528. {
  4529. return 0;
  4530. }*/
  4531. // Some test to guess with no need to make database access
  4532. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4533. if ($local == 1) {
  4534. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  4535. if ($thirdparty_seller->id == $mysoc->id) {
  4536. if (!$thirdparty_buyer->localtax1_assuj) return 0;
  4537. } else {
  4538. if (!$thirdparty_seller->localtax1_assuj) return 0;
  4539. }
  4540. }
  4541. if ($local == 2) {
  4542. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4543. if (!$mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0.
  4544. if ($thirdparty_seller->id == $mysoc->id) {
  4545. if (!$thirdparty_buyer->localtax2_assuj) return 0;
  4546. } else {
  4547. if (!$thirdparty_seller->localtax2_assuj) return 0;
  4548. }
  4549. }
  4550. } else {
  4551. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) return 0;
  4552. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) return 0;
  4553. }
  4554. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4555. if (in_array($mysoc->country_code, array('ES'))) {
  4556. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4557. }
  4558. // Search local taxes
  4559. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  4560. {
  4561. if ($local == 1) {
  4562. if ($thirdparty_seller != $mysoc) {
  4563. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4564. {
  4565. return $thirdparty_seller->localtax1_value;
  4566. }
  4567. } else { // i am the seller
  4568. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4569. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4570. }
  4571. }
  4572. }
  4573. if ($local == 2) {
  4574. if ($thirdparty_seller != $mysoc) {
  4575. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4576. // TODO We should also return value defined on thirdparty only if defined
  4577. {
  4578. return $thirdparty_seller->localtax2_value;
  4579. }
  4580. } else { // i am the seller
  4581. if (in_array($mysoc->country_code, array('ES'))) {
  4582. return $thirdparty_buyer->localtax2_value;
  4583. } else {
  4584. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4585. }
  4586. }
  4587. }
  4588. }
  4589. // By default, search value of local tax on line of common tax
  4590. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4591. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4592. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  4593. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4594. if (!empty($vatratecode)) $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  4595. else $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  4596. dol_syslog("get_localtax", LOG_DEBUG);
  4597. $resql = $db->query($sql);
  4598. if ($resql)
  4599. {
  4600. $obj = $db->fetch_object($resql);
  4601. if ($obj) {
  4602. if ($local == 1) return $obj->localtax1;
  4603. elseif ($local == 2) return $obj->localtax2;
  4604. }
  4605. }
  4606. return 0;
  4607. }
  4608. /**
  4609. * Return true if LocalTax (1 or 2) is unique.
  4610. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  4611. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  4612. *
  4613. * @param int $local Local tax to test (1 or 2)
  4614. * @return boolean True if LocalTax have multiple values, False if not
  4615. */
  4616. function isOnlyOneLocalTax($local)
  4617. {
  4618. $tax = get_localtax_by_third($local);
  4619. $valors = explode(":", $tax);
  4620. if (count($valors) > 1) {
  4621. return false;
  4622. } else {
  4623. return true;
  4624. }
  4625. }
  4626. /**
  4627. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  4628. *
  4629. * @param int $local LocalTax to get
  4630. * @return number Values of localtax
  4631. */
  4632. function get_localtax_by_third($local)
  4633. {
  4634. global $db, $mysoc;
  4635. $sql = "SELECT t.localtax1, t.localtax2 ";
  4636. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  4637. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  4638. $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";
  4639. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  4640. $sql .= " )";
  4641. $resql = $db->query($sql);
  4642. if ($resql)
  4643. {
  4644. $obj = $db->fetch_object($resql);
  4645. if ($local == 1) return $obj->localtax1;
  4646. elseif ($local == 2) return $obj->localtax2;
  4647. }
  4648. return 0;
  4649. }
  4650. /**
  4651. * Get tax (VAT) main information from Id.
  4652. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  4653. *
  4654. * @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.
  4655. * @param Societe $buyer Company object
  4656. * @param Societe $seller Company object
  4657. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  4658. * @return array array('rowid'=> , 'code'=> ...)
  4659. * @see getLocalTaxesFromRate()
  4660. */
  4661. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  4662. {
  4663. global $db, $mysoc;
  4664. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  4665. // Search local taxes
  4666. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  4667. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  4668. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4669. if ($firstparamisid) {
  4670. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4671. } else {
  4672. $vatratecleaned = $vatrate;
  4673. $vatratecode = '';
  4674. $reg = array();
  4675. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4676. {
  4677. $vatratecleaned = $reg[1];
  4678. $vatratecode = $reg[2];
  4679. }
  4680. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4681. /*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 ??
  4682. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  4683. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  4684. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4685. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4686. }
  4687. $resql = $db->query($sql);
  4688. if ($resql) {
  4689. $obj = $db->fetch_object($resql);
  4690. if ($obj) return array(
  4691. 'rowid'=>$obj->rowid,
  4692. 'code'=>$obj->code,
  4693. 'rate'=>$obj->rate,
  4694. 'localtax1'=>$obj->localtax1,
  4695. 'localtax1_type'=>$obj->localtax1_type,
  4696. 'localtax2'=>$obj->localtax2,
  4697. 'localtax2_type'=>$obj->localtax2_type,
  4698. 'npr'=>$obj->npr,
  4699. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  4700. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  4701. );
  4702. else return array();
  4703. } else dol_print_error($db);
  4704. return array();
  4705. }
  4706. /**
  4707. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  4708. * This does not take into account the seller setup if subject to vat or not, only country.
  4709. *
  4710. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  4711. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  4712. * provide the selected value to the function calcul_price_total.
  4713. *
  4714. * @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.
  4715. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  4716. * @param Societe $buyer Company object
  4717. * @param Societe $seller Company object
  4718. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  4719. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  4720. * @see getTaxesFromId()
  4721. */
  4722. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  4723. {
  4724. global $db, $mysoc;
  4725. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  4726. // Search local taxes
  4727. $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";
  4728. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4729. if ($firstparamisid) {
  4730. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4731. } else {
  4732. $vatratecleaned = $vatrate;
  4733. $vatratecode = '';
  4734. $reg = array();
  4735. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  4736. $vatratecleaned = $reg[1];
  4737. $vatratecode = $reg[2];
  4738. }
  4739. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4740. if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  4741. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  4742. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4743. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4744. }
  4745. $resql = $db->query($sql);
  4746. if ($resql) {
  4747. $obj = $db->fetch_object($resql);
  4748. if ($obj) {
  4749. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  4750. if ($local == 1) {
  4751. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4752. } elseif ($local == 2) {
  4753. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4754. } else {
  4755. 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);
  4756. }
  4757. }
  4758. }
  4759. return array();
  4760. }
  4761. /**
  4762. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  4763. * Function called by get_default_tva
  4764. *
  4765. * @param int $idprod Id of product or 0 if not a predefined product
  4766. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4767. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  4768. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  4769. * @see get_product_localtax_for_country()
  4770. */
  4771. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice = 0)
  4772. {
  4773. global $db, $conf, $mysoc;
  4774. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4775. $ret = 0;
  4776. $found = 0;
  4777. if ($idprod > 0)
  4778. {
  4779. // Load product
  4780. $product = new Product($db);
  4781. $result = $product->fetch($idprod);
  4782. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4783. {
  4784. if ($idprodfournprice > 0) // We want vat for product for a "supplier" object
  4785. {
  4786. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  4787. $ret = $product->vatrate_supplier;
  4788. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4789. } else {
  4790. $ret = $product->tva_tx; // Default vat of product we defined
  4791. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4792. }
  4793. $found = 1;
  4794. } else {
  4795. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  4796. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  4797. }
  4798. }
  4799. if (!$found)
  4800. {
  4801. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  4802. {
  4803. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  4804. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  4805. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4806. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4807. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  4808. $sql .= $db->plimit(1);
  4809. $resql = $db->query($sql);
  4810. if ($resql)
  4811. {
  4812. $obj = $db->fetch_object($resql);
  4813. if ($obj)
  4814. {
  4815. $ret = $obj->vat_rate;
  4816. if ($obj->default_vat_code) $ret .= ' ('.$obj->default_vat_code.')';
  4817. }
  4818. $db->free($sql);
  4819. } else dol_print_error($db);
  4820. } else $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  4821. }
  4822. dol_syslog("get_product_vat_for_country: ret=".$ret);
  4823. return $ret;
  4824. }
  4825. /**
  4826. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  4827. *
  4828. * @param int $idprod Id of product
  4829. * @param int $local 1 for localtax1, 2 for localtax 2
  4830. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4831. * @return int <0 if KO, Vat rate if OK
  4832. * @see get_product_vat_for_country()
  4833. */
  4834. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  4835. {
  4836. global $db, $mysoc;
  4837. if (!class_exists('Product')) {
  4838. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4839. }
  4840. $ret = 0;
  4841. $found = 0;
  4842. if ($idprod > 0)
  4843. {
  4844. // Load product
  4845. $product = new Product($db);
  4846. $result = $product->fetch($idprod);
  4847. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4848. {
  4849. /* Not defined yet, so we don't use this
  4850. if ($local==1) $ret=$product->localtax1_tx;
  4851. elseif ($local==2) $ret=$product->localtax2_tx;
  4852. $found=1;
  4853. */
  4854. } else {
  4855. // TODO Read default product vat according to countrycode and product
  4856. }
  4857. }
  4858. if (!$found)
  4859. {
  4860. // If vat of product for the country not found or not defined, we return higher vat of country.
  4861. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  4862. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4863. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4864. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  4865. $sql .= $db->plimit(1);
  4866. $resql = $db->query($sql);
  4867. if ($resql)
  4868. {
  4869. $obj = $db->fetch_object($resql);
  4870. if ($obj)
  4871. {
  4872. if ($local == 1) $ret = $obj->localtax1;
  4873. elseif ($local == 2) $ret = $obj->localtax2;
  4874. }
  4875. } else dol_print_error($db);
  4876. }
  4877. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  4878. return $ret;
  4879. }
  4880. /**
  4881. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  4882. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4883. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4884. * Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  4885. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4886. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  4887. * Sinon TVA proposee par defaut=0. Fin de regle.
  4888. *
  4889. * @param Societe $thirdparty_seller Objet societe vendeuse
  4890. * @param Societe $thirdparty_buyer Objet societe acheteuse
  4891. * @param int $idprod Id product
  4892. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  4893. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  4894. * @see get_default_npr(), get_default_localtax()
  4895. */
  4896. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4897. {
  4898. global $conf;
  4899. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4900. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  4901. $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;
  4902. $seller_country_code = $thirdparty_seller->country_code;
  4903. $seller_in_cee = isInEEC($thirdparty_seller);
  4904. $buyer_country_code = $thirdparty_buyer->country_code;
  4905. $buyer_in_cee = isInEEC($thirdparty_buyer);
  4906. 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 : ''));
  4907. // 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)
  4908. // we use the buyer VAT.
  4909. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  4910. {
  4911. if ($seller_in_cee && $buyer_in_cee && !$thirdparty_buyer->isACompany())
  4912. {
  4913. //print 'VATRULE 0';
  4914. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  4915. }
  4916. }
  4917. // If seller does not use VAT
  4918. if (!$seller_use_vat)
  4919. {
  4920. //print 'VATRULE 1';
  4921. return 0;
  4922. }
  4923. // Le test ci-dessus ne devrait pas etre necessaire. Me signaler l'exemple du cas juridique concerne si le test suivant n'est pas suffisant.
  4924. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4925. if (($seller_country_code == $buyer_country_code)
  4926. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) // Warning ->country_code not always defined
  4927. {
  4928. //print 'VATRULE 2';
  4929. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4930. }
  4931. // Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  4932. // Not supported
  4933. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  4934. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4935. if (($seller_in_cee && $buyer_in_cee))
  4936. {
  4937. $isacompany = $thirdparty_buyer->isACompany();
  4938. if ($isacompany)
  4939. {
  4940. //print 'VATRULE 3';
  4941. return 0;
  4942. } else {
  4943. //print 'VATRULE 4';
  4944. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4945. }
  4946. }
  4947. // Si (vendeur en France et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4948. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee) && !$thirdparty_buyer->isACompany()) {
  4949. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4950. }
  4951. // Sinon la TVA proposee par defaut=0. Fin de regle.
  4952. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  4953. //print 'VATRULE 5';
  4954. return 0;
  4955. }
  4956. /**
  4957. * Fonction qui renvoie si tva doit etre tva percue recuperable
  4958. *
  4959. * @param Societe $thirdparty_seller Thirdparty seller
  4960. * @param Societe $thirdparty_buyer Thirdparty buyer
  4961. * @param int $idprod Id product
  4962. * @param int $idprodfournprice Id supplier price for product
  4963. * @return float 0 or 1
  4964. * @see get_default_tva(), get_default_localtax()
  4965. */
  4966. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4967. {
  4968. global $db;
  4969. if ($idprodfournprice > 0)
  4970. {
  4971. if (!class_exists('ProductFournisseur')) {
  4972. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  4973. }
  4974. $prodprice = new ProductFournisseur($db);
  4975. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  4976. return $prodprice->fourn_tva_npr;
  4977. } elseif ($idprod > 0)
  4978. {
  4979. if (!class_exists('Product')) {
  4980. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4981. }
  4982. $prod = new Product($db);
  4983. $prod->fetch($idprod);
  4984. return $prod->tva_npr;
  4985. }
  4986. return 0;
  4987. }
  4988. /**
  4989. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4990. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4991. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4992. * Sinon TVA proposee par defaut=0. Fin de regle.
  4993. *
  4994. * @param Societe $thirdparty_seller Thirdparty seller
  4995. * @param Societe $thirdparty_buyer Thirdparty buyer
  4996. * @param int $local Localtax to process (1 or 2)
  4997. * @param int $idprod Id product
  4998. * @return integer localtax, -1 si ne peut etre determine
  4999. * @see get_default_tva(), get_default_npr()
  5000. */
  5001. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5002. {
  5003. global $mysoc;
  5004. if (!is_object($thirdparty_seller)) return -1;
  5005. if (!is_object($thirdparty_buyer)) return -1;
  5006. if ($local == 1) // Localtax 1
  5007. {
  5008. if ($mysoc->country_code == 'ES')
  5009. {
  5010. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) return 0;
  5011. } else {
  5012. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5013. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) return 0;
  5014. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') return 0;
  5015. }
  5016. } elseif ($local == 2) //I Localtax 2
  5017. {
  5018. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5019. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) return 0;
  5020. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') return 0;
  5021. }
  5022. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  5023. {
  5024. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5025. }
  5026. return 0;
  5027. }
  5028. /**
  5029. * Return yes or no in current language
  5030. *
  5031. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5032. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5033. * @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.
  5034. * @return string HTML string
  5035. */
  5036. function yn($yesno, $case = 1, $color = 0)
  5037. {
  5038. global $langs;
  5039. $result = 'unknown'; $classname = '';
  5040. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  5041. {
  5042. $result = $langs->trans('yes');
  5043. if ($case == 1 || $case == 3) $result = $langs->trans("Yes");
  5044. if ($case == 2) $result = '<input type="checkbox" value="1" checked disabled>';
  5045. if ($case == 3) $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5046. $classname = 'ok';
  5047. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  5048. {
  5049. $result = $langs->trans("no");
  5050. if ($case == 1 || $case == 3) $result = $langs->trans("No");
  5051. if ($case == 2) $result = '<input type="checkbox" value="0" disabled>';
  5052. if ($case == 3) $result = '<input type="checkbox" value="0" disabled> '.$result;
  5053. if ($color == 2) $classname = 'ok';
  5054. else $classname = 'error';
  5055. }
  5056. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  5057. return $result;
  5058. }
  5059. /**
  5060. * Return a path to have a the directory according to object where files are stored.
  5061. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5062. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5063. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5064. * 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/"
  5065. *
  5066. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5067. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5068. * @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)
  5069. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5070. * @param Object $object Object to use to get ref to forge the path.
  5071. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5072. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5073. */
  5074. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5075. {
  5076. global $conf;
  5077. if (empty($modulepart) && !empty($object->module)) $modulepart = $object->module;
  5078. $path = '';
  5079. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5080. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[] = 'product';
  5081. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5082. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  5083. if (empty($alpha)) $num = preg_replace('/([^0-9])/i', '', $num);
  5084. else $num = preg_replace('/^.*\-/i', '', $num);
  5085. $num = substr("000".$num, -$level);
  5086. if ($level == 1) $path = substr($num, 0, 1);
  5087. if ($level == 2) $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5088. if ($level == 3) $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5089. } else {
  5090. // We will enhance here a common way of forging path for document storage.
  5091. // In a future, we may distribute directories on several levels depending on setup and object.
  5092. // Here, $object->id, $object->ref and $modulepart are required.
  5093. //var_dump($modulepart);
  5094. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5095. }
  5096. if (empty($withoutslash) && !empty($path)) $path .= '/';
  5097. return $path;
  5098. }
  5099. /**
  5100. * Creation of a directory (this can create recursive subdir)
  5101. *
  5102. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5103. * @param string $dataroot Data root directory (To avoid having the data root in the loop. Using this will also lost the warning on first dir PHP has no permission when open_basedir is used)
  5104. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5105. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5106. */
  5107. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5108. {
  5109. global $conf;
  5110. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5111. $dir_osencoded = dol_osencode($dir);
  5112. if (@is_dir($dir_osencoded)) return 0;
  5113. $nberr = 0;
  5114. $nbcreated = 0;
  5115. $ccdir = '';
  5116. if (!empty($dataroot)) {
  5117. // Remove data root from loop
  5118. $dir = str_replace($dataroot.'/', '', $dir);
  5119. $ccdir = $dataroot.'/';
  5120. }
  5121. $cdir = explode("/", $dir);
  5122. $num = count($cdir);
  5123. for ($i = 0; $i < $num; $i++)
  5124. {
  5125. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  5126. else $ccdir .= $cdir[$i];
  5127. if (preg_match("/^.:$/", $ccdir, $regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5128. // Attention, le is_dir() peut echouer bien que le rep existe.
  5129. // (ex selon config de open_basedir)
  5130. if ($ccdir)
  5131. {
  5132. $ccdir_osencoded = dol_osencode($ccdir);
  5133. if (!@is_dir($ccdir_osencoded))
  5134. {
  5135. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5136. umask(0);
  5137. $dirmaskdec = octdec($newmask);
  5138. if (empty($newmask)) {
  5139. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5140. }
  5141. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5142. if (!@mkdir($ccdir_osencoded, $dirmaskdec))
  5143. {
  5144. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5145. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5146. $nberr++;
  5147. } else {
  5148. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5149. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5150. $nbcreated++;
  5151. }
  5152. } else {
  5153. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5154. }
  5155. }
  5156. }
  5157. return ($nberr ? -$nberr : $nbcreated);
  5158. }
  5159. /**
  5160. * Return picto saying a field is required
  5161. *
  5162. * @return string Chaine avec picto obligatoire
  5163. */
  5164. function picto_required()
  5165. {
  5166. return '<span class="fieldrequired">*</span>';
  5167. }
  5168. /**
  5169. * Clean a string from all HTML tags and entities.
  5170. * This function differs from strip_tags because:
  5171. * - <br> are replaced with \n if removelinefeed=0 or 1
  5172. * - if entities are found, they are decoded BEFORE the strip
  5173. * - you can decide to convert line feed into a space
  5174. *
  5175. * @param string $stringtoclean String to clean
  5176. * @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..."
  5177. * @param string $pagecodeto Encoding of input/output string
  5178. * @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)
  5179. * @param integer $removedoublespaces Replace double space into one space
  5180. * @return string String cleaned
  5181. *
  5182. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5183. */
  5184. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5185. {
  5186. if ($removelinefeed == 2) $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5187. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5188. // 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)
  5189. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5190. $temp = str_replace('< ', '__ltspace__', $temp);
  5191. if ($strip_tags) {
  5192. $temp = strip_tags($temp);
  5193. } else {
  5194. $pattern = "/<[^<>]+>/";
  5195. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5196. $temp = preg_replace($pattern, "", $temp); // pass 1
  5197. // $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5198. $temp = preg_replace($pattern, "", $temp); // pass 2
  5199. // $temp after pass 2: 0000-021
  5200. }
  5201. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5202. // Remove also carriage returns
  5203. if ($removelinefeed == 1) $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5204. // And double quotes
  5205. if ($removedoublespaces) {
  5206. while (strpos($temp, " ")) {
  5207. $temp = str_replace(" ", " ", $temp);
  5208. }
  5209. }
  5210. $temp = str_replace('__ltspace__', '< ', $temp);
  5211. return trim($temp);
  5212. }
  5213. /**
  5214. * Clean a string to keep only desirable HTML tags.
  5215. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  5216. *
  5217. * @param string $stringtoclean String to clean
  5218. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5219. * @param int $removeclassattribute Remove the class attribute from tags
  5220. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  5221. * @return string String cleaned
  5222. *
  5223. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5224. */
  5225. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0)
  5226. {
  5227. $allowed_tags = array(
  5228. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5229. "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"
  5230. );
  5231. $allowed_tags_string = join("><", $allowed_tags);
  5232. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5233. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5234. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5235. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  5236. $stringtoclean = preg_replace('/&#58;|&#0000058|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
  5237. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  5238. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  5239. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5240. $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
  5241. }
  5242. if ($removeclassattribute) { // Clean for remaining html tags
  5243. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5244. }
  5245. // Remove 'javascript:' that we should not find into a text with
  5246. // 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 the GETPOST).
  5247. if ($cleanalsojavascript) {
  5248. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5249. }
  5250. return $temp;
  5251. }
  5252. /**
  5253. * Clean a string from some undesirable HTML tags.
  5254. * Note. Not as secured as dol_string_onlythesehtmltags().
  5255. *
  5256. * @param string $stringtoclean String to clean
  5257. * @param array $disallowed_tags Array of tags not allowed
  5258. * @param string $cleanalsosomestyles Clean also some tags
  5259. * @return string String cleaned
  5260. *
  5261. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags()
  5262. */
  5263. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5264. {
  5265. $temp = $stringtoclean;
  5266. foreach ($disallowed_tags as $tagtoremove)
  5267. {
  5268. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5269. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5270. }
  5271. if ($cleanalsosomestyles) {
  5272. $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
  5273. }
  5274. return $temp;
  5275. }
  5276. /**
  5277. * Return first line of text. Cut will depends if content is HTML or not.
  5278. *
  5279. * @param string $text Input text
  5280. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5281. * @param string $charset Charset of $text string (UTF-8 by default)
  5282. * @return string Output text
  5283. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5284. */
  5285. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5286. {
  5287. if ($nboflines == 1)
  5288. {
  5289. if (dol_textishtml($text))
  5290. {
  5291. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5292. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5293. } else {
  5294. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5295. }
  5296. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5297. } else {
  5298. $ishtml = 0;
  5299. if (dol_textishtml($text))
  5300. {
  5301. $text = preg_replace('/\n/', '', $text);
  5302. $ishtml = 1;
  5303. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5304. } else {
  5305. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5306. }
  5307. $text = strtr($text, $repTable);
  5308. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5309. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5310. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5311. $firstline = '';
  5312. $i = 0;
  5313. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5314. while (($i < $nba) && ($i < ($nboflines * 2)))
  5315. {
  5316. if ($i % 2 == 0) $firstline .= $a[$i];
  5317. elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) $firstline .= ($ishtml ? "<br>\n" : "\n");
  5318. $i++;
  5319. }
  5320. unset($a);
  5321. return $firstline.(($i < $nba) ? '...' : '');
  5322. }
  5323. }
  5324. /**
  5325. * Replace CRLF in string with a HTML BR tag.
  5326. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have encode the special chars of stringtoencode into HTML before.
  5327. *
  5328. * @param string $stringtoencode String to encode
  5329. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5330. * @param bool $forxml false=Use <br>, true=Use <br />
  5331. * @return string String encoded
  5332. * @see dol_nboflines(), dolGetFirstLineOfText()
  5333. */
  5334. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5335. {
  5336. if (!$nl2brmode) {
  5337. return nl2br($stringtoencode, $forxml);
  5338. } else {
  5339. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  5340. return $ret;
  5341. }
  5342. }
  5343. /**
  5344. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5345. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5346. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5347. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5348. * For PDF usage, you can show text by 2 ways:
  5349. * - writeHTMLCell -> param must be encoded into HTML.
  5350. * - MultiCell -> param must not be encoded into HTML.
  5351. * Because writeHTMLCell convert also \n into <br>, if function
  5352. * is used to build PDF, nl2brmode must be 1.
  5353. *
  5354. * @param string $stringtoencode String to encode
  5355. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5356. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5357. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5358. * @return string String encoded
  5359. */
  5360. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  5361. {
  5362. $newstring = $stringtoencode;
  5363. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  5364. {
  5365. $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.
  5366. if ($removelasteolbr) $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  5367. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  5368. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  5369. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  5370. } else {
  5371. if ($removelasteolbr) $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  5372. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  5373. }
  5374. // Other substitutions that htmlentities does not do
  5375. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5376. return $newstring;
  5377. }
  5378. /**
  5379. * This function is called to decode a HTML string (it decodes entities and br tags)
  5380. *
  5381. * @param string $stringtodecode String to decode
  5382. * @param string $pagecodeto Page code for result
  5383. * @return string String decoded
  5384. */
  5385. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  5386. {
  5387. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5388. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  5389. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  5390. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  5391. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  5392. return $ret;
  5393. }
  5394. /**
  5395. * This function remove all ending \n and br at end
  5396. *
  5397. * @param string $stringtodecode String to decode
  5398. * @return string String decoded
  5399. */
  5400. function dol_htmlcleanlastbr($stringtodecode)
  5401. {
  5402. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
  5403. return $ret;
  5404. }
  5405. /**
  5406. * Replace html_entity_decode functions to manage errors
  5407. *
  5408. * @param string $a Operand a
  5409. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  5410. * @param string $c Operand c
  5411. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  5412. * @return string String decoded
  5413. */
  5414. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  5415. {
  5416. $newstring = $a;
  5417. if ($keepsomeentities) $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  5418. $newstring = html_entity_decode($newstring, $b, $c);
  5419. if ($keepsomeentities) $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  5420. return $newstring;
  5421. }
  5422. /**
  5423. * Replace htmlentities functions.
  5424. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5425. *
  5426. * @param string $string The input string to encode
  5427. * @param int $flags Flags (see PHP doc above)
  5428. * @param string $encoding Encoding page code
  5429. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5430. * @return string $ret Encoded string
  5431. */
  5432. function dol_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = false)
  5433. {
  5434. return htmlentities($string, $flags, $encoding, $double_encode);
  5435. }
  5436. /**
  5437. * Check if a string is a correct iso string
  5438. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5439. * Example, if string contains euro symbol that has ascii code 128
  5440. *
  5441. * @param string $s String to check
  5442. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  5443. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  5444. */
  5445. function dol_string_is_good_iso($s, $clean = 0)
  5446. {
  5447. $len = dol_strlen($s);
  5448. $out = '';
  5449. $ok = 1;
  5450. for ($scursor = 0; $scursor < $len; $scursor++)
  5451. {
  5452. $ordchar = ord($s[$scursor]);
  5453. //print $scursor.'-'.$ordchar.'<br>';
  5454. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok = 0; break; } elseif ($ordchar > 126 && $ordchar < 160) { $ok = 0; break; } elseif ($clean) {
  5455. $out .= $s[$scursor];
  5456. }
  5457. }
  5458. if ($clean) return $out;
  5459. return $ok;
  5460. }
  5461. /**
  5462. * Return nb of lines of a clear text
  5463. *
  5464. * @param string $s String to check
  5465. * @param int $maxchar Not yet used
  5466. * @return int Number of lines
  5467. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  5468. */
  5469. function dol_nboflines($s, $maxchar = 0)
  5470. {
  5471. if ($s == '') return 0;
  5472. $arraystring = explode("\n", $s);
  5473. $nb = count($arraystring);
  5474. return $nb;
  5475. }
  5476. /**
  5477. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  5478. *
  5479. * @param string $text Text
  5480. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  5481. * @param string $charset Give the charset used to encode the $text variable in memory.
  5482. * @return int Number of lines
  5483. * @see dol_nboflines(), dolGetFirstLineOfText()
  5484. */
  5485. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  5486. {
  5487. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5488. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5489. $text = strtr($text, $repTable);
  5490. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5491. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5492. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5493. $nblines = (int) floor((count($a) + 1) / 2);
  5494. // count possible auto line breaks
  5495. if ($maxlinesize)
  5496. {
  5497. foreach ($a as $line)
  5498. {
  5499. if (dol_strlen($line) > $maxlinesize)
  5500. {
  5501. //$line_dec = html_entity_decode(strip_tags($line));
  5502. $line_dec = html_entity_decode($line);
  5503. if (dol_strlen($line_dec) > $maxlinesize)
  5504. {
  5505. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  5506. $nblines += substr_count($line_dec, '\n');
  5507. }
  5508. }
  5509. }
  5510. }
  5511. unset($a);
  5512. return $nblines;
  5513. }
  5514. /**
  5515. * Return if a text is a html content
  5516. *
  5517. * @param string $msg Content to check
  5518. * @param int $option 0=Full detection, 1=Fast check
  5519. * @return boolean true/false
  5520. * @see dol_concatdesc()
  5521. */
  5522. function dol_textishtml($msg, $option = 0)
  5523. {
  5524. if ($option == 1)
  5525. {
  5526. if (preg_match('/<html/i', $msg)) return true;
  5527. elseif (preg_match('/<body/i', $msg)) return true;
  5528. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5529. elseif (preg_match('/<br/i', $msg)) return true;
  5530. return false;
  5531. } else {
  5532. if (preg_match('/<html/i', $msg)) return true;
  5533. elseif (preg_match('/<body/i', $msg)) return true;
  5534. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5535. elseif (preg_match('/<(b|em|i|u)>/i', $msg)) return true;
  5536. elseif (preg_match('/<br\/>/i', $msg)) return true;
  5537. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) return true;
  5538. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg)) return true;
  5539. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg)) return true;
  5540. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  5541. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  5542. elseif (preg_match('/<h[0-9]>/i', $msg)) return true;
  5543. elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  5544. elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  5545. return false;
  5546. }
  5547. }
  5548. /**
  5549. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  5550. * text1 html + text2 html => text1 + '<br>' + text2
  5551. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  5552. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  5553. * text1 txt + text2 txt => text1 + '\n' + text2
  5554. *
  5555. * @param string $text1 Text 1
  5556. * @param string $text2 Text 2
  5557. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  5558. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  5559. * @return string Text 1 + new line + Text2
  5560. * @see dol_textishtml()
  5561. */
  5562. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  5563. {
  5564. if (!empty($invert))
  5565. {
  5566. $tmp = $text1;
  5567. $text1 = $text2;
  5568. $text2 = $tmp;
  5569. }
  5570. $ret = '';
  5571. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  5572. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  5573. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  5574. return $ret;
  5575. }
  5576. /**
  5577. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  5578. *
  5579. * @param Translate $outputlangs Output language
  5580. * @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)
  5581. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  5582. * @param Object $object Object for keys on object
  5583. * @return array Array of substitutions
  5584. * @see setSubstitFromObject()
  5585. */
  5586. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  5587. {
  5588. global $db, $conf, $mysoc, $user, $extrafields;
  5589. $substitutionarray = array();
  5590. if (empty($exclude) || !in_array('user', $exclude))
  5591. {
  5592. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  5593. // this will include signature content first and then replace var found into content of signature
  5594. $signature = $user->signature;
  5595. $substitutionarray = array_merge($substitutionarray, array(
  5596. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  5597. )
  5598. );
  5599. $substitutionarray = array_merge($substitutionarray, array(
  5600. '__USER_ID__' => (string) $user->id,
  5601. '__USER_LOGIN__' => (string) $user->login,
  5602. '__USER_EMAIL__' => (string) $user->email,
  5603. '__USER_LASTNAME__' => (string) $user->lastname,
  5604. '__USER_FIRSTNAME__' => (string) $user->firstname,
  5605. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  5606. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  5607. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  5608. )
  5609. );
  5610. }
  5611. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc))
  5612. {
  5613. $substitutionarray = array_merge($substitutionarray, array(
  5614. '__MYCOMPANY_NAME__' => $mysoc->name,
  5615. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  5616. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  5617. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  5618. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  5619. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  5620. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  5621. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  5622. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  5623. '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '),
  5624. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  5625. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  5626. '__MYCOMPANY_TOWN__' => $mysoc->town,
  5627. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  5628. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  5629. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  5630. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  5631. ));
  5632. }
  5633. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)))
  5634. {
  5635. if ($onlykey)
  5636. {
  5637. $substitutionarray['__ID__'] = '__ID__';
  5638. $substitutionarray['__REF__'] = '__REF__';
  5639. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  5640. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  5641. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  5642. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  5643. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  5644. if (!empty($conf->societe->enabled)) // Most objects are concerned
  5645. {
  5646. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  5647. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  5648. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  5649. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  5650. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  5651. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  5652. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  5653. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  5654. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  5655. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  5656. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  5657. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  5658. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  5659. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  5660. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  5661. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  5662. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  5663. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  5664. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  5665. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  5666. }
  5667. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent'))
  5668. {
  5669. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  5670. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  5671. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  5672. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  5673. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  5674. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  5675. }
  5676. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature'))
  5677. {
  5678. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  5679. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  5680. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  5681. }
  5682. if (!empty($conf->projet->enabled)) // Most objects
  5683. {
  5684. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  5685. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  5686. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  5687. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  5688. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  5689. }
  5690. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract'))
  5691. {
  5692. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  5693. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  5694. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  5695. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  5696. }
  5697. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  5698. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  5699. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  5700. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  5701. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  5702. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  5703. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  5704. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  5705. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  5706. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  5707. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping'))
  5708. {
  5709. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  5710. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  5711. }
  5712. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception'))
  5713. {
  5714. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  5715. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  5716. }
  5717. } else {
  5718. $substitutionarray['__ID__'] = $object->id;
  5719. $substitutionarray['__REF__'] = $object->ref;
  5720. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5721. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5722. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  5723. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  5724. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5725. // For backward compatibility
  5726. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5727. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5728. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5729. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5730. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5731. $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 : '')) : '');
  5732. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0)
  5733. {
  5734. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  5735. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  5736. if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  5737. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  5738. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  5739. if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  5740. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  5741. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  5742. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  5743. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  5744. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  5745. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  5746. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  5747. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  5748. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  5749. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  5750. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  5751. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  5752. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  5753. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  5754. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  5755. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  5756. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  5757. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  5758. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  5759. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  5760. }
  5761. if (is_object($object) && $object->element == 'societe') {
  5762. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  5763. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  5764. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  5765. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  5766. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  5767. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  5768. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  5769. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  5770. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  5771. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  5772. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  5773. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  5774. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  5775. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  5776. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  5777. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  5778. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  5779. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  5780. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  5781. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  5782. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  5783. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  5784. } elseif (is_object($object->thirdparty)) {
  5785. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  5786. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  5787. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  5788. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  5789. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  5790. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  5791. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  5792. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  5793. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  5794. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  5795. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  5796. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  5797. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  5798. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  5799. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  5800. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  5801. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  5802. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  5803. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  5804. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  5805. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  5806. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  5807. }
  5808. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  5809. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  5810. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  5811. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  5812. }
  5813. if (is_object($object->project))
  5814. {
  5815. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  5816. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  5817. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  5818. }
  5819. if (is_object($object->projet)) // Deprecated, for backward compatibility
  5820. {
  5821. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  5822. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  5823. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  5824. }
  5825. if (is_object($object) && $object->element == 'shipping')
  5826. {
  5827. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  5828. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  5829. }
  5830. if (is_object($object) && $object->element == 'reception')
  5831. {
  5832. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  5833. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  5834. }
  5835. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines))
  5836. {
  5837. $dateplannedstart = '';
  5838. $datenextexpiration = '';
  5839. foreach ($object->lines as $line)
  5840. {
  5841. if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue;
  5842. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue;
  5843. }
  5844. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  5845. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  5846. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  5847. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  5848. }
  5849. // Create dynamic tags for __EXTRAFIELD_FIELD__
  5850. if ($object->table_element && $object->id > 0)
  5851. {
  5852. if (!is_object($extrafields)) $extrafields = new ExtraFields($db);
  5853. $extrafields->fetch_name_optionals_label($object->table_element, true);
  5854. if ($object->fetch_optionals() > 0)
  5855. {
  5856. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
  5857. {
  5858. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  5859. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  5860. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  5861. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  5862. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  5863. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  5864. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  5865. $datetime = $object->array_options['options_'.$key];
  5866. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  5867. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  5868. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  5869. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  5870. }
  5871. }
  5872. }
  5873. }
  5874. }
  5875. // Complete substitution array with the url to make online payment
  5876. $paymenturl = '';
  5877. if (empty($substitutionarray['__REF__']))
  5878. {
  5879. $paymenturl = '';
  5880. } else {
  5881. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  5882. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  5883. $outputlangs->loadLangs(array('paypal', 'other'));
  5884. $typeforonlinepayment = 'free';
  5885. if (is_object($object) && $object->element == 'commande') $typeforonlinepayment = 'order';
  5886. if (is_object($object) && $object->element == 'facture') $typeforonlinepayment = 'invoice';
  5887. if (is_object($object) && $object->element == 'member') $typeforonlinepayment = 'member';
  5888. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  5889. $paymenturl = $url;
  5890. }
  5891. if ($object->id > 0)
  5892. {
  5893. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  5894. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  5895. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal')
  5896. {
  5897. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  5898. } else $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  5899. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande')
  5900. {
  5901. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  5902. } else $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  5903. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture')
  5904. {
  5905. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  5906. } else $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  5907. if (is_object($object) && $object->element == 'propal') $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  5908. if (is_object($object) && $object->element == 'commande') $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  5909. if (is_object($object) && $object->element == 'facture') $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  5910. }
  5911. if (is_object($object) && $object->element == 'action')
  5912. {
  5913. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  5914. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  5915. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  5916. }
  5917. }
  5918. }
  5919. if (empty($exclude) || !in_array('objectamount', $exclude))
  5920. {
  5921. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  5922. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  5923. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  5924. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  5925. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  5926. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  5927. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  5928. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  5929. $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)) : '';
  5930. $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)) : '';
  5931. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  5932. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  5933. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5934. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5935. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? (isset($object->total_vat) ? price($object->total_vat, 0, $outputlangs, 0, 0, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, 0, -1, $conf->currency) : null)) : '';
  5936. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5937. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5938. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  5939. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  5940. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  5941. // TODO Add other keys for foreign multicurrency
  5942. // For backward compatibility
  5943. if ($onlykey != 2)
  5944. {
  5945. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  5946. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  5947. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  5948. }
  5949. }
  5950. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  5951. if (empty($exclude) || !in_array('date', $exclude))
  5952. {
  5953. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5954. $tmp = dol_getdate(dol_now(), true);
  5955. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5956. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  5957. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5958. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  5959. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  5960. $substitutionarray = array_merge($substitutionarray, array(
  5961. '__DAY__' => (string) $tmp['mday'],
  5962. '__DAY_TEXT__' => $daytext, // Monday
  5963. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  5964. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  5965. '__MONTH__' => (string) $tmp['mon'],
  5966. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  5967. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  5968. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  5969. '__YEAR__' => (string) $tmp['year'],
  5970. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  5971. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  5972. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  5973. '__NEXT_DAY__' => (string) $tmp4['day'],
  5974. '__NEXT_MONTH__' => (string) $tmp5['month'],
  5975. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  5976. ));
  5977. }
  5978. if (!empty($conf->multicompany->enabled))
  5979. {
  5980. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  5981. }
  5982. if (empty($exclude) || !in_array('system', $exclude))
  5983. {
  5984. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  5985. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  5986. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  5987. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  5988. }
  5989. return $substitutionarray;
  5990. }
  5991. /**
  5992. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  5993. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  5994. * Example of usage:
  5995. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  5996. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  5997. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  5998. *
  5999. * @param string $text Source string in which we must do substitution
  6000. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  6001. * @param Translate $outputlangs Output language
  6002. * @return string Output string after substitutions
  6003. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  6004. */
  6005. function make_substitutions($text, $substitutionarray, $outputlangs = null)
  6006. {
  6007. global $conf, $langs;
  6008. if (!is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  6009. if (empty($outputlangs)) $outputlangs = $langs;
  6010. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  6011. if (is_object($outputlangs))
  6012. {
  6013. $reg = array();
  6014. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg))
  6015. {
  6016. $msgishtml = 0;
  6017. if (dol_textishtml($text, 1)) $msgishtml = 1;
  6018. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  6019. $tmp = explode('|', $reg[1]);
  6020. if (!empty($tmp[1])) $outputlangs->load($tmp[1]);
  6021. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
  6022. }
  6023. }
  6024. // Make substitution for constant keys.
  6025. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  6026. $reg = array();
  6027. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg))
  6028. {
  6029. $msgishtml = 0;
  6030. if (dol_textishtml($text, 1)) $msgishtml = 1;
  6031. $keyfound = $reg[1];
  6032. if (isASecretKey($keyfound)) $newval = '*****forbidden*****';
  6033. else $newval = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  6034. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ?dol_htmlentitiesbr($newval) : $newval, $text);
  6035. }
  6036. // Make substitition for array $substitutionarray
  6037. foreach ($substitutionarray as $key => $value)
  6038. {
  6039. if (!isset($value)) continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  6040. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value = ''; // Protection
  6041. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6042. }
  6043. return $text;
  6044. }
  6045. /**
  6046. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6047. * In this case, method completesubstitutionarray provided by module is called.
  6048. *
  6049. * @param array $substitutionarray Array substitution old value => new value value
  6050. * @param Translate $outputlangs Output language
  6051. * @param Object $object Source object
  6052. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6053. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6054. * @return void
  6055. * @see make_substitutions()
  6056. */
  6057. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6058. {
  6059. global $conf, $user;
  6060. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6061. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  6062. // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
  6063. /*if (is_object($object) && is_array($object->array_options))
  6064. {
  6065. foreach($object->array_options as $key => $val)
  6066. {
  6067. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  6068. $substitutionarray['__EXTRAFIELD_'.$keyshort.'__']=$val;
  6069. // For backward compatibiliy
  6070. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  6071. }
  6072. }*/
  6073. // Check if there is external substitution to do, requested by plugins
  6074. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  6075. foreach ($dirsubstitutions as $reldir)
  6076. {
  6077. $dir = dol_buildpath($reldir, 0);
  6078. // Check if directory exists
  6079. if (!dol_is_dir($dir)) continue;
  6080. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  6081. foreach ($substitfiles as $substitfile)
  6082. {
  6083. $reg = array();
  6084. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg))
  6085. {
  6086. $module = $reg[1];
  6087. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  6088. // Include the user's functions file
  6089. require_once $dir.$substitfile['name'];
  6090. // Call the user's function, and only if it is defined
  6091. $function_name = $module."_".$callfunc;
  6092. if (function_exists($function_name)) {
  6093. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  6094. }
  6095. }
  6096. }
  6097. }
  6098. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  6099. // to list all tags in odt template
  6100. $tags = '';
  6101. foreach ($substitutionarray as $key => $value) {
  6102. $tags .= '{'.$key.'} => '.$value."\n";
  6103. }
  6104. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  6105. }
  6106. }
  6107. /**
  6108. * Format output for start and end date
  6109. *
  6110. * @param int $date_start Start date
  6111. * @param int $date_end End date
  6112. * @param string $format Output format
  6113. * @param Translate $outputlangs Output language
  6114. * @return void
  6115. */
  6116. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  6117. {
  6118. print get_date_range($date_start, $date_end, $format, $outputlangs);
  6119. }
  6120. /**
  6121. * Format output for start and end date
  6122. *
  6123. * @param int $date_start Start date
  6124. * @param int $date_end End date
  6125. * @param string $format Output format
  6126. * @param Translate $outputlangs Output language
  6127. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  6128. * @return string String
  6129. */
  6130. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  6131. {
  6132. global $langs;
  6133. $out = '';
  6134. if (!is_object($outputlangs)) $outputlangs = $langs;
  6135. if ($date_start && $date_end)
  6136. {
  6137. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6138. }
  6139. if ($date_start && !$date_end)
  6140. {
  6141. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6142. }
  6143. if (!$date_start && $date_end)
  6144. {
  6145. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6146. }
  6147. return $out;
  6148. }
  6149. /**
  6150. * Return firstname and lastname in correct order
  6151. *
  6152. * @param string $firstname Firstname
  6153. * @param string $lastname Lastname
  6154. * @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
  6155. * @return string Firstname + lastname or Lastname + firstname
  6156. */
  6157. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  6158. {
  6159. global $conf;
  6160. $ret = '';
  6161. // If order not defined, we use the setup
  6162. if ($nameorder < 0) $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  6163. if ($nameorder == 1) {
  6164. $ret .= $firstname;
  6165. if ($firstname && $lastname) $ret .= ' ';
  6166. $ret .= $lastname;
  6167. } elseif ($nameorder == 2 || $nameorder == 3) {
  6168. $ret .= $firstname;
  6169. if (empty($ret) && $nameorder == 3) {
  6170. $ret .= $lastname;
  6171. }
  6172. } else { // 0, 4 or 5
  6173. $ret .= $lastname;
  6174. if (empty($ret) && $nameorder == 5) {
  6175. $ret .= $firstname;
  6176. }
  6177. if ($nameorder == 0) {
  6178. if ($firstname && $lastname) $ret .= ' ';
  6179. $ret .= $firstname;
  6180. }
  6181. }
  6182. return $ret;
  6183. }
  6184. /**
  6185. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  6186. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6187. * Note: Prefer to use setEventMessages instead.
  6188. *
  6189. * @param string|string[] $mesgs Message string or array
  6190. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6191. * @return void
  6192. * @see dol_htmloutput_events()
  6193. */
  6194. function setEventMessage($mesgs, $style = 'mesgs')
  6195. {
  6196. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  6197. if (!is_array($mesgs)) {
  6198. // If mesgs is a string
  6199. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  6200. } else {
  6201. // If mesgs is an array
  6202. foreach ($mesgs as $mesg)
  6203. {
  6204. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  6205. }
  6206. }
  6207. }
  6208. /**
  6209. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  6210. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6211. *
  6212. * @param string $mesg Message string
  6213. * @param array $mesgs Message array
  6214. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6215. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  6216. * @return void
  6217. * @see dol_htmloutput_events()
  6218. */
  6219. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  6220. {
  6221. if (empty($mesg) && empty($mesgs))
  6222. {
  6223. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  6224. } else {
  6225. if ($messagekey)
  6226. {
  6227. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  6228. // TODO
  6229. $mesg .= '';
  6230. }
  6231. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey]))
  6232. {
  6233. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  6234. if (empty($mesgs)) setEventMessage($mesg, $style);
  6235. else {
  6236. if (!empty($mesg) && !in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  6237. setEventMessage($mesgs, $style);
  6238. }
  6239. }
  6240. }
  6241. }
  6242. /**
  6243. * Print formated messages to output (Used to show messages on html output).
  6244. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  6245. * no need to call it explicitely.
  6246. *
  6247. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  6248. * @return void
  6249. * @see dol_htmloutput_mesg()
  6250. */
  6251. function dol_htmloutput_events($disabledoutputofmessages = 0)
  6252. {
  6253. // Show mesgs
  6254. if (isset($_SESSION['dol_events']['mesgs'])) {
  6255. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  6256. unset($_SESSION['dol_events']['mesgs']);
  6257. }
  6258. // Show errors
  6259. if (isset($_SESSION['dol_events']['errors'])) {
  6260. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  6261. unset($_SESSION['dol_events']['errors']);
  6262. }
  6263. // Show warnings
  6264. if (isset($_SESSION['dol_events']['warnings'])) {
  6265. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  6266. unset($_SESSION['dol_events']['warnings']);
  6267. }
  6268. }
  6269. /**
  6270. * Get formated messages to output (Used to show messages on html output).
  6271. * This include also the translation of the message key.
  6272. *
  6273. * @param string $mesgstring Message string or message key
  6274. * @param string[] $mesgarray Array of message strings or message keys
  6275. * @param string $style Style of message output ('ok' or 'error')
  6276. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6277. * @return string Return html output
  6278. *
  6279. * @see dol_print_error()
  6280. * @see dol_htmloutput_errors()
  6281. * @see setEventMessages()
  6282. */
  6283. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  6284. {
  6285. global $conf, $langs;
  6286. $ret = 0; $return = '';
  6287. $out = '';
  6288. $divstart = $divend = '';
  6289. // If inline message with no format, we add it.
  6290. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out))
  6291. {
  6292. $divstart = '<div class="'.$style.' clearboth">';
  6293. $divend = '</div>';
  6294. }
  6295. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  6296. {
  6297. $langs->load("errors");
  6298. $out .= $divstart;
  6299. if (is_array($mesgarray) && count($mesgarray))
  6300. {
  6301. foreach ($mesgarray as $message)
  6302. {
  6303. $ret++;
  6304. $out .= $langs->trans($message);
  6305. if ($ret < count($mesgarray)) $out .= "<br>\n";
  6306. }
  6307. }
  6308. if ($mesgstring)
  6309. {
  6310. $langs->load("errors");
  6311. $ret++;
  6312. $out .= $langs->trans($mesgstring);
  6313. }
  6314. $out .= $divend;
  6315. }
  6316. if ($out)
  6317. {
  6318. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  6319. {
  6320. $return = '<script>
  6321. $(document).ready(function() {
  6322. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  6323. if (block) {
  6324. $.dolEventValid("","'.dol_escape_js($out).'");
  6325. } else {
  6326. /* jnotify(message, preset of message type, keepmessage) */
  6327. $.jnotify("'.dol_escape_js($out).'",
  6328. "'.($style == "ok" ? 3000 : $style).'",
  6329. '.($style == "ok" ? "false" : "true").',
  6330. { remove: function (){} } );
  6331. }
  6332. });
  6333. </script>';
  6334. } else {
  6335. $return = $out;
  6336. }
  6337. }
  6338. return $return;
  6339. }
  6340. /**
  6341. * Get formated error messages to output (Used to show messages on html output).
  6342. *
  6343. * @param string $mesgstring Error message
  6344. * @param array $mesgarray Error messages array
  6345. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6346. * @return string Return html output
  6347. *
  6348. * @see dol_print_error()
  6349. * @see dol_htmloutput_mesg()
  6350. */
  6351. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6352. {
  6353. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6354. }
  6355. /**
  6356. * Print formated messages to output (Used to show messages on html output).
  6357. *
  6358. * @param string $mesgstring Message string or message key
  6359. * @param string[] $mesgarray Array of message strings or message keys
  6360. * @param string $style Which style to use ('ok', 'warning', 'error')
  6361. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  6362. * @return void
  6363. *
  6364. * @see dol_print_error()
  6365. * @see dol_htmloutput_errors()
  6366. * @see setEventMessages()
  6367. */
  6368. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  6369. {
  6370. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) return;
  6371. $iserror = 0;
  6372. $iswarning = 0;
  6373. if (is_array($mesgarray))
  6374. {
  6375. foreach ($mesgarray as $val)
  6376. {
  6377. if ($val && preg_match('/class="error"/i', $val)) { $iserror++; break; }
  6378. if ($val && preg_match('/class="warning"/i', $val)) { $iswarning++; break; }
  6379. }
  6380. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) $iserror++;
  6381. elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) $iswarning++;
  6382. if ($style == 'error') $iserror++;
  6383. if ($style == 'warning') $iswarning++;
  6384. if ($iserror || $iswarning)
  6385. {
  6386. // Remove div from texts
  6387. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  6388. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  6389. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  6390. // Remove div from texts array
  6391. if (is_array($mesgarray))
  6392. {
  6393. $newmesgarray = array();
  6394. foreach ($mesgarray as $val)
  6395. {
  6396. if (is_string($val))
  6397. {
  6398. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  6399. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  6400. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  6401. $newmesgarray[] = $tmpmesgstring;
  6402. } else {
  6403. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  6404. }
  6405. }
  6406. $mesgarray = $newmesgarray;
  6407. }
  6408. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  6409. } else print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  6410. }
  6411. /**
  6412. * Print formated error messages to output (Used to show messages on html output).
  6413. *
  6414. * @param string $mesgstring Error message
  6415. * @param array $mesgarray Error messages array
  6416. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6417. * @return void
  6418. *
  6419. * @see dol_print_error()
  6420. * @see dol_htmloutput_mesg()
  6421. */
  6422. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6423. {
  6424. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6425. }
  6426. /**
  6427. * Advanced sort array by second index function, which produces ascending (default)
  6428. * or descending output and uses optionally natural case insensitive sorting (which
  6429. * can be optionally case sensitive as well).
  6430. *
  6431. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  6432. * @param string $index Key in array to use for sorting criteria
  6433. * @param int $order Sort order ('asc' or 'desc')
  6434. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  6435. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  6436. * @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.
  6437. * @return array Sorted array
  6438. */
  6439. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  6440. {
  6441. // Clean parameters
  6442. $order = strtolower($order);
  6443. if (is_array($array))
  6444. {
  6445. $sizearray = count($array);
  6446. if ($sizearray > 0)
  6447. {
  6448. $temp = array();
  6449. foreach (array_keys($array) as $key)
  6450. {
  6451. if (is_object($array[$key])) {
  6452. $temp[$key] = $array[$key]->$index;
  6453. } else {
  6454. $temp[$key] = $array[$key][$index];
  6455. }
  6456. }
  6457. if (!$natsort) {
  6458. ($order == 'asc') ? asort($temp) : arsort($temp);
  6459. } else {
  6460. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  6461. if ($order != 'asc') $temp = array_reverse($temp, true);
  6462. }
  6463. $sorted = array();
  6464. foreach (array_keys($temp) as $key)
  6465. {
  6466. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  6467. }
  6468. return $sorted;
  6469. }
  6470. }
  6471. return $array;
  6472. }
  6473. /**
  6474. * Check if a string is in UTF8
  6475. *
  6476. * @param string $str String to check
  6477. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  6478. */
  6479. function utf8_check($str)
  6480. {
  6481. $str = (string) $str; // Sometimes string is an int.
  6482. // We must use here a binary strlen function (so not dol_strlen)
  6483. $strLength = dol_strlen($str);
  6484. for ($i = 0; $i < $strLength; $i++) {
  6485. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  6486. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n = 1; // 110bbbbb
  6487. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n = 2; // 1110bbbb
  6488. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n = 3; // 11110bbb
  6489. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n = 4; // 111110bb
  6490. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n = 5; // 1111110b
  6491. else return false; // Does not match any model
  6492. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  6493. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  6494. return false;
  6495. }
  6496. }
  6497. return true;
  6498. }
  6499. /**
  6500. * Check if a string is in ASCII
  6501. *
  6502. * @param string $str String to check
  6503. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  6504. */
  6505. function ascii_check($str)
  6506. {
  6507. if (function_exists('mb_check_encoding')) {
  6508. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  6509. if (!mb_check_encoding($str, 'ASCII')) return false;
  6510. } else {
  6511. if (preg_match('/[^\x00-\x7f]/', $str)) return false; // Contains a byte > 7f
  6512. }
  6513. return true;
  6514. }
  6515. /**
  6516. * Return a string encoded into OS filesystem encoding. This function is used to define
  6517. * value to pass to filesystem PHP functions.
  6518. *
  6519. * @param string $str String to encode (UTF-8)
  6520. * @return string Encoded string (UTF-8, ISO-8859-1)
  6521. */
  6522. function dol_osencode($str)
  6523. {
  6524. global $conf;
  6525. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  6526. if (empty($tmp) && !empty($_SERVER["WINDIR"])) $tmp = 'iso-8859-1'; // By default for windows
  6527. if (empty($tmp)) $tmp = 'utf-8'; // By default for other
  6528. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  6529. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  6530. return $str;
  6531. }
  6532. /**
  6533. * Return an id or code from a code or id.
  6534. * Store also Code-Id into a cache to speed up next request on same key.
  6535. *
  6536. * @param DoliDB $db Database handler
  6537. * @param string $key Code or Id to get Id or Code
  6538. * @param string $tablename Table name without prefix
  6539. * @param string $fieldkey Field to search the key into
  6540. * @param string $fieldid Field to get
  6541. * @param int $entityfilter Filter by entity
  6542. * @return int <0 if KO, Id of code if OK
  6543. * @see $langs->getLabelFromKey
  6544. */
  6545. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  6546. {
  6547. global $cache_codes;
  6548. // If key empty
  6549. if ($key == '') return '';
  6550. // Check in cache
  6551. if (isset($cache_codes[$tablename][$key][$fieldid])) // Can be defined to 0 or ''
  6552. {
  6553. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  6554. }
  6555. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  6556. $sql = "SELECT ".$fieldid." as valuetoget";
  6557. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  6558. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  6559. if (!empty($entityfilter))
  6560. $sql .= " AND entity IN (".getEntity($tablename).")";
  6561. $resql = $db->query($sql);
  6562. if ($resql)
  6563. {
  6564. $obj = $db->fetch_object($resql);
  6565. if ($obj) $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  6566. else $cache_codes[$tablename][$key][$fieldid] = '';
  6567. $db->free($resql);
  6568. return $cache_codes[$tablename][$key][$fieldid];
  6569. } else {
  6570. return -1;
  6571. }
  6572. }
  6573. /**
  6574. * Verify if condition in string is ok or not
  6575. *
  6576. * @param string $strRights String with condition to check
  6577. * @return boolean True or False. Return True if strRights is ''
  6578. */
  6579. function verifCond($strRights)
  6580. {
  6581. global $user, $conf, $langs;
  6582. global $leftmenu;
  6583. global $rights; // To export to dol_eval function
  6584. //print $strRights."<br>\n";
  6585. $rights = true;
  6586. if ($strRights != '')
  6587. {
  6588. $str = 'if(!('.$strRights.')) { $rights = false; }';
  6589. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  6590. }
  6591. return $rights;
  6592. }
  6593. /**
  6594. * Replace eval function to add more security.
  6595. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  6596. *
  6597. * @param string $s String to evaluate
  6598. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  6599. * @param int $hideerrors 1=Hide errors
  6600. * @return mixed Nothing or return result of eval
  6601. */
  6602. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  6603. {
  6604. // Only global variables can be changed by eval function and returned to caller
  6605. global $db, $langs, $user, $conf, $website, $websitepage;
  6606. global $action, $mainmenu, $leftmenu;
  6607. global $rights;
  6608. global $object;
  6609. global $mysoc;
  6610. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  6611. global $soc; // For backward compatibility
  6612. //print $s."<br>\n";
  6613. if ($returnvalue) {
  6614. if ($hideerrors) return @eval('return '.$s.';');
  6615. else return eval('return '.$s.';');
  6616. } else {
  6617. if ($hideerrors) @eval($s);
  6618. else eval($s);
  6619. }
  6620. }
  6621. /**
  6622. * Return if var element is ok
  6623. *
  6624. * @param string $element Variable to check
  6625. * @return boolean Return true of variable is not empty
  6626. */
  6627. function dol_validElement($element)
  6628. {
  6629. return (trim($element) != '');
  6630. }
  6631. /**
  6632. * Return img flag of country for a language code or country code
  6633. *
  6634. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  6635. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  6636. * @return string HTML img string with flag.
  6637. */
  6638. function picto_from_langcode($codelang, $moreatt = '')
  6639. {
  6640. if (empty($codelang)) return '';
  6641. if ($codelang == 'auto')
  6642. {
  6643. return '<span class="fa fa-globe"></span>';
  6644. }
  6645. $langtocountryflag = array(
  6646. 'ar_AR' => '',
  6647. 'ca_ES' => 'catalonia',
  6648. 'da_DA' => 'dk',
  6649. 'fr_CA' => 'mq',
  6650. 'sv_SV' => 'se',
  6651. 'AQ' => 'unknown',
  6652. 'CW' => 'unknown',
  6653. 'IM' => 'unknown',
  6654. 'JE' => 'unknown',
  6655. 'MF' => 'unknown',
  6656. 'BL' => 'unknown',
  6657. 'SX' => 'unknown'
  6658. );
  6659. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  6660. else {
  6661. $tmparray = explode('_', $codelang);
  6662. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  6663. }
  6664. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  6665. }
  6666. /**
  6667. * Return default language from country code.
  6668. * Return null if not found.
  6669. *
  6670. * @param string $countrycode Country code like 'US', 'FR', 'CA', ...
  6671. * @return string Value of locale like 'en_US', 'fr_FR', ...
  6672. */
  6673. function getLanguageCodeFromCountryCode($countrycode)
  6674. {
  6675. global $mysoc;
  6676. if (empty($countrycode)) return null;
  6677. if (strtoupper($countrycode) == 'MQ') return 'fr_CA';
  6678. if (strtoupper($countrycode) == 'SE') return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  6679. if (strtoupper($countrycode) == 'CH')
  6680. {
  6681. if ($mysoc->country_code == 'FR') return 'fr_CH';
  6682. if ($mysoc->country_code == 'DE') return 'de_CH';
  6683. }
  6684. // Locale list taken from:
  6685. // http://stackoverflow.com/questions/3191664/
  6686. // list-of-all-locales-and-their-short-codes
  6687. $locales = array(
  6688. 'af-ZA',
  6689. 'am-ET',
  6690. 'ar-AE',
  6691. 'ar-BH',
  6692. 'ar-DZ',
  6693. 'ar-EG',
  6694. 'ar-IQ',
  6695. 'ar-JO',
  6696. 'ar-KW',
  6697. 'ar-LB',
  6698. 'ar-LY',
  6699. 'ar-MA',
  6700. 'ar-OM',
  6701. 'ar-QA',
  6702. 'ar-SA',
  6703. 'ar-SY',
  6704. 'ar-TN',
  6705. 'ar-YE',
  6706. 'as-IN',
  6707. 'ba-RU',
  6708. 'be-BY',
  6709. 'bg-BG',
  6710. 'bn-BD',
  6711. 'bn-IN',
  6712. 'bo-CN',
  6713. 'br-FR',
  6714. 'ca-ES',
  6715. 'co-FR',
  6716. 'cs-CZ',
  6717. 'cy-GB',
  6718. 'da-DK',
  6719. 'de-AT',
  6720. 'de-CH',
  6721. 'de-DE',
  6722. 'de-LI',
  6723. 'de-LU',
  6724. 'dv-MV',
  6725. 'el-GR',
  6726. 'en-AU',
  6727. 'en-BZ',
  6728. 'en-CA',
  6729. 'en-GB',
  6730. 'en-IE',
  6731. 'en-IN',
  6732. 'en-JM',
  6733. 'en-MY',
  6734. 'en-NZ',
  6735. 'en-PH',
  6736. 'en-SG',
  6737. 'en-TT',
  6738. 'en-US',
  6739. 'en-ZA',
  6740. 'en-ZW',
  6741. 'es-AR',
  6742. 'es-BO',
  6743. 'es-CL',
  6744. 'es-CO',
  6745. 'es-CR',
  6746. 'es-DO',
  6747. 'es-EC',
  6748. 'es-ES',
  6749. 'es-GT',
  6750. 'es-HN',
  6751. 'es-MX',
  6752. 'es-NI',
  6753. 'es-PA',
  6754. 'es-PE',
  6755. 'es-PR',
  6756. 'es-PY',
  6757. 'es-SV',
  6758. 'es-US',
  6759. 'es-UY',
  6760. 'es-VE',
  6761. 'et-EE',
  6762. 'eu-ES',
  6763. 'fa-IR',
  6764. 'fi-FI',
  6765. 'fo-FO',
  6766. 'fr-BE',
  6767. 'fr-CA',
  6768. 'fr-CH',
  6769. 'fr-FR',
  6770. 'fr-LU',
  6771. 'fr-MC',
  6772. 'fy-NL',
  6773. 'ga-IE',
  6774. 'gd-GB',
  6775. 'gl-ES',
  6776. 'gu-IN',
  6777. 'he-IL',
  6778. 'hi-IN',
  6779. 'hr-BA',
  6780. 'hr-HR',
  6781. 'hu-HU',
  6782. 'hy-AM',
  6783. 'id-ID',
  6784. 'ig-NG',
  6785. 'ii-CN',
  6786. 'is-IS',
  6787. 'it-CH',
  6788. 'it-IT',
  6789. 'ja-JP',
  6790. 'ka-GE',
  6791. 'kk-KZ',
  6792. 'kl-GL',
  6793. 'km-KH',
  6794. 'kn-IN',
  6795. 'ko-KR',
  6796. 'ky-KG',
  6797. 'lb-LU',
  6798. 'lo-LA',
  6799. 'lt-LT',
  6800. 'lv-LV',
  6801. 'mi-NZ',
  6802. 'mk-MK',
  6803. 'ml-IN',
  6804. 'mn-MN',
  6805. 'mr-IN',
  6806. 'ms-BN',
  6807. 'ms-MY',
  6808. 'mt-MT',
  6809. 'nb-NO',
  6810. 'ne-NP',
  6811. 'nl-BE',
  6812. 'nl-NL',
  6813. 'nn-NO',
  6814. 'oc-FR',
  6815. 'or-IN',
  6816. 'pa-IN',
  6817. 'pl-PL',
  6818. 'ps-AF',
  6819. 'pt-BR',
  6820. 'pt-PT',
  6821. 'rm-CH',
  6822. 'ro-RO',
  6823. 'ru-RU',
  6824. 'rw-RW',
  6825. 'sa-IN',
  6826. 'se-FI',
  6827. 'se-NO',
  6828. 'se-SE',
  6829. 'si-LK',
  6830. 'sk-SK',
  6831. 'sl-SI',
  6832. 'sq-AL',
  6833. 'sv-FI',
  6834. 'sv-SE',
  6835. 'sw-KE',
  6836. 'ta-IN',
  6837. 'te-IN',
  6838. 'th-TH',
  6839. 'tk-TM',
  6840. 'tn-ZA',
  6841. 'tr-TR',
  6842. 'tt-RU',
  6843. 'ug-CN',
  6844. 'uk-UA',
  6845. 'ur-PK',
  6846. 'vi-VN',
  6847. 'wo-SN',
  6848. 'xh-ZA',
  6849. 'yo-NG',
  6850. 'zh-CN',
  6851. 'zh-HK',
  6852. 'zh-MO',
  6853. 'zh-SG',
  6854. 'zh-TW',
  6855. 'zu-ZA',
  6856. );
  6857. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  6858. if (in_array($buildprimarykeytotest, $locales)) return strtolower($countrycode).'_'.strtoupper($countrycode);
  6859. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) // Need extension php-intl
  6860. {
  6861. foreach ($locales as $locale)
  6862. {
  6863. $locale_language = locale_get_primary_language($locale);
  6864. $locale_region = locale_get_region($locale);
  6865. if (strtoupper($countrycode) == $locale_region)
  6866. {
  6867. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  6868. return strtolower($locale_language).'_'.strtoupper($locale_region);
  6869. }
  6870. }
  6871. } else {
  6872. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  6873. }
  6874. return null;
  6875. }
  6876. /**
  6877. * Complete or removed entries into a head array (used to build tabs).
  6878. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  6879. * Or by change using hook completeTabsHead
  6880. *
  6881. * @param Conf $conf Object conf
  6882. * @param Translate $langs Object langs
  6883. * @param object|null $object Object object
  6884. * @param array $head Object head
  6885. * @param int $h New position to fill
  6886. * @param string $type Value for object where objectvalue can be
  6887. * 'thirdparty' to add a tab in third party view
  6888. * 'intervention' to add a tab in intervention view
  6889. * 'supplier_order' to add a tab in supplier order view
  6890. * 'supplier_invoice' to add a tab in supplier invoice view
  6891. * 'invoice' to add a tab in customer invoice view
  6892. * 'order' to add a tab in customer order view
  6893. * 'contract' to add a tabl in contract view
  6894. * 'product' to add a tab in product view
  6895. * 'propal' to add a tab in propal view
  6896. * 'user' to add a tab in user view
  6897. * 'group' to add a tab in group view
  6898. * 'member' to add a tab in fundation member view
  6899. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  6900. * 'ecm' to add a tab for another ecm view
  6901. * 'stock' to add a tab for warehouse view
  6902. * @param string $mode 'add' to complete head, 'remove' to remove entries
  6903. * @return void
  6904. */
  6905. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  6906. {
  6907. global $hookmanager;
  6908. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  6909. {
  6910. foreach ($conf->modules_parts['tabs'][$type] as $value)
  6911. {
  6912. $values = explode(':', $value);
  6913. if ($mode == 'add' && !preg_match('/^\-/', $values[1]))
  6914. {
  6915. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  6916. {
  6917. if ($values[0] != $type) continue;
  6918. if (verifCond($values[4]))
  6919. {
  6920. if ($values[3]) $langs->load($values[3]);
  6921. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6922. {
  6923. $substitutionarray = array();
  6924. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6925. $label = make_substitutions($reg[1], $substitutionarray);
  6926. } else $label = $langs->trans($values[2]);
  6927. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  6928. $head[$h][1] = $label;
  6929. $head[$h][2] = str_replace('+', '', $values[1]);
  6930. $h++;
  6931. }
  6932. } elseif (count($values) == 5) // deprecated
  6933. {
  6934. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  6935. if ($values[0] != $type) continue;
  6936. if ($values[3]) $langs->load($values[3]);
  6937. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6938. {
  6939. $substitutionarray = array();
  6940. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6941. $label = make_substitutions($reg[1], $substitutionarray);
  6942. } else $label = $langs->trans($values[2]);
  6943. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  6944. $head[$h][1] = $label;
  6945. $head[$h][2] = str_replace('+', '', $values[1]);
  6946. $h++;
  6947. }
  6948. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1]))
  6949. {
  6950. if ($values[0] != $type) continue;
  6951. $tabname = str_replace('-', '', $values[1]);
  6952. foreach ($head as $key => $val)
  6953. {
  6954. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  6955. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  6956. if ($head[$key][2] == $tabname && $condition)
  6957. {
  6958. unset($head[$key]);
  6959. break;
  6960. }
  6961. }
  6962. }
  6963. }
  6964. }
  6965. // No need to make a return $head. Var is modified as a reference
  6966. if (!empty($hookmanager))
  6967. {
  6968. $parameters = array('object' => $object, 'mode' => $mode, 'head' => $head);
  6969. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  6970. if ($reshook > 0)
  6971. {
  6972. $head = $hookmanager->resArray;
  6973. $h = count($head);
  6974. }
  6975. }
  6976. }
  6977. /**
  6978. * Print common footer :
  6979. * conf->global->MAIN_HTML_FOOTER
  6980. * js for switch of menu hider
  6981. * js for conf->global->MAIN_GOOGLE_AN_ID
  6982. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  6983. * js for conf->logbuffer
  6984. *
  6985. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  6986. * @return void
  6987. */
  6988. function printCommonFooter($zone = 'private')
  6989. {
  6990. global $conf, $hookmanager, $user, $debugbar;
  6991. global $action;
  6992. global $micro_start_time;
  6993. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  6994. else print "\n".'<!-- Common footer for public page -->'."\n";
  6995. // A div to store page_y POST parameter so we can read it using javascript
  6996. print "\n<!-- A div to store page_y POST parameter -->\n";
  6997. print '<div id="page_y" style="display: none;">'.(empty($_POST['page_y']) ? '' : $_POST['page_y']).'</div>'."\n";
  6998. $parameters = array();
  6999. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  7000. if (empty($reshook))
  7001. {
  7002. if (!empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  7003. print "\n";
  7004. if (!empty($conf->use_javascript_ajax))
  7005. {
  7006. print '<script>'."\n";
  7007. print 'jQuery(document).ready(function() {'."\n";
  7008. if ($zone == 'private' && empty($conf->dol_use_jmobile))
  7009. {
  7010. print "\n";
  7011. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  7012. print 'jQuery("li.menuhider").click(function(event) {';
  7013. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  7014. print ' console.log("We click on .menuhider");'."\n";
  7015. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  7016. print '});'."\n";
  7017. }
  7018. // Management of focus and mandatory for fields
  7019. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))))
  7020. {
  7021. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  7022. $relativepathstring = $_SERVER["PHP_SELF"];
  7023. // Clean $relativepathstring
  7024. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  7025. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  7026. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  7027. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  7028. if (!empty($user->default_values[$relativepathstring]['focus']))
  7029. {
  7030. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval)
  7031. {
  7032. $qualified = 0;
  7033. if ($defkey != '_noquery_')
  7034. {
  7035. $tmpqueryarraytohave = explode('&', $defkey);
  7036. $foundintru = 0;
  7037. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  7038. {
  7039. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7040. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7041. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  7042. }
  7043. if (!$foundintru) $qualified = 1;
  7044. //var_dump($defkey.'-'.$qualified);
  7045. } else $qualified = 1;
  7046. if ($qualified)
  7047. {
  7048. foreach ($defval as $paramkey => $paramval)
  7049. {
  7050. // Set focus on field
  7051. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  7052. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  7053. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  7054. }
  7055. }
  7056. }
  7057. }
  7058. if (!empty($user->default_values[$relativepathstring]['mandatory']))
  7059. {
  7060. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval)
  7061. {
  7062. $qualified = 0;
  7063. if ($defkey != '_noquery_')
  7064. {
  7065. $tmpqueryarraytohave = explode('&', $defkey);
  7066. $foundintru = 0;
  7067. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  7068. {
  7069. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7070. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7071. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  7072. }
  7073. if (!$foundintru) $qualified = 1;
  7074. //var_dump($defkey.'-'.$qualified);
  7075. } else $qualified = 1;
  7076. if ($qualified)
  7077. {
  7078. foreach ($defval as $paramkey => $paramval)
  7079. {
  7080. // Add property 'required' on input
  7081. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7082. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7083. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
  7084. }
  7085. }
  7086. }
  7087. }
  7088. }
  7089. print '});'."\n";
  7090. // End of tuning
  7091. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO))
  7092. {
  7093. print "\n";
  7094. print "/* JS CODE TO ENABLE to add memory info */\n";
  7095. print 'window.console && console.log("';
  7096. if (!empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  7097. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  7098. if (!empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  7099. {
  7100. $micro_end_time = microtime(true);
  7101. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  7102. }
  7103. if (function_exists("memory_get_usage")) {
  7104. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  7105. }
  7106. if (function_exists("memory_get_peak_usage")) {
  7107. print ' - Real mem peak: '.memory_get_peak_usage(true);
  7108. }
  7109. if (function_exists("zend_loader_file_encoded"))
  7110. {
  7111. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  7112. }
  7113. print '");'."\n";
  7114. }
  7115. print "\n".'</script>'."\n";
  7116. // Google Analytics
  7117. // TODO Add a hook here
  7118. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID))
  7119. {
  7120. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  7121. foreach ($tmptagarray as $tmptag) {
  7122. print "\n";
  7123. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  7124. print "
  7125. <!-- Global site tag (gtag.js) - Google Analytics -->
  7126. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  7127. <script>
  7128. window.dataLayer = window.dataLayer || [];
  7129. function gtag(){dataLayer.push(arguments);}
  7130. gtag('js', new Date());
  7131. gtag('config', '".trim($tmptag)."');
  7132. </script>";
  7133. print "\n";
  7134. }
  7135. }
  7136. }
  7137. // Add Xdebug coverage of code
  7138. if (defined('XDEBUGCOVERAGE'))
  7139. {
  7140. print_r(xdebug_get_code_coverage());
  7141. }
  7142. // Add DebugBar data
  7143. if (!empty($user->rights->debugbar->read) && is_object($debugbar))
  7144. {
  7145. $debugbar['time']->stopMeasure('pageaftermaster');
  7146. print '<!-- Output debugbar data -->'."\n";
  7147. $renderer = $debugbar->getRenderer();
  7148. print $debugbar->getRenderer()->render();
  7149. } elseif (count($conf->logbuffer)) // If there is some logs in buffer to show
  7150. {
  7151. print "\n";
  7152. print "<!-- Start of log output\n";
  7153. //print '<div class="hidden">'."\n";
  7154. foreach ($conf->logbuffer as $logline)
  7155. {
  7156. print $logline."<br>\n";
  7157. }
  7158. //print '</div>'."\n";
  7159. print "End of log output -->\n";
  7160. }
  7161. }
  7162. }
  7163. /**
  7164. * Split a string with 2 keys into key array.
  7165. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  7166. *
  7167. * @param string $string String to explode
  7168. * @param string $delimiter Delimiter between each couple of data
  7169. * @param string $kv Delimiter between key and value
  7170. * @return array Array of data exploded
  7171. */
  7172. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  7173. {
  7174. if ($a = explode($delimiter, $string))
  7175. {
  7176. $ka = array();
  7177. foreach ($a as $s) { // each part
  7178. if ($s) {
  7179. if ($pos = strpos($s, $kv)) { // key/value delimiter
  7180. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  7181. } else { // key delimiter not found
  7182. $ka[] = trim($s);
  7183. }
  7184. }
  7185. }
  7186. return $ka;
  7187. }
  7188. return array();
  7189. }
  7190. /**
  7191. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  7192. *
  7193. * @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.
  7194. * @return string HTML code to set focus
  7195. */
  7196. function dol_set_focus($selector)
  7197. {
  7198. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  7199. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  7200. }
  7201. /**
  7202. * Return getmypid() or random PID when function is disabled
  7203. * Some web hosts disable this php function for security reasons
  7204. * and sometimes we can't redeclare function
  7205. *
  7206. * @return int
  7207. */
  7208. function dol_getmypid()
  7209. {
  7210. if (!function_exists('getmypid')) {
  7211. return mt_rand(1, 32768);
  7212. } else {
  7213. return getmypid();
  7214. }
  7215. }
  7216. /**
  7217. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  7218. *
  7219. * @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")
  7220. * @param string $value The value to look for.
  7221. * If param $mode is 0, can contains several keywords separated with a space or |
  7222. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  7223. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  7224. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  7225. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  7226. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  7227. * @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')
  7228. * 3=value is list of string separated with comma (Example 'text 1,text 2'), 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
  7229. * @param integer $nofirstand 1=Do not output the first 'AND'
  7230. * @return string $res The statement to append to the SQL query
  7231. */
  7232. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  7233. {
  7234. global $db, $langs;
  7235. $value = trim($value);
  7236. if ($mode == 0)
  7237. {
  7238. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  7239. }
  7240. if ($mode == 1)
  7241. {
  7242. $value = preg_replace('/([<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do
  7243. }
  7244. $value = preg_replace('/\s*\|\s*/', '|', $value);
  7245. $crits = explode(' ', $value);
  7246. $res = '';
  7247. if (!is_array($fields)) $fields = array($fields);
  7248. $j = 0;
  7249. foreach ($crits as $crit)
  7250. {
  7251. $crit = trim($crit);
  7252. $i = 0; $i2 = 0;
  7253. $newres = '';
  7254. foreach ($fields as $field)
  7255. {
  7256. if ($mode == 1)
  7257. {
  7258. $operator = '=';
  7259. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  7260. $reg = array();
  7261. preg_match('/([<>=]+)/', $crit, $reg);
  7262. if ($reg[1])
  7263. {
  7264. $operator = $reg[1];
  7265. }
  7266. if ($newcrit != '')
  7267. {
  7268. $numnewcrit = price2num($newcrit);
  7269. if (is_numeric($numnewcrit))
  7270. {
  7271. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric
  7272. } else {
  7273. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  7274. }
  7275. $i2++; // a criteria was added to string
  7276. }
  7277. } elseif ($mode == 2 || $mode == -2)
  7278. {
  7279. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  7280. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  7281. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  7282. if ($mode == -2) $newres .= ' OR '.$field.' IS NULL';
  7283. $i2++; // a criteria was added to string
  7284. } elseif ($mode == 3 || $mode == -3)
  7285. {
  7286. $tmparray = explode(',', $crit);
  7287. if (count($tmparray))
  7288. {
  7289. $listofcodes = '';
  7290. foreach ($tmparray as $val)
  7291. {
  7292. $val = trim($val);
  7293. if ($val)
  7294. {
  7295. $listofcodes .= ($listofcodes ? ',' : '');
  7296. $listofcodes .= "'".$db->escape($val)."'";
  7297. }
  7298. }
  7299. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  7300. $i2++; // a criteria was added to string
  7301. }
  7302. if ($mode == -3) $newres .= ' OR '.$field.' IS NULL';
  7303. } elseif ($mode == 4)
  7304. {
  7305. $tmparray = explode(',', $crit);
  7306. if (count($tmparray))
  7307. {
  7308. $listofcodes = '';
  7309. foreach ($tmparray as $val)
  7310. {
  7311. $val = trim($val);
  7312. if ($val)
  7313. {
  7314. $newres .= ($i2 > 0 ? ' OR (' : '(').$field.' LIKE \''.$db->escape($val).',%\'';
  7315. $newres .= ' OR '.$field.' = \''.$db->escape($val).'\'';
  7316. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).'\'';
  7317. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).',%\'';
  7318. $newres .= ')';
  7319. $i2++;
  7320. }
  7321. }
  7322. }
  7323. } else // $mode=0
  7324. {
  7325. $tmpcrits = explode('|', $crit);
  7326. $i3 = 0;
  7327. foreach ($tmpcrits as $tmpcrit)
  7328. {
  7329. if ($tmpcrit !== '0' && empty($tmpcrit)) continue;
  7330. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  7331. if (preg_match('/\.(id|rowid)$/', $field)) // Special case for rowid that is sometimes a ref so used as a search field
  7332. {
  7333. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ?trim($tmpcrit) : '0');
  7334. } else {
  7335. $newres .= $field." LIKE '";
  7336. $tmpcrit = trim($tmpcrit);
  7337. $tmpcrit2 = $tmpcrit;
  7338. $tmpbefore = '%'; $tmpafter = '%';
  7339. if (preg_match('/^[\^\$]/', $tmpcrit))
  7340. {
  7341. $tmpbefore = '';
  7342. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  7343. }
  7344. if (preg_match('/[\^\$]$/', $tmpcrit))
  7345. {
  7346. $tmpafter = '';
  7347. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  7348. }
  7349. $newres .= $tmpbefore;
  7350. $newres .= $db->escape($tmpcrit2);
  7351. $newres .= $tmpafter;
  7352. $newres .= "'";
  7353. if ($tmpcrit2 == '')
  7354. {
  7355. $newres .= ' OR '.$field." IS NULL";
  7356. }
  7357. }
  7358. $i3++;
  7359. }
  7360. $i2++; // a criteria was added to string
  7361. }
  7362. $i++;
  7363. }
  7364. if ($newres) $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  7365. $j++;
  7366. }
  7367. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  7368. //print 'xx'.$res.'yy';
  7369. return $res;
  7370. }
  7371. /**
  7372. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  7373. *
  7374. * @param Object $object Object
  7375. * @return string Url string
  7376. */
  7377. function showDirectDownloadLink($object)
  7378. {
  7379. global $conf, $langs;
  7380. $out = '';
  7381. $url = $object->getLastMainDocLink($object->element);
  7382. if ($url)
  7383. {
  7384. $out .= img_picto('', 'globe').' '.$langs->trans("DirectDownloadLink").'<br>';
  7385. $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
  7386. $out .= ajax_autoselect("directdownloadlink", 0);
  7387. }
  7388. return $out;
  7389. }
  7390. /**
  7391. * Return the filename of file to get the thumbs
  7392. *
  7393. * @param string $file Original filename (full or relative path)
  7394. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  7395. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  7396. * @return string New file name (full or relative path, including the thumbs/)
  7397. */
  7398. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  7399. {
  7400. $dirName = dirname($file);
  7401. if ($dirName == '.') $dirName = '';
  7402. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  7403. $fileName = basename($fileName);
  7404. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  7405. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  7406. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  7407. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  7408. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  7409. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  7410. if (!$extImgTarget) return $file;
  7411. $subdir = '';
  7412. if ($extName) $subdir = 'thumbs/';
  7413. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  7414. }
  7415. /**
  7416. * Return URL we can use for advanced preview links
  7417. *
  7418. * @param string $modulepart propal, facture, facture_fourn, ...
  7419. * @param string $relativepath Relative path of docs.
  7420. * @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)
  7421. * @param string $param More param on http links
  7422. * @return string|array Output string with href link or array with all components of link
  7423. */
  7424. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  7425. {
  7426. global $conf, $langs;
  7427. if (empty($conf->use_javascript_ajax)) return '';
  7428. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  7429. if ($alldata == 1)
  7430. {
  7431. if ($isAllowedForPreview) return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : ''), 'mime'=>dol_mimetype($relativepath));
  7432. else return array();
  7433. }
  7434. // old behavior, return a string
  7435. if ($isAllowedForPreview) return 'javascript:document_preview(\''.dol_escape_js(DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : '')).'\', \''.dol_mimetype($relativepath).'\', \''.dol_escape_js($langs->trans('Preview')).'\')';
  7436. else return '';
  7437. }
  7438. /**
  7439. * Make content of an input box selected when we click into input field.
  7440. *
  7441. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  7442. * @param string $addlink Add a 'link to' after
  7443. * @return string
  7444. */
  7445. function ajax_autoselect($htmlname, $addlink = '')
  7446. {
  7447. global $langs;
  7448. $out = '<script>
  7449. jQuery(document).ready(function () {
  7450. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  7451. });
  7452. </script>';
  7453. if ($addlink) $out .= ' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  7454. return $out;
  7455. }
  7456. /**
  7457. * Return if a file is qualified for preview
  7458. *
  7459. * @param string $file Filename we looking for information
  7460. * @return int 1 If allowed, 0 otherwise
  7461. * @see dol_mimetype(), image_format_supported() from images.lib.php
  7462. */
  7463. function dolIsAllowedForPreview($file)
  7464. {
  7465. global $conf;
  7466. // Check .noexe extension in filename
  7467. if (preg_match('/\.noexe$/i', $file)) return 0;
  7468. // Check mime types
  7469. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  7470. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) $mime_preview[] = 'svg+xml';
  7471. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  7472. //$mime_preview[]='archive';
  7473. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  7474. if ($num_mime !== false) return 1;
  7475. // By default, not allowed for preview
  7476. return 0;
  7477. }
  7478. /**
  7479. * Return mime type of a file
  7480. *
  7481. * @param string $file Filename we looking for MIME type
  7482. * @param string $default Default mime type if extension not found in known list
  7483. * @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
  7484. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  7485. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  7486. */
  7487. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  7488. {
  7489. $mime = $default;
  7490. $imgmime = 'other.png';
  7491. $famime = 'file-o';
  7492. $srclang = '';
  7493. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  7494. // Plain text files
  7495. if (preg_match('/\.txt$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7496. if (preg_match('/\.rtx$/i', $tmpfile)) { $mime = 'text/richtext'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7497. if (preg_match('/\.csv$/i', $tmpfile)) { $mime = 'text/csv'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7498. if (preg_match('/\.tsv$/i', $tmpfile)) { $mime = 'text/tab-separated-values'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7499. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7500. if (preg_match('/\.ini$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'ini'; $famime = 'file-text-o'; }
  7501. if (preg_match('/\.md$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'md'; $famime = 'file-text-o'; }
  7502. if (preg_match('/\.css$/i', $tmpfile)) { $mime = 'text/css'; $imgmime = 'css.png'; $srclang = 'css'; $famime = 'file-text-o'; }
  7503. if (preg_match('/\.lang$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'lang'; $famime = 'file-text-o'; }
  7504. // Certificate files
  7505. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7506. // XML based (HTML/XML/XAML)
  7507. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { $mime = 'text/html'; $imgmime = 'html.png'; $srclang = 'html'; $famime = 'file-text-o'; }
  7508. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xml'; $famime = 'file-text-o'; }
  7509. if (preg_match('/\.xaml$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xaml'; $famime = 'file-text-o'; }
  7510. // Languages
  7511. if (preg_match('/\.bas$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'bas'; $famime = 'file-code-o'; }
  7512. if (preg_match('/\.(c)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'c'; $famime = 'file-code-o'; }
  7513. if (preg_match('/\.(cpp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cpp'; $famime = 'file-code-o'; }
  7514. if (preg_match('/\.cs$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cs'; $famime = 'file-code-o'; }
  7515. if (preg_match('/\.(h)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'h'; $famime = 'file-code-o'; }
  7516. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'java'; $famime = 'file-code-o'; }
  7517. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7518. if (preg_match('/\.phtml$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7519. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'pl.png'; $srclang = 'perl'; $famime = 'file-code-o'; }
  7520. if (preg_match('/\.sql$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'sql'; $famime = 'file-code-o'; }
  7521. if (preg_match('/\.js$/i', $tmpfile)) { $mime = 'text/x-javascript'; $imgmime = 'jscript.png'; $srclang = 'js'; $famime = 'file-code-o'; }
  7522. // Open office
  7523. if (preg_match('/\.odp$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.presentation'; $imgmime = 'ooffice.png'; $famime = 'file-powerpoint-o'; }
  7524. if (preg_match('/\.ods$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.spreadsheet'; $imgmime = 'ooffice.png'; $famime = 'file-excel-o'; }
  7525. if (preg_match('/\.odt$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.text'; $imgmime = 'ooffice.png'; $famime = 'file-word-o'; }
  7526. // MS Office
  7527. if (preg_match('/\.mdb$/i', $tmpfile)) { $mime = 'application/msaccess'; $imgmime = 'mdb.png'; $famime = 'file-o'; }
  7528. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7529. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7530. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7531. if (preg_match('/\.xla(m)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7532. if (preg_match('/\.xls$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7533. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) { $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7534. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-powerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7535. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) { $mime = 'application/x-mspowerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7536. // Other
  7537. if (preg_match('/\.pdf$/i', $tmpfile)) { $mime = 'application/pdf'; $imgmime = 'pdf.png'; $famime = 'file-pdf-o'; }
  7538. // Scripts
  7539. if (preg_match('/\.bat$/i', $tmpfile)) { $mime = 'text/x-bat'; $imgmime = 'script.png'; $srclang = 'dos'; $famime = 'file-code-o'; }
  7540. if (preg_match('/\.sh$/i', $tmpfile)) { $mime = 'text/x-sh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7541. if (preg_match('/\.ksh$/i', $tmpfile)) { $mime = 'text/x-ksh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7542. if (preg_match('/\.bash$/i', $tmpfile)) { $mime = 'text/x-bash'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7543. // Images
  7544. if (preg_match('/\.ico$/i', $tmpfile)) { $mime = 'image/x-icon'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7545. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) { $mime = 'image/jpeg'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7546. if (preg_match('/\.png$/i', $tmpfile)) { $mime = 'image/png'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7547. if (preg_match('/\.gif$/i', $tmpfile)) { $mime = 'image/gif'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7548. if (preg_match('/\.bmp$/i', $tmpfile)) { $mime = 'image/bmp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7549. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) { $mime = 'image/tiff'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7550. if (preg_match('/\.svg$/i', $tmpfile)) { $mime = 'image/svg+xml'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7551. if (preg_match('/\.webp$/i', $tmpfile)) { $mime = 'image/webp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7552. // Calendar
  7553. if (preg_match('/\.vcs$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7554. if (preg_match('/\.ics$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7555. // Other
  7556. if (preg_match('/\.torrent$/i', $tmpfile)) { $mime = 'application/x-bittorrent'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7557. // Audio
  7558. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { $mime = 'audio'; $imgmime = 'audio.png'; $famime = 'file-audio-o'; }
  7559. // Video
  7560. if (preg_match('/\.ogv$/i', $tmpfile)) { $mime = 'video/ogg'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7561. if (preg_match('/\.webm$/i', $tmpfile)) { $mime = 'video/webm'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7562. if (preg_match('/\.avi$/i', $tmpfile)) { $mime = 'video/x-msvideo'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7563. if (preg_match('/\.divx$/i', $tmpfile)) { $mime = 'video/divx'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7564. if (preg_match('/\.xvid$/i', $tmpfile)) { $mime = 'video/xvid'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7565. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) { $mime = 'video'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7566. // Archive
  7567. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i', $tmpfile)) { $mime = 'archive'; $imgmime = 'archive.png'; $famime = 'file-archive-o'; } // application/xxx where zzz is zip, ...
  7568. // Exe
  7569. if (preg_match('/\.(exe|com)$/i', $tmpfile)) { $mime = 'application/octet-stream'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7570. // Lib
  7571. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { $mime = 'library'; $imgmime = 'library.png'; $famime = 'file-o'; }
  7572. // Err
  7573. if (preg_match('/\.err$/i', $tmpfile)) { $mime = 'error'; $imgmime = 'error.png'; $famime = 'file-text-o'; }
  7574. // Return string
  7575. if ($mode == 1)
  7576. {
  7577. $tmp = explode('/', $mime);
  7578. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  7579. }
  7580. if ($mode == 2)
  7581. {
  7582. return $imgmime;
  7583. }
  7584. if ($mode == 3)
  7585. {
  7586. return $srclang;
  7587. }
  7588. if ($mode == 4)
  7589. {
  7590. return $famime;
  7591. }
  7592. return $mime;
  7593. }
  7594. /**
  7595. * Return value from dictionary
  7596. *
  7597. * @param string $tablename name of dictionary
  7598. * @param string $field the value to return
  7599. * @param int $id id of line
  7600. * @param bool $checkentity add filter on entity
  7601. * @param string $rowidfield name of the column rowid
  7602. * @return string
  7603. */
  7604. function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  7605. {
  7606. global $dictvalues, $db, $langs;
  7607. if (!isset($dictvalues[$tablename]))
  7608. {
  7609. $dictvalues[$tablename] = array();
  7610. $sql = 'SELECT * FROM '.$tablename.' WHERE 1'; // Here select * is allowed as it is generic code and we don't have list of fields
  7611. if ($checkentity) $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  7612. $resql = $db->query($sql);
  7613. if ($resql)
  7614. {
  7615. while ($obj = $db->fetch_object($resql))
  7616. {
  7617. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  7618. }
  7619. } else {
  7620. dol_print_error($db);
  7621. }
  7622. }
  7623. if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
  7624. else // Not found
  7625. {
  7626. if ($id > 0) return $id;
  7627. return '';
  7628. }
  7629. }
  7630. /**
  7631. * Return true if the color is light
  7632. *
  7633. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  7634. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  7635. */
  7636. function colorIsLight($stringcolor)
  7637. {
  7638. $stringcolor = str_replace('#', '', $stringcolor);
  7639. $res = -1;
  7640. if (!empty($stringcolor))
  7641. {
  7642. $res = 0;
  7643. $tmp = explode(',', $stringcolor);
  7644. if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
  7645. {
  7646. $r = $tmp[0];
  7647. $g = $tmp[1];
  7648. $b = $tmp[2];
  7649. } else {
  7650. $hexr = $stringcolor[0].$stringcolor[1];
  7651. $hexg = $stringcolor[2].$stringcolor[3];
  7652. $hexb = $stringcolor[4].$stringcolor[5];
  7653. $r = hexdec($hexr);
  7654. $g = hexdec($hexg);
  7655. $b = hexdec($hexb);
  7656. }
  7657. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  7658. if ($bright > 0.6) $res = 1;
  7659. }
  7660. return $res;
  7661. }
  7662. /**
  7663. * Function to test if an entry is enabled or not
  7664. *
  7665. * @param string $type_user 0=We test for internal user, 1=We test for external user
  7666. * @param array $menuentry Array for feature entry to test
  7667. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  7668. * @return int 0=Hide, 1=Show, 2=Show gray
  7669. */
  7670. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  7671. {
  7672. global $conf;
  7673. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  7674. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  7675. if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
  7676. if ($type_user && $menuentry['module'])
  7677. {
  7678. $tmploops = explode('|', $menuentry['module']);
  7679. $found = 0;
  7680. foreach ($tmploops as $tmploop)
  7681. {
  7682. if (in_array($tmploop, $listofmodulesforexternal)) {
  7683. $found++; break;
  7684. }
  7685. }
  7686. if (!$found) return 0; // Entry is for menus all excluded to external users
  7687. }
  7688. if (!$menuentry['perms'] && $type_user) return 0; // No permissions and user is external
  7689. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  7690. if (!$menuentry['perms']) return 2; // No permissions and user is external
  7691. return 1;
  7692. }
  7693. /**
  7694. * Round to next multiple.
  7695. *
  7696. * @param double $n Number to round up
  7697. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  7698. * @return integer Value rounded.
  7699. */
  7700. function roundUpToNextMultiple($n, $x = 5)
  7701. {
  7702. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  7703. }
  7704. /**
  7705. * Function dolGetBadge
  7706. *
  7707. * @param string $label label of badge no html : use in alt attribute for accessibility
  7708. * @param string $html optional : label of badge with html
  7709. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  7710. * @param string $mode default '' , 'pill', 'dot'
  7711. * @param string $url the url for link
  7712. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  7713. * @return string Html badge
  7714. */
  7715. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  7716. {
  7717. $attr = array(
  7718. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  7719. );
  7720. if (empty($html)) {
  7721. $html = $label;
  7722. }
  7723. if (!empty($url)) {
  7724. $attr['href'] = $url;
  7725. }
  7726. if ($mode === 'dot') {
  7727. $attr['class'] .= ' classfortooltip';
  7728. $attr['title'] = $html;
  7729. $attr['aria-label'] = $label;
  7730. $html = '';
  7731. }
  7732. // Override attr
  7733. if (!empty($params['attr']) && is_array($params['attr'])) {
  7734. foreach ($params['attr']as $key => $value) {
  7735. if ($key == 'class') {
  7736. $attr['class'] .= ' '.$value;
  7737. } elseif ($key == 'classOverride') {
  7738. $attr['class'] = $value;
  7739. } else {
  7740. $attr[$key] = $value;
  7741. }
  7742. }
  7743. }
  7744. // TODO: add hook
  7745. // escape all attribute
  7746. $attr = array_map('dol_escape_htmltag', $attr);
  7747. $TCompiledAttr = array();
  7748. foreach ($attr as $key => $value) {
  7749. $TCompiledAttr[] = $key.'="'.$value.'"';
  7750. }
  7751. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7752. $tag = !empty($url) ? 'a' : 'span';
  7753. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  7754. }
  7755. /**
  7756. * Output the badge of a status.
  7757. *
  7758. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  7759. * @param string $statusLabelShort Short label of badge no html
  7760. * @param string $html Optional : label of badge with html
  7761. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  7762. * @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
  7763. * @param string $url The url for link
  7764. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  7765. * @return string Html status string
  7766. */
  7767. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  7768. {
  7769. global $conf;
  7770. $return = '';
  7771. $dolGetBadgeParams = array();
  7772. if (!empty($params['badgeParams'])) {
  7773. $dolGetBadgeParams = $params['badgeParams'];
  7774. }
  7775. // TODO : add a hook
  7776. if ($displayMode == 0) {
  7777. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  7778. } elseif ($displayMode == 1) {
  7779. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7780. } // Use status with images (for backward compatibility)
  7781. elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  7782. $return = '';
  7783. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  7784. $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>' : '');
  7785. // For small screen, we always use the short label instead of long label.
  7786. if (!empty($conf->dol_optimize_smallscreen))
  7787. {
  7788. if ($displayMode == 0) $displayMode = 1;
  7789. elseif ($displayMode == 4) $displayMode = 2;
  7790. elseif ($displayMode == 6) $displayMode = 5;
  7791. }
  7792. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  7793. $statusImg = array(
  7794. 'status0' => 'statut0',
  7795. 'status1' => 'statut1',
  7796. 'status2' => 'statut2',
  7797. 'status3' => 'statut3',
  7798. 'status4' => 'statut4',
  7799. 'status5' => 'statut5',
  7800. 'status6' => 'statut6',
  7801. 'status7' => 'statut7',
  7802. 'status8' => 'statut8',
  7803. 'status9' => 'statut9'
  7804. );
  7805. if (!empty($statusImg[$statusType])) {
  7806. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  7807. } else {
  7808. $htmlImg = img_picto($statusLabel, $statusType);
  7809. }
  7810. if ($displayMode === 2) {
  7811. $return = $htmlImg.' '.$htmlLabelShort;
  7812. } elseif ($displayMode === 3) {
  7813. $return = $htmlImg;
  7814. } elseif ($displayMode === 4) {
  7815. $return = $htmlImg.' '.$htmlLabel;
  7816. } elseif ($displayMode === 5) {
  7817. $return = $htmlLabelShort.' '.$htmlImg;
  7818. } else { // $displayMode >= 6
  7819. $return = $htmlLabel.' '.$htmlImg;
  7820. }
  7821. } // Use new badge
  7822. elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  7823. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7824. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  7825. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  7826. if ($displayMode == 3) {
  7827. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  7828. } elseif ($displayMode === 5) {
  7829. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  7830. } else {
  7831. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  7832. }
  7833. }
  7834. return $return;
  7835. }
  7836. /**
  7837. * Function dolGetButtonAction
  7838. *
  7839. * @param string $label label of button no html : use in alt attribute for accessibility $html is not empty
  7840. * @param string $html optional : content with html
  7841. * @param string $actionType default, delete, danger
  7842. * @param string $url the url for link
  7843. * @param string $id attribute id of button
  7844. * @param int $userRight user action right
  7845. * @param array $params various params for future : recommended rather than adding more function arguments
  7846. * @return string html button
  7847. */
  7848. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  7849. {
  7850. $class = 'butAction';
  7851. if ($actionType == 'danger' || $actionType == 'delete') {
  7852. $class = 'butActionDelete';
  7853. }
  7854. $attr = array(
  7855. 'class' => $class
  7856. ,'href' => empty($url) ? '' : $url
  7857. );
  7858. if (empty($html)) {
  7859. $html = $label;
  7860. } else {
  7861. $attr['aria-label'] = $label;
  7862. }
  7863. if (empty($userRight)) {
  7864. $attr['class'] = 'butActionRefused';
  7865. $attr['href'] = '';
  7866. }
  7867. if (!empty($id)) {
  7868. $attr['id'] = $id;
  7869. }
  7870. // Override attr
  7871. if (!empty($params['attr']) && is_array($params['attr'])) {
  7872. foreach ($params['attr'] as $key => $value) {
  7873. if ($key == 'class') {
  7874. $attr['class'] .= ' '.$value;
  7875. } elseif ($key == 'classOverride') {
  7876. $attr['class'] = $value;
  7877. } else {
  7878. $attr[$key] = $value;
  7879. }
  7880. }
  7881. }
  7882. if (isset($attr['href']) && empty($attr['href'])) {
  7883. unset($attr['href']);
  7884. }
  7885. // TODO : add a hook
  7886. // escape all attribute
  7887. $attr = array_map('dol_escape_htmltag', $attr);
  7888. $TCompiledAttr = array();
  7889. foreach ($attr as $key => $value) {
  7890. $TCompiledAttr[] = $key.'="'.$value.'"';
  7891. }
  7892. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7893. $tag = !empty($attr['href']) ? 'a' : 'span';
  7894. return '<div class="inline-block divButAction"><'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'></div>';
  7895. }
  7896. /**
  7897. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  7898. *
  7899. * @param string $label label of button
  7900. * @param string $helpText optional : content for help tooltip
  7901. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  7902. * @param string $url the url for link
  7903. * @param string $id attribute id of button
  7904. * @param int $status 0 no user rights, 1 active, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  7905. * @param array $params various params for future : recommended rather than adding more function arguments
  7906. * @return string html button
  7907. */
  7908. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  7909. {
  7910. global $langs, $conf, $user;
  7911. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  7912. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  7913. return '';
  7914. }
  7915. $class = 'btnTitle';
  7916. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-comment-dots'))) $class .= ' btnTitlePlus';
  7917. $useclassfortooltip = 1;
  7918. if (!empty($params['morecss'])) $class .= ' '.$params['morecss'];
  7919. $attr = array(
  7920. 'class' => $class,
  7921. 'href' => empty($url) ? '' : $url
  7922. );
  7923. if (!empty($helpText)) {
  7924. $attr['title'] = dol_escape_htmltag($helpText);
  7925. } elseif (empty($attr['title']) && $label) {
  7926. $attr['title'] = $label;
  7927. $useclassfortooltip = 0;
  7928. }
  7929. if ($status <= 0) {
  7930. $attr['class'] .= ' refused';
  7931. $attr['href'] = '';
  7932. if ($status == -1) { // disable
  7933. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  7934. } elseif ($status == 0) { // Not enough permissions
  7935. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  7936. }
  7937. }
  7938. if (!empty($attr['title']) && $useclassfortooltip) {
  7939. $attr['class'] .= ' classfortooltip';
  7940. }
  7941. if (!empty($id)) {
  7942. $attr['id'] = $id;
  7943. }
  7944. // Override attr
  7945. if (!empty($params['attr']) && is_array($params['attr'])) {
  7946. foreach ($params['attr'] as $key => $value) {
  7947. if ($key == 'class') {
  7948. $attr['class'] .= ' '.$value;
  7949. } elseif ($key == 'classOverride') {
  7950. $attr['class'] = $value;
  7951. } else {
  7952. $attr[$key] = $value;
  7953. }
  7954. }
  7955. }
  7956. if (isset($attr['href']) && empty($attr['href'])) {
  7957. unset($attr['href']);
  7958. }
  7959. // TODO : add a hook
  7960. // escape all attribute
  7961. $attr = array_map('dol_escape_htmltag', $attr);
  7962. $TCompiledAttr = array();
  7963. foreach ($attr as $key => $value) {
  7964. $TCompiledAttr[] = $key.'="'.$value.'"';
  7965. }
  7966. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  7967. $tag = (empty($attr['href']) ? 'span' : 'a');
  7968. $button = '<'.$tag.' '.$compiledAttributes.'>';
  7969. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  7970. if (!empty($params['forcenohideoftext'])) {
  7971. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  7972. }
  7973. $button .= '</'.$tag.'>';
  7974. return $button;
  7975. }
  7976. /**
  7977. * Get an array with properties of an element.
  7978. * Called by fetchObjectByElement.
  7979. *
  7980. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  7981. * @return array (module, classpath, element, subelement, classfile, classname)
  7982. */
  7983. function getElementProperties($element_type)
  7984. {
  7985. $regs = array();
  7986. $classfile = $classname = $classpath = '';
  7987. // Parse element/subelement (ex: project_task)
  7988. $module = $element_type;
  7989. $element = $element_type;
  7990. $subelement = $element_type;
  7991. // If we ask an resource form external module (instead of default path)
  7992. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  7993. $element = $subelement = $regs[1];
  7994. $module = $regs[2];
  7995. }
  7996. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  7997. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  7998. $module = $element = $regs[1];
  7999. $subelement = $regs[2];
  8000. }
  8001. // For compat
  8002. if ($element_type == "action") {
  8003. $classpath = 'comm/action/class';
  8004. $subelement = 'Actioncomm';
  8005. $module = 'agenda';
  8006. }
  8007. // To work with non standard path
  8008. if ($element_type == 'facture' || $element_type == 'invoice') {
  8009. $classpath = 'compta/facture/class';
  8010. $module = 'facture';
  8011. $subelement = 'facture';
  8012. }
  8013. if ($element_type == 'commande' || $element_type == 'order') {
  8014. $classpath = 'commande/class';
  8015. $module = 'commande';
  8016. $subelement = 'commande';
  8017. }
  8018. if ($element_type == 'propal') {
  8019. $classpath = 'comm/propal/class';
  8020. }
  8021. if ($element_type == 'supplier_proposal') {
  8022. $classpath = 'supplier_proposal/class';
  8023. }
  8024. if ($element_type == 'shipping') {
  8025. $classpath = 'expedition/class';
  8026. $subelement = 'expedition';
  8027. $module = 'expedition_bon';
  8028. }
  8029. if ($element_type == 'delivery') {
  8030. $classpath = 'delivery/class';
  8031. $subelement = 'delivery';
  8032. $module = 'delivery_note';
  8033. }
  8034. if ($element_type == 'contract') {
  8035. $classpath = 'contrat/class';
  8036. $module = 'contrat';
  8037. $subelement = 'contrat';
  8038. }
  8039. if ($element_type == 'member') {
  8040. $classpath = 'adherents/class';
  8041. $module = 'adherent';
  8042. $subelement = 'adherent';
  8043. }
  8044. if ($element_type == 'cabinetmed_cons') {
  8045. $classpath = 'cabinetmed/class';
  8046. $module = 'cabinetmed';
  8047. $subelement = 'cabinetmedcons';
  8048. }
  8049. if ($element_type == 'fichinter') {
  8050. $classpath = 'fichinter/class';
  8051. $module = 'ficheinter';
  8052. $subelement = 'fichinter';
  8053. }
  8054. if ($element_type == 'dolresource' || $element_type == 'resource') {
  8055. $classpath = 'resource/class';
  8056. $module = 'resource';
  8057. $subelement = 'dolresource';
  8058. }
  8059. if ($element_type == 'propaldet') {
  8060. $classpath = 'comm/propal/class';
  8061. $module = 'propal';
  8062. $subelement = 'propaleligne';
  8063. }
  8064. if ($element_type == 'order_supplier') {
  8065. $classpath = 'fourn/class';
  8066. $module = 'fournisseur';
  8067. $subelement = 'commandefournisseur';
  8068. $classfile = 'fournisseur.commande';
  8069. }
  8070. if ($element_type == 'invoice_supplier') {
  8071. $classpath = 'fourn/class';
  8072. $module = 'fournisseur';
  8073. $subelement = 'facturefournisseur';
  8074. $classfile = 'fournisseur.facture';
  8075. }
  8076. if ($element_type == "service") {
  8077. $classpath = 'product/class';
  8078. $subelement = 'product';
  8079. }
  8080. if (empty($classfile)) $classfile = strtolower($subelement);
  8081. if (empty($classname)) $classname = ucfirst($subelement);
  8082. if (empty($classpath)) $classpath = $module.'/class';
  8083. $element_properties = array(
  8084. 'module' => $module,
  8085. 'classpath' => $classpath,
  8086. 'element' => $element,
  8087. 'subelement' => $subelement,
  8088. 'classfile' => $classfile,
  8089. 'classname' => $classname
  8090. );
  8091. return $element_properties;
  8092. }
  8093. /**
  8094. * Fetch an object from its id and element_type
  8095. * Inclusion of classes is automatic
  8096. *
  8097. * @param int $element_id Element id
  8098. * @param string $element_type Element type
  8099. * @param string $element_ref Element ref (Use this or element_id but not both)
  8100. * @return int|object object || 0 || -1 if error
  8101. */
  8102. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  8103. {
  8104. global $conf, $db;
  8105. $element_prop = getElementProperties($element_type);
  8106. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
  8107. {
  8108. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  8109. $objecttmp = new $element_prop['classname']($db);
  8110. $ret = $objecttmp->fetch($element_id, $element_ref);
  8111. if ($ret >= 0)
  8112. {
  8113. return $objecttmp;
  8114. }
  8115. }
  8116. return 0;
  8117. }
  8118. /**
  8119. * Return if a file can contains executable content
  8120. *
  8121. * @param string $filename File name to test
  8122. * @return boolean True if yes, False if no
  8123. */
  8124. function isAFileWithExecutableContent($filename)
  8125. {
  8126. 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))
  8127. {
  8128. return true;
  8129. }
  8130. return false;
  8131. }
  8132. /**
  8133. * Return the value of token currently saved into session with name 'newtoken'.
  8134. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  8135. *
  8136. * @return string
  8137. */
  8138. function newToken()
  8139. {
  8140. return $_SESSION['newtoken'];
  8141. }
  8142. /**
  8143. * Return the value of token currently saved into session with name 'token'.
  8144. *
  8145. * @return string
  8146. */
  8147. function currentToken()
  8148. {
  8149. return $_SESSION['token'];
  8150. }
  8151. /**
  8152. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  8153. *
  8154. * @param string $header The first left header of the table (automatic translated)
  8155. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  8156. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  8157. * @param integer $emptyRows (optional) The count of empty rows after the first header
  8158. * @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"
  8159. * @return void
  8160. *
  8161. * @see finishSimpleTable()
  8162. */
  8163. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  8164. {
  8165. global $langs;
  8166. print '<div class="div-table-responsive-no-min">';
  8167. print '<table class="noborder centpercent">';
  8168. print '<tr class="liste_titre">';
  8169. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  8170. print $langs->trans($header);
  8171. // extra space between the first header and the number
  8172. if ($number > -1) {
  8173. print ' ';
  8174. }
  8175. if (!empty($link)) {
  8176. if (!empty($arguments)) {
  8177. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  8178. } else {
  8179. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  8180. }
  8181. }
  8182. if ($number > -1) {
  8183. print '<span class="badge">'.$number.'</span>';
  8184. }
  8185. if (!empty($link)) {
  8186. print '</a>';
  8187. }
  8188. print '</th>';
  8189. if ($number < 0 && !empty($link)) {
  8190. print '<th class="right">';
  8191. if (!empty($arguments)) {
  8192. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  8193. } else {
  8194. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  8195. }
  8196. print $langs->trans("FullList");
  8197. print '</a>';
  8198. print '</th>';
  8199. }
  8200. print '</tr>';
  8201. }
  8202. /**
  8203. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  8204. *
  8205. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  8206. * @return void
  8207. *
  8208. * @see startSimpleTable()
  8209. */
  8210. function finishSimpleTable($addLineBreak = false)
  8211. {
  8212. print '</table>';
  8213. print '</div>';
  8214. if ($addLineBreak) {
  8215. print '<br>';
  8216. }
  8217. }
  8218. /**
  8219. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  8220. *
  8221. * @param integer $tableColumnCount The complete count columns of the table
  8222. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  8223. * @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)
  8224. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  8225. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  8226. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  8227. * @return void
  8228. */
  8229. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  8230. {
  8231. global $langs;
  8232. if ($num === 0) {
  8233. print '<tr class="oddeven">';
  8234. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  8235. print '</tr>';
  8236. return;
  8237. }
  8238. if ($nbofloop === 0)
  8239. {
  8240. // don't show a summary line
  8241. return;
  8242. }
  8243. if ($num === 0) {
  8244. $colspan = $tableColumnCount;
  8245. }
  8246. elseif ($num > $nbofloop) {
  8247. $colspan = $tableColumnCount;
  8248. } else {
  8249. $colspan = $tableColumnCount - 1;
  8250. }
  8251. if ($extraRightColumn) {
  8252. $colspan--;
  8253. }
  8254. print '<tr class="liste_total">';
  8255. if ($nbofloop > 0 && $num > $nbofloop) {
  8256. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  8257. } else {
  8258. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  8259. print '<td class="right" width="100">'.price($total).'</td>';
  8260. }
  8261. if ($extraRightColumn) {
  8262. print '<td></td>';
  8263. }
  8264. print '</tr>';
  8265. }
  8266. /**
  8267. * Return a file on output using a low memory. It can return very large files with no need of memory.
  8268. * WARNING: This close output buffers.
  8269. *
  8270. * @param string $fullpath_original_file_osencoded Full path of file to return.
  8271. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  8272. * @return void
  8273. */
  8274. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  8275. {
  8276. global $conf;
  8277. if ($method == -1) {
  8278. $method = 0;
  8279. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1;
  8280. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2;
  8281. }
  8282. // Be sure we don't have output buffering enabled to have readfile working correctly
  8283. while (ob_get_level()) ob_end_flush();
  8284. // Solution 0
  8285. if ($method == 0) {
  8286. readfile($fullpath_original_file_osencoded);
  8287. }
  8288. // Solution 1
  8289. elseif ($method == 1) {
  8290. $handle = fopen($fullpath_original_file_osencoded, "rb");
  8291. while (!feof($handle)) {
  8292. print fread($handle, 8192);
  8293. }
  8294. fclose($handle);
  8295. }
  8296. // Solution 2
  8297. elseif ($method == 2) {
  8298. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  8299. $handle2 = fopen("php://output", "wb");
  8300. stream_copy_to_stream($handle1, $handle2);
  8301. fclose($handle1);
  8302. fclose($handle2);
  8303. }
  8304. }