functions.lib.php 370 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965
  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 information about user browser
  112. *
  113. * Returns array with the following format:
  114. * array(
  115. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  116. * 'browserversion' => Browser version. Empty if unknown
  117. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  118. * 'layout' => (tablet|phone|classic)
  119. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  120. * 'tablet' => true/false
  121. * )
  122. *
  123. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  124. * @return array Check function documentation
  125. */
  126. function getBrowserInfo($user_agent)
  127. {
  128. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  129. $name = 'unknown';
  130. $version = '';
  131. $os = 'unknown';
  132. $phone = '';
  133. $detectmobile = new Mobile_Detect(null, $user_agent);
  134. $tablet = $detectmobile->isTablet();
  135. if ($detectmobile->isMobile()) {
  136. $phone = 'unknown';
  137. // If phone/smartphone, we set phone os name.
  138. if ($detectmobile->is('AndroidOS')) {
  139. $os = $phone = 'android';
  140. } elseif ($detectmobile->is('BlackBerryOS')) {
  141. $os = $phone = 'blackberry';
  142. } elseif ($detectmobile->is('iOS')) {
  143. $os = 'ios';
  144. $phone = 'iphone';
  145. } elseif ($detectmobile->is('PalmOS')) {
  146. $os = $phone = 'palm';
  147. } elseif ($detectmobile->is('SymbianOS')) {
  148. $os = 'symbian';
  149. } elseif ($detectmobile->is('webOS')) {
  150. $os = 'webos';
  151. } elseif ($detectmobile->is('MaemoOS')) {
  152. $os = 'maemo';
  153. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  154. $os = 'windows';
  155. }
  156. }
  157. // OS
  158. 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'; }
  159. // Name
  160. 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
  161. 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.
  162. 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
  163. 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
  164. elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name = 'lynxlinks'; $version = $reg[4]; }
  165. if ($tablet) {
  166. $layout = 'tablet';
  167. } elseif ($phone) {
  168. $layout = 'phone';
  169. } else {
  170. $layout = 'classic';
  171. }
  172. return array(
  173. 'browsername' => $name,
  174. 'browserversion' => $version,
  175. 'browseros' => $os,
  176. 'layout' => $layout,
  177. 'phone' => $phone,
  178. 'tablet' => $tablet
  179. );
  180. }
  181. /**
  182. * Function called at end of web php process
  183. *
  184. * @return void
  185. */
  186. function dol_shutdown()
  187. {
  188. global $conf, $user, $langs, $db;
  189. $disconnectdone = false; $depth = 0;
  190. if (is_object($db) && !empty($db->connected)) { $depth = $db->transaction_opened; $disconnectdone = $db->close(); }
  191. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  192. }
  193. /**
  194. * Return true if we are in a context of submitting a parameter
  195. *
  196. * @param string $paramname Name or parameter to test
  197. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  198. */
  199. function GETPOSTISSET($paramname)
  200. {
  201. $isset = 0;
  202. $relativepathstring = $_SERVER["PHP_SELF"];
  203. // Clean $relativepathstring
  204. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  205. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  206. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  207. //var_dump($relativepathstring);
  208. //var_dump($user->default_values);
  209. // Code for search criteria persistence.
  210. // Retrieve values if restore_lastsearch_values
  211. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  212. {
  213. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  214. {
  215. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  216. if (is_array($tmp))
  217. {
  218. foreach ($tmp as $key => $val)
  219. {
  220. if ($key == $paramname) // We are on the requested parameter
  221. {
  222. $isset = 1;
  223. break;
  224. }
  225. }
  226. }
  227. }
  228. // If there is saved contextpage, page or limit
  229. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  230. {
  231. $isset = 1;
  232. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  233. {
  234. $isset = 1;
  235. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  236. {
  237. $isset = 1;
  238. }
  239. } else {
  240. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname]));
  241. }
  242. return $isset;
  243. }
  244. /**
  245. * Return value of a param into GET or POST supervariable.
  246. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  247. * Note: The property $user->default_values is loaded by main.php when loading the user.
  248. *
  249. * @param string $paramname Name of parameter to found
  250. * @param string $check Type of check
  251. * ''=no check (deprecated)
  252. * 'none'=no check (only for param that should have very rich content)
  253. * 'int'=check it's numeric (integer or float)
  254. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  255. * 'alpha'=Same than alphanohtml since v13
  256. * 'alphanohtml'=check there is no html content and no " and no ../
  257. * 'aZ'=check it's a-z only
  258. * 'aZ09'=check it's simple alpha string (recommended for keys)
  259. * 'array'=check it's array
  260. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  261. * 'nohtml'=check there is no html content and no " and no ../
  262. * 'restricthtml'=check html content is restricted to some tags only
  263. * 'custom'= custom filter specify $filter and $options)
  264. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  265. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  266. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  267. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  268. * @return string|array Value found (string or array), or '' if check fails
  269. */
  270. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  271. {
  272. global $mysoc, $user, $conf;
  273. if (empty($paramname)) return 'BadFirstParameterForGETPOST';
  274. if (empty($check))
  275. {
  276. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  277. // Enable this line to know who call the GETPOST with '' $check parameter.
  278. //var_dump(debug_backtrace()[0]);
  279. }
  280. if (empty($method)) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  281. elseif ($method == 1) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  282. elseif ($method == 2) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  283. elseif ($method == 3) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  284. else return 'BadThirdParameterForGETPOST';
  285. if (empty($method) || $method == 3 || $method == 4)
  286. {
  287. $relativepathstring = $_SERVER["PHP_SELF"];
  288. // Clean $relativepathstring
  289. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  290. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  291. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  292. //var_dump($relativepathstring);
  293. //var_dump($user->default_values);
  294. // Code for search criteria persistence.
  295. // Retrieve values if restore_lastsearch_values
  296. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  297. {
  298. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  299. {
  300. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  301. if (is_array($tmp))
  302. {
  303. foreach ($tmp as $key => $val)
  304. {
  305. if ($key == $paramname) // We are on the requested parameter
  306. {
  307. $out = $val;
  308. break;
  309. }
  310. }
  311. }
  312. }
  313. // If there is saved contextpage, page or limit
  314. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  315. {
  316. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  317. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  318. {
  319. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  320. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  321. {
  322. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  323. }
  324. } // Else, retreive default values if we are not doing a sort
  325. 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
  326. {
  327. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  328. {
  329. // Search default value from $object->field
  330. global $object;
  331. if (is_object($object) && isset($object->fields[$paramname]['default']))
  332. {
  333. $out = $object->fields[$paramname]['default'];
  334. }
  335. }
  336. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
  337. {
  338. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  339. {
  340. // Now search in setup to overwrite default values
  341. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  342. {
  343. if (isset($user->default_values[$relativepathstring]['createform']))
  344. {
  345. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval)
  346. {
  347. $qualified = 0;
  348. if ($defkey != '_noquery_')
  349. {
  350. $tmpqueryarraytohave = explode('&', $defkey);
  351. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  352. $foundintru = 0;
  353. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  354. {
  355. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  356. }
  357. if (!$foundintru) $qualified = 1;
  358. //var_dump($defkey.'-'.$qualified);
  359. } else $qualified = 1;
  360. if ($qualified)
  361. {
  362. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname]))
  363. {
  364. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  365. break;
  366. }
  367. }
  368. }
  369. }
  370. }
  371. } // Management of default search_filters and sort order
  372. //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  373. elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  374. {
  375. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  376. {
  377. //var_dump($user->default_values[$relativepathstring]);
  378. if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ?
  379. {
  380. if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...']
  381. {
  382. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval)
  383. {
  384. $qualified = 0;
  385. if ($defkey != '_noquery_')
  386. {
  387. $tmpqueryarraytohave = explode('&', $defkey);
  388. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  389. $foundintru = 0;
  390. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  391. {
  392. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  393. }
  394. if (!$foundintru) $qualified = 1;
  395. //var_dump($defkey.'-'.$qualified);
  396. } else $qualified = 1;
  397. if ($qualified)
  398. {
  399. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  400. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val)
  401. {
  402. if ($out) $out .= ', ';
  403. if ($paramname == 'sortfield')
  404. {
  405. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  406. }
  407. if ($paramname == 'sortorder')
  408. {
  409. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  410. }
  411. }
  412. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  413. }
  414. }
  415. }
  416. } elseif (isset($user->default_values[$relativepathstring]['filters']))
  417. {
  418. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  419. {
  420. $qualified = 0;
  421. if ($defkey != '_noquery_')
  422. {
  423. $tmpqueryarraytohave = explode('&', $defkey);
  424. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  425. $foundintru = 0;
  426. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  427. {
  428. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  429. }
  430. if (!$foundintru) $qualified = 1;
  431. //var_dump($defkey.'-'.$qualified);
  432. } else $qualified = 1;
  433. if ($qualified)
  434. {
  435. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all']))
  436. {
  437. // We made a search from quick search menu, do we still use default filter ?
  438. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH))
  439. {
  440. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  441. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  442. }
  443. } else {
  444. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  445. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  446. }
  447. break;
  448. }
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. }
  456. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  457. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  458. // 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.
  459. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace))
  460. {
  461. $reg = array();
  462. $maxloop = 20; $loopnb = 0; // Protection against infinite loop
  463. 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.
  464. {
  465. $loopnb++; $newout = '';
  466. if ($reg[1] == 'DAY') {
  467. $tmp = dol_getdate(dol_now(), true);
  468. $newout = $tmp['mday'];
  469. } elseif ($reg[1] == 'MONTH') {
  470. $tmp = dol_getdate(dol_now(), true);
  471. $newout = $tmp['mon'];
  472. } elseif ($reg[1] == 'YEAR') {
  473. $tmp = dol_getdate(dol_now(), true);
  474. $newout = $tmp['year'];
  475. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  476. $tmp = dol_getdate(dol_now(), true);
  477. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  478. $newout = $tmp2['day'];
  479. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  480. $tmp = dol_getdate(dol_now(), true);
  481. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  482. $newout = $tmp2['month'];
  483. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  484. $tmp = dol_getdate(dol_now(), true);
  485. $newout = ($tmp['year'] - 1);
  486. } elseif ($reg[1] == 'NEXT_DAY') {
  487. $tmp = dol_getdate(dol_now(), true);
  488. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  489. $newout = $tmp2['day'];
  490. } elseif ($reg[1] == 'NEXT_MONTH') {
  491. $tmp = dol_getdate(dol_now(), true);
  492. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  493. $newout = $tmp2['month'];
  494. } elseif ($reg[1] == 'NEXT_YEAR') {
  495. $tmp = dol_getdate(dol_now(), true);
  496. $newout = ($tmp['year'] + 1);
  497. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  498. $newout = $mysoc->country_id;
  499. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  500. $newout = $user->id;
  501. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  502. $newout = $user->fk_user;
  503. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  504. $newout = $conf->entity;
  505. } else {
  506. $newout = ''; // Key not found, we replace with empty string
  507. }
  508. //var_dump('__'.$reg[1].'__ -> '.$newout);
  509. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  510. }
  511. }
  512. // Check rule
  513. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09'
  514. if (!is_array($out) || empty($out)) {
  515. $out = array();
  516. } else {
  517. $tmparray = explode(':', $check);
  518. if (!empty($tmparray[1])) {
  519. $tmpcheck = $tmparray[1];
  520. } else {
  521. $tmpcheck = 'alphanohtml';
  522. }
  523. foreach ($out as $outkey => $outval) {
  524. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  525. }
  526. }
  527. }
  528. else {
  529. $out = checkVal($out, $check, $filter, $options);
  530. }
  531. // Sanitizing for special parameters. There is no reason to allow the backtopage parameter to contains an external URL.
  532. if ($paramname == 'backtopage') {
  533. $out = str_replace('\\', '/', $out);
  534. $out = preg_replace(array('/^\/\/+/', '/^[a-z]*:/i'), '', $out);
  535. }
  536. // Code for search criteria persistence.
  537. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  538. if (empty($method) || $method == 3 || $method == 4)
  539. {
  540. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield')))
  541. {
  542. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  543. // We save search key only if $out not empty that means:
  544. // - posted value not empty, or
  545. // - 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).
  546. if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep
  547. {
  548. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  549. }
  550. }
  551. }
  552. return $out;
  553. }
  554. /**
  555. * Return a value after checking on a rule.
  556. *
  557. * @param string $out Value to get/check
  558. * @param string $check Type of check
  559. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  560. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  561. * @return string|array Value found (string or array), or '' if check fails
  562. */
  563. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  564. {
  565. // Check is done after replacement
  566. switch ($check)
  567. {
  568. case 'none':
  569. break;
  570. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  571. if (!is_numeric($out)) { $out = ''; }
  572. break;
  573. case 'intcomma':
  574. if (preg_match('/[^0-9,-]+/i', $out)) $out = '';
  575. break;
  576. case 'san_alpha':
  577. $out = filter_var($out, FILTER_SANITIZE_STRING);
  578. break;
  579. case 'aZ':
  580. if (!is_array($out))
  581. {
  582. $out = trim($out);
  583. if (preg_match('/[^a-z]+/i', $out)) $out = '';
  584. }
  585. break;
  586. case 'aZ09':
  587. if (!is_array($out))
  588. {
  589. $out = trim($out);
  590. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) $out = '';
  591. }
  592. break;
  593. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  594. if (!is_array($out))
  595. {
  596. $out = trim($out);
  597. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out = '';
  598. }
  599. break;
  600. case 'nohtml':
  601. $out = dol_string_nohtmltag($out, 0);
  602. break;
  603. case 'alpha': // No html and no " and no ../
  604. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  605. if (!is_array($out))
  606. {
  607. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  608. // '../' is dangerous because it allows dir transversals
  609. $out = str_replace(array('&quot;', '"', '../'), '', trim($out));
  610. $out = dol_string_nohtmltag($out, 0);
  611. }
  612. break;
  613. case 'restricthtml': // Recommended for most html textarea
  614. $out = dol_string_onlythesehtmltags($out, 0);
  615. // TODO We can also remove all javascripts reference
  616. break;
  617. case 'custom':
  618. if (empty($filter)) return 'BadFourthParameterForGETPOST';
  619. $out = filter_var($out, $filter, $options);
  620. break;
  621. }
  622. return $out;
  623. }
  624. if (!function_exists('dol_getprefix'))
  625. {
  626. /**
  627. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  628. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  629. * or two instances in same virtual servers.
  630. *
  631. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  632. * @return string A calculated prefix
  633. */
  634. function dol_getprefix($mode = '')
  635. {
  636. global $conf;
  637. // If prefix is for email
  638. if ($mode == 'email')
  639. {
  640. 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)
  641. {
  642. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  643. elseif (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"];
  644. }
  645. // The recommended value (may be not defined for old versions)
  646. if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id;
  647. // For backward compatibility
  648. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  649. }
  650. // The recommended value (may be not defined for old versions)
  651. if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id;
  652. // For backward compatibility
  653. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"]))
  654. {
  655. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  656. }
  657. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  658. }
  659. }
  660. /**
  661. * Make an include_once using default root and alternate root if it fails.
  662. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  663. * To link to a module file from a module file, use include './mymodulefile';
  664. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  665. *
  666. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  667. * @param string $classname Class name (deprecated)
  668. * @return bool True if load is a success, False if it fails
  669. */
  670. function dol_include_once($relpath, $classname = '')
  671. {
  672. global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var']
  673. $fullpath = dol_buildpath($relpath);
  674. if (!file_exists($fullpath)) {
  675. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  676. return false;
  677. }
  678. if (!empty($classname) && !class_exists($classname)) {
  679. return include $fullpath;
  680. } else {
  681. return include_once $fullpath;
  682. }
  683. }
  684. /**
  685. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  686. *
  687. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  688. * @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)
  689. * @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)
  690. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  691. * 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
  692. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  693. */
  694. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  695. {
  696. global $conf;
  697. $path = preg_replace('/^\//', '', $path);
  698. if (empty($type)) // For a filesystem path
  699. {
  700. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  701. if (is_array($conf->file->dol_document_root))
  702. {
  703. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  704. {
  705. if ($key == 'main')
  706. {
  707. continue;
  708. }
  709. if (file_exists($dirroot.'/'.$path))
  710. {
  711. $res = $dirroot.'/'.$path;
  712. return $res;
  713. }
  714. }
  715. }
  716. if ($returnemptyifnotfound) // Not found into alternate dir
  717. {
  718. if ($returnemptyifnotfound == 1 || !file_exists($res)) return '';
  719. }
  720. } else // For an url path
  721. {
  722. // We try to get local path of file on filesystem from url
  723. // Note that trying to know if a file on disk exist by forging path on disk from url
  724. // works only for some web server and some setup. This is bugged when
  725. // using proxy, rewriting, virtual path, etc...
  726. $res = '';
  727. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  728. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  729. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  730. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  731. {
  732. if ($key == 'main')
  733. {
  734. if ($type == 3)
  735. {
  736. global $dolibarr_main_url_root;
  737. // Define $urlwithroot
  738. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  739. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  740. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  741. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  742. }
  743. continue;
  744. }
  745. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  746. if (!empty($regs[1]))
  747. {
  748. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  749. if (file_exists($dirroot.'/'.$regs[1]))
  750. {
  751. if ($type == 1)
  752. {
  753. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  754. }
  755. if ($type == 2)
  756. {
  757. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  758. }
  759. if ($type == 3)
  760. {
  761. global $dolibarr_main_url_root;
  762. // Define $urlwithroot
  763. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  764. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  765. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  766. $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
  767. }
  768. break;
  769. }
  770. }
  771. }
  772. }
  773. return $res;
  774. }
  775. /**
  776. * Create a clone of instance of object (new instance with same value for properties)
  777. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  778. * 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.
  779. *
  780. * @param object $object Object to clone
  781. * @param int $native 0=Full isolation method, 1=Native PHP method
  782. * @return object Clone object
  783. * @see https://php.net/manual/language.oop5.cloning.php
  784. */
  785. function dol_clone($object, $native = 0)
  786. {
  787. if (empty($native))
  788. {
  789. $myclone = unserialize(serialize($object));
  790. } else {
  791. $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable)
  792. }
  793. return $myclone;
  794. }
  795. /**
  796. * Optimize a size for some browsers (phone, smarphone, ...)
  797. *
  798. * @param int $size Size we want
  799. * @param string $type Type of optimizing:
  800. * '' = function used to define a size for truncation
  801. * 'width' = function is used to define a width
  802. * @return int New size after optimizing
  803. */
  804. function dol_size($size, $type = '')
  805. {
  806. global $conf;
  807. if (empty($conf->dol_optimize_smallscreen)) return $size;
  808. if ($type == 'width' && $size > 250) return 250;
  809. else return 10;
  810. }
  811. /**
  812. * Clean a string to use it as a file name
  813. *
  814. * @param string $str String to clean
  815. * @param string $newstr String to replace bad chars with
  816. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  817. * @return string String cleaned (a-zA-Z_)
  818. *
  819. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  820. */
  821. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  822. {
  823. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  824. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  825. // Char '/' and '\' are file delimiters.
  826. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  827. return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  828. }
  829. /**
  830. * Clean a string to use it as a path name
  831. *
  832. * @param string $str String to clean
  833. * @param string $newstr String to replace bad chars with
  834. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  835. * @return string String cleaned (a-zA-Z_)
  836. *
  837. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  838. */
  839. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  840. {
  841. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°');
  842. return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  843. }
  844. /**
  845. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  846. *
  847. * @param string $str String to clean
  848. * @return string Cleaned string
  849. *
  850. * @see dol_sanitizeFilename(), dol_string_nospecial()
  851. */
  852. function dol_string_unaccent($str)
  853. {
  854. if (utf8_check($str))
  855. {
  856. // See http://www.utf8-chartable.de/
  857. $string = rawurlencode($str);
  858. $replacements = array(
  859. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  860. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  861. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  862. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  863. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  864. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  865. '%C3%A7' => 'c',
  866. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  867. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  868. '%C3%B1' => 'n',
  869. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  870. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  871. '%C3%BF' => 'y'
  872. );
  873. $string = strtr($string, $replacements);
  874. return rawurldecode($string);
  875. } else {
  876. // See http://www.ascii-code.com/
  877. $string = strtr(
  878. $str,
  879. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  880. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  881. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  882. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  883. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  884. \xF9\xFA\xFB\xFC\xFD\xFF",
  885. "AAAAAAC
  886. EEEEIIIIDN
  887. OOOOOUUUY
  888. aaaaaaceeee
  889. iiiidnooooo
  890. uuuuyy"
  891. );
  892. $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"));
  893. return $string;
  894. }
  895. }
  896. /**
  897. * Clean a string from all punctuation characters to use it as a ref or login.
  898. * This is a more complete function than dol_sanitizeFileName.
  899. *
  900. * @param string $str String to clean
  901. * @param string $newstr String to replace forbidden chars with
  902. * @param array $badcharstoreplace List of forbidden characters
  903. * @return string Cleaned string
  904. *
  905. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  906. */
  907. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
  908. {
  909. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  910. $forbidden_chars_to_remove = array();
  911. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace = $badcharstoreplace;
  912. //$forbidden_chars_to_remove=array("(",")");
  913. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  914. }
  915. /**
  916. * Clean a string from all non printable ascii chars (0x00-0x1F and 0x7F). It removes also CR-LF
  917. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  918. *
  919. * @param string $str String to clean
  920. * @return string Cleaned string
  921. *
  922. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  923. */
  924. function dol_string_nounprintableascii($str)
  925. {
  926. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str);
  927. }
  928. /**
  929. * Returns text escaped for inclusion into javascript code
  930. *
  931. * @param string $stringtoescape String to escape
  932. * @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 \
  933. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  934. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  935. */
  936. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  937. {
  938. // escape quotes and backslashes, newlines, etc.
  939. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  940. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  941. if (empty($noescapebackslashn)) { $substitjs["\n"] = '\\n'; $substitjs['\\'] = '\\\\'; }
  942. if (empty($mode)) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\'"; } elseif ($mode == 1) $substitjs["'"] = "\\'";
  943. elseif ($mode == 2) { $substitjs['"'] = '\\"'; } elseif ($mode == 3) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\\""; }
  944. return strtr($stringtoescape, $substitjs);
  945. }
  946. /**
  947. * Returns text escaped for inclusion into javascript code
  948. *
  949. * @param string $stringtoescape String to escape
  950. * @return string Escaped string for json content.
  951. */
  952. function dol_escape_json($stringtoescape)
  953. {
  954. return str_replace('"', '\"', $stringtoescape);
  955. }
  956. /**
  957. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  958. *
  959. * @param string $stringtoescape String to escape
  960. * @param int $keepb 1=Preserve b tags (otherwise, remove them)
  961. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  962. * @param string $keepmoretags '' or 'common' or list of tags
  963. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  964. * @return string Escaped string
  965. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  966. */
  967. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $keepmoretags = '', $escapeonlyhtmltags = 0)
  968. {
  969. if ($keepmoretags == 'common') $keepmoretags = 'html,body,a,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  970. // TODO Implement $keepmoretags
  971. // escape quotes and backslashes, newlines, etc.
  972. if ($escapeonlyhtmltags) {
  973. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  974. } else {
  975. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  976. }
  977. if (!$keepb) $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  978. if (!$keepn) $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  979. if ($escapeonlyhtmltags) {
  980. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  981. } else {
  982. return htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  983. }
  984. }
  985. /**
  986. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  987. *
  988. * @param string $utf8_string String to encode
  989. * @return string String converted
  990. */
  991. function dol_strtolower($utf8_string)
  992. {
  993. return mb_strtolower($utf8_string, "UTF-8");
  994. }
  995. /**
  996. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  997. *
  998. * @param string $utf8_string String to encode
  999. * @return string String converted
  1000. */
  1001. function dol_strtoupper($utf8_string)
  1002. {
  1003. return mb_strtoupper($utf8_string, "UTF-8");
  1004. }
  1005. /**
  1006. * Write log message into outputs. Possible outputs can be:
  1007. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1008. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1009. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1010. * this, use logging to files instead of syslog (see setup of module).
  1011. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1012. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1013. * This function works only if syslog module is enabled.
  1014. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1015. *
  1016. * @param string $message Line to log. ''=Show nothing
  1017. * @param int $level Log level
  1018. * 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
  1019. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  1020. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1021. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1022. * @param string $restricttologhandler Force output of log only to this log handler
  1023. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1024. * @return void
  1025. */
  1026. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1027. {
  1028. global $conf, $user, $debugbar;
  1029. // If syslog module enabled
  1030. if (empty($conf->syslog->enabled)) return;
  1031. // Check if we are into execution of code of a website
  1032. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1033. global $website, $websitekey;
  1034. if (is_object($website) && !empty($website->ref)) $suffixinfilename .= '_website_'.$website->ref;
  1035. elseif (!empty($websitekey)) $suffixinfilename .= '_website_'.$websitekey;
  1036. }
  1037. if ($ident < 0)
  1038. {
  1039. foreach ($conf->loghandlers as $loghandlerinstance)
  1040. {
  1041. $loghandlerinstance->setIdent($ident);
  1042. }
  1043. }
  1044. if (!empty($message))
  1045. {
  1046. // Test log level
  1047. $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');
  1048. if (!array_key_exists($level, $logLevels))
  1049. {
  1050. throw new Exception('Incorrect log level');
  1051. }
  1052. if ($level > $conf->global->SYSLOG_LEVEL) return;
  1053. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1054. // If adding log inside HTML page is required
  1055. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1056. || (!empty($user->rights->debugbar->read) && is_object($debugbar)))
  1057. {
  1058. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1059. }
  1060. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1061. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1062. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"]))
  1063. {
  1064. print "\n\n<!-- Log start\n";
  1065. print $message."\n";
  1066. print "Log end -->\n";
  1067. }
  1068. $data = array(
  1069. 'message' => $message,
  1070. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1071. 'level' => $level,
  1072. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1073. 'ip' => false
  1074. );
  1075. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1076. if (!empty($remoteip)) {
  1077. $data['ip'] = $remoteip;
  1078. // This is when server run behind a reverse proxy
  1079. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1080. elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1081. } // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1082. elseif (!empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  1083. // 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).
  1084. elseif (!empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1085. // 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).
  1086. elseif (!empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1087. // Loop on each log handler and send output
  1088. foreach ($conf->loghandlers as $loghandlerinstance)
  1089. {
  1090. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  1091. $loghandlerinstance->export($data, $suffixinfilename);
  1092. }
  1093. unset($data);
  1094. }
  1095. if ($ident > 0)
  1096. {
  1097. foreach ($conf->loghandlers as $loghandlerinstance)
  1098. {
  1099. $loghandlerinstance->setIdent($ident);
  1100. }
  1101. }
  1102. }
  1103. /**
  1104. * Show tab header of a card
  1105. *
  1106. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1107. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1108. * @param string $title Title
  1109. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using dol_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1110. * @param string $picto Add a picto on tab title
  1111. * @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.
  1112. * @param string $morehtmlright Add more html content on right of tabs title
  1113. * @param string $morecss More Css
  1114. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1115. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1116. * @return void
  1117. */
  1118. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1119. {
  1120. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1121. }
  1122. /**
  1123. * Show tabs of a record
  1124. *
  1125. * @param array $links Array of tabs
  1126. * @param string $active Active tab name
  1127. * @param string $title Title
  1128. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using dol_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1129. * @param string $picto Add a picto on tab title
  1130. * @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.
  1131. * @param string $morehtmlright Add more html content on right of tabs title
  1132. * @param string $morecss More Css
  1133. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1134. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1135. * @return string
  1136. */
  1137. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1138. {
  1139. global $conf, $langs, $hookmanager;
  1140. // Show title
  1141. $showtitle = 1;
  1142. if (!empty($conf->dol_optimize_smallscreen)) $showtitle = 0;
  1143. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1144. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1145. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1146. }
  1147. // Show right part
  1148. 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.
  1149. // Show title
  1150. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1151. {
  1152. $limittitle = 30;
  1153. $out .= '<a class="tabTitle">';
  1154. if ($picto) $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1155. $out .= '<span class="tabTitleText">'.dol_trunc($title, $limittitle).'</span>';
  1156. $out .= '</a>';
  1157. }
  1158. // Show tabs
  1159. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1160. $maxkey = -1;
  1161. if (is_array($links) && !empty($links))
  1162. {
  1163. $keys = array_keys($links);
  1164. if (count($keys)) $maxkey = max($keys);
  1165. }
  1166. // Show tabs
  1167. // if =0 we don't use the feature
  1168. if (empty($limittoshow)) {
  1169. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1170. }
  1171. if (!empty($conf->dol_optimize_smallscreen)) $limittoshow = 2;
  1172. $displaytab = 0;
  1173. $nbintab = 0;
  1174. $popuptab = 0;
  1175. $outmore = '';
  1176. for ($i = 0; $i <= $maxkey; $i++)
  1177. {
  1178. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1179. // If active tab is already present
  1180. if ($i >= $limittoshow) $limittoshow--;
  1181. }
  1182. }
  1183. for ($i = 0; $i <= $maxkey; $i++)
  1184. {
  1185. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1186. $isactive = true;
  1187. } else {
  1188. $isactive = false;
  1189. }
  1190. if ($i < $limittoshow || $isactive)
  1191. {
  1192. $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]).' -->';
  1193. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1194. {
  1195. if (!empty($links[$i][0]))
  1196. {
  1197. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1198. } else {
  1199. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1200. }
  1201. } elseif (!empty($links[$i][1]))
  1202. {
  1203. //print "x $i $active ".$links[$i][2]." z";
  1204. if ($isactive)
  1205. {
  1206. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1207. $out .= $links[$i][1];
  1208. $out .= '</a>'."\n";
  1209. } else {
  1210. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabunactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1211. $out .= $links[$i][1];
  1212. $out .= '</a>'."\n";
  1213. }
  1214. }
  1215. $out .= '</div>';
  1216. } else {
  1217. // The popup with the other tabs
  1218. if (!$popuptab)
  1219. {
  1220. $popuptab = 1;
  1221. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1222. }
  1223. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1224. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1225. {
  1226. if (!empty($links[$i][0]))
  1227. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1228. else $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1229. } elseif (!empty($links[$i][1]))
  1230. {
  1231. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1232. $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.
  1233. $outmore .= '</a>'."\n";
  1234. }
  1235. $outmore .= '</div>';
  1236. $nbintab++;
  1237. }
  1238. $displaytab = $i;
  1239. }
  1240. if ($popuptab) $outmore .= '</div>';
  1241. if ($popuptab) // If there is some tabs not shown
  1242. {
  1243. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1244. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1245. $widthofpopup = 200;
  1246. $tabsname = $moretabssuffix;
  1247. if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); }
  1248. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1249. $out .= '<a href="#" class="tab moretab inline-block tabunactive">'.$langs->trans("More").'... ('.$nbintab.')</a>'; // Do not use "reposition" class in the "More".
  1250. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1251. $out .= $outmore;
  1252. $out .= '</div>';
  1253. $out .= '<div></div>';
  1254. $out .= "</div>\n";
  1255. $out .= "<script>";
  1256. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1257. var x = this.offsetLeft, y = this.offsetTop;
  1258. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1259. if ((window.innerWidth - x) < ".($widthofpopup+10).") {
  1260. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1261. }
  1262. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1263. });
  1264. ";
  1265. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1266. $out .= "</script>";
  1267. }
  1268. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1269. $out .= "</div>\n";
  1270. }
  1271. if (!$notab || $notab == -1 || $notab == -2) $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1272. $parameters = array('tabname' => $active, 'out' => $out);
  1273. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1274. if ($reshook > 0)
  1275. {
  1276. $out = $hookmanager->resPrint;
  1277. }
  1278. return $out;
  1279. }
  1280. /**
  1281. * Show tab footer of a card
  1282. *
  1283. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1284. * @return void
  1285. */
  1286. function dol_fiche_end($notab = 0)
  1287. {
  1288. print dol_get_fiche_end($notab);
  1289. }
  1290. /**
  1291. * Return tab footer of a card
  1292. *
  1293. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1294. * @return string
  1295. */
  1296. function dol_get_fiche_end($notab = 0)
  1297. {
  1298. if (!$notab || $notab == -1) return "\n</div>\n";
  1299. else return '';
  1300. }
  1301. /**
  1302. * Show tab footer of a card.
  1303. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1304. *
  1305. * @param Object $object Object to show
  1306. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1307. * @param string $morehtml More html content to output just before the nav bar
  1308. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1309. * @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.
  1310. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1311. * @param string $morehtmlref More html to show after ref
  1312. * @param string $moreparam More param to add in nav link url.
  1313. * @param int $nodbprefix Do not include DB prefix to forge table name
  1314. * @param string $morehtmlleft More html code to show before ref
  1315. * @param string $morehtmlstatus More html code to show under navigation arrows
  1316. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1317. * @param string $morehtmlright More html code to show before navigation arrows
  1318. * @return void
  1319. */
  1320. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1321. {
  1322. global $conf, $form, $user, $langs;
  1323. $error = 0;
  1324. $maxvisiblephotos = 1;
  1325. $showimage = 1;
  1326. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1327. $showbarcode = empty($conf->barcode->enabled) ? 0 : ($object->barcode ? 1 : 0);
  1328. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0;
  1329. $modulepart = 'unknown';
  1330. if ($object->element == 'societe') $modulepart = 'societe';
  1331. if ($object->element == 'contact') $modulepart = 'contact';
  1332. if ($object->element == 'member') $modulepart = 'memberphoto';
  1333. if ($object->element == 'user') $modulepart = 'userphoto';
  1334. if ($object->element == 'product') $modulepart = 'product';
  1335. if ($object->element == 'ticket') $modulepart = 'ticket';
  1336. if (class_exists("Imagick"))
  1337. {
  1338. if ($object->element == 'propal') $modulepart = 'propal';
  1339. if ($object->element == 'commande') $modulepart = 'commande';
  1340. if ($object->element == 'facture') $modulepart = 'facture';
  1341. if ($object->element == 'fichinter') $modulepart = 'ficheinter';
  1342. if ($object->element == 'contrat') $modulepart = 'contract';
  1343. if ($object->element == 'supplier_proposal') $modulepart = 'supplier_proposal';
  1344. if ($object->element == 'order_supplier') $modulepart = 'supplier_order';
  1345. if ($object->element == 'invoice_supplier') $modulepart = 'supplier_invoice';
  1346. if ($object->element == 'expensereport') $modulepart = 'expensereport';
  1347. }
  1348. if ($object->element == 'product')
  1349. {
  1350. $width = 80; $cssclass = 'photoref';
  1351. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1352. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1353. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1354. if ($showimage) $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>';
  1355. else {
  1356. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1357. $nophoto = '';
  1358. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1359. } else { // Show no photo link
  1360. $nophoto = '/public/theme/common/nophoto.png';
  1361. $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>';
  1362. }
  1363. }
  1364. } elseif ($object->element == 'ticket') {
  1365. $width = 80; $cssclass = 'photoref';
  1366. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1367. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1368. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1369. if ($showimage)
  1370. {
  1371. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1372. if ($object->nbphoto > 0)
  1373. {
  1374. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1375. } else {
  1376. $showimage = 0;
  1377. }
  1378. }
  1379. if (!$showimage)
  1380. {
  1381. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1382. $nophoto = '';
  1383. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1384. } else { // Show no photo link
  1385. $nophoto = '/public/theme/common/nophoto.png';
  1386. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" border="0"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1387. }
  1388. }
  1389. } else {
  1390. if ($showimage)
  1391. {
  1392. if ($modulepart != 'unknown')
  1393. {
  1394. $phototoshow = '';
  1395. // Check if a preview file is available
  1396. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick"))
  1397. {
  1398. $objectref = dol_sanitizeFileName($object->ref);
  1399. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1400. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1401. {
  1402. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1403. $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
  1404. } else {
  1405. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1406. }
  1407. if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1408. $filepath = $dir_output.$subdir."/";
  1409. $filepdf = $filepath.$objectref.".pdf";
  1410. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1411. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1412. $fileimage = $filepdf.'_preview.png';
  1413. $relativepathimage = $relativepath.'_preview.png';
  1414. $pdfexists = file_exists($filepdf);
  1415. // If PDF file exists
  1416. if ($pdfexists)
  1417. {
  1418. // Conversion du PDF en image png si fichier png non existant
  1419. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
  1420. {
  1421. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1422. {
  1423. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1424. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1425. if ($ret < 0) $error++;
  1426. }
  1427. }
  1428. }
  1429. if ($pdfexists && !$error)
  1430. {
  1431. $heightforphotref = 70;
  1432. if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
  1433. // If the preview file is found
  1434. if (file_exists($fileimage))
  1435. {
  1436. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1437. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1438. $phototoshow .= '</div></div>';
  1439. }
  1440. }
  1441. } elseif (!$phototoshow)
  1442. {
  1443. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1444. }
  1445. if ($phototoshow)
  1446. {
  1447. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1448. $morehtmlleft .= $phototoshow;
  1449. $morehtmlleft .= '</div>';
  1450. }
  1451. }
  1452. if (!$phototoshow) // Show No photo link (picto of object)
  1453. {
  1454. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1455. if ($object->element == 'action')
  1456. {
  1457. $width = 80;
  1458. $cssclass = 'photorefcenter';
  1459. $nophoto = img_picto('No photo', 'title_agenda');
  1460. } else {
  1461. $width = 14; $cssclass = 'photorefcenter';
  1462. $picto = $object->picto;
  1463. if ($object->element == 'project' && !$object->public) $picto = 'project'; // instead of projectpub
  1464. $nophoto = img_picto('No photo', 'object_'.$picto);
  1465. }
  1466. $morehtmlleft .= '<!-- No photo to show -->';
  1467. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1468. $morehtmlleft .= $nophoto;
  1469. $morehtmlleft .= '</div></div>';
  1470. $morehtmlleft .= '</div>';
  1471. }
  1472. }
  1473. }
  1474. if ($showbarcode) $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1475. if ($object->element == 'societe')
  1476. {
  1477. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1478. {
  1479. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1480. } else {
  1481. $morehtmlstatus .= $object->getLibStatut(6);
  1482. }
  1483. } elseif ($object->element == 'product')
  1484. {
  1485. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1486. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1487. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1488. } else {
  1489. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1490. }
  1491. $morehtmlstatus .= ' &nbsp; ';
  1492. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1493. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1494. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1495. } else {
  1496. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1497. }
  1498. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan')))
  1499. {
  1500. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1501. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1502. $morehtmlstatus .= $tmptxt;
  1503. } elseif ($object->element == 'contrat' || $object->element == 'contract')
  1504. {
  1505. if ($object->statut == 0) $morehtmlstatus .= $object->getLibStatut(5);
  1506. else $morehtmlstatus .= $object->getLibStatut(4);
  1507. } elseif ($object->element == 'facturerec')
  1508. {
  1509. if ($object->frequency == 0) $morehtmlstatus .= $object->getLibStatut(2);
  1510. else $morehtmlstatus .= $object->getLibStatut(5);
  1511. } elseif ($object->element == 'project_task')
  1512. {
  1513. $object->fk_statut = 1;
  1514. if ($object->progress > 0) $object->fk_statut = 2;
  1515. if ($object->progress >= 100) $object->fk_statut = 3;
  1516. $tmptxt = $object->getLibStatut(5);
  1517. $morehtmlstatus .= $tmptxt; // No status on task
  1518. } else { // Generic case
  1519. $tmptxt = $object->getLibStatut(6);
  1520. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5);
  1521. $morehtmlstatus .= $tmptxt;
  1522. }
  1523. // Add if object was dispatched "into accountancy"
  1524. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various')))
  1525. {
  1526. if (method_exists($object, 'getVentilExportCompta'))
  1527. {
  1528. $accounted = $object->getVentilExportCompta();
  1529. $langs->load("accountancy");
  1530. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1531. }
  1532. }
  1533. // Add alias for thirdparty
  1534. if (!empty($object->name_alias)) $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1535. // Add label
  1536. if (in_array($object->element, array('product', 'bank_account', 'project_task')))
  1537. {
  1538. if (!empty($object->label)) $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1539. }
  1540. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files')))
  1541. {
  1542. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1543. if ($moreaddress) {
  1544. $morehtmlref .= '<div class="refidno">';
  1545. $morehtmlref .= $moreaddress;
  1546. $morehtmlref .= '</div>';
  1547. }
  1548. }
  1549. 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))
  1550. {
  1551. $morehtmlref .= '<div style="clear: both;"></div>';
  1552. $morehtmlref .= '<div class="refidno">';
  1553. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1554. $morehtmlref .= '</div>';
  1555. }
  1556. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1557. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1558. print '</div>';
  1559. print '<div class="underrefbanner clearboth"></div>';
  1560. }
  1561. /**
  1562. * Show a string with the label tag dedicated to the HTML edit field.
  1563. *
  1564. * @param string $langkey Translation key
  1565. * @param string $fieldkey Key of the html select field the text refers to
  1566. * @param int $fieldrequired 1=Field is mandatory
  1567. * @return string
  1568. * @deprecated Form::editfieldkey
  1569. */
  1570. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1571. {
  1572. global $langs;
  1573. $ret = '';
  1574. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  1575. $ret .= '<label for="'.$fieldkey.'">';
  1576. $ret .= $langs->trans($langkey);
  1577. $ret .= '</label>';
  1578. if ($fieldrequired) $ret .= '</span>';
  1579. return $ret;
  1580. }
  1581. /**
  1582. * Return string to add class property on html element with pair/impair.
  1583. *
  1584. * @param string $var 0 or 1
  1585. * @param string $moreclass More class to add
  1586. * @return string String to add class onto HTML element
  1587. */
  1588. function dol_bc($var, $moreclass = '')
  1589. {
  1590. global $bc;
  1591. $ret = ' '.$bc[$var];
  1592. if ($moreclass) $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  1593. return $ret;
  1594. }
  1595. /**
  1596. * Return a formated address (part address/zip/town/state) according to country rules.
  1597. * See https://en.wikipedia.org/wiki/Address
  1598. *
  1599. * @param Object $object A company or contact object
  1600. * @param int $withcountry 1=Add country into address string
  1601. * @param string $sep Separator to use to build string
  1602. * @param Translate $outputlangs Object lang that contains language for text translation.
  1603. * @param int $mode 0=Standard output, 1=Remove address
  1604. * @param string $extralangcode User extralanguage $langcode as values for address, town
  1605. * @return string Formated string
  1606. * @see dol_print_address()
  1607. */
  1608. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  1609. {
  1610. global $conf, $langs;
  1611. $ret = '';
  1612. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1613. // See format of addresses on https://en.wikipedia.org/wiki/Address
  1614. // Address
  1615. if (empty($mode)) {
  1616. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : $object->address);
  1617. }
  1618. // Zip/Town/State
  1619. if (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
  1620. {
  1621. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1622. $ret .= ($ret ? $sep : '').$town;
  1623. if ($object->state)
  1624. {
  1625. $ret .= ($ret ? ", " : '').$object->state;
  1626. }
  1627. if ($object->zip) $ret .= ($ret ? ", " : '').$object->zip;
  1628. } elseif (in_array($object->country_code, array('GB', 'UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country
  1629. {
  1630. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1631. $ret .= ($ret ? $sep : '').$town;
  1632. if ($object->state)
  1633. {
  1634. $ret .= ($ret ? ", " : '').$object->state;
  1635. }
  1636. if ($object->zip) $ret .= ($ret ? $sep : '').$object->zip;
  1637. } elseif (in_array($object->country_code, array('ES', 'TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country
  1638. {
  1639. $ret .= ($ret ? $sep : '').$object->zip;
  1640. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1641. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1642. if ($object->state)
  1643. {
  1644. $ret .= "\n".$object->state;
  1645. }
  1646. } elseif (in_array($object->country_code, array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1647. {
  1648. $ret .= ($ret ? $sep : '').$object->zip;
  1649. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1650. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1651. $ret .= ($object->state_code ? (' '.($object->state_code)) : '');
  1652. } else // Other: title firstname name \n address lines \n zip town \n country
  1653. {
  1654. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1655. $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : '';
  1656. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  1657. if ($object->state && in_array($object->country_code, $countriesusingstate))
  1658. {
  1659. $ret .= ($ret ? ", " : '').$object->state;
  1660. }
  1661. }
  1662. if (!is_object($outputlangs)) $outputlangs = $langs;
  1663. if ($withcountry)
  1664. {
  1665. $langs->load("dict");
  1666. $ret .= ($object->country_code ? ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)) : '');
  1667. }
  1668. return $ret;
  1669. }
  1670. /**
  1671. * Format a string.
  1672. *
  1673. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1674. * @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)
  1675. * @param int $is_gmt See comment of timestamp parameter
  1676. * @return string A formatted string
  1677. */
  1678. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  1679. {
  1680. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1681. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  1682. } else return 'Error date into a not supported range';
  1683. }
  1684. /**
  1685. * Output date in a string format according to outputlangs (or langs if not defined).
  1686. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1687. *
  1688. * @param int $time GM Timestamps date
  1689. * @param string $format Output date format (tag of strftime function)
  1690. * "%d %b %Y",
  1691. * "%d/%m/%Y %H:%M",
  1692. * "%d/%m/%Y %H:%M:%S",
  1693. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1694. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1695. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1696. * false or 'tzserver' => output string is for local PHP server TZ usage
  1697. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  1698. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  1699. * @param Translate $outputlangs Object lang that contains language for text translation.
  1700. * @param boolean $encodetooutput false=no convert into output pagecode
  1701. * @return string Formated date or '' if time is null
  1702. *
  1703. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  1704. */
  1705. function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlangs = '', $encodetooutput = false)
  1706. {
  1707. global $conf, $langs;
  1708. // Clean parameters
  1709. $to_gmt = false;
  1710. $offsettz = $offsetdst = 0;
  1711. if ($tzoutput)
  1712. {
  1713. $to_gmt = true; // For backward compatibility
  1714. if (is_string($tzoutput))
  1715. {
  1716. if ($tzoutput == 'tzserver')
  1717. {
  1718. $to_gmt = false;
  1719. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1720. $offsettz = 0;
  1721. $offsetdst = 0;
  1722. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel')
  1723. {
  1724. $to_gmt = true;
  1725. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1726. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  1727. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  1728. }
  1729. }
  1730. }
  1731. if (!is_object($outputlangs)) $outputlangs = $langs;
  1732. if (!$format) $format = 'daytextshort';
  1733. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0;
  1734. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  1735. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat = 1; } // so format 'dayreduceformat' is processed like day
  1736. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1737. // TODO Add format daysmallyear and dayhoursmallyear
  1738. if ($format == 'day') $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  1739. elseif ($format == 'hour') $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  1740. elseif ($format == 'hourduration') $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  1741. elseif ($format == 'daytext') $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  1742. elseif ($format == 'daytextshort') $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  1743. elseif ($format == 'dayhour') $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  1744. elseif ($format == 'dayhoursec') $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  1745. elseif ($format == 'dayhourtext') $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  1746. elseif ($format == 'dayhourtextshort') $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  1747. // Format not sensitive to language
  1748. elseif ($format == 'dayhourlog') $format = '%Y%m%d%H%M%S';
  1749. elseif ($format == 'dayhourldap') $format = '%Y%m%d%H%M%SZ';
  1750. elseif ($format == 'dayhourxcard') $format = '%Y%m%dT%H%M%SZ';
  1751. elseif ($format == 'dayxcard') $format = '%Y%m%d';
  1752. elseif ($format == 'dayrfc') $format = '%Y-%m-%d'; // DATE_RFC3339
  1753. elseif ($format == 'dayhourrfc') $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1754. elseif ($format == 'standard') $format = '%Y-%m-%d %H:%M:%S';
  1755. if ($reduceformat)
  1756. {
  1757. $format = str_replace('%Y', '%y', $format);
  1758. $format = str_replace('yyyy', 'yy', $format);
  1759. }
  1760. // If date undefined or "", we return ""
  1761. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1762. // Clean format
  1763. if (preg_match('/%b/i', $format)) // There is some text to translate
  1764. {
  1765. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1766. $format = str_replace('%b', '__b__', $format);
  1767. $format = str_replace('%B', '__B__', $format);
  1768. }
  1769. if (preg_match('/%a/i', $format)) // There is some text to translate
  1770. {
  1771. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1772. $format = str_replace('%a', '__a__', $format);
  1773. $format = str_replace('%A', '__A__', $format);
  1774. }
  1775. // Analyze date
  1776. $reg = array();
  1777. 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
  1778. {
  1779. dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  1780. return '';
  1781. } 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
  1782. {
  1783. // This part of code should not be used.
  1784. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  1785. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  1786. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  1787. $syear = (!empty($reg[1]) ? $reg[1] : '');
  1788. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  1789. $sday = (!empty($reg[3]) ? $reg[3] : '');
  1790. $shour = (!empty($reg[4]) ? $reg[4] : '');
  1791. $smin = (!empty($reg[5]) ? $reg[5] : '');
  1792. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  1793. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  1794. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  1795. } else {
  1796. // Date is a timestamps
  1797. if ($time < 100000000000) // Protection against bad date values
  1798. {
  1799. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1800. $ret = adodb_strftime($format, $timetouse, $to_gmt);
  1801. } else $ret = 'Bad value '.$time.' for date';
  1802. }
  1803. if (preg_match('/__b__/i', $format))
  1804. {
  1805. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1806. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1807. $month = adodb_strftime('%m', $timetouse);
  1808. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  1809. if ($encodetooutput)
  1810. {
  1811. $monthtext = $outputlangs->transnoentities('Month'.$month);
  1812. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  1813. } else {
  1814. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  1815. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1816. }
  1817. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1818. $ret = str_replace('__b__', $monthtextshort, $ret);
  1819. $ret = str_replace('__B__', $monthtext, $ret);
  1820. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1821. //return $ret;
  1822. }
  1823. if (preg_match('/__a__/i', $format))
  1824. {
  1825. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1826. $w = adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1827. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  1828. $ret = str_replace('__A__', $dayweek, $ret);
  1829. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  1830. }
  1831. return $ret;
  1832. }
  1833. /**
  1834. * Return an array with locale date info.
  1835. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1836. * WARNING: This function always use PHP server timezone to return locale informations !!!
  1837. * Usage must be avoid.
  1838. * FIXME: Replace this with PHP date function and a parameter $gm
  1839. *
  1840. * @param int $timestamp Timestamp
  1841. * @param boolean $fast Fast mode
  1842. * @return array Array of informations
  1843. * If no fast mode:
  1844. * 'seconds' => $secs,
  1845. * 'minutes' => $min,
  1846. * 'hours' => $hour,
  1847. * 'mday' => $day,
  1848. * 'wday' => $dow, 0=sunday, 6=saturday
  1849. * 'mon' => $month,
  1850. * 'year' => $year,
  1851. * 'yday' => floor($secsInYear/$_day_power),
  1852. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  1853. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  1854. * If fast mode:
  1855. * 'seconds' => $secs,
  1856. * 'minutes' => $min,
  1857. * 'hours' => $hour,
  1858. * 'mday' => $day,
  1859. * 'mon' => $month,
  1860. * 'year' => $year,
  1861. * 'yday' => floor($secsInYear/$_day_power),
  1862. * 'leap' => $leaf,
  1863. * 'ndays' => $ndays
  1864. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  1865. */
  1866. function dol_getdate($timestamp, $fast = false)
  1867. {
  1868. global $conf;
  1869. $usealternatemethod = false;
  1870. if ($timestamp <= 0) $usealternatemethod = true; // <= 1970
  1871. if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038
  1872. if ($usealternatemethod)
  1873. {
  1874. $arrayinfo = adodb_getdate($timestamp, $fast);
  1875. } else {
  1876. $arrayinfo = getdate($timestamp);
  1877. }
  1878. return $arrayinfo;
  1879. }
  1880. /**
  1881. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  1882. * Replace function mktime not available under Windows if year < 1970
  1883. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1884. *
  1885. * @param int $hour Hour (can be -1 for undefined)
  1886. * @param int $minute Minute (can be -1 for undefined)
  1887. * @param int $second Second (can be -1 for undefined)
  1888. * @param int $month Month (1 to 12)
  1889. * @param int $day Day (1 to 31)
  1890. * @param int $year Year
  1891. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  1892. * False or 0 or 'server' = local to server TZ
  1893. * 'user' = local to user TZ
  1894. * 'tz,TimeZone' = use specified timezone
  1895. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  1896. * @return int|string Date as a timestamp, '' or false if error
  1897. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  1898. */
  1899. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $check = 1)
  1900. {
  1901. global $conf;
  1902. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  1903. // Clean parameters
  1904. if ($hour == -1 || empty($hour)) $hour = 0;
  1905. if ($minute == -1 || empty($minute)) $minute = 0;
  1906. if ($second == -1 || empty($second)) $second = 0;
  1907. // Check parameters
  1908. if ($check)
  1909. {
  1910. if (!$month || !$day) return '';
  1911. if ($day > 31) return '';
  1912. if ($month > 12) return '';
  1913. if ($hour < 0 || $hour > 24) return '';
  1914. if ($minute < 0 || $minute > 60) return '';
  1915. if ($second < 0 || $second > 60) return '';
  1916. }
  1917. if (empty($gm) || $gm === 'server')
  1918. {
  1919. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  1920. $localtz = new DateTimeZone($default_timezone);
  1921. } elseif ($gm === 'user')
  1922. {
  1923. // We use dol_tz_string first because it is more reliable.
  1924. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  1925. try {
  1926. $localtz = new DateTimeZone($default_timezone);
  1927. } catch (Exception $e)
  1928. {
  1929. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  1930. $default_timezone = @date_default_timezone_get();
  1931. }
  1932. } elseif (strrpos($gm, "tz,") !== false)
  1933. {
  1934. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  1935. try {
  1936. $localtz = new DateTimeZone($timezone);
  1937. } catch (Exception $e)
  1938. {
  1939. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  1940. }
  1941. }
  1942. if (empty($localtz)) {
  1943. $localtz = new DateTimeZone('UTC');
  1944. }
  1945. //var_dump($localtz);
  1946. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  1947. $dt = new DateTime(null, $localtz);
  1948. $dt->setDate((int) $year, (int) $month, (int) $day);
  1949. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  1950. $date = $dt->getTimestamp(); // should include daylight saving time
  1951. //var_dump($date);
  1952. return $date;
  1953. }
  1954. /**
  1955. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  1956. *
  1957. * @param string $mode 'gmt' => we return GMT timestamp,
  1958. * 'tzserver' => we add the PHP server timezone
  1959. * 'tzref' => we add the company timezone
  1960. * 'tzuser' => we add the user timezone
  1961. * @return int $date Timestamp
  1962. */
  1963. function dol_now($mode = 'gmt')
  1964. {
  1965. $ret = 0;
  1966. if ($mode == 'gmt') $ret = time(); // Time for now at greenwich.
  1967. elseif ($mode == 'tzserver') // Time for now with PHP server timezone added
  1968. {
  1969. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1970. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  1971. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  1972. } /*elseif ($mode == 'tzref') // Time for now with parent company timezone is added
  1973. {
  1974. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1975. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  1976. $ret=dol_now('gmt')+($tzsecond*3600);
  1977. }*/
  1978. elseif ($mode == 'tzuser') // Time for now with user timezone added
  1979. {
  1980. //print 'time: '.time();
  1981. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  1982. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  1983. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  1984. }
  1985. return $ret;
  1986. }
  1987. /**
  1988. * Return string with formated size
  1989. *
  1990. * @param int $size Size to print
  1991. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1992. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  1993. * @return string Link
  1994. */
  1995. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  1996. {
  1997. global $conf, $langs;
  1998. $level = 1024;
  1999. if (!empty($conf->dol_optimize_smallscreen)) $shortunit = 1;
  2000. // Set value text
  2001. if (empty($shortvalue) || $size < ($level * 10))
  2002. {
  2003. $ret = $size;
  2004. $textunitshort = $langs->trans("b");
  2005. $textunitlong = $langs->trans("Bytes");
  2006. } else {
  2007. $ret = round($size / $level, 0);
  2008. $textunitshort = $langs->trans("Kb");
  2009. $textunitlong = $langs->trans("KiloBytes");
  2010. }
  2011. // Use long or short text unit
  2012. if (empty($shortunit)) { $ret .= ' '.$textunitlong; } else { $ret .= ' '.$textunitshort; }
  2013. return $ret;
  2014. }
  2015. /**
  2016. * Show Url link
  2017. *
  2018. * @param string $url Url to show
  2019. * @param string $target Target for link
  2020. * @param int $max Max number of characters to show
  2021. * @param int $withpicto With picto
  2022. * @return string HTML Link
  2023. */
  2024. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2025. {
  2026. global $langs;
  2027. if (empty($url)) return '';
  2028. $link = '<a href="';
  2029. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2030. $link .= $url;
  2031. $link .= '"';
  2032. if ($target) $link .= ' target="'.$target.'"';
  2033. $link .= '>';
  2034. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2035. $link .= dol_trunc($url, $max);
  2036. $link .= '</a>';
  2037. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2038. }
  2039. /**
  2040. * Show EMail link
  2041. *
  2042. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2043. * @param int $cid Id of contact if known
  2044. * @param int $socid Id of third party if known
  2045. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2046. * @param int $max Max number of characters to show
  2047. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2048. * @param int $withpicto Show picto
  2049. * @return string HTML Link
  2050. */
  2051. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2052. {
  2053. global $conf, $user, $langs, $hookmanager;
  2054. $newemail = $email;
  2055. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0;
  2056. if (empty($email)) return '&nbsp;';
  2057. if (!empty($addlink))
  2058. {
  2059. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2060. if (!preg_match('/^mailto:/i', $email)) $newemail .= 'mailto:';
  2061. $newemail .= $email;
  2062. $newemail .= '">';
  2063. $newemail .= dol_trunc($email, $max);
  2064. $newemail .= '</a>';
  2065. if ($showinvalid && !isValidEmail($email))
  2066. {
  2067. $langs->load("errors");
  2068. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2069. }
  2070. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2071. {
  2072. $type = 'AC_EMAIL'; $link = '';
  2073. 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>';
  2074. if ($link) $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2075. }
  2076. } else {
  2077. if ($showinvalid && !isValidEmail($email))
  2078. {
  2079. $langs->load("errors");
  2080. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2081. }
  2082. }
  2083. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2084. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2085. //$rep .= '</div>';
  2086. if ($hookmanager) {
  2087. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2088. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2089. if ($reshook > 0) {
  2090. $rep = '';
  2091. }
  2092. $rep .= $hookmanager->resPrint;
  2093. }
  2094. return $rep;
  2095. }
  2096. /**
  2097. * Get array of social network dictionary
  2098. *
  2099. * @return array Array of Social Networks Dictionary
  2100. */
  2101. function getArrayOfSocialNetworks()
  2102. {
  2103. global $conf, $db;
  2104. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2105. $sql .= " WHERE entity=".$conf->entity;
  2106. $socialnetworks = array();
  2107. $resql = $db->query($sql);
  2108. if ($resql) {
  2109. while ($obj = $db->fetch_object($resql)) {
  2110. $socialnetworks[$obj->code] = array(
  2111. 'rowid' => $obj->rowid,
  2112. 'label' => $obj->label,
  2113. 'url' => $obj->url,
  2114. 'icon' => $obj->icon,
  2115. 'active' => $obj->active,
  2116. );
  2117. }
  2118. }
  2119. return $socialnetworks;
  2120. }
  2121. /**
  2122. * Show social network link
  2123. *
  2124. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2125. * @param int $cid Id of contact if known
  2126. * @param int $socid Id of third party if known
  2127. * @param string $type 'skype','facebook',...
  2128. * @return string HTML Link
  2129. */
  2130. function dol_print_socialnetworks($value, $cid, $socid, $type)
  2131. {
  2132. global $conf, $user, $langs;
  2133. $htmllink = $value;
  2134. if (empty($value)) return '&nbsp;';
  2135. if (!empty($type))
  2136. {
  2137. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2138. $htmllink .= img_picto($langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright', 0);
  2139. $htmllink .= $value;
  2140. if ($type == 'skype')
  2141. {
  2142. $htmllink .= '&nbsp;';
  2143. $htmllink .= '<a href="skype:';
  2144. $htmllink .= $value;
  2145. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2146. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2147. $htmllink .= '</a><a href="skype:';
  2148. $htmllink .= $value;
  2149. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2150. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2151. $htmllink .= '</a>';
  2152. }
  2153. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype')
  2154. {
  2155. $addlink = 'AC_SKYPE';
  2156. $link = '';
  2157. 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>';
  2158. $htmllink .= ($link ? ' '.$link : '');
  2159. }
  2160. $htmllink .= '</div>';
  2161. } else {
  2162. $langs->load("errors");
  2163. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2164. }
  2165. return $htmllink;
  2166. }
  2167. /**
  2168. * Format phone numbers according to country
  2169. *
  2170. * @param string $phone Phone number to format
  2171. * @param string $countrycode Country code to use for formatting
  2172. * @param int $cid Id of contact if known
  2173. * @param int $socid Id of third party if known
  2174. * @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)
  2175. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2176. * @param string $withpicto Show picto
  2177. * @param string $titlealt Text to show on alt
  2178. * @param int $adddivfloat Add div float around phone.
  2179. * @return string Formated phone number
  2180. */
  2181. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2182. {
  2183. global $conf, $user, $langs, $mysoc, $hookmanager;
  2184. // Clean phone parameter
  2185. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2186. if (empty($phone)) { return ''; }
  2187. if ($conf->global->MAIN_PHONE_SEPAR) $separ = $conf->global->MAIN_PHONE_SEPAR;
  2188. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2189. // Short format for small screens
  2190. if ($conf->dol_optimize_smallscreen) $separ = '';
  2191. $newphone = $phone;
  2192. if (strtoupper($countrycode) == "FR")
  2193. {
  2194. // France
  2195. if (dol_strlen($phone) == 10) {
  2196. $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);
  2197. } elseif (dol_strlen($phone) == 7)
  2198. {
  2199. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2200. } elseif (dol_strlen($phone) == 9)
  2201. {
  2202. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2203. } elseif (dol_strlen($phone) == 11)
  2204. {
  2205. $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);
  2206. } elseif (dol_strlen($phone) == 12)
  2207. {
  2208. $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);
  2209. }
  2210. } elseif (strtoupper($countrycode) == "CA")
  2211. {
  2212. if (dol_strlen($phone) == 10) {
  2213. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2214. }
  2215. } elseif (strtoupper($countrycode) == "PT")
  2216. {//Portugal
  2217. if (dol_strlen($phone) == 13)
  2218. {//ex: +351_ABC_DEF_GHI
  2219. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2220. }
  2221. } elseif (strtoupper($countrycode) == "SR")
  2222. {//Suriname
  2223. if (dol_strlen($phone) == 10)
  2224. {//ex: +597_ABC_DEF
  2225. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2226. } elseif (dol_strlen($phone) == 11)
  2227. {//ex: +597_ABC_DEFG
  2228. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2229. }
  2230. } elseif (strtoupper($countrycode) == "DE")
  2231. {//Allemagne
  2232. if (dol_strlen($phone) == 14)
  2233. {//ex: +49_ABCD_EFGH_IJK
  2234. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2235. } elseif (dol_strlen($phone) == 13)
  2236. {//ex: +49_ABC_DEFG_HIJ
  2237. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2238. }
  2239. } elseif (strtoupper($countrycode) == "ES")
  2240. {//Espagne
  2241. if (dol_strlen($phone) == 12)
  2242. {//ex: +34_ABC_DEF_GHI
  2243. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2244. }
  2245. } elseif (strtoupper($countrycode) == "BF")
  2246. {// Burkina Faso
  2247. if (dol_strlen($phone) == 12)
  2248. {//ex : +22 A BC_DE_FG_HI
  2249. $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);
  2250. }
  2251. } elseif (strtoupper($countrycode) == "RO")
  2252. {// Roumanie
  2253. if (dol_strlen($phone) == 12)
  2254. {//ex : +40 AB_CDE_FG_HI
  2255. $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);
  2256. }
  2257. } elseif (strtoupper($countrycode) == "TR")
  2258. {//Turquie
  2259. if (dol_strlen($phone) == 13)
  2260. {//ex : +90 ABC_DEF_GHIJ
  2261. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2262. }
  2263. } elseif (strtoupper($countrycode) == "US")
  2264. {//Etat-Unis
  2265. if (dol_strlen($phone) == 12)
  2266. {//ex: +1 ABC_DEF_GHIJ
  2267. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2268. }
  2269. } elseif (strtoupper($countrycode) == "MX")
  2270. {//Mexique
  2271. if (dol_strlen($phone) == 12)
  2272. {//ex: +52 ABCD_EFG_HI
  2273. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2274. } elseif (dol_strlen($phone) == 11)
  2275. {//ex: +52 AB_CD_EF_GH
  2276. $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);
  2277. } elseif (dol_strlen($phone) == 13)
  2278. {//ex: +52 ABC_DEF_GHIJ
  2279. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2280. }
  2281. } elseif (strtoupper($countrycode) == "ML")
  2282. {//Mali
  2283. if (dol_strlen($phone) == 12)
  2284. {//ex: +223 AB_CD_EF_GH
  2285. $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);
  2286. }
  2287. } elseif (strtoupper($countrycode) == "TH")
  2288. {//Thaïlande
  2289. if (dol_strlen($phone) == 11)
  2290. {//ex: +66_ABC_DE_FGH
  2291. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2292. } elseif (dol_strlen($phone) == 12)
  2293. {//ex: +66_A_BCD_EF_GHI
  2294. $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);
  2295. }
  2296. } elseif (strtoupper($countrycode) == "MU")
  2297. {
  2298. //Maurice
  2299. if (dol_strlen($phone) == 11)
  2300. {//ex: +230_ABC_DE_FG
  2301. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2302. } elseif (dol_strlen($phone) == 12)
  2303. {//ex: +230_ABCD_EF_GH
  2304. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2305. }
  2306. } elseif (strtoupper($countrycode) == "ZA")
  2307. {//Afrique du sud
  2308. if (dol_strlen($phone) == 12)
  2309. {//ex: +27_AB_CDE_FG_HI
  2310. $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);
  2311. }
  2312. } elseif (strtoupper($countrycode) == "SY")
  2313. {//Syrie
  2314. if (dol_strlen($phone) == 12)
  2315. {//ex: +963_AB_CD_EF_GH
  2316. $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);
  2317. } elseif (dol_strlen($phone) == 13)
  2318. {//ex: +963_AB_CD_EF_GHI
  2319. $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);
  2320. }
  2321. } elseif (strtoupper($countrycode) == "AE")
  2322. {//Emirats Arabes Unis
  2323. if (dol_strlen($phone) == 12)
  2324. {//ex: +971_ABC_DEF_GH
  2325. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2326. } elseif (dol_strlen($phone) == 13)
  2327. {//ex: +971_ABC_DEF_GHI
  2328. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2329. } elseif (dol_strlen($phone) == 14)
  2330. {//ex: +971_ABC_DEF_GHIK
  2331. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2332. }
  2333. } elseif (strtoupper($countrycode) == "DZ")
  2334. {//Algérie
  2335. if (dol_strlen($phone) == 13)
  2336. {//ex: +213_ABC_DEF_GHI
  2337. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2338. }
  2339. } elseif (strtoupper($countrycode) == "BE")
  2340. {//Belgique
  2341. if (dol_strlen($phone) == 11)
  2342. {//ex: +32_ABC_DE_FGH
  2343. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2344. } elseif (dol_strlen($phone) == 12)
  2345. {//ex: +32_ABC_DEF_GHI
  2346. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2347. }
  2348. } elseif (strtoupper($countrycode) == "PF")
  2349. {//Polynésie française
  2350. if (dol_strlen($phone) == 12)
  2351. {//ex: +689_AB_CD_EF_GH
  2352. $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);
  2353. }
  2354. } elseif (strtoupper($countrycode) == "CO")
  2355. {//Colombie
  2356. if (dol_strlen($phone) == 13)
  2357. {//ex: +57_ABC_DEF_GH_IJ
  2358. $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);
  2359. }
  2360. } elseif (strtoupper($countrycode) == "JO")
  2361. {//Jordanie
  2362. if (dol_strlen($phone) == 12)
  2363. {//ex: +962_A_BCD_EF_GH
  2364. $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);
  2365. }
  2366. } elseif (strtoupper($countrycode) == "JM")
  2367. {//Jamaïque
  2368. if (dol_strlen($newphone) == 12)
  2369. {//ex: +1867_ABC_DEFG
  2370. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2371. }
  2372. } elseif (strtoupper($countrycode) == "MG")
  2373. {//Madagascar
  2374. if (dol_strlen($phone) == 13)
  2375. {//ex: +261_AB_CD_EF_GHI
  2376. $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);
  2377. }
  2378. } elseif (strtoupper($countrycode) == "GB")
  2379. {//Royaume uni
  2380. if (dol_strlen($phone) == 13)
  2381. {//ex: +44_ABCD_EFG_HIJ
  2382. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2383. }
  2384. } elseif (strtoupper($countrycode) == "CH")
  2385. {//Suisse
  2386. if (dol_strlen($phone) == 12)
  2387. {//ex: +41_AB_CDE_FG_HI
  2388. $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);
  2389. } elseif (dol_strlen($phone) == 15)
  2390. {// +41_AB_CDE_FGH_IJKL
  2391. $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);
  2392. }
  2393. } elseif (strtoupper($countrycode) == "TN")
  2394. {//Tunisie
  2395. if (dol_strlen($phone) == 12)
  2396. {//ex: +216_AB_CDE_FGH
  2397. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2398. }
  2399. } elseif (strtoupper($countrycode) == "GF")
  2400. {//Guyane francaise
  2401. if (dol_strlen($phone) == 13)
  2402. {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2403. $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);
  2404. }
  2405. } elseif (strtoupper($countrycode) == "GP")
  2406. {//Guadeloupe
  2407. if (dol_strlen($phone) == 13)
  2408. {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2409. $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);
  2410. }
  2411. } elseif (strtoupper($countrycode) == "MQ")
  2412. {//Martinique
  2413. if (dol_strlen($phone) == 13)
  2414. {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2415. $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);
  2416. }
  2417. } elseif (strtoupper($countrycode) == "IT")
  2418. {//Italie
  2419. if (dol_strlen($phone) == 12)
  2420. {//ex: +39_ABC_DEF_GHI
  2421. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2422. } elseif (dol_strlen($phone) == 13)
  2423. {//ex: +39_ABC_DEF_GH_IJ
  2424. $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);
  2425. }
  2426. } elseif (strtoupper($countrycode) == "AU")
  2427. {
  2428. //Australie
  2429. if (dol_strlen($phone) == 12)
  2430. {
  2431. //ex: +61_A_BCDE_FGHI
  2432. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2433. }
  2434. }
  2435. if (!empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2436. {
  2437. 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
  2438. {
  2439. $newphoneform = $newphone;
  2440. $newphone = '<a href="tel:'.$phone.'"';
  2441. $newphone .= '>'.$newphoneform.'</a>';
  2442. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  2443. {
  2444. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  2445. // Define urlmask
  2446. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2447. if (!empty($conf->global->CLICKTODIAL_URL)) $urlmask = $conf->global->CLICKTODIAL_URL;
  2448. if (!empty($user->clicktodial_url)) $urlmask = $user->clicktodial_url;
  2449. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2450. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2451. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2452. // This line is for backward compatibility
  2453. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2454. // Thoose lines are for substitution
  2455. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2456. '__PHONETO__'=>urlencode($phone),
  2457. '__LOGIN__'=>$clicktodial_login,
  2458. '__PASS__'=>$clicktodial_password);
  2459. $url = make_substitutions($url, $substitarray);
  2460. $newphonesav = $newphone;
  2461. $newphone = '<a href="'.$url.'"';
  2462. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone .= ' target="_blank"';
  2463. $newphone .= '>'.$newphonesav.'</a>';
  2464. }
  2465. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2466. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2467. {
  2468. $type = 'AC_TEL'; $link = '';
  2469. if ($addlink == 'AC_FAX') $type = 'AC_FAX';
  2470. 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>';
  2471. if ($link) $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2472. }
  2473. }
  2474. if (empty($titlealt))
  2475. {
  2476. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2477. }
  2478. $rep = '';
  2479. if ($hookmanager) {
  2480. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2481. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2482. $rep .= $hookmanager->resPrint;
  2483. }
  2484. if (empty($reshook))
  2485. {
  2486. $picto = '';
  2487. if ($withpicto) {
  2488. if ($withpicto == 'fax') {
  2489. $picto = 'phoning_fax';
  2490. } elseif ($withpicto == 'phone') {
  2491. $picto = 'phoning';
  2492. } elseif ($withpicto == 'mobile') {
  2493. $picto = 'phoning_mobile';
  2494. } else {
  2495. $picto = '';
  2496. }
  2497. }
  2498. if ($adddivfloat) $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2499. else $rep .= '<span style="margin-right: 10px;">';
  2500. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2501. if ($adddivfloat) $rep .= '</div>';
  2502. else $rep .= '</span>';
  2503. }
  2504. return $rep;
  2505. }
  2506. /**
  2507. * Return an IP formated to be shown on screen
  2508. *
  2509. * @param string $ip IP
  2510. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2511. * @return string Formated IP, with country if GeoIP module is enabled
  2512. */
  2513. function dol_print_ip($ip, $mode = 0)
  2514. {
  2515. global $conf, $langs;
  2516. $ret = '';
  2517. if (empty($mode)) $ret .= $ip;
  2518. if ($mode != 2)
  2519. {
  2520. $countrycode = dolGetCountryCodeFromIp($ip);
  2521. if ($countrycode) // If success, countrycode is us, fr, ...
  2522. {
  2523. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  2524. {
  2525. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2526. } else $ret .= ' ('.$countrycode.')';
  2527. } else {
  2528. // Nothing
  2529. }
  2530. }
  2531. return $ret;
  2532. }
  2533. /**
  2534. * Return the IP of remote user.
  2535. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2536. * Then HTTP_CLIENT_IP if defined (rare)
  2537. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2538. *
  2539. * @return string Ip of remote user.
  2540. */
  2541. function getUserRemoteIP()
  2542. {
  2543. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  2544. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  2545. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']);
  2546. } else {
  2547. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here
  2548. }
  2549. } else {
  2550. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here
  2551. }
  2552. return $ip;
  2553. }
  2554. /**
  2555. * Return a country code from IP. Empty string if not found.
  2556. *
  2557. * @param string $ip IP
  2558. * @return string Country code ('us', 'fr', ...)
  2559. */
  2560. function dolGetCountryCodeFromIp($ip)
  2561. {
  2562. global $conf;
  2563. $countrycode = '';
  2564. if (!empty($conf->geoipmaxmind->enabled))
  2565. {
  2566. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2567. //$ip='24.24.24.24';
  2568. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  2569. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2570. $geoip = new DolGeoIP('country', $datafile);
  2571. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2572. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2573. }
  2574. return $countrycode;
  2575. }
  2576. /**
  2577. * Return country code for current user.
  2578. * If software is used inside a local network, detection may fails (we need a public ip)
  2579. *
  2580. * @return string Country code (fr, es, it, us, ...)
  2581. */
  2582. function dol_user_country()
  2583. {
  2584. global $conf, $langs, $user;
  2585. //$ret=$user->xxx;
  2586. $ret = '';
  2587. if (!empty($conf->geoipmaxmind->enabled))
  2588. {
  2589. $ip = getUserRemoteIP();
  2590. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2591. //$ip='24.24.24.24';
  2592. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2593. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2594. $geoip = new DolGeoIP('country', $datafile);
  2595. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2596. $ret = $countrycode;
  2597. }
  2598. return $ret;
  2599. }
  2600. /**
  2601. * Format address string
  2602. *
  2603. * @param string $address Address string, already formatted with dol_format_address()
  2604. * @param int $htmlid Html ID (for example 'gmap')
  2605. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  2606. * @param int $id Id of object
  2607. * @param int $noprint No output. Result is the function return
  2608. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2609. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2610. * @see dol_format_address()
  2611. */
  2612. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  2613. {
  2614. global $conf, $user, $langs, $hookmanager;
  2615. $out = '';
  2616. if ($address)
  2617. {
  2618. if ($hookmanager) {
  2619. $parameters = array('element' => $element, 'id' => $id);
  2620. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2621. $out .= $hookmanager->resPrint;
  2622. }
  2623. if (empty($reshook))
  2624. {
  2625. if (empty($charfornl)) $out .= nl2br($address);
  2626. else $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  2627. // TODO Remove this block, we can add this using the hook now
  2628. $showgmap = $showomap = 0;
  2629. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap = 1;
  2630. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap = 1;
  2631. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap = 1;
  2632. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap = 1;
  2633. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap = 1;
  2634. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap = 1;
  2635. if ($showgmap)
  2636. {
  2637. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  2638. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2639. }
  2640. if ($showomap)
  2641. {
  2642. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  2643. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2644. }
  2645. }
  2646. }
  2647. if ($noprint) return $out;
  2648. else print $out;
  2649. }
  2650. /**
  2651. * Return true if email syntax is ok
  2652. *
  2653. * @param string $address email (Ex: "toto@examle.com", "John Do <johndo@example.com>")
  2654. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2655. * @return boolean true if email syntax is OK, false if KO or empty string
  2656. */
  2657. function isValidEmail($address, $acceptsupervisorkey = 0)
  2658. {
  2659. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2660. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2661. return false;
  2662. }
  2663. /**
  2664. * Return if the domain name has a valid MX record.
  2665. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  2666. *
  2667. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  2668. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  2669. */
  2670. function isValidMXRecord($domain)
  2671. {
  2672. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr'))
  2673. {
  2674. if (!checkdnsrr(idn_to_ascii($domain), 'MX'))
  2675. {
  2676. return 0;
  2677. }
  2678. if (function_exists('getmxrr'))
  2679. {
  2680. $mxhosts = array();
  2681. $weight = array();
  2682. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  2683. if (count($mxhosts) > 1) return 1;
  2684. if (count($mxhosts) == 1 && !empty($mxhosts[0])) return 1;
  2685. return 0;
  2686. }
  2687. }
  2688. return -1;
  2689. }
  2690. /**
  2691. * Return true if phone number syntax is ok
  2692. * TODO Decide what to do with this
  2693. *
  2694. * @param string $phone phone (Ex: "0601010101")
  2695. * @return boolean true if phone syntax is OK, false if KO or empty string
  2696. */
  2697. function isValidPhone($phone)
  2698. {
  2699. return true;
  2700. }
  2701. /**
  2702. * Make a strlen call. Works even if mbstring module not enabled
  2703. *
  2704. * @param string $string String to calculate length
  2705. * @param string $stringencoding Encoding of string
  2706. * @return int Length of string
  2707. */
  2708. function dol_strlen($string, $stringencoding = 'UTF-8')
  2709. {
  2710. if (function_exists('mb_strlen')) return mb_strlen($string, $stringencoding);
  2711. else return strlen($string);
  2712. }
  2713. /**
  2714. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  2715. *
  2716. * @param string $string String to scan
  2717. * @param string $start Start position
  2718. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  2719. * @param string $stringencoding Page code used for input string encoding
  2720. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  2721. * @return string substring
  2722. */
  2723. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  2724. {
  2725. global $langs;
  2726. if (empty($stringencoding)) $stringencoding = $langs->charset_output;
  2727. $ret = '';
  2728. if (empty($trunconbytes))
  2729. {
  2730. if (function_exists('mb_substr'))
  2731. {
  2732. $ret = mb_substr($string, $start, $length, $stringencoding);
  2733. } else {
  2734. $ret = substr($string, $start, $length);
  2735. }
  2736. } else {
  2737. if (function_exists('mb_strcut'))
  2738. {
  2739. $ret = mb_strcut($string, $start, $length, $stringencoding);
  2740. } else {
  2741. $ret = substr($string, $start, $length);
  2742. }
  2743. }
  2744. return $ret;
  2745. }
  2746. /**
  2747. * Truncate a string to a particular length adding '...' if string larger than length.
  2748. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2749. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2750. *
  2751. * @param string $string String to truncate
  2752. * @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 ...)
  2753. * @param string $trunc Where to trunc: right, left, middle (size must be a 2 power), wrap
  2754. * @param string $stringencoding Tell what is source string encoding
  2755. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2756. * @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)
  2757. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  2758. */
  2759. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  2760. {
  2761. global $conf;
  2762. if ($size == 0 || !empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2763. if (empty($stringencoding)) $stringencoding = 'UTF-8';
  2764. // reduce for small screen
  2765. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) $size = round($size / 3);
  2766. // We go always here
  2767. if ($trunc == 'right')
  2768. {
  2769. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2770. 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 ...
  2771. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...');
  2772. else //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  2773. return $string;
  2774. } elseif ($trunc == 'middle')
  2775. {
  2776. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2777. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1))
  2778. {
  2779. $size1 = round($size / 2);
  2780. $size2 = round($size / 2);
  2781. return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  2782. } else return $string;
  2783. } elseif ($trunc == 'left')
  2784. {
  2785. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2786. 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 ...
  2787. return '...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  2788. else return $string;
  2789. } elseif ($trunc == 'wrap')
  2790. {
  2791. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2792. if (dol_strlen($newstring, $stringencoding) > ($size + 1))
  2793. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  2794. else return $string;
  2795. } else return 'BadParam3CallingDolTrunc';
  2796. }
  2797. /**
  2798. * Show picto whatever it's its name (generic function)
  2799. *
  2800. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  2801. * @param string $picto Name of image file to show ('filenew', ...)
  2802. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2803. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2804. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2805. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2806. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2807. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  2808. * @param int $srconly Return only content of the src attribute of img.
  2809. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2810. * @param string $alt Force alt for bind people
  2811. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  2812. * @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.
  2813. * @return string Return img tag
  2814. * @see img_object(), img_picto_common()
  2815. */
  2816. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  2817. {
  2818. global $conf, $langs;
  2819. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2820. $url = DOL_URL_ROOT;
  2821. $theme = $conf->theme;
  2822. $path = 'theme/'.$theme;
  2823. // Define fullpathpicto to use into src
  2824. if ($pictoisfullpath) {
  2825. // Clean parameters
  2826. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  2827. $picto .= '.png';
  2828. }
  2829. $fullpathpicto = $picto;
  2830. $reg = array();
  2831. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2832. $morecss .= ($morecss ? ' ' : '').$reg[1];
  2833. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  2834. }
  2835. } else {
  2836. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  2837. if (empty($srconly) && in_array($pictowithouttext, array(
  2838. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  2839. 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'bank_account', 'barcode', 'bank', 'bill', 'bookmark', 'bom', 'building',
  2840. 'cash-register', 'category', 'check', 'clock', 'close_title', 'company', 'contact', 'contract', 'cubes',
  2841. 'delete', 'dolly', 'dollyrevert', 'edit', 'ellipsis-h', 'email', 'external-link-alt', 'external-link-square-alt',
  2842. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title',
  2843. 'help', 'holiday',
  2844. 'intervention', 'label', 'language', 'list', 'listlight', 'lot',
  2845. 'map-marker-alt', 'money-bill-alt', 'mrp', 'note',
  2846. 'object_accounting', 'object_account', 'object_accountline', 'object_action', 'object_barcode', 'object_bill', 'object_billa', 'object_billd', 'object_bom',
  2847. 'object_category', 'object_conversation', 'object_bookmark', 'object_bug', 'object_dolly', 'object_dollyrevert', 'object_generic', 'object_folder',
  2848. 'object_list-alt', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser',
  2849. 'object_cash-register', 'object_company', 'object_contact', 'object_contract', 'object_donation', 'object_dynamicprice',
  2850. 'object_globe', 'object_holiday', 'object_hrm', 'object_invoice', 'object_intervention', 'object_label',
  2851. 'object_margin', 'object_money-bill-alt', 'object_multicurrency', 'object_order', 'object_payment',
  2852. 'object_lot', 'object_mrp', 'object_payment', 'object_product', 'object_propal',
  2853. 'object_other', 'object_paragraph', 'object_poll', 'object_printer', 'object_project', 'object_projectpub', 'object_propal', 'object_resource', 'object_rss', 'object_projecttask',
  2854. 'object_recruitmentjobposition', 'object_recruitmentcandidature',
  2855. 'object_shipment', 'object_share-alt', 'object_supplier_invoice', 'object_supplier_invoicea', 'object_supplier_invoiced', 'object_supplier_order', 'object_supplier_proposal', 'object_service', 'object_stock',
  2856. 'object_technic', 'object_ticket', 'object_trip', 'object_user', 'object_group', 'object_member',
  2857. 'object_phoning', 'object_phoning_mobile', 'object_phoning_fax', 'object_email', 'object_website',
  2858. 'off', 'on', 'order',
  2859. 'paiment', 'play', 'playdisabled', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip',
  2860. 'setup', 'share-alt', 'sign-out', 'split', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  2861. 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  2862. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  2863. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  2864. 'payment', 'pencil-ruler', 'preview', 'project', 'projectpub', 'refresh', 'supplier_invoice', 'ticket',
  2865. 'error', 'warning',
  2866. 'recruitmentcandidature', 'recruitmentjobposition', 'resource',
  2867. 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  2868. 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda'
  2869. )
  2870. )) {
  2871. $fakey = $pictowithouttext;
  2872. $facolor = ''; $fasize = '';
  2873. $fa = 'fas';
  2874. if (in_array($pictowithouttext, array('clock', 'object_generic', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  2875. $fa = 'far';
  2876. }
  2877. if (in_array($pictowithouttext, array('black-tie', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  2878. $fa = 'fab';
  2879. }
  2880. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  2881. $arrayconvpictotofa = array(
  2882. 'account'=>'university', 'accountline'=>'receipt', 'accountancy'=>'money-check-alt', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book',
  2883. 'bank_account'=>'university', 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'supplier_invoicea'=>'file-excel', 'billd'=>'file-medical', 'supplier_invoiced'=>'file-medical', 'bom'=>'cubes',
  2884. 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'conversation'=>'comments', 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  2885. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  2886. 'accounting'=>'chart-line', 'category'=>'tag', 'dollyrevert'=>'dolly',
  2887. 'hrm'=>'user-tie', 'margin'=>'calculator', 'members'=>'users', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  2888. 'email'=>'at',
  2889. 'edit'=>'pencil-alt', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  2890. 'generic'=>'file', 'holiday'=>'umbrella-beach', 'label'=>'layer-group',
  2891. 'member'=>'users', 'mrp'=>'cubes', 'trip'=>'wallet', 'group'=>'users',
  2892. 'sign-out'=>'sign-out-alt',
  2893. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star',
  2894. 'bank'=>'university', 'close_title'=>'window-close', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter',
  2895. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  2896. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  2897. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  2898. 'other'=>'square',
  2899. 'playdisabled'=>'play', 'poll'=>'check-double', 'preview'=>'binoculars', 'project'=>'sitemap', 'projectpub'=>'sitemap', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  2900. 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  2901. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  2902. 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell',
  2903. 'refresh'=>'redo', 'resource'=>'laptop-house',
  2904. 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt',
  2905. 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  2906. 'title_agenda'=>'calendar-alt',
  2907. 'uparrow'=>'mail-forward', 'vcard'=>'address-card',
  2908. 'jabber'=>'comment-o',
  2909. 'website'=>'globe-americas'
  2910. );
  2911. if ($pictowithouttext == 'off') {
  2912. $fakey = 'fa-square';
  2913. $fasize = '1.3em';
  2914. } elseif ($pictowithouttext == 'on') {
  2915. $fakey = 'fa-check-square';
  2916. $fasize = '1.3em';
  2917. } elseif ($pictowithouttext == 'listlight') {
  2918. $fakey = 'fa-download';
  2919. $marginleftonlyshort = 1;
  2920. } elseif ($pictowithouttext == 'printer') {
  2921. $fakey = 'fa-print';
  2922. $fasize = '1.2em';
  2923. } elseif ($pictowithouttext == 'note') {
  2924. $fakey = 'fa-sticky-note';
  2925. $marginleftonlyshort = 1;
  2926. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  2927. $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');
  2928. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  2929. if (preg_match('/selected/', $pictowithouttext)) $facolor = '#888';
  2930. $marginleftonlyshort = 1;
  2931. } elseif (!empty($arrayconvpictotofa[$pictowithouttext]))
  2932. {
  2933. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  2934. } else {
  2935. $fakey = 'fa-'.$pictowithouttext;
  2936. }
  2937. // Define $marginleftonlyshort
  2938. $arrayconvpictotomarginleftonly = array(
  2939. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  2940. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_off',
  2941. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  2942. );
  2943. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  2944. $marginleftonlyshort = 0;
  2945. }
  2946. // Add CSS
  2947. $arrayconvpictotomorcess = array(
  2948. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account',
  2949. 'bank_account'=>'bg-infobox-bank_account',
  2950. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billd'=>'infobox-commande',
  2951. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'conversation'=>'infobox-contrat',
  2952. 'donation'=>'infobox-commande', 'dollyrevert'=>'flip', 'ecm'=>'infobox-action',
  2953. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  2954. 'multicurrency'=>'infobox-bank_account',
  2955. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  2956. 'order'=>'infobox-commande',
  2957. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  2958. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4',
  2959. 'holiday'=>'infobox-holiday', 'invoice'=>'infobox-commande',
  2960. 'payment'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  2961. 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  2962. 'resource'=>'infobox-action',
  2963. 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  2964. 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  2965. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  2966. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  2967. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  2968. );
  2969. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  2970. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  2971. }
  2972. // Define $color
  2973. $arrayconvpictotocolor = array(
  2974. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  2975. 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#37a', 'dynamicprice'=>'#a69944',
  2976. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999',
  2977. 'dolly'=>'#a69944', 'dollyrevert'=>'#a69944', 'lot'=>'#a69944',
  2978. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'stock'=>'#a69944',
  2979. 'other'=>'#ddd',
  2980. 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'resize'=>'#444', 'rss'=>'#cba',
  2981. 'shipment'=>'#a69944', 'stats'=>'#444', 'switch_off'=>'#999', 'uparrow'=>'#555', 'globe-americas'=>'#aaa',
  2982. 'website'=>'#304'
  2983. );
  2984. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  2985. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  2986. }
  2987. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  2988. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  2989. $reg = array();
  2990. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2991. $morecss .= ($morecss ? ' ' : '').$reg[1];
  2992. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  2993. }
  2994. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  2995. $morestyle = ' '.$reg[1];
  2996. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  2997. }
  2998. $moreatt = trim($moreatt);
  2999. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3000. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3001. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3002. $enabledisablehtml .= $titlealt;
  3003. }
  3004. $enabledisablehtml .= '</span>';
  3005. return $enabledisablehtml;
  3006. }
  3007. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3008. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3009. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3010. $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
  3011. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3012. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3013. }
  3014. // If we ask an image into $url/$mymodule/img (instead of default path)
  3015. $regs = array();
  3016. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3017. $picto = $regs[1];
  3018. $path = $regs[2]; // $path is $mymodule
  3019. }
  3020. // Clean parameters
  3021. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3022. $picto .= '.png';
  3023. }
  3024. // If alt path are defined, define url where img file is, according to physical path
  3025. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3026. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3027. if ($type == 'main') {
  3028. continue;
  3029. }
  3030. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3031. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3032. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3033. break;
  3034. }
  3035. }
  3036. // $url is '' or '/custom', $path is current theme or
  3037. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3038. }
  3039. if ($srconly) {
  3040. return $fullpathpicto;
  3041. }
  3042. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3043. 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
  3044. }
  3045. /**
  3046. * Show a picto called object_picto (generic function)
  3047. *
  3048. * @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.
  3049. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3050. * For external modules use imagename@mymodule to search into directory "img" of module.
  3051. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3052. * @param int $pictoisfullpath If 1, image path is a full path
  3053. * @param int $srconly Return only content of the src attribute of img.
  3054. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3055. * @return string Return img tag
  3056. * @see img_picto(), img_picto_common()
  3057. */
  3058. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3059. {
  3060. if (strpos($picto, '^') === 0) return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3061. else return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3062. }
  3063. /**
  3064. * Show weather picto
  3065. *
  3066. * @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.
  3067. * @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).
  3068. * @param string $moreatt Add more attribute on img tag
  3069. * @param int $pictoisfullpath If 1, image path is a full path
  3070. * @param string $morecss More CSS
  3071. * @return string Return img tag
  3072. * @see img_object(), img_picto()
  3073. */
  3074. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3075. {
  3076. global $conf;
  3077. if (is_numeric($picto)) {
  3078. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3079. //$picto = $leveltopicto[$picto];
  3080. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3081. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3082. $picto .= '.png';
  3083. }
  3084. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3085. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3086. }
  3087. /**
  3088. * Show picto (generic function)
  3089. *
  3090. * @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.
  3091. * @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.
  3092. * @param string $moreatt Add more attribute on img tag
  3093. * @param int $pictoisfullpath If 1, image path is a full path
  3094. * @return string Return img tag
  3095. * @see img_object(), img_picto()
  3096. */
  3097. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  3098. {
  3099. global $conf;
  3100. if (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  3101. if ($pictoisfullpath) $path = $picto;
  3102. else {
  3103. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3104. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  3105. {
  3106. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3107. if (file_exists($themepath)) $path = $themepath;
  3108. }
  3109. }
  3110. return img_picto($titlealt, $path, $moreatt, 1);
  3111. }
  3112. /**
  3113. * Show logo action
  3114. *
  3115. * @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.
  3116. * @param string $numaction Action id or code to show
  3117. * @param string $picto Name of image file to show ('filenew', ...)
  3118. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3119. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3120. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3121. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3122. * @return string Return an img tag
  3123. */
  3124. function img_action($titlealt, $numaction, $picto = '')
  3125. {
  3126. global $langs;
  3127. if (empty($titlealt) || $titlealt == 'default')
  3128. {
  3129. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3130. $numaction = -1;
  3131. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3132. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3133. $numaction = 0;
  3134. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3135. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3136. $numaction = 1;
  3137. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3138. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3139. $numaction = 2;
  3140. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3141. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3142. $numaction = 3;
  3143. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3144. } else {
  3145. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3146. $numaction = 0;
  3147. }
  3148. }
  3149. if (!is_numeric($numaction)) $numaction = 0;
  3150. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3151. }
  3152. /**
  3153. * Show pdf logo
  3154. *
  3155. * @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.
  3156. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3157. * @return string Retourne tag img
  3158. */
  3159. function img_pdf($titlealt = 'default', $size = 3)
  3160. {
  3161. global $langs;
  3162. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  3163. return img_picto($titlealt, 'pdf'.$size.'.png');
  3164. }
  3165. /**
  3166. * Show logo +
  3167. *
  3168. * @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.
  3169. * @param string $other Add more attributes on img
  3170. * @return string Return tag img
  3171. */
  3172. function img_edit_add($titlealt = 'default', $other = '')
  3173. {
  3174. global $langs;
  3175. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  3176. return img_picto($titlealt, 'edit_add.png', $other);
  3177. }
  3178. /**
  3179. * Show logo -
  3180. *
  3181. * @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.
  3182. * @param string $other Add more attributes on img
  3183. * @return string Return tag img
  3184. */
  3185. function img_edit_remove($titlealt = 'default', $other = '')
  3186. {
  3187. global $langs;
  3188. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  3189. return img_picto($titlealt, 'edit_remove.png', $other);
  3190. }
  3191. /**
  3192. * Show logo editer/modifier fiche
  3193. *
  3194. * @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.
  3195. * @param integer $float If you have to put the style "float: right"
  3196. * @param string $other Add more attributes on img
  3197. * @return string Return tag img
  3198. */
  3199. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3200. {
  3201. global $langs;
  3202. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  3203. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3204. }
  3205. /**
  3206. * Show logo view card
  3207. *
  3208. * @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.
  3209. * @param integer $float If you have to put the style "float: right"
  3210. * @param string $other Add more attributes on img
  3211. * @return string Return tag img
  3212. */
  3213. function img_view($titlealt = 'default', $float = 0, $other = '')
  3214. {
  3215. global $langs;
  3216. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  3217. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3218. return img_picto($titlealt, 'view.png', $moreatt);
  3219. }
  3220. /**
  3221. * Show delete logo
  3222. *
  3223. * @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.
  3224. * @param string $other Add more attributes on img
  3225. * @param string $morecss More CSS
  3226. * @return string Retourne tag img
  3227. */
  3228. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3229. {
  3230. global $langs;
  3231. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  3232. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3233. }
  3234. /**
  3235. * Show printer logo
  3236. *
  3237. * @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.
  3238. * @param string $other Add more attributes on img
  3239. * @return string Retourne tag img
  3240. */
  3241. function img_printer($titlealt = "default", $other = '')
  3242. {
  3243. global $langs;
  3244. if ($titlealt == "default") $titlealt = $langs->trans("Print");
  3245. return img_picto($titlealt, 'printer.png', $other);
  3246. }
  3247. /**
  3248. * Show split logo
  3249. *
  3250. * @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.
  3251. * @param string $other Add more attributes on img
  3252. * @return string Retourne tag img
  3253. */
  3254. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3255. {
  3256. global $langs;
  3257. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  3258. return img_picto($titlealt, 'split.png', $other);
  3259. }
  3260. /**
  3261. * Show help logo with cursor "?"
  3262. *
  3263. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3264. * @param int|string $usealttitle Text to use as alt title
  3265. * @return string Return tag img
  3266. */
  3267. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3268. {
  3269. global $langs;
  3270. if ($usealttitle)
  3271. {
  3272. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  3273. else $usealttitle = $langs->trans('Info');
  3274. }
  3275. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3276. }
  3277. /**
  3278. * Show info logo
  3279. *
  3280. * @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.
  3281. * @return string Return img tag
  3282. */
  3283. function img_info($titlealt = 'default')
  3284. {
  3285. global $langs;
  3286. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  3287. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3288. }
  3289. /**
  3290. * Show warning logo
  3291. *
  3292. * @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.
  3293. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3294. * @param string $morecss Add more CSS
  3295. * @return string Return img tag
  3296. */
  3297. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3298. {
  3299. global $langs;
  3300. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  3301. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3302. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3303. }
  3304. /**
  3305. * Show error logo
  3306. *
  3307. * @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.
  3308. * @return string Return img tag
  3309. */
  3310. function img_error($titlealt = 'default')
  3311. {
  3312. global $langs;
  3313. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  3314. return img_picto($titlealt, 'error.png');
  3315. }
  3316. /**
  3317. * Show next logo
  3318. *
  3319. * @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.
  3320. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3321. * @return string Return img tag
  3322. */
  3323. function img_next($titlealt = 'default', $moreatt = '')
  3324. {
  3325. global $langs;
  3326. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  3327. //return img_picto($titlealt, 'next.png', $moreatt);
  3328. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3329. }
  3330. /**
  3331. * Show previous logo
  3332. *
  3333. * @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.
  3334. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3335. * @return string Return img tag
  3336. */
  3337. function img_previous($titlealt = 'default', $moreatt = '')
  3338. {
  3339. global $langs;
  3340. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  3341. //return img_picto($titlealt, 'previous.png', $moreatt);
  3342. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3343. }
  3344. /**
  3345. * Show down arrow logo
  3346. *
  3347. * @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.
  3348. * @param int $selected Selected
  3349. * @param string $moreclass Add more CSS classes
  3350. * @return string Return img tag
  3351. */
  3352. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3353. {
  3354. global $langs;
  3355. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  3356. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3357. }
  3358. /**
  3359. * Show top arrow logo
  3360. *
  3361. * @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.
  3362. * @param int $selected Selected
  3363. * @param string $moreclass Add more CSS classes
  3364. * @return string Return img tag
  3365. */
  3366. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3367. {
  3368. global $langs;
  3369. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  3370. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3371. }
  3372. /**
  3373. * Show left arrow logo
  3374. *
  3375. * @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.
  3376. * @param int $selected Selected
  3377. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3378. * @return string Return img tag
  3379. */
  3380. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3381. {
  3382. global $langs;
  3383. if ($titlealt == 'default') {
  3384. $titlealt = $langs->trans('Left');
  3385. }
  3386. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3387. }
  3388. /**
  3389. * Show right arrow logo
  3390. *
  3391. * @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.
  3392. * @param int $selected Selected
  3393. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3394. * @return string Return img tag
  3395. */
  3396. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3397. {
  3398. global $langs;
  3399. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  3400. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3401. }
  3402. /**
  3403. * Show tick logo if allowed
  3404. *
  3405. * @param string $allow Allow
  3406. * @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.
  3407. * @return string Return img tag
  3408. */
  3409. function img_allow($allow, $titlealt = 'default')
  3410. {
  3411. global $langs;
  3412. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  3413. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  3414. return '-';
  3415. }
  3416. /**
  3417. * Return image of a credit card according to its brand name
  3418. *
  3419. * @param string $brand Brand name of credit card
  3420. * @param string $morecss More CSS
  3421. * @return string Return img tag
  3422. */
  3423. function img_credit_card($brand, $morecss = null)
  3424. {
  3425. if (is_null($morecss)) $morecss = 'fa-2x';
  3426. if ($brand == 'visa' || $brand == 'Visa') {
  3427. $brand = 'cc-visa';
  3428. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  3429. $brand = 'cc-mastercard';
  3430. } elseif ($brand == 'amex' || $brand == 'American Express') {
  3431. $brand = 'cc-amex';
  3432. } elseif ($brand == 'discover' || $brand == 'Discover') {
  3433. $brand = 'cc-discover';
  3434. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  3435. $brand = 'cc-jcb';
  3436. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  3437. $brand = 'cc-diners-club';
  3438. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  3439. $brand = 'credit-card';
  3440. }
  3441. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  3442. }
  3443. /**
  3444. * Show MIME img of a file
  3445. *
  3446. * @param string $file Filename
  3447. * @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.
  3448. * @param string $morecss More css
  3449. * @return string Return img tag
  3450. */
  3451. function img_mime($file, $titlealt = '', $morecss = '')
  3452. {
  3453. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3454. $mimetype = dol_mimetype($file, '', 1);
  3455. $mimeimg = dol_mimetype($file, '', 2);
  3456. $mimefa = dol_mimetype($file, '', 4);
  3457. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  3458. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3459. return '<i class="fa fa-'.$mimefa.' paddingright"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  3460. }
  3461. /**
  3462. * Show search logo
  3463. *
  3464. * @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.
  3465. * @param string $other Add more attributes on img
  3466. * @return string Retourne tag img
  3467. */
  3468. function img_search($titlealt = 'default', $other = '')
  3469. {
  3470. global $conf, $langs;
  3471. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3472. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3473. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3474. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3475. return $input;
  3476. }
  3477. /**
  3478. * Show search logo
  3479. *
  3480. * @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.
  3481. * @param string $other Add more attributes on img
  3482. * @return string Retourne tag img
  3483. */
  3484. function img_searchclear($titlealt = 'default', $other = '')
  3485. {
  3486. global $conf, $langs;
  3487. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3488. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3489. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3490. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3491. return $input;
  3492. }
  3493. /**
  3494. * Show information for admin users or standard users
  3495. *
  3496. * @param string $text Text info
  3497. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3498. * @param int $nodiv No div
  3499. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error','xxx'=Other
  3500. * @param string $morecss More CSS ('', 'warning', 'error')
  3501. * @param string $textfordropdown Show a text to click to dropdown the info box.
  3502. * @return string String with info text
  3503. */
  3504. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  3505. {
  3506. global $conf, $langs;
  3507. if ($infoonimgalt)
  3508. {
  3509. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  3510. } else {
  3511. if (empty($conf->use_javascript_ajax)) $textfordropdown = '';
  3512. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  3513. $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>');
  3514. if ($textfordropdown) {
  3515. $tmpresult .= '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  3516. $tmpresult .= '<script type="text/javascript" language="javascript">
  3517. jQuery(document).ready(function() {
  3518. jQuery(".'.$class.'text").click(function() {
  3519. console.log("toggle text");
  3520. jQuery(".'.$class.'").toggle();
  3521. });
  3522. });
  3523. </script>';
  3524. $result = $tmpresult.$result;
  3525. }
  3526. }
  3527. return $result;
  3528. }
  3529. /**
  3530. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  3531. * This function must be called when a blocking technical error is encountered.
  3532. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  3533. *
  3534. * @param DoliDB $db Database handler
  3535. * @param mixed $error String or array of errors strings to show
  3536. * @param array $errors Array of errors
  3537. * @return void
  3538. * @see dol_htmloutput_errors()
  3539. */
  3540. function dol_print_error($db = '', $error = '', $errors = null)
  3541. {
  3542. global $conf, $langs, $argv;
  3543. global $dolibarr_main_prod;
  3544. $out = '';
  3545. $syslog = '';
  3546. // If error occurs before the $lang object was loaded
  3547. if (!$langs)
  3548. {
  3549. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  3550. $langs = new Translate('', $conf);
  3551. $langs->load("main");
  3552. }
  3553. // Load translation files required by the error messages
  3554. $langs->loadLangs(array('main', 'errors'));
  3555. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3556. {
  3557. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  3558. 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";
  3559. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  3560. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  3561. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  3562. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  3563. if (function_exists("phpversion"))
  3564. {
  3565. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  3566. }
  3567. $out .= "<b>".$langs->trans("Server").":</b> ".dol_htmlentities($_SERVER["SERVER_SOFTWARE"])."<br>\n";
  3568. if (function_exists("php_uname"))
  3569. {
  3570. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  3571. }
  3572. $out .= "<b>".$langs->trans("UserAgent").":</b> ".dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3573. $out .= "<br>\n";
  3574. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3575. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '')."<br>\n";
  3576. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu) : '')."<br>\n";
  3577. $out .= "<br>\n";
  3578. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  3579. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  3580. } else // Mode CLI
  3581. {
  3582. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  3583. $syslog .= "pid=".dol_getmypid();
  3584. }
  3585. if (!empty($conf->modules))
  3586. {
  3587. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  3588. }
  3589. if (is_object($db))
  3590. {
  3591. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3592. {
  3593. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  3594. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3595. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3596. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3597. $out .= "<br>\n";
  3598. } else // Mode CLI
  3599. {
  3600. // No dol_escape_htmltag for output, we are in CLI mode
  3601. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  3602. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3603. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3604. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3605. }
  3606. $syslog .= ", sql=".$db->lastquery();
  3607. $syslog .= ", db_error=".$db->lasterror();
  3608. }
  3609. if ($error || $errors)
  3610. {
  3611. $langs->load("errors");
  3612. // Merge all into $errors array
  3613. if (is_array($error) && is_array($errors)) $errors = array_merge($error, $errors);
  3614. elseif (is_array($error)) $errors = $error;
  3615. elseif (is_array($errors)) $errors = array_merge(array($error), $errors);
  3616. else $errors = array_merge(array($error));
  3617. foreach ($errors as $msg)
  3618. {
  3619. if (empty($msg)) continue;
  3620. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3621. {
  3622. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  3623. } else // Mode CLI
  3624. {
  3625. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  3626. }
  3627. $syslog .= ", msg=".$msg;
  3628. }
  3629. }
  3630. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  3631. {
  3632. xdebug_print_function_stack();
  3633. $out .= '<b>XDebug informations:</b>'."<br>\n";
  3634. $out .= 'File: '.xdebug_call_file()."<br>\n";
  3635. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  3636. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  3637. $out .= "<br>\n";
  3638. }
  3639. // Return a http error code if possible
  3640. if (! headers_sent()) {
  3641. http_response_code(500);
  3642. }
  3643. if (empty($dolibarr_main_prod)) {
  3644. print $out;
  3645. } else {
  3646. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  3647. 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";
  3648. $langs->load("errors");
  3649. print $langs->trans("DolibarrHasDetectedError").'. ';
  3650. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  3651. define("MAIN_CORE_ERROR", 1);
  3652. }
  3653. dol_syslog("Error ".$syslog, LOG_ERR);
  3654. }
  3655. /**
  3656. * Show a public email and error code to contact if technical error
  3657. *
  3658. * @param string $prefixcode Prefix of public error code
  3659. * @param string $errormessage Complete error message
  3660. * @param array $errormessages Array of error messages
  3661. * @param string $morecss More css
  3662. * @param string $email Email
  3663. * @return void
  3664. */
  3665. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  3666. {
  3667. global $langs, $conf;
  3668. if (empty($email)) $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  3669. $langs->load("errors");
  3670. $now = dol_now();
  3671. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  3672. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  3673. if ($errormessage) print '<br><br>'.$errormessage;
  3674. if (is_array($errormessages) && count($errormessages))
  3675. {
  3676. foreach ($errormessages as $mesgtoshow)
  3677. {
  3678. print '<br><br>'.$mesgtoshow;
  3679. }
  3680. }
  3681. print '</div></div>';
  3682. }
  3683. /**
  3684. * Show title line of an array
  3685. *
  3686. * @param string $name Label of field
  3687. * @param string $file Url used when we click on sort picto
  3688. * @param string $field Field to use for new sorting
  3689. * @param string $begin ("" by defaut)
  3690. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3691. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  3692. * @param string $sortfield Current field used to sort
  3693. * @param string $sortorder Current sort order
  3694. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  3695. * @param string $tooltip Tooltip
  3696. * @return void
  3697. */
  3698. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "")
  3699. {
  3700. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip);
  3701. }
  3702. /**
  3703. * Get title line of an array
  3704. *
  3705. * @param string $name Translation key of field
  3706. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  3707. * @param string $file Url used when we click on sort picto
  3708. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  3709. * @param string $begin ("" by defaut)
  3710. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3711. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  3712. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  3713. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  3714. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  3715. * @param string $disablesortlink 1=Disable sort link
  3716. * @param string $tooltip Tooltip
  3717. * @return string
  3718. */
  3719. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '')
  3720. {
  3721. global $conf, $langs, $form;
  3722. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  3723. if ($moreattrib == 'class="right"') $prefix .= 'right '; // For backward compatibility
  3724. $sortorder = strtoupper($sortorder);
  3725. $out = '';
  3726. $sortimg = '';
  3727. $tag = 'th';
  3728. if ($thead == 2) $tag = 'div';
  3729. $tmpsortfield = explode(',', $sortfield);
  3730. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  3731. $tmpfield = explode(',', $field);
  3732. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  3733. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE)) {
  3734. $prefix = 'wrapcolumntitle '.$prefix;
  3735. }
  3736. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  3737. // If field is used as sort criteria we use a specific css class liste_titre_sel
  3738. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  3739. $liste_titre = 'liste_titre';
  3740. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  3741. $liste_titre = 'liste_titre_sel';
  3742. }
  3743. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  3744. //$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)).'"' : '');
  3745. $out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3746. $out .= '>';
  3747. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3748. {
  3749. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  3750. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3751. $options = preg_replace('/&+/i', '&', $options);
  3752. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3753. $sortordertouseinlink = '';
  3754. if ($field1 != $sortfield1) // We are on another field than current sorted field
  3755. {
  3756. if (preg_match('/^DESC/i', $sortorder))
  3757. {
  3758. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3759. } else // We reverse the var $sortordertouseinlink
  3760. {
  3761. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3762. }
  3763. } else // We are on field that is the first current sorting criteria
  3764. {
  3765. if (preg_match('/^ASC/i', $sortorder)) // We reverse the var $sortordertouseinlink
  3766. {
  3767. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3768. } else {
  3769. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3770. }
  3771. }
  3772. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  3773. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  3774. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3775. $out .= '>';
  3776. }
  3777. if ($tooltip) $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tooltip));
  3778. else $out .= $langs->trans($name);
  3779. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3780. {
  3781. $out .= '</a>';
  3782. }
  3783. if (empty($thead) && $field) // If this is a sort field
  3784. {
  3785. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  3786. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3787. $options = preg_replace('/&+/i', '&', $options);
  3788. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3789. if (!$sortorder || $field1 != $sortfield1)
  3790. {
  3791. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3792. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3793. } else {
  3794. if (preg_match('/^DESC/', $sortorder)) {
  3795. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3796. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3797. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  3798. }
  3799. if (preg_match('/^ASC/', $sortorder)) {
  3800. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3801. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3802. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  3803. }
  3804. }
  3805. }
  3806. $out .= $sortimg;
  3807. $out .= '</'.$tag.'>';
  3808. return $out;
  3809. }
  3810. /**
  3811. * Show a title.
  3812. *
  3813. * @param string $title Title to show
  3814. * @return string Title to show
  3815. * @deprecated Use load_fiche_titre instead
  3816. * @see load_fiche_titre()
  3817. */
  3818. function print_titre($title)
  3819. {
  3820. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  3821. print '<div class="titre">'.$title.'</div>';
  3822. }
  3823. /**
  3824. * Show a title with picto
  3825. *
  3826. * @param string $title Title to show
  3827. * @param string $mesg Added message to show on right
  3828. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3829. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3830. * @param int $id To force an id on html objects
  3831. * @return void
  3832. * @deprecated Use print load_fiche_titre instead
  3833. */
  3834. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  3835. {
  3836. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3837. }
  3838. /**
  3839. * Load a title with picto
  3840. *
  3841. * @param string $titre Title to show
  3842. * @param string $morehtmlright Added message to show on right
  3843. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3844. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3845. * @param string $id To force an id on html objects
  3846. * @param string $morecssontable More css on table
  3847. * @param string $morehtmlcenter Added message to show on center
  3848. * @return string
  3849. * @see print_barre_liste()
  3850. */
  3851. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  3852. {
  3853. global $conf;
  3854. $return = '';
  3855. if ($picto == 'setup') $picto = 'generic';
  3856. $return .= "\n";
  3857. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  3858. $return .= '<tr class="titre">';
  3859. if ($picto) $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  3860. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  3861. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  3862. $return .= '</td>';
  3863. if (dol_strlen($morehtmlcenter))
  3864. {
  3865. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3866. }
  3867. if (dol_strlen($morehtmlright))
  3868. {
  3869. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  3870. }
  3871. $return .= '</tr></table>'."\n";
  3872. return $return;
  3873. }
  3874. /**
  3875. * Print a title with navigation controls for pagination
  3876. *
  3877. * @param string $titre Title to show (required)
  3878. * @param int $page Numero of page to show in navigation links (required)
  3879. * @param string $file Url of page (required)
  3880. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  3881. * @param string $sortfield Field to sort on ('' by default)
  3882. * @param string $sortorder Order to sort ('' by default)
  3883. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  3884. * @param int $num Number of records found by select with limit+1
  3885. * @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.
  3886. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3887. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3888. * @param string $morehtmlright More html to show (after arrows)
  3889. * @param string $morecss More css to the table
  3890. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  3891. * @param int $hideselectlimit Force to hide select limit
  3892. * @param int $hidenavigation Force to hide all navigation tools
  3893. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  3894. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  3895. * @return void
  3896. */
  3897. 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 = '')
  3898. {
  3899. global $conf, $langs;
  3900. $savlimit = $limit;
  3901. $savtotalnboflines = $totalnboflines;
  3902. $totalnboflines = abs($totalnboflines);
  3903. if ($picto == 'setup') $picto = 'title_setup.png';
  3904. if (($conf->browser->name == 'ie') && $picto == 'generic') $picto = 'title.gif';
  3905. if ($limit < 0) $limit = $conf->liste_limit;
  3906. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  3907. {
  3908. $nextpage = 1;
  3909. } else {
  3910. $nextpage = 0;
  3911. }
  3912. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  3913. print "\n";
  3914. print "<!-- Begin title '".$titre."' -->\n";
  3915. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  3916. // Left
  3917. if ($picto && $titre) print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  3918. print '<td class="nobordernopadding valignmiddle col-title">';
  3919. print '<div class="titre inline-block">'.$titre;
  3920. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  3921. print '</div></td>';
  3922. // Center
  3923. if ($morehtmlcenter)
  3924. {
  3925. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3926. }
  3927. // Right
  3928. print '<td class="nobordernopadding valignmiddle right">';
  3929. if ($sortfield) $options .= "&sortfield=".urlencode($sortfield);
  3930. if ($sortorder) $options .= "&sortorder=".urlencode($sortorder);
  3931. // Show navigation bar
  3932. $pagelist = '';
  3933. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  3934. {
  3935. if ($totalnboflines) // If we know total nb of lines
  3936. {
  3937. // Define nb of extra page links before and after selected page + ... + first or last
  3938. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  3939. if ($limit > 0) $nbpages = ceil($totalnboflines / $limit);
  3940. else $nbpages = 1;
  3941. $cpt = ($page - $maxnbofpage);
  3942. if ($cpt < 0) { $cpt = 0; }
  3943. if ($cpt >= 1)
  3944. {
  3945. if (empty($pagenavastextinput)) {
  3946. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  3947. if ($cpt > 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  3948. elseif ($cpt == 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  3949. }
  3950. }
  3951. do {
  3952. if ($pagenavastextinput) {
  3953. if ($cpt == $page)
  3954. {
  3955. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  3956. $pagelist .= '/';
  3957. //if (($cpt + 1) < $nbpages) $pagelist .= '/';
  3958. }
  3959. } else {
  3960. if ($cpt == $page)
  3961. {
  3962. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  3963. } else {
  3964. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  3965. }
  3966. }
  3967. $cpt++;
  3968. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  3969. if (empty($pagenavastextinput)) {
  3970. if ($cpt < $nbpages)
  3971. {
  3972. if ($cpt < $nbpages - 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  3973. elseif ($cpt == $nbpages - 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  3974. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  3975. }
  3976. } else {
  3977. //var_dump($page.' '.$cpt.' '.$nbpages);
  3978. //if (($page + 1) < $nbpages) {
  3979. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  3980. //}
  3981. }
  3982. } else {
  3983. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  3984. }
  3985. }
  3986. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  3987. 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
  3988. }
  3989. // js to autoselect page field on focus
  3990. if ($pagenavastextinput) {
  3991. print ajax_autoselect('.pageplusone');
  3992. }
  3993. print '</td>';
  3994. print '</tr></table>'."\n";
  3995. print "<!-- End title -->\n\n";
  3996. }
  3997. /**
  3998. * Function to show navigation arrows into lists
  3999. *
  4000. * @param int $page Number of page
  4001. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4002. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4003. * @param integer $nextpage Do we show a next page button
  4004. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4005. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4006. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4007. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4008. * @param int $hideselectlimit Force to hide select limit
  4009. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4010. * @return void
  4011. */
  4012. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4013. {
  4014. global $conf, $langs;
  4015. print '<div class="pagination"><ul>';
  4016. if ($beforearrows)
  4017. {
  4018. print '<li class="paginationbeforearrows">';
  4019. print $beforearrows;
  4020. print '</li>';
  4021. }
  4022. if ((int) $limit > 0 && empty($hideselectlimit))
  4023. {
  4024. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  4025. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4026. //$pagesizechoices.=',2:2';
  4027. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4028. print '<li class="pagination">';
  4029. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4030. $tmpchoice = explode(',', $pagesizechoices);
  4031. $tmpkey = $limit.':'.$limit;
  4032. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4033. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4034. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4035. asort($tmpchoice, SORT_NUMERIC);
  4036. foreach ($tmpchoice as $val)
  4037. {
  4038. $selected = '';
  4039. $tmp = explode(':', $val);
  4040. $key = $tmp[0];
  4041. $val = $tmp[1];
  4042. if ($key != '' && $val != '')
  4043. {
  4044. if ((int) $key == (int) $limit)
  4045. {
  4046. $selected = ' selected="selected"';
  4047. }
  4048. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4049. }
  4050. }
  4051. print '</select>';
  4052. if ($conf->use_javascript_ajax)
  4053. {
  4054. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4055. <script>
  4056. jQuery(document).ready(function () {
  4057. jQuery(".selectlimit").change(function() {
  4058. console.log("Change limit. Send submit");
  4059. $(this).parents(\'form:first\').submit();
  4060. });
  4061. });
  4062. </script>
  4063. ';
  4064. }
  4065. print '</li>';
  4066. }
  4067. if ($page > 0)
  4068. {
  4069. 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>';
  4070. }
  4071. if ($betweenarrows)
  4072. {
  4073. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4074. print $betweenarrows;
  4075. print '<!--</div>-->';
  4076. }
  4077. if ($nextpage > 0)
  4078. {
  4079. 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>';
  4080. }
  4081. if ($afterarrows)
  4082. {
  4083. print '<li class="paginationafterarrows">';
  4084. print $afterarrows;
  4085. print '</li>';
  4086. }
  4087. print '</ul></div>'."\n";
  4088. }
  4089. /**
  4090. * Return a string with VAT rate label formated for view output
  4091. * Used into pdf and HTML pages
  4092. *
  4093. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4094. * @param boolean $addpercent Add a percent % sign in output
  4095. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4096. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4097. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4098. */
  4099. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4100. {
  4101. $morelabel = '';
  4102. if (preg_match('/%/', $rate))
  4103. {
  4104. $rate = str_replace('%', '', $rate);
  4105. $addpercent = true;
  4106. }
  4107. if (preg_match('/\((.*)\)/', $rate, $reg))
  4108. {
  4109. $morelabel = ' ('.$reg[1].')';
  4110. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4111. }
  4112. if (preg_match('/\*/', $rate))
  4113. {
  4114. $rate = str_replace('*', '', $rate);
  4115. $info_bits |= 1;
  4116. }
  4117. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4118. if (!preg_match('/\//', $rate)) $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4119. else {
  4120. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4121. $ret = $rate.($addpercent ? '%' : '');
  4122. }
  4123. if (($info_bits & 1) && $usestarfornpr >= 0) $ret .= ' *';
  4124. $ret .= $morelabel;
  4125. return $ret;
  4126. }
  4127. /**
  4128. * Function to format a value into an amount for visual output
  4129. * Function used into PDF and HTML pages
  4130. *
  4131. * @param float $amount Amount to format
  4132. * @param integer $form Type of format, HTML or not (not by default)
  4133. * @param Translate $outlangs Object langs for output
  4134. * @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.
  4135. * @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)
  4136. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4137. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4138. * @return string Chaine avec montant formate
  4139. *
  4140. * @see price2num() Revert function of price
  4141. */
  4142. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4143. {
  4144. global $langs, $conf;
  4145. // Clean parameters
  4146. if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = ''
  4147. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4148. if ($rounding < 0) $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4149. $nbdecimal = $rounding;
  4150. // Output separators by default (french)
  4151. $dec = ','; $thousand = ' ';
  4152. // If $outlangs not forced, we use use language
  4153. if (!is_object($outlangs)) $outlangs = $langs;
  4154. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4155. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4156. if ($thousand == 'None') $thousand = '';
  4157. elseif ($thousand == 'Space') $thousand = ' ';
  4158. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4159. //print "amount=".$amount."-";
  4160. $amount = str_replace(',', '.', $amount); // should be useless
  4161. //print $amount."-";
  4162. $datas = explode('.', $amount);
  4163. $decpart = isset($datas[1]) ? $datas[1] : '';
  4164. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4165. //print "decpart=".$decpart."<br>";
  4166. $end = '';
  4167. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4168. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal = dol_strlen($decpart);
  4169. // Si on depasse max
  4170. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  4171. {
  4172. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4173. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN))
  4174. {
  4175. // Si un affichage est tronque, on montre des ...
  4176. $end = '...';
  4177. }
  4178. }
  4179. // If force rounding
  4180. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  4181. // Format number
  4182. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4183. if ($form)
  4184. {
  4185. $output = preg_replace('/\s/', '&nbsp;', $output);
  4186. $output = preg_replace('/\'/', '&#039;', $output);
  4187. }
  4188. // Add symbol of currency if requested
  4189. $cursymbolbefore = $cursymbolafter = '';
  4190. if ($currency_code)
  4191. {
  4192. if ($currency_code == 'auto') $currency_code = $conf->currency;
  4193. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4194. $listoflanguagesbefore = array('nl_NL');
  4195. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore))
  4196. {
  4197. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4198. } else {
  4199. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4200. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4201. }
  4202. }
  4203. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4204. return $output;
  4205. }
  4206. /**
  4207. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4208. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4209. * should be roundtext2num().
  4210. *
  4211. * @param float $amount Amount to convert/clean or round
  4212. * @param string $rounding ''=No rounding
  4213. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4214. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4215. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4216. * 'CR'=Currency rate
  4217. * Numeric = Nb of digits for rounding
  4218. * @param int $alreadysqlnb Put 1 if you know that content is already universal format number
  4219. * @return string Amount with universal numeric format (Example: '99.99999').
  4220. * If conversion fails, it return text unchanged if $rounding = '' or '0' if $rounding is defined.
  4221. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined..
  4222. *
  4223. * @see price() Opposite function of price2num
  4224. */
  4225. function price2num($amount, $rounding = '', $alreadysqlnb = 0)
  4226. {
  4227. global $langs, $conf;
  4228. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4229. // Numbers must be '1234.56'
  4230. // Decimal delimiter for PHP and database SQL requests must be '.'
  4231. $dec = ','; $thousand = ' ';
  4232. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4233. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4234. if ($thousand == 'None') $thousand = '';
  4235. elseif ($thousand == 'Space') $thousand = ' ';
  4236. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4237. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4238. if ($alreadysqlnb != 1) // If not a PHP number or unknown, we change format
  4239. {
  4240. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4241. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4242. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4243. if (is_numeric($amount))
  4244. {
  4245. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4246. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4247. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4248. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4249. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4250. }
  4251. //print "QQ".$amount.'<br>';
  4252. // Now make replace (the main goal of function)
  4253. if ($thousand != ',' && $thousand != '.') $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4254. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4255. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4256. $amount = str_replace($dec, '.', $amount);
  4257. }
  4258. // Now, make a rounding if required
  4259. if ($rounding)
  4260. {
  4261. $nbofdectoround = '';
  4262. if ($rounding == 'MU') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4263. elseif ($rounding == 'MT') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4264. elseif ($rounding == 'MS') $nbofdectoround = empty($conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : $conf->global->MAIN_MAX_DECIMALS_STOCK;
  4265. elseif ($rounding == 'CR') $nbofdectoround = 8;
  4266. elseif (is_numeric($rounding)) $nbofdectoround = $rounding;
  4267. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  4268. if (dol_strlen($nbofdectoround)) $amount = round($amount, $nbofdectoround); // $nbofdectoround can be 0.
  4269. else return 'ErrorBadParameterProvidedToFunction';
  4270. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4271. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4272. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4273. if (is_numeric($amount))
  4274. {
  4275. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4276. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4277. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4278. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4279. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4280. }
  4281. //print "TT".$amount.'<br>';
  4282. // Always make replace because each math function (like round) replace
  4283. // with local values and we want a number that has a SQL string format x.y
  4284. if ($thousand != ',' && $thousand != '.') $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4285. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4286. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4287. $amount = str_replace($dec, '.', $amount);
  4288. }
  4289. return $amount;
  4290. }
  4291. /**
  4292. * Output a dimension with best unit
  4293. *
  4294. * @param float $dimension Dimension
  4295. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4296. * @param string $type 'weight', 'volume', ...
  4297. * @param Translate $outputlangs Translate language object
  4298. * @param int $round -1 = non rounding, x = number of decimal
  4299. * @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)
  4300. * @return string String to show dimensions
  4301. */
  4302. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
  4303. {
  4304. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4305. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  4306. {
  4307. $dimension = $dimension * 1000000;
  4308. $unit = $unit - 6;
  4309. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  4310. {
  4311. $dimension = $dimension * 1000;
  4312. $unit = $unit - 3;
  4313. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  4314. {
  4315. $dimension = $dimension / 1000000;
  4316. $unit = $unit + 6;
  4317. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  4318. {
  4319. $dimension = $dimension / 1000;
  4320. $unit = $unit + 3;
  4321. }
  4322. // Special case when we want output unit into pound or ounce
  4323. /* TODO
  4324. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4325. {
  4326. $dimension = // convert dimension from standard unit into ounce or pound
  4327. $unit = $forceunitoutput;
  4328. }
  4329. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4330. {
  4331. $dimension = // convert dimension from standard unit into ounce or pound
  4332. $unit = $forceunitoutput;
  4333. }*/
  4334. $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuringUnitString(0, $type, $unit);
  4335. return $ret;
  4336. }
  4337. /**
  4338. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4339. * Note: This function applies same rules than get_default_tva
  4340. *
  4341. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4342. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4343. * @param Societe $thirdparty_buyer Object of buying third party
  4344. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4345. * @param int $vatnpr If vat rate is NPR or not
  4346. * @return mixed 0 if not found, localtax rate if found
  4347. * @see get_default_tva()
  4348. */
  4349. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  4350. {
  4351. global $db, $conf, $mysoc;
  4352. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) $thirdparty_seller = $mysoc;
  4353. 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);
  4354. $vatratecleaned = $vatrate;
  4355. $reg = array();
  4356. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4357. {
  4358. $vatratecleaned = trim($reg[1]);
  4359. $vatratecode = $reg[2];
  4360. }
  4361. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4362. {
  4363. return 0;
  4364. }*/
  4365. // Some test to guess with no need to make database access
  4366. if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4367. {
  4368. if ($local == 1)
  4369. {
  4370. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  4371. if ($thirdparty_seller->id == $mysoc->id)
  4372. {
  4373. if (!$thirdparty_buyer->localtax1_assuj) return 0;
  4374. } else {
  4375. if (!$thirdparty_seller->localtax1_assuj) return 0;
  4376. }
  4377. }
  4378. if ($local == 2)
  4379. {
  4380. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4381. if (!$mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0.
  4382. if ($thirdparty_seller->id == $mysoc->id)
  4383. {
  4384. if (!$thirdparty_buyer->localtax2_assuj) return 0;
  4385. } else {
  4386. if (!$thirdparty_seller->localtax2_assuj) return 0;
  4387. }
  4388. }
  4389. } else {
  4390. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) return 0;
  4391. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) return 0;
  4392. }
  4393. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4394. if (in_array($mysoc->country_code, array('ES')))
  4395. {
  4396. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4397. }
  4398. // Search local taxes
  4399. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  4400. {
  4401. if ($local == 1)
  4402. {
  4403. if ($thirdparty_seller != $mysoc)
  4404. {
  4405. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4406. {
  4407. return $thirdparty_seller->localtax1_value;
  4408. }
  4409. } else // i am the seller
  4410. {
  4411. if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4412. {
  4413. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4414. }
  4415. }
  4416. }
  4417. if ($local == 2)
  4418. {
  4419. if ($thirdparty_seller != $mysoc)
  4420. {
  4421. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4422. // TODO We should also return value defined on thirdparty only if defined
  4423. {
  4424. return $thirdparty_seller->localtax2_value;
  4425. }
  4426. } else // i am the seller
  4427. {
  4428. if (in_array($mysoc->country_code, array('ES')))
  4429. {
  4430. return $thirdparty_buyer->localtax2_value;
  4431. } else {
  4432. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4433. }
  4434. }
  4435. }
  4436. }
  4437. // By default, search value of local tax on line of common tax
  4438. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4439. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4440. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  4441. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4442. if ($vatratecode) $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  4443. else $sql .= " AND t.recuperableonly ='".$db->escape($vatnpr)."'";
  4444. dol_syslog("get_localtax", LOG_DEBUG);
  4445. $resql = $db->query($sql);
  4446. if ($resql)
  4447. {
  4448. $obj = $db->fetch_object($resql);
  4449. if ($local == 1) return $obj->localtax1;
  4450. elseif ($local == 2) return $obj->localtax2;
  4451. }
  4452. return 0;
  4453. }
  4454. /**
  4455. * Return true if LocalTax (1 or 2) is unique.
  4456. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  4457. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  4458. *
  4459. * @param int $local Local tax to test (1 or 2)
  4460. * @return boolean True if LocalTax have multiple values, False if not
  4461. */
  4462. function isOnlyOneLocalTax($local)
  4463. {
  4464. $tax = get_localtax_by_third($local);
  4465. $valors = explode(":", $tax);
  4466. if (count($valors) > 1)
  4467. {
  4468. return false;
  4469. } else {
  4470. return true;
  4471. }
  4472. }
  4473. /**
  4474. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  4475. *
  4476. * @param int $local LocalTax to get
  4477. * @return number Values of localtax
  4478. */
  4479. function get_localtax_by_third($local)
  4480. {
  4481. global $db, $mysoc;
  4482. $sql = "SELECT t.localtax1, t.localtax2 ";
  4483. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  4484. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  4485. $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";
  4486. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  4487. $sql .= " )";
  4488. $resql = $db->query($sql);
  4489. if ($resql)
  4490. {
  4491. $obj = $db->fetch_object($resql);
  4492. if ($local == 1) return $obj->localtax1;
  4493. elseif ($local == 2) return $obj->localtax2;
  4494. }
  4495. return 0;
  4496. }
  4497. /**
  4498. * Get vat main information from Id.
  4499. * You can call getLocalTaxesFromRate after to get other fields.
  4500. *
  4501. * @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.
  4502. * @param Societe $buyer Company object
  4503. * @param Societe $seller Company object
  4504. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  4505. * @return array array('rowid'=> , 'code'=> ...)
  4506. * @see getLocalTaxesFromRate()
  4507. */
  4508. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  4509. {
  4510. global $db, $mysoc;
  4511. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  4512. // Search local taxes
  4513. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
  4514. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4515. if ($firstparamisid) $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4516. else {
  4517. $vatratecleaned = $vatrate;
  4518. $vatratecode = '';
  4519. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4520. {
  4521. $vatratecleaned = $reg[1];
  4522. $vatratecode = $reg[2];
  4523. }
  4524. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4525. /*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 ??
  4526. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  4527. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  4528. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4529. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4530. }
  4531. $resql = $db->query($sql);
  4532. if ($resql)
  4533. {
  4534. $obj = $db->fetch_object($resql);
  4535. if ($obj) return array('rowid'=>$obj->rowid, 'code'=>$obj->code, 'rate'=>$obj->rate, 'npr'=>$obj->npr, 'accountancy_code_sell'=>$obj->accountancy_code_sell, 'accountancy_code_buy'=>$obj->accountancy_code_buy);
  4536. else return array();
  4537. } else dol_print_error($db);
  4538. return array();
  4539. }
  4540. /**
  4541. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  4542. * This does not take into account the seller setup if subject to vat or not, only country.
  4543. * TODO
  4544. * This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  4545. * Instead this function must be called when adding a line to get the array of localtax and type, and then
  4546. * provide it to the function calcul_price_total.
  4547. *
  4548. * @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.
  4549. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  4550. * @param Societe $buyer Company object
  4551. * @param Societe $seller Company object
  4552. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  4553. * @return array array(localtax_type1(1-6/0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  4554. * @see getTaxesFromId()
  4555. */
  4556. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  4557. {
  4558. global $db, $mysoc;
  4559. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  4560. // Search local taxes
  4561. $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";
  4562. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4563. if ($firstparamisid) $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4564. else {
  4565. $vatratecleaned = $vatrate;
  4566. $vatratecode = '';
  4567. $reg = array();
  4568. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "x.x (yy)"
  4569. {
  4570. $vatratecleaned = $reg[1];
  4571. $vatratecode = $reg[2];
  4572. }
  4573. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4574. 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 ??
  4575. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  4576. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4577. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4578. }
  4579. $resql = $db->query($sql);
  4580. if ($resql)
  4581. {
  4582. $obj = $db->fetch_object($resql);
  4583. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  4584. if ($local == 1)
  4585. {
  4586. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4587. } elseif ($local == 2)
  4588. {
  4589. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4590. } else {
  4591. 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);
  4592. }
  4593. }
  4594. return 0;
  4595. }
  4596. /**
  4597. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  4598. * Function called by get_default_tva
  4599. *
  4600. * @param int $idprod Id of product or 0 if not a predefined product
  4601. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4602. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  4603. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  4604. * @see get_product_localtax_for_country()
  4605. */
  4606. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice = 0)
  4607. {
  4608. global $db, $conf, $mysoc;
  4609. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4610. $ret = 0;
  4611. $found = 0;
  4612. if ($idprod > 0)
  4613. {
  4614. // Load product
  4615. $product = new Product($db);
  4616. $result = $product->fetch($idprod);
  4617. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4618. {
  4619. if ($idprodfournprice > 0) // We want vat for product for a "supplier" object
  4620. {
  4621. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  4622. $ret = $product->vatrate_supplier;
  4623. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4624. } else {
  4625. $ret = $product->tva_tx; // Default vat of product we defined
  4626. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4627. }
  4628. $found = 1;
  4629. } else {
  4630. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  4631. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  4632. }
  4633. }
  4634. if (!$found)
  4635. {
  4636. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  4637. {
  4638. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  4639. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  4640. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4641. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4642. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  4643. $sql .= $db->plimit(1);
  4644. $resql = $db->query($sql);
  4645. if ($resql)
  4646. {
  4647. $obj = $db->fetch_object($resql);
  4648. if ($obj)
  4649. {
  4650. $ret = $obj->vat_rate;
  4651. if ($obj->default_vat_code) $ret .= ' ('.$obj->default_vat_code.')';
  4652. }
  4653. $db->free($sql);
  4654. } else dol_print_error($db);
  4655. } else $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  4656. }
  4657. dol_syslog("get_product_vat_for_country: ret=".$ret);
  4658. return $ret;
  4659. }
  4660. /**
  4661. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  4662. *
  4663. * @param int $idprod Id of product
  4664. * @param int $local 1 for localtax1, 2 for localtax 2
  4665. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4666. * @return int <0 if KO, Vat rate if OK
  4667. * @see get_product_vat_for_country()
  4668. */
  4669. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  4670. {
  4671. global $db, $mysoc;
  4672. if (!class_exists('Product')) {
  4673. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4674. }
  4675. $ret = 0;
  4676. $found = 0;
  4677. if ($idprod > 0)
  4678. {
  4679. // Load product
  4680. $product = new Product($db);
  4681. $result = $product->fetch($idprod);
  4682. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4683. {
  4684. /* Not defined yet, so we don't use this
  4685. if ($local==1) $ret=$product->localtax1_tx;
  4686. elseif ($local==2) $ret=$product->localtax2_tx;
  4687. $found=1;
  4688. */
  4689. } else {
  4690. // TODO Read default product vat according to countrycode and product
  4691. }
  4692. }
  4693. if (!$found)
  4694. {
  4695. // If vat of product for the country not found or not defined, we return higher vat of country.
  4696. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  4697. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4698. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4699. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  4700. $sql .= $db->plimit(1);
  4701. $resql = $db->query($sql);
  4702. if ($resql)
  4703. {
  4704. $obj = $db->fetch_object($resql);
  4705. if ($obj)
  4706. {
  4707. if ($local == 1) $ret = $obj->localtax1;
  4708. elseif ($local == 2) $ret = $obj->localtax2;
  4709. }
  4710. } else dol_print_error($db);
  4711. }
  4712. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  4713. return $ret;
  4714. }
  4715. /**
  4716. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  4717. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4718. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4719. * 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.
  4720. * 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
  4721. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  4722. * Sinon TVA proposee par defaut=0. Fin de regle.
  4723. *
  4724. * @param Societe $thirdparty_seller Objet societe vendeuse
  4725. * @param Societe $thirdparty_buyer Objet societe acheteuse
  4726. * @param int $idprod Id product
  4727. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  4728. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  4729. * @see get_default_npr(), get_default_localtax()
  4730. */
  4731. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4732. {
  4733. global $conf;
  4734. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4735. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  4736. $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;
  4737. $seller_country_code = $thirdparty_seller->country_code;
  4738. $seller_in_cee = isInEEC($thirdparty_seller);
  4739. $buyer_country_code = $thirdparty_buyer->country_code;
  4740. $buyer_in_cee = isInEEC($thirdparty_buyer);
  4741. 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 : ''));
  4742. // 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)
  4743. // we use the buyer VAT.
  4744. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  4745. {
  4746. if ($seller_in_cee && $buyer_in_cee && !$thirdparty_buyer->isACompany())
  4747. {
  4748. //print 'VATRULE 0';
  4749. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  4750. }
  4751. }
  4752. // If seller does not use VAT
  4753. if (!$seller_use_vat)
  4754. {
  4755. //print 'VATRULE 1';
  4756. return 0;
  4757. }
  4758. // 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.
  4759. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4760. if (($seller_country_code == $buyer_country_code)
  4761. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) // Warning ->country_code not always defined
  4762. {
  4763. //print 'VATRULE 2';
  4764. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4765. }
  4766. // 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.
  4767. // Not supported
  4768. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  4769. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4770. if (($seller_in_cee && $buyer_in_cee))
  4771. {
  4772. $isacompany = $thirdparty_buyer->isACompany();
  4773. if ($isacompany)
  4774. {
  4775. //print 'VATRULE 3';
  4776. return 0;
  4777. } else {
  4778. //print 'VATRULE 4';
  4779. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4780. }
  4781. }
  4782. // Si (vendeur en France et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4783. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee) && !$thirdparty_buyer->isACompany()) {
  4784. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4785. }
  4786. // Sinon la TVA proposee par defaut=0. Fin de regle.
  4787. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  4788. //print 'VATRULE 5';
  4789. return 0;
  4790. }
  4791. /**
  4792. * Fonction qui renvoie si tva doit etre tva percue recuperable
  4793. *
  4794. * @param Societe $thirdparty_seller Thirdparty seller
  4795. * @param Societe $thirdparty_buyer Thirdparty buyer
  4796. * @param int $idprod Id product
  4797. * @param int $idprodfournprice Id supplier price for product
  4798. * @return float 0 or 1
  4799. * @see get_default_tva(), get_default_localtax()
  4800. */
  4801. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4802. {
  4803. global $db;
  4804. if ($idprodfournprice > 0)
  4805. {
  4806. if (!class_exists('ProductFournisseur')) {
  4807. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  4808. }
  4809. $prodprice = new ProductFournisseur($db);
  4810. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  4811. return $prodprice->fourn_tva_npr;
  4812. } elseif ($idprod > 0)
  4813. {
  4814. if (!class_exists('Product')) {
  4815. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4816. }
  4817. $prod = new Product($db);
  4818. $prod->fetch($idprod);
  4819. return $prod->tva_npr;
  4820. }
  4821. return 0;
  4822. }
  4823. /**
  4824. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4825. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4826. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4827. * Sinon TVA proposee par defaut=0. Fin de regle.
  4828. *
  4829. * @param Societe $thirdparty_seller Thirdparty seller
  4830. * @param Societe $thirdparty_buyer Thirdparty buyer
  4831. * @param int $local Localtax to process (1 or 2)
  4832. * @param int $idprod Id product
  4833. * @return integer localtax, -1 si ne peut etre determine
  4834. * @see get_default_tva(), get_default_npr()
  4835. */
  4836. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  4837. {
  4838. global $mysoc;
  4839. if (!is_object($thirdparty_seller)) return -1;
  4840. if (!is_object($thirdparty_buyer)) return -1;
  4841. if ($local == 1) // Localtax 1
  4842. {
  4843. if ($mysoc->country_code == 'ES')
  4844. {
  4845. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) return 0;
  4846. } else {
  4847. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  4848. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) return 0;
  4849. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') return 0;
  4850. }
  4851. } elseif ($local == 2) //I Localtax 2
  4852. {
  4853. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  4854. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) return 0;
  4855. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') return 0;
  4856. }
  4857. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  4858. {
  4859. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  4860. }
  4861. return 0;
  4862. }
  4863. /**
  4864. * Return yes or no in current language
  4865. *
  4866. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  4867. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  4868. * @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.
  4869. * @return string HTML string
  4870. */
  4871. function yn($yesno, $case = 1, $color = 0)
  4872. {
  4873. global $langs;
  4874. $result = 'unknown'; $classname = '';
  4875. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  4876. {
  4877. $result = $langs->trans('yes');
  4878. if ($case == 1 || $case == 3) $result = $langs->trans("Yes");
  4879. if ($case == 2) $result = '<input type="checkbox" value="1" checked disabled>';
  4880. if ($case == 3) $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  4881. $classname = 'ok';
  4882. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  4883. {
  4884. $result = $langs->trans("no");
  4885. if ($case == 1 || $case == 3) $result = $langs->trans("No");
  4886. if ($case == 2) $result = '<input type="checkbox" value="0" disabled>';
  4887. if ($case == 3) $result = '<input type="checkbox" value="0" disabled> '.$result;
  4888. if ($color == 2) $classname = 'ok';
  4889. else $classname = 'error';
  4890. }
  4891. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  4892. return $result;
  4893. }
  4894. /**
  4895. * Return a path to have a the directory according to object where files are stored.
  4896. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart)
  4897. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, $modulepart) if multidir_output not defined.
  4898. * Example our with new usage: $object is invoice -> 'INYYMM-ABCD'
  4899. * Example our with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  4900. *
  4901. * @param string $num Id of object (deprecated, $object will be used in future)
  4902. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  4903. * @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)
  4904. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  4905. * @param Object $object Object
  4906. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...')
  4907. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  4908. */
  4909. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
  4910. {
  4911. global $conf;
  4912. $path = '';
  4913. $arrayforoldpath = array('cheque', 'user', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  4914. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[] = 'product';
  4915. if (!empty($level) && in_array($modulepart, $arrayforoldpath))
  4916. {
  4917. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  4918. if (empty($alpha)) $num = preg_replace('/([^0-9])/i', '', $num);
  4919. else $num = preg_replace('/^.*\-/i', '', $num);
  4920. $num = substr("000".$num, -$level);
  4921. if ($level == 1) $path = substr($num, 0, 1);
  4922. if ($level == 2) $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  4923. if ($level == 3) $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  4924. } else {
  4925. // TODO
  4926. // We will enhance here a common way of forging path for document storage
  4927. // Here, object->id, object->ref and modulepart are required.
  4928. //var_dump($modulepart);
  4929. if (in_array($modulepart, array('thirdparty', 'contact', 'member', 'propal', 'proposal', 'commande', 'order', 'facture', 'invoice',
  4930. 'supplier_order', 'supplier_proposal', 'shipment', 'contract', 'expensereport', 'ficheinter')))
  4931. {
  4932. $path = ($object->ref ? $object->ref : $object->id);
  4933. }
  4934. }
  4935. if (empty($withoutslash) && !empty($path)) $path .= '/';
  4936. return $path;
  4937. }
  4938. /**
  4939. * Creation of a directory (this can create recursive subdir)
  4940. *
  4941. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  4942. * @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)
  4943. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  4944. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  4945. */
  4946. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  4947. {
  4948. global $conf;
  4949. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  4950. $dir_osencoded = dol_osencode($dir);
  4951. if (@is_dir($dir_osencoded)) return 0;
  4952. $nberr = 0;
  4953. $nbcreated = 0;
  4954. $ccdir = '';
  4955. if (!empty($dataroot)) {
  4956. // Remove data root from loop
  4957. $dir = str_replace($dataroot.'/', '', $dir);
  4958. $ccdir = $dataroot.'/';
  4959. }
  4960. $cdir = explode("/", $dir);
  4961. $num = count($cdir);
  4962. for ($i = 0; $i < $num; $i++)
  4963. {
  4964. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  4965. else $ccdir .= $cdir[$i];
  4966. if (preg_match("/^.:$/", $ccdir, $regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  4967. // Attention, le is_dir() peut echouer bien que le rep existe.
  4968. // (ex selon config de open_basedir)
  4969. if ($ccdir)
  4970. {
  4971. $ccdir_osencoded = dol_osencode($ccdir);
  4972. if (!@is_dir($ccdir_osencoded))
  4973. {
  4974. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  4975. umask(0);
  4976. $dirmaskdec = octdec($newmask);
  4977. if (empty($newmask)) {
  4978. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  4979. }
  4980. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  4981. if (!@mkdir($ccdir_osencoded, $dirmaskdec))
  4982. {
  4983. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  4984. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  4985. $nberr++;
  4986. } else {
  4987. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  4988. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  4989. $nbcreated++;
  4990. }
  4991. } else {
  4992. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  4993. }
  4994. }
  4995. }
  4996. return ($nberr ? -$nberr : $nbcreated);
  4997. }
  4998. /**
  4999. * Return picto saying a field is required
  5000. *
  5001. * @return string Chaine avec picto obligatoire
  5002. */
  5003. function picto_required()
  5004. {
  5005. return '<span class="fieldrequired">*</span>';
  5006. }
  5007. /**
  5008. * Clean a string from all HTML tags and entities.
  5009. * This function differs from strip_tags because:
  5010. * - <br> are replaced with \n if removelinefeed=0 or 1
  5011. * - if entities are found, they are decoded BEFORE the strip
  5012. * - you can decide to convert line feed into a space
  5013. *
  5014. * @param string $stringtoclean String to clean
  5015. * @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..."
  5016. * @param string $pagecodeto Encoding of input/output string
  5017. * @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)
  5018. * @return string String cleaned
  5019. *
  5020. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5021. */
  5022. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0)
  5023. {
  5024. if ($removelinefeed == 2) $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5025. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5026. // We remove entities BEFORE stripping (in case of a separator char is encoded and not the other, the strip will fails)
  5027. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5028. if ($strip_tags) {
  5029. $temp = strip_tags($temp);
  5030. } else {
  5031. $pattern = "/<[^<>]+>/";
  5032. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5033. $temp = preg_replace($pattern, "", $temp); // pass 1
  5034. // $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5035. $temp = preg_replace($pattern, "", $temp); // pass 2
  5036. // $temp after pass 2: 0000-021
  5037. }
  5038. // Remove also CR LF
  5039. if ($removelinefeed == 1) $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5040. // and double spaces
  5041. while (strpos($temp, " "))
  5042. {
  5043. $temp = str_replace(" ", " ", $temp);
  5044. }
  5045. return trim($temp);
  5046. }
  5047. /**
  5048. * Clean a string to keep only desirable HTML tags.
  5049. *
  5050. * @param string $stringtoclean String to clean
  5051. * @param boolean $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5052. * @param boolean $removeclassattribute Remove the class attribute from tags
  5053. * @return string String cleaned
  5054. *
  5055. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5056. */
  5057. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1)
  5058. {
  5059. $allowed_tags = array(
  5060. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5061. "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"
  5062. );
  5063. $allowed_tags_string = join("><", $allowed_tags);
  5064. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5065. if ($cleanalsosomestyles) {
  5066. $stringtoclean = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $stringtoclean); // 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
  5067. }
  5068. if ($removeclassattribute) {
  5069. $stringtoclean = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $stringtoclean);
  5070. }
  5071. // TODO Remove '/href=("|\'|)javascript/' string ?
  5072. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  5073. return $temp;
  5074. }
  5075. /**
  5076. * Clean a string from some undesirable HTML tags.
  5077. * Note. Not enough secured as dol_string_onlythesehtmltags().
  5078. *
  5079. * @param string $stringtoclean String to clean
  5080. * @param array $disallowed_tags Array of tags not allowed
  5081. * @param string $cleanalsosomestyles Clean also some tags
  5082. * @return string String cleaned
  5083. *
  5084. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags()
  5085. */
  5086. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5087. {
  5088. $temp = $stringtoclean;
  5089. foreach ($disallowed_tags as $tagtoremove)
  5090. {
  5091. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5092. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5093. }
  5094. if ($cleanalsosomestyles) {
  5095. $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
  5096. }
  5097. return $temp;
  5098. }
  5099. /**
  5100. * Return first line of text. Cut will depends if content is HTML or not.
  5101. *
  5102. * @param string $text Input text
  5103. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5104. * @param string $charset Charset of $text string (UTF-8 by default)
  5105. * @return string Output text
  5106. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5107. */
  5108. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5109. {
  5110. if ($nboflines == 1)
  5111. {
  5112. if (dol_textishtml($text))
  5113. {
  5114. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5115. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5116. } else {
  5117. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5118. }
  5119. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5120. } else {
  5121. $ishtml = 0;
  5122. if (dol_textishtml($text))
  5123. {
  5124. $text = preg_replace('/\n/', '', $text);
  5125. $ishtml = 1;
  5126. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5127. } else {
  5128. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5129. }
  5130. $text = strtr($text, $repTable);
  5131. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5132. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5133. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5134. $firstline = '';
  5135. $i = 0;
  5136. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5137. while (($i < $nba) && ($i < ($nboflines * 2)))
  5138. {
  5139. if ($i % 2 == 0) $firstline .= $a[$i];
  5140. elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) $firstline .= ($ishtml ? "<br>\n" : "\n");
  5141. $i++;
  5142. }
  5143. unset($a);
  5144. return $firstline.(($i < $nba) ? '...' : '');
  5145. }
  5146. }
  5147. /**
  5148. * Replace CRLF in string with a HTML BR tag.
  5149. * 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.
  5150. *
  5151. * @param string $stringtoencode String to encode
  5152. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5153. * @param bool $forxml false=Use <br>, true=Use <br />
  5154. * @return string String encoded
  5155. * @see dol_nboflines(), dolGetFirstLineOfText()
  5156. */
  5157. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5158. {
  5159. if (!$nl2brmode) {
  5160. return nl2br($stringtoencode, $forxml);
  5161. } else {
  5162. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  5163. return $ret;
  5164. }
  5165. }
  5166. /**
  5167. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5168. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5169. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5170. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5171. * For PDF usage, you can show text by 2 ways:
  5172. * - writeHTMLCell -> param must be encoded into HTML.
  5173. * - MultiCell -> param must not be encoded into HTML.
  5174. * Because writeHTMLCell convert also \n into <br>, if function
  5175. * is used to build PDF, nl2brmode must be 1.
  5176. *
  5177. * @param string $stringtoencode String to encode
  5178. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5179. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5180. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5181. * @return string String encoded
  5182. */
  5183. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  5184. {
  5185. $newstring = $stringtoencode;
  5186. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  5187. {
  5188. $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.
  5189. if ($removelasteolbr) $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  5190. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  5191. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  5192. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  5193. } else {
  5194. if ($removelasteolbr) $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  5195. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  5196. }
  5197. // Other substitutions that htmlentities does not do
  5198. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5199. return $newstring;
  5200. }
  5201. /**
  5202. * This function is called to decode a HTML string (it decodes entities and br tags)
  5203. *
  5204. * @param string $stringtodecode String to decode
  5205. * @param string $pagecodeto Page code for result
  5206. * @return string String decoded
  5207. */
  5208. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  5209. {
  5210. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT, $pagecodeto);
  5211. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  5212. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  5213. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  5214. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  5215. return $ret;
  5216. }
  5217. /**
  5218. * This function remove all ending \n and br at end
  5219. *
  5220. * @param string $stringtodecode String to decode
  5221. * @return string String decoded
  5222. */
  5223. function dol_htmlcleanlastbr($stringtodecode)
  5224. {
  5225. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
  5226. return $ret;
  5227. }
  5228. /**
  5229. * Replace html_entity_decode functions to manage errors
  5230. *
  5231. * @param string $a Operand a
  5232. * @param string $b Operand b (ENT_QUOTES=convert simple and double quotes)
  5233. * @param string $c Operand c
  5234. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  5235. * @return string String decoded
  5236. */
  5237. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  5238. {
  5239. $newstring = $a;
  5240. if ($keepsomeentities) $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  5241. $newstring = html_entity_decode($newstring, $b, $c);
  5242. if ($keepsomeentities) $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  5243. return $newstring;
  5244. }
  5245. /**
  5246. * Replace htmlentities functions.
  5247. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5248. *
  5249. * @param string $string The input string to encode
  5250. * @param int $flags Flags (see PHP doc above)
  5251. * @param string $encoding Encoding page code
  5252. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5253. * @return string $ret Encoded string
  5254. */
  5255. function dol_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = false)
  5256. {
  5257. return htmlentities($string, $flags, $encoding, $double_encode);
  5258. }
  5259. /**
  5260. * Check if a string is a correct iso string
  5261. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5262. * Example, if string contains euro symbol that has ascii code 128
  5263. *
  5264. * @param string $s String to check
  5265. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  5266. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  5267. */
  5268. function dol_string_is_good_iso($s, $clean = 0)
  5269. {
  5270. $len = dol_strlen($s);
  5271. $out = '';
  5272. $ok = 1;
  5273. for ($scursor = 0; $scursor < $len; $scursor++)
  5274. {
  5275. $ordchar = ord($s[$scursor]);
  5276. //print $scursor.'-'.$ordchar.'<br>';
  5277. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok = 0; break; } elseif ($ordchar > 126 && $ordchar < 160) { $ok = 0; break; } elseif ($clean) {
  5278. $out .= $s[$scursor];
  5279. }
  5280. }
  5281. if ($clean) return $out;
  5282. return $ok;
  5283. }
  5284. /**
  5285. * Return nb of lines of a clear text
  5286. *
  5287. * @param string $s String to check
  5288. * @param int $maxchar Not yet used
  5289. * @return int Number of lines
  5290. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  5291. */
  5292. function dol_nboflines($s, $maxchar = 0)
  5293. {
  5294. if ($s == '') return 0;
  5295. $arraystring = explode("\n", $s);
  5296. $nb = count($arraystring);
  5297. return $nb;
  5298. }
  5299. /**
  5300. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  5301. *
  5302. * @param string $text Text
  5303. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  5304. * @param string $charset Give the charset used to encode the $text variable in memory.
  5305. * @return int Number of lines
  5306. * @see dol_nboflines(), dolGetFirstLineOfText()
  5307. */
  5308. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  5309. {
  5310. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5311. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5312. $text = strtr($text, $repTable);
  5313. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5314. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5315. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5316. $nblines = (int) floor((count($a) + 1) / 2);
  5317. // count possible auto line breaks
  5318. if ($maxlinesize)
  5319. {
  5320. foreach ($a as $line)
  5321. {
  5322. if (dol_strlen($line) > $maxlinesize)
  5323. {
  5324. //$line_dec = html_entity_decode(strip_tags($line));
  5325. $line_dec = html_entity_decode($line);
  5326. if (dol_strlen($line_dec) > $maxlinesize)
  5327. {
  5328. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  5329. $nblines += substr_count($line_dec, '\n');
  5330. }
  5331. }
  5332. }
  5333. }
  5334. unset($a);
  5335. return $nblines;
  5336. }
  5337. /**
  5338. * Return if a text is a html content
  5339. *
  5340. * @param string $msg Content to check
  5341. * @param int $option 0=Full detection, 1=Fast check
  5342. * @return boolean true/false
  5343. * @see dol_concatdesc()
  5344. */
  5345. function dol_textishtml($msg, $option = 0)
  5346. {
  5347. if ($option == 1)
  5348. {
  5349. if (preg_match('/<html/i', $msg)) return true;
  5350. elseif (preg_match('/<body/i', $msg)) return true;
  5351. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5352. elseif (preg_match('/<br/i', $msg)) return true;
  5353. return false;
  5354. } else {
  5355. if (preg_match('/<html/i', $msg)) return true;
  5356. elseif (preg_match('/<body/i', $msg)) return true;
  5357. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5358. elseif (preg_match('/<(b|em|i|u)>/i', $msg)) return true;
  5359. elseif (preg_match('/<br\/>/i', $msg)) return true;
  5360. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) return true;
  5361. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg)) return true;
  5362. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg)) return true;
  5363. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  5364. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  5365. elseif (preg_match('/<h[0-9]>/i', $msg)) return true;
  5366. elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  5367. elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  5368. return false;
  5369. }
  5370. }
  5371. /**
  5372. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  5373. * text1 html + text2 html => text1 + '<br>' + text2
  5374. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  5375. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  5376. * text1 txt + text2 txt => text1 + '\n' + text2
  5377. *
  5378. * @param string $text1 Text 1
  5379. * @param string $text2 Text 2
  5380. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  5381. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  5382. * @return string Text 1 + new line + Text2
  5383. * @see dol_textishtml()
  5384. */
  5385. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  5386. {
  5387. if (!empty($invert))
  5388. {
  5389. $tmp = $text1;
  5390. $text1 = $text2;
  5391. $text2 = $tmp;
  5392. }
  5393. $ret = '';
  5394. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  5395. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  5396. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  5397. return $ret;
  5398. }
  5399. /**
  5400. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  5401. *
  5402. * @param Translate $outputlangs Output language
  5403. * @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)
  5404. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  5405. * @param Object $object Object for keys on object
  5406. * @return array Array of substitutions
  5407. * @see setSubstitFromObject()
  5408. */
  5409. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  5410. {
  5411. global $db, $conf, $mysoc, $user, $extrafields;
  5412. $substitutionarray = array();
  5413. if (empty($exclude) || !in_array('user', $exclude))
  5414. {
  5415. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  5416. // this will include signature content first and then replace var found into content of signature
  5417. $signature = $user->signature;
  5418. $substitutionarray = array_merge($substitutionarray, array(
  5419. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  5420. )
  5421. );
  5422. $substitutionarray = array_merge($substitutionarray, array(
  5423. '__USER_ID__' => (string) $user->id,
  5424. '__USER_LOGIN__' => (string) $user->login,
  5425. '__USER_EMAIL__' => (string) $user->email,
  5426. '__USER_LASTNAME__' => (string) $user->lastname,
  5427. '__USER_FIRSTNAME__' => (string) $user->firstname,
  5428. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  5429. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  5430. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  5431. )
  5432. );
  5433. }
  5434. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc))
  5435. {
  5436. $substitutionarray = array_merge($substitutionarray, array(
  5437. '__MYCOMPANY_NAME__' => $mysoc->name,
  5438. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  5439. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  5440. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  5441. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  5442. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  5443. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  5444. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  5445. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  5446. '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '),
  5447. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  5448. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  5449. '__MYCOMPANY_TOWN__' => $mysoc->town,
  5450. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  5451. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  5452. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  5453. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  5454. ));
  5455. }
  5456. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)))
  5457. {
  5458. if ($onlykey)
  5459. {
  5460. $substitutionarray['__ID__'] = '__ID__';
  5461. $substitutionarray['__REF__'] = '__REF__';
  5462. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  5463. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  5464. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  5465. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  5466. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  5467. if (!empty($conf->societe->enabled)) // Most objects are concerned
  5468. {
  5469. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  5470. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  5471. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  5472. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  5473. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  5474. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  5475. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  5476. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  5477. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  5478. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  5479. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  5480. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  5481. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  5482. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  5483. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  5484. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  5485. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  5486. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  5487. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  5488. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  5489. }
  5490. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent'))
  5491. {
  5492. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  5493. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  5494. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  5495. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  5496. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  5497. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  5498. }
  5499. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature'))
  5500. {
  5501. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  5502. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  5503. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  5504. }
  5505. if (!empty($conf->projet->enabled)) // Most objects
  5506. {
  5507. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  5508. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  5509. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  5510. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  5511. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  5512. }
  5513. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract'))
  5514. {
  5515. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  5516. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  5517. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  5518. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  5519. }
  5520. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  5521. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  5522. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  5523. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  5524. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  5525. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  5526. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  5527. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  5528. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  5529. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  5530. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping'))
  5531. {
  5532. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tacking number';
  5533. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  5534. }
  5535. } else {
  5536. $substitutionarray['__ID__'] = $object->id;
  5537. $substitutionarray['__REF__'] = $object->ref;
  5538. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5539. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5540. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  5541. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  5542. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5543. // For backward compatibility
  5544. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5545. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5546. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5547. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5548. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5549. $substitutionarray['__SUPPLIER_ORDER_DELAY_DELIVERY__'] = $outputlangs->transnoentities("AvailabilityType".$object->availability_code) != ('AvailabilityType'.$object->availability_code) ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : '');
  5550. $birthday = dol_print_date($object->birth, 'day');
  5551. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0)
  5552. {
  5553. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  5554. if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  5555. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  5556. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  5557. if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  5558. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  5559. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  5560. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  5561. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  5562. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  5563. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  5564. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  5565. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  5566. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  5567. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  5568. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  5569. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  5570. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  5571. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  5572. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  5573. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  5574. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  5575. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  5576. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  5577. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  5578. }
  5579. if (is_object($object) && $object->element == 'societe') {
  5580. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  5581. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  5582. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  5583. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  5584. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  5585. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  5586. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  5587. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  5588. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  5589. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  5590. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  5591. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  5592. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  5593. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  5594. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  5595. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  5596. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  5597. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  5598. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  5599. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  5600. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  5601. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  5602. } elseif (is_object($object->thirdparty)) {
  5603. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  5604. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  5605. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  5606. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  5607. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  5608. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  5609. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  5610. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  5611. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  5612. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  5613. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  5614. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  5615. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  5616. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  5617. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  5618. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  5619. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  5620. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  5621. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  5622. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  5623. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  5624. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  5625. }
  5626. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  5627. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  5628. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  5629. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  5630. }
  5631. if (is_object($object->project))
  5632. {
  5633. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  5634. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  5635. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  5636. }
  5637. if (is_object($object->projet)) // Deprecated, for backward compatibility
  5638. {
  5639. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  5640. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  5641. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  5642. }
  5643. if (is_object($object) && $object->element == 'shipping')
  5644. {
  5645. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  5646. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  5647. }
  5648. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines))
  5649. {
  5650. $dateplannedstart = '';
  5651. $datenextexpiration = '';
  5652. foreach ($object->lines as $line)
  5653. {
  5654. if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue;
  5655. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue;
  5656. }
  5657. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  5658. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  5659. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  5660. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  5661. }
  5662. // Create dynamic tags for __EXTRAFIELD_FIELD__
  5663. if ($object->table_element && $object->id > 0)
  5664. {
  5665. if (!is_object($extrafields)) $extrafields = new ExtraFields($db);
  5666. $extrafields->fetch_name_optionals_label($object->table_element, true);
  5667. if ($object->fetch_optionals() > 0)
  5668. {
  5669. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
  5670. {
  5671. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  5672. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  5673. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  5674. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  5675. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  5676. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  5677. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  5678. $datetime = $object->array_options['options_'.$key];
  5679. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  5680. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  5681. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  5682. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  5683. }
  5684. }
  5685. }
  5686. }
  5687. }
  5688. // Complete substitution array with the url to make online payment
  5689. $paymenturl = '';
  5690. if (empty($substitutionarray['__REF__']))
  5691. {
  5692. $paymenturl = '';
  5693. } else {
  5694. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  5695. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  5696. $outputlangs->loadLangs(array('paypal', 'other'));
  5697. $typeforonlinepayment = 'free';
  5698. if (is_object($object) && $object->element == 'commande') $typeforonlinepayment = 'order';
  5699. if (is_object($object) && $object->element == 'facture') $typeforonlinepayment = 'invoice';
  5700. if (is_object($object) && $object->element == 'member') $typeforonlinepayment = 'member';
  5701. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  5702. $paymenturl = $url;
  5703. }
  5704. if ($object->id > 0)
  5705. {
  5706. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  5707. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  5708. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal')
  5709. {
  5710. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  5711. } else $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  5712. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande')
  5713. {
  5714. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  5715. } else $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  5716. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture')
  5717. {
  5718. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  5719. } else $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  5720. if (is_object($object) && $object->element == 'propal') $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  5721. if (is_object($object) && $object->element == 'commande') $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  5722. if (is_object($object) && $object->element == 'facture') $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  5723. }
  5724. if (is_object($object) && $object->element == 'action')
  5725. {
  5726. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  5727. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  5728. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  5729. }
  5730. }
  5731. }
  5732. if (empty($exclude) || !in_array('objectamount', $exclude))
  5733. {
  5734. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  5735. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  5736. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  5737. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  5738. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? ($object->total_vat ? $object->total_vat : $object->total_tva) : '';
  5739. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  5740. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  5741. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5742. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5743. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? ($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)) : '';
  5744. 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) : '';
  5745. 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) : '';
  5746. // TODO Add keys for foreign multicurrency
  5747. // For backward compatibility
  5748. if ($onlykey != 2)
  5749. {
  5750. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  5751. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  5752. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? ($object->total_vat ? $object->total_vat : $object->total_tva) : '';
  5753. }
  5754. }
  5755. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  5756. if (empty($exclude) || !in_array('date', $exclude))
  5757. {
  5758. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5759. $tmp = dol_getdate(dol_now(), true);
  5760. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5761. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  5762. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5763. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  5764. $substitutionarray = array_merge($substitutionarray, array(
  5765. '__DAY__' => (string) $tmp['mday'],
  5766. '__DAY_TEXT__' => $outputlangs->trans('Day'.$tmp['wday']), // Monday
  5767. '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'].'Min'), // Mon
  5768. '__DAY_TEXT_MIN__' => $outputlangs->trans('Short'.$tmp['weekday']), // M
  5769. '__MONTH__' => (string) $tmp['mon'],
  5770. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  5771. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  5772. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  5773. '__YEAR__' => (string) $tmp['year'],
  5774. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  5775. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  5776. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  5777. '__NEXT_DAY__' => (string) $tmp4['day'],
  5778. '__NEXT_MONTH__' => (string) $tmp5['month'],
  5779. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  5780. ));
  5781. }
  5782. if (!empty($conf->multicompany->enabled))
  5783. {
  5784. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  5785. }
  5786. if (empty($exclude) || !in_array('system', $exclude))
  5787. {
  5788. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  5789. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  5790. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  5791. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  5792. }
  5793. return $substitutionarray;
  5794. }
  5795. /**
  5796. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  5797. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  5798. * Example of usage:
  5799. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  5800. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  5801. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  5802. *
  5803. * @param string $text Source string in which we must do substitution
  5804. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  5805. * @param Translate $outputlangs Output language
  5806. * @return string Output string after substitutions
  5807. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  5808. */
  5809. function make_substitutions($text, $substitutionarray, $outputlangs = null)
  5810. {
  5811. global $conf, $langs;
  5812. if (!is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  5813. if (empty($outputlangs)) $outputlangs = $langs;
  5814. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  5815. if (is_object($outputlangs))
  5816. {
  5817. $reg = array();
  5818. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg))
  5819. {
  5820. $msgishtml = 0;
  5821. if (dol_textishtml($text, 1)) $msgishtml = 1;
  5822. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  5823. $tmp = explode('|', $reg[1]);
  5824. if (!empty($tmp[1])) $outputlangs->load($tmp[1]);
  5825. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
  5826. }
  5827. }
  5828. // Make substitution for constant keys.
  5829. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  5830. $reg = array();
  5831. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg))
  5832. {
  5833. $msgishtml = 0;
  5834. if (dol_textishtml($text, 1)) $msgishtml = 1;
  5835. $keyfound = $reg[1];
  5836. if (preg_match('/(_pass|_pw|password|secret|_key|key$)/i', $keyfound)) $newval = '*****forbidden*****';
  5837. else $newval = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  5838. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ?dol_htmlentitiesbr($newval) : $newval, $text);
  5839. }
  5840. // Make substitition for array $substitutionarray
  5841. foreach ($substitutionarray as $key => $value)
  5842. {
  5843. if (!isset($value)) continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  5844. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value = ''; // Protection
  5845. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  5846. }
  5847. return $text;
  5848. }
  5849. /**
  5850. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  5851. * In this case, method completesubstitutionarray provided by module is called.
  5852. *
  5853. * @param array $substitutionarray Array substitution old value => new value value
  5854. * @param Translate $outputlangs Output language
  5855. * @param Object $object Source object
  5856. * @param mixed $parameters Add more parameters (useful to pass product lines)
  5857. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  5858. * @return void
  5859. * @see make_substitutions()
  5860. */
  5861. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  5862. {
  5863. global $conf, $user;
  5864. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5865. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  5866. // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
  5867. /*if (is_object($object) && is_array($object->array_options))
  5868. {
  5869. foreach($object->array_options as $key => $val)
  5870. {
  5871. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  5872. $substitutionarray['__EXTRAFIELD_'.$keyshort.'__']=$val;
  5873. // For backward compatibiliy
  5874. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  5875. }
  5876. }*/
  5877. // Check if there is external substitution to do, requested by plugins
  5878. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  5879. foreach ($dirsubstitutions as $reldir)
  5880. {
  5881. $dir = dol_buildpath($reldir, 0);
  5882. // Check if directory exists
  5883. if (!dol_is_dir($dir)) continue;
  5884. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  5885. foreach ($substitfiles as $substitfile)
  5886. {
  5887. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg))
  5888. {
  5889. $module = $reg[1];
  5890. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  5891. // Include the user's functions file
  5892. require_once $dir.$substitfile['name'];
  5893. // Call the user's function, and only if it is defined
  5894. $function_name = $module."_".$callfunc;
  5895. if (function_exists($function_name)) $function_name($substitutionarray, $outputlangs, $object, $parameters);
  5896. }
  5897. }
  5898. }
  5899. }
  5900. /**
  5901. * Format output for start and end date
  5902. *
  5903. * @param int $date_start Start date
  5904. * @param int $date_end End date
  5905. * @param string $format Output format
  5906. * @param Translate $outputlangs Output language
  5907. * @return void
  5908. */
  5909. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  5910. {
  5911. print get_date_range($date_start, $date_end, $format, $outputlangs);
  5912. }
  5913. /**
  5914. * Format output for start and end date
  5915. *
  5916. * @param int $date_start Start date
  5917. * @param int $date_end End date
  5918. * @param string $format Output format
  5919. * @param Translate $outputlangs Output language
  5920. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  5921. * @return string String
  5922. */
  5923. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  5924. {
  5925. global $langs;
  5926. $out = '';
  5927. if (!is_object($outputlangs)) $outputlangs = $langs;
  5928. if ($date_start && $date_end)
  5929. {
  5930. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  5931. }
  5932. if ($date_start && !$date_end)
  5933. {
  5934. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  5935. }
  5936. if (!$date_start && $date_end)
  5937. {
  5938. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  5939. }
  5940. return $out;
  5941. }
  5942. /**
  5943. * Return firstname and lastname in correct order
  5944. *
  5945. * @param string $firstname Firstname
  5946. * @param string $lastname Lastname
  5947. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname
  5948. * @return string Firstname + lastname or Lastname + firstname
  5949. */
  5950. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  5951. {
  5952. global $conf;
  5953. $ret = '';
  5954. // If order not defined, we use the setup
  5955. if ($nameorder < 0) $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  5956. if ($nameorder && $nameorder != 2 && $nameorder != 3)
  5957. {
  5958. $ret .= $firstname;
  5959. if ($firstname && $lastname) $ret .= ' ';
  5960. $ret .= $lastname;
  5961. } elseif ($nameorder == 2 || $nameorder == 3)
  5962. {
  5963. $ret .= $firstname;
  5964. if (empty($ret) && $nameorder == 3)
  5965. {
  5966. $ret .= $lastname;
  5967. }
  5968. } else {
  5969. $ret .= $lastname;
  5970. if ($firstname && $lastname) $ret .= ' ';
  5971. $ret .= $firstname;
  5972. }
  5973. return $ret;
  5974. }
  5975. /**
  5976. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  5977. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5978. * Note: Prefer to use setEventMessages instead.
  5979. *
  5980. * @param mixed $mesgs Message string or array
  5981. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5982. * @return void
  5983. * @see dol_htmloutput_events()
  5984. */
  5985. function setEventMessage($mesgs, $style = 'mesgs')
  5986. {
  5987. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  5988. if (!is_array($mesgs)) // If mesgs is a string
  5989. {
  5990. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  5991. } else // If mesgs is an array
  5992. {
  5993. foreach ($mesgs as $mesg)
  5994. {
  5995. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  5996. }
  5997. }
  5998. }
  5999. /**
  6000. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  6001. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6002. *
  6003. * @param string $mesg Message string
  6004. * @param array $mesgs Message array
  6005. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6006. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  6007. * @return void
  6008. * @see dol_htmloutput_events()
  6009. */
  6010. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  6011. {
  6012. if (empty($mesg) && empty($mesgs))
  6013. {
  6014. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  6015. } else {
  6016. if ($messagekey)
  6017. {
  6018. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  6019. // TODO
  6020. $mesg .= '';
  6021. }
  6022. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey]))
  6023. {
  6024. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  6025. if (empty($mesgs)) setEventMessage($mesg, $style);
  6026. else {
  6027. if (!empty($mesg) && !in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  6028. setEventMessage($mesgs, $style);
  6029. }
  6030. }
  6031. }
  6032. }
  6033. /**
  6034. * Print formated messages to output (Used to show messages on html output).
  6035. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  6036. * no need to call it explicitely.
  6037. *
  6038. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  6039. * @return void
  6040. * @see dol_htmloutput_mesg()
  6041. */
  6042. function dol_htmloutput_events($disabledoutputofmessages = 0)
  6043. {
  6044. // Show mesgs
  6045. if (isset($_SESSION['dol_events']['mesgs'])) {
  6046. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  6047. unset($_SESSION['dol_events']['mesgs']);
  6048. }
  6049. // Show errors
  6050. if (isset($_SESSION['dol_events']['errors'])) {
  6051. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  6052. unset($_SESSION['dol_events']['errors']);
  6053. }
  6054. // Show warnings
  6055. if (isset($_SESSION['dol_events']['warnings'])) {
  6056. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  6057. unset($_SESSION['dol_events']['warnings']);
  6058. }
  6059. }
  6060. /**
  6061. * Get formated messages to output (Used to show messages on html output).
  6062. * This include also the translation of the message key.
  6063. *
  6064. * @param string $mesgstring Message string or message key
  6065. * @param string[] $mesgarray Array of message strings or message keys
  6066. * @param string $style Style of message output ('ok' or 'error')
  6067. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6068. * @return string Return html output
  6069. *
  6070. * @see dol_print_error()
  6071. * @see dol_htmloutput_errors()
  6072. * @see setEventMessages()
  6073. */
  6074. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  6075. {
  6076. global $conf, $langs;
  6077. $ret = 0; $return = '';
  6078. $out = '';
  6079. $divstart = $divend = '';
  6080. // If inline message with no format, we add it.
  6081. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out))
  6082. {
  6083. $divstart = '<div class="'.$style.' clearboth">';
  6084. $divend = '</div>';
  6085. }
  6086. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  6087. {
  6088. $langs->load("errors");
  6089. $out .= $divstart;
  6090. if (is_array($mesgarray) && count($mesgarray))
  6091. {
  6092. foreach ($mesgarray as $message)
  6093. {
  6094. $ret++;
  6095. $out .= $langs->trans($message);
  6096. if ($ret < count($mesgarray)) $out .= "<br>\n";
  6097. }
  6098. }
  6099. if ($mesgstring)
  6100. {
  6101. $langs->load("errors");
  6102. $ret++;
  6103. $out .= $langs->trans($mesgstring);
  6104. }
  6105. $out .= $divend;
  6106. }
  6107. if ($out)
  6108. {
  6109. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  6110. {
  6111. $return = '<script>
  6112. $(document).ready(function() {
  6113. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  6114. if (block) {
  6115. $.dolEventValid("","'.dol_escape_js($out).'");
  6116. } else {
  6117. /* jnotify(message, preset of message type, keepmessage) */
  6118. $.jnotify("'.dol_escape_js($out).'",
  6119. "'.($style == "ok" ? 3000 : $style).'",
  6120. '.($style == "ok" ? "false" : "true").',
  6121. { remove: function (){} } );
  6122. }
  6123. });
  6124. </script>';
  6125. } else {
  6126. $return = $out;
  6127. }
  6128. }
  6129. return $return;
  6130. }
  6131. /**
  6132. * Get formated error messages to output (Used to show messages on html output).
  6133. *
  6134. * @param string $mesgstring Error message
  6135. * @param array $mesgarray Error messages array
  6136. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6137. * @return string Return html output
  6138. *
  6139. * @see dol_print_error()
  6140. * @see dol_htmloutput_mesg()
  6141. */
  6142. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6143. {
  6144. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6145. }
  6146. /**
  6147. * Print formated messages to output (Used to show messages on html output).
  6148. *
  6149. * @param string $mesgstring Message string or message key
  6150. * @param string[] $mesgarray Array of message strings or message keys
  6151. * @param string $style Which style to use ('ok', 'warning', 'error')
  6152. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  6153. * @return void
  6154. *
  6155. * @see dol_print_error()
  6156. * @see dol_htmloutput_errors()
  6157. * @see setEventMessages()
  6158. */
  6159. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  6160. {
  6161. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) return;
  6162. $iserror = 0;
  6163. $iswarning = 0;
  6164. if (is_array($mesgarray))
  6165. {
  6166. foreach ($mesgarray as $val)
  6167. {
  6168. if ($val && preg_match('/class="error"/i', $val)) { $iserror++; break; }
  6169. if ($val && preg_match('/class="warning"/i', $val)) { $iswarning++; break; }
  6170. }
  6171. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) $iserror++;
  6172. elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) $iswarning++;
  6173. if ($style == 'error') $iserror++;
  6174. if ($style == 'warning') $iswarning++;
  6175. if ($iserror || $iswarning)
  6176. {
  6177. // Remove div from texts
  6178. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  6179. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  6180. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  6181. // Remove div from texts array
  6182. if (is_array($mesgarray))
  6183. {
  6184. $newmesgarray = array();
  6185. foreach ($mesgarray as $val)
  6186. {
  6187. if (is_string($val))
  6188. {
  6189. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  6190. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  6191. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  6192. $newmesgarray[] = $tmpmesgstring;
  6193. } else {
  6194. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  6195. }
  6196. }
  6197. $mesgarray = $newmesgarray;
  6198. }
  6199. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  6200. } else print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  6201. }
  6202. /**
  6203. * Print formated error messages to output (Used to show messages on html output).
  6204. *
  6205. * @param string $mesgstring Error message
  6206. * @param array $mesgarray Error messages array
  6207. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6208. * @return void
  6209. *
  6210. * @see dol_print_error()
  6211. * @see dol_htmloutput_mesg()
  6212. */
  6213. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6214. {
  6215. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6216. }
  6217. /**
  6218. * Advanced sort array by second index function, which produces ascending (default)
  6219. * or descending output and uses optionally natural case insensitive sorting (which
  6220. * can be optionally case sensitive as well).
  6221. *
  6222. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  6223. * @param string $index Key in array to use for sorting criteria
  6224. * @param int $order Sort order ('asc' or 'desc')
  6225. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  6226. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  6227. * @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.
  6228. * @return array Sorted array
  6229. */
  6230. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  6231. {
  6232. // Clean parameters
  6233. $order = strtolower($order);
  6234. if (is_array($array))
  6235. {
  6236. $sizearray = count($array);
  6237. if ($sizearray > 0)
  6238. {
  6239. $temp = array();
  6240. foreach (array_keys($array) as $key)
  6241. {
  6242. if (is_object($array[$key]))
  6243. {
  6244. $temp[$key] = $array[$key]->$index;
  6245. } else {
  6246. $temp[$key] = $array[$key][$index];
  6247. }
  6248. }
  6249. if (!$natsort) {
  6250. ($order == 'asc') ? asort($temp) : arsort($temp);
  6251. } else {
  6252. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  6253. if ($order != 'asc') $temp = array_reverse($temp, true);
  6254. }
  6255. $sorted = array();
  6256. foreach (array_keys($temp) as $key)
  6257. {
  6258. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  6259. }
  6260. return $sorted;
  6261. }
  6262. }
  6263. return $array;
  6264. }
  6265. /**
  6266. * Check if a string is in UTF8
  6267. *
  6268. * @param string $str String to check
  6269. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  6270. */
  6271. function utf8_check($str)
  6272. {
  6273. // We must use here a binary strlen function (so not dol_strlen)
  6274. $strLength = dol_strlen($str);
  6275. for ($i = 0; $i < $strLength; $i++)
  6276. {
  6277. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  6278. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n = 1; // 110bbbbb
  6279. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n = 2; // 1110bbbb
  6280. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n = 3; // 11110bbb
  6281. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n = 4; // 111110bb
  6282. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n = 5; // 1111110b
  6283. else return false; // Does not match any model
  6284. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  6285. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  6286. return false;
  6287. }
  6288. }
  6289. return true;
  6290. }
  6291. /**
  6292. * Check if a string is in ASCII
  6293. *
  6294. * @param string $str String to check
  6295. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  6296. */
  6297. function ascii_check($str)
  6298. {
  6299. if (function_exists('mb_check_encoding')) {
  6300. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  6301. if (!mb_check_encoding($str, 'ASCII')) return false;
  6302. } else {
  6303. if (preg_match('/[^\x00-\x7f]/', $str)) return false; // Contains a byte > 7f
  6304. }
  6305. return true;
  6306. }
  6307. /**
  6308. * Return a string encoded into OS filesystem encoding. This function is used to define
  6309. * value to pass to filesystem PHP functions.
  6310. *
  6311. * @param string $str String to encode (UTF-8)
  6312. * @return string Encoded string (UTF-8, ISO-8859-1)
  6313. */
  6314. function dol_osencode($str)
  6315. {
  6316. global $conf;
  6317. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  6318. if (empty($tmp) && !empty($_SERVER["WINDIR"])) $tmp = 'iso-8859-1'; // By default for windows
  6319. if (empty($tmp)) $tmp = 'utf-8'; // By default for other
  6320. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  6321. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  6322. return $str;
  6323. }
  6324. /**
  6325. * Return an id or code from a code or id.
  6326. * Store also Code-Id into a cache to speed up next request on same key.
  6327. *
  6328. * @param DoliDB $db Database handler
  6329. * @param string $key Code or Id to get Id or Code
  6330. * @param string $tablename Table name without prefix
  6331. * @param string $fieldkey Field to search the key into
  6332. * @param string $fieldid Field to get
  6333. * @param int $entityfilter Filter by entity
  6334. * @return int <0 if KO, Id of code if OK
  6335. * @see $langs->getLabelFromKey
  6336. */
  6337. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  6338. {
  6339. global $cache_codes;
  6340. // If key empty
  6341. if ($key == '') return '';
  6342. // Check in cache
  6343. if (isset($cache_codes[$tablename][$key][$fieldid])) // Can be defined to 0 or ''
  6344. {
  6345. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  6346. }
  6347. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  6348. $sql = "SELECT ".$fieldid." as valuetoget";
  6349. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  6350. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  6351. if (!empty($entityfilter))
  6352. $sql .= " AND entity IN (".getEntity($tablename).")";
  6353. $resql = $db->query($sql);
  6354. if ($resql)
  6355. {
  6356. $obj = $db->fetch_object($resql);
  6357. if ($obj) $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  6358. else $cache_codes[$tablename][$key][$fieldid] = '';
  6359. $db->free($resql);
  6360. return $cache_codes[$tablename][$key][$fieldid];
  6361. } else {
  6362. return -1;
  6363. }
  6364. }
  6365. /**
  6366. * Verify if condition in string is ok or not
  6367. *
  6368. * @param string $strRights String with condition to check
  6369. * @return boolean True or False. Return True if strRights is ''
  6370. */
  6371. function verifCond($strRights)
  6372. {
  6373. global $user, $conf, $langs;
  6374. global $leftmenu;
  6375. global $rights; // To export to dol_eval function
  6376. //print $strRights."<br>\n";
  6377. $rights = true;
  6378. if ($strRights != '')
  6379. {
  6380. $str = 'if(!('.$strRights.')) { $rights = false; }';
  6381. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  6382. }
  6383. return $rights;
  6384. }
  6385. /**
  6386. * Replace eval function to add more security.
  6387. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  6388. *
  6389. * @param string $s String to evaluate
  6390. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  6391. * @param int $hideerrors 1=Hide errors
  6392. * @return mixed Nothing or return result of eval
  6393. */
  6394. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  6395. {
  6396. // Only global variables can be changed by eval function and returned to caller
  6397. global $db, $langs, $user, $conf, $website, $websitepage;
  6398. global $action, $mainmenu, $leftmenu;
  6399. global $rights;
  6400. global $object;
  6401. global $mysoc;
  6402. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  6403. global $soc; // For backward compatibility
  6404. //print $s."<br>\n";
  6405. if ($returnvalue)
  6406. {
  6407. if ($hideerrors) return @eval('return '.$s.';');
  6408. else return eval('return '.$s.';');
  6409. } else {
  6410. if ($hideerrors) @eval($s);
  6411. else eval($s);
  6412. }
  6413. }
  6414. /**
  6415. * Return if var element is ok
  6416. *
  6417. * @param string $element Variable to check
  6418. * @return boolean Return true of variable is not empty
  6419. */
  6420. function dol_validElement($element)
  6421. {
  6422. return (trim($element) != '');
  6423. }
  6424. /**
  6425. * Return img flag of country for a language code or country code
  6426. *
  6427. * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR)
  6428. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  6429. * @return string HTML img string with flag.
  6430. */
  6431. function picto_from_langcode($codelang, $moreatt = '')
  6432. {
  6433. global $langs;
  6434. if (empty($codelang)) return '';
  6435. if ($codelang == 'auto')
  6436. {
  6437. return '<span class="fa fa-globe"></span>';
  6438. }
  6439. $langtocountryflag = array(
  6440. 'ar_AR' => '',
  6441. 'ca_ES' => 'catalonia',
  6442. 'da_DA' => 'dk',
  6443. 'fr_CA' => 'mq',
  6444. 'sv_SV' => 'se'
  6445. );
  6446. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  6447. else {
  6448. $tmparray = explode('_', $codelang);
  6449. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  6450. }
  6451. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  6452. }
  6453. /**
  6454. * Return default language from country code.
  6455. * Return null if not found.
  6456. *
  6457. * @param string $countrycode Country code like 'US', 'FR', 'CA', ...
  6458. * @return string Value of locale like 'en_US', 'fr_FR', ...
  6459. */
  6460. function getLanguageCodeFromCountryCode($countrycode)
  6461. {
  6462. global $mysoc;
  6463. if (empty($countrycode)) return null;
  6464. if (strtoupper($countrycode) == 'MQ') return 'fr_CA';
  6465. if (strtoupper($countrycode) == 'SE') return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  6466. if (strtoupper($countrycode) == 'CH')
  6467. {
  6468. if ($mysoc->country_code == 'FR') return 'fr_CH';
  6469. if ($mysoc->country_code == 'DE') return 'de_CH';
  6470. }
  6471. // Locale list taken from:
  6472. // http://stackoverflow.com/questions/3191664/
  6473. // list-of-all-locales-and-their-short-codes
  6474. $locales = array(
  6475. 'af-ZA',
  6476. 'am-ET',
  6477. 'ar-AE',
  6478. 'ar-BH',
  6479. 'ar-DZ',
  6480. 'ar-EG',
  6481. 'ar-IQ',
  6482. 'ar-JO',
  6483. 'ar-KW',
  6484. 'ar-LB',
  6485. 'ar-LY',
  6486. 'ar-MA',
  6487. 'ar-OM',
  6488. 'ar-QA',
  6489. 'ar-SA',
  6490. 'ar-SY',
  6491. 'ar-TN',
  6492. 'ar-YE',
  6493. 'as-IN',
  6494. 'ba-RU',
  6495. 'be-BY',
  6496. 'bg-BG',
  6497. 'bn-BD',
  6498. 'bn-IN',
  6499. 'bo-CN',
  6500. 'br-FR',
  6501. 'ca-ES',
  6502. 'co-FR',
  6503. 'cs-CZ',
  6504. 'cy-GB',
  6505. 'da-DK',
  6506. 'de-AT',
  6507. 'de-CH',
  6508. 'de-DE',
  6509. 'de-LI',
  6510. 'de-LU',
  6511. 'dv-MV',
  6512. 'el-GR',
  6513. 'en-AU',
  6514. 'en-BZ',
  6515. 'en-CA',
  6516. 'en-GB',
  6517. 'en-IE',
  6518. 'en-IN',
  6519. 'en-JM',
  6520. 'en-MY',
  6521. 'en-NZ',
  6522. 'en-PH',
  6523. 'en-SG',
  6524. 'en-TT',
  6525. 'en-US',
  6526. 'en-ZA',
  6527. 'en-ZW',
  6528. 'es-AR',
  6529. 'es-BO',
  6530. 'es-CL',
  6531. 'es-CO',
  6532. 'es-CR',
  6533. 'es-DO',
  6534. 'es-EC',
  6535. 'es-ES',
  6536. 'es-GT',
  6537. 'es-HN',
  6538. 'es-MX',
  6539. 'es-NI',
  6540. 'es-PA',
  6541. 'es-PE',
  6542. 'es-PR',
  6543. 'es-PY',
  6544. 'es-SV',
  6545. 'es-US',
  6546. 'es-UY',
  6547. 'es-VE',
  6548. 'et-EE',
  6549. 'eu-ES',
  6550. 'fa-IR',
  6551. 'fi-FI',
  6552. 'fo-FO',
  6553. 'fr-BE',
  6554. 'fr-CA',
  6555. 'fr-CH',
  6556. 'fr-FR',
  6557. 'fr-LU',
  6558. 'fr-MC',
  6559. 'fy-NL',
  6560. 'ga-IE',
  6561. 'gd-GB',
  6562. 'gl-ES',
  6563. 'gu-IN',
  6564. 'he-IL',
  6565. 'hi-IN',
  6566. 'hr-BA',
  6567. 'hr-HR',
  6568. 'hu-HU',
  6569. 'hy-AM',
  6570. 'id-ID',
  6571. 'ig-NG',
  6572. 'ii-CN',
  6573. 'is-IS',
  6574. 'it-CH',
  6575. 'it-IT',
  6576. 'ja-JP',
  6577. 'ka-GE',
  6578. 'kk-KZ',
  6579. 'kl-GL',
  6580. 'km-KH',
  6581. 'kn-IN',
  6582. 'ko-KR',
  6583. 'ky-KG',
  6584. 'lb-LU',
  6585. 'lo-LA',
  6586. 'lt-LT',
  6587. 'lv-LV',
  6588. 'mi-NZ',
  6589. 'mk-MK',
  6590. 'ml-IN',
  6591. 'mn-MN',
  6592. 'mr-IN',
  6593. 'ms-BN',
  6594. 'ms-MY',
  6595. 'mt-MT',
  6596. 'nb-NO',
  6597. 'ne-NP',
  6598. 'nl-BE',
  6599. 'nl-NL',
  6600. 'nn-NO',
  6601. 'oc-FR',
  6602. 'or-IN',
  6603. 'pa-IN',
  6604. 'pl-PL',
  6605. 'ps-AF',
  6606. 'pt-BR',
  6607. 'pt-PT',
  6608. 'rm-CH',
  6609. 'ro-RO',
  6610. 'ru-RU',
  6611. 'rw-RW',
  6612. 'sa-IN',
  6613. 'se-FI',
  6614. 'se-NO',
  6615. 'se-SE',
  6616. 'si-LK',
  6617. 'sk-SK',
  6618. 'sl-SI',
  6619. 'sq-AL',
  6620. 'sv-FI',
  6621. 'sv-SE',
  6622. 'sw-KE',
  6623. 'ta-IN',
  6624. 'te-IN',
  6625. 'th-TH',
  6626. 'tk-TM',
  6627. 'tn-ZA',
  6628. 'tr-TR',
  6629. 'tt-RU',
  6630. 'ug-CN',
  6631. 'uk-UA',
  6632. 'ur-PK',
  6633. 'vi-VN',
  6634. 'wo-SN',
  6635. 'xh-ZA',
  6636. 'yo-NG',
  6637. 'zh-CN',
  6638. 'zh-HK',
  6639. 'zh-MO',
  6640. 'zh-SG',
  6641. 'zh-TW',
  6642. 'zu-ZA',
  6643. );
  6644. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  6645. if (in_array($buildprimarykeytotest, $locales)) return strtolower($countrycode).'_'.strtoupper($countrycode);
  6646. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) // Need extension php-intl
  6647. {
  6648. foreach ($locales as $locale)
  6649. {
  6650. $locale_language = locale_get_primary_language($locale);
  6651. $locale_region = locale_get_region($locale);
  6652. if (strtoupper($countrycode) == $locale_region)
  6653. {
  6654. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  6655. return strtolower($locale_language).'_'.strtoupper($locale_region);
  6656. }
  6657. }
  6658. } else {
  6659. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  6660. }
  6661. return null;
  6662. }
  6663. /**
  6664. * Complete or removed entries into a head array (used to build tabs).
  6665. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  6666. * Or by change using hook completeTabsHead
  6667. *
  6668. * @param Conf $conf Object conf
  6669. * @param Translate $langs Object langs
  6670. * @param object|null $object Object object
  6671. * @param array $head Object head
  6672. * @param int $h New position to fill
  6673. * @param string $type Value for object where objectvalue can be
  6674. * 'thirdparty' to add a tab in third party view
  6675. * 'intervention' to add a tab in intervention view
  6676. * 'supplier_order' to add a tab in supplier order view
  6677. * 'supplier_invoice' to add a tab in supplier invoice view
  6678. * 'invoice' to add a tab in customer invoice view
  6679. * 'order' to add a tab in customer order view
  6680. * 'contract' to add a tabl in contract view
  6681. * 'product' to add a tab in product view
  6682. * 'propal' to add a tab in propal view
  6683. * 'user' to add a tab in user view
  6684. * 'group' to add a tab in group view
  6685. * 'member' to add a tab in fundation member view
  6686. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  6687. * 'ecm' to add a tab for another ecm view
  6688. * 'stock' to add a tab for warehouse view
  6689. * @param string $mode 'add' to complete head, 'remove' to remove entries
  6690. * @return void
  6691. */
  6692. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  6693. {
  6694. global $hookmanager;
  6695. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  6696. {
  6697. foreach ($conf->modules_parts['tabs'][$type] as $value)
  6698. {
  6699. $values = explode(':', $value);
  6700. if ($mode == 'add' && !preg_match('/^\-/', $values[1]))
  6701. {
  6702. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  6703. {
  6704. if ($values[0] != $type) continue;
  6705. if (verifCond($values[4]))
  6706. {
  6707. if ($values[3]) $langs->load($values[3]);
  6708. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6709. {
  6710. $substitutionarray = array();
  6711. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6712. $label = make_substitutions($reg[1], $substitutionarray);
  6713. } else $label = $langs->trans($values[2]);
  6714. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  6715. $head[$h][1] = $label;
  6716. $head[$h][2] = str_replace('+', '', $values[1]);
  6717. $h++;
  6718. }
  6719. } elseif (count($values) == 5) // deprecated
  6720. {
  6721. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  6722. if ($values[0] != $type) continue;
  6723. if ($values[3]) $langs->load($values[3]);
  6724. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6725. {
  6726. $substitutionarray = array();
  6727. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6728. $label = make_substitutions($reg[1], $substitutionarray);
  6729. } else $label = $langs->trans($values[2]);
  6730. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  6731. $head[$h][1] = $label;
  6732. $head[$h][2] = str_replace('+', '', $values[1]);
  6733. $h++;
  6734. }
  6735. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1]))
  6736. {
  6737. if ($values[0] != $type) continue;
  6738. $tabname = str_replace('-', '', $values[1]);
  6739. foreach ($head as $key => $val)
  6740. {
  6741. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  6742. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  6743. if ($head[$key][2] == $tabname && $condition)
  6744. {
  6745. unset($head[$key]);
  6746. break;
  6747. }
  6748. }
  6749. }
  6750. }
  6751. }
  6752. // No need to make a return $head. Var is modified as a reference
  6753. if (!empty($hookmanager))
  6754. {
  6755. $parameters = array('object' => $object, 'mode' => $mode, 'head' => $head);
  6756. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  6757. if ($reshook > 0)
  6758. {
  6759. $head = $hookmanager->resArray;
  6760. $h = count($head);
  6761. }
  6762. }
  6763. }
  6764. /**
  6765. * Print common footer :
  6766. * conf->global->MAIN_HTML_FOOTER
  6767. * js for switch of menu hider
  6768. * js for conf->global->MAIN_GOOGLE_AN_ID
  6769. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  6770. * js for conf->logbuffer
  6771. *
  6772. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  6773. * @return void
  6774. */
  6775. function printCommonFooter($zone = 'private')
  6776. {
  6777. global $conf, $hookmanager, $user, $debugbar;
  6778. global $action;
  6779. global $micro_start_time;
  6780. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  6781. else print "\n".'<!-- Common footer for public page -->'."\n";
  6782. // A div to store page_y POST parameter so we can read it using javascript
  6783. print "\n<!-- A div to store page_y POST parameter -->\n";
  6784. print '<div id="page_y" style="display: none;">'.$_POST['page_y'].'</div>'."\n";
  6785. $parameters = array();
  6786. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  6787. if (empty($reshook))
  6788. {
  6789. if (!empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  6790. print "\n";
  6791. if (!empty($conf->use_javascript_ajax))
  6792. {
  6793. print '<script>'."\n";
  6794. print 'jQuery(document).ready(function() {'."\n";
  6795. if ($zone == 'private' && empty($conf->dol_use_jmobile))
  6796. {
  6797. print "\n";
  6798. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  6799. print 'jQuery("li.menuhider").click(function(event) {';
  6800. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  6801. print ' console.log("We click on .menuhider");'."\n";
  6802. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  6803. print '});'."\n";
  6804. }
  6805. // Management of focus and mandatory for fields
  6806. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))))
  6807. {
  6808. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  6809. $relativepathstring = $_SERVER["PHP_SELF"];
  6810. // Clean $relativepathstring
  6811. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  6812. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  6813. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  6814. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  6815. if (!empty($user->default_values[$relativepathstring]['focus']))
  6816. {
  6817. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval)
  6818. {
  6819. $qualified = 0;
  6820. if ($defkey != '_noquery_')
  6821. {
  6822. $tmpqueryarraytohave = explode('&', $defkey);
  6823. $foundintru = 0;
  6824. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  6825. {
  6826. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  6827. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  6828. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  6829. }
  6830. if (!$foundintru) $qualified = 1;
  6831. //var_dump($defkey.'-'.$qualified);
  6832. } else $qualified = 1;
  6833. if ($qualified)
  6834. {
  6835. foreach ($defval as $paramkey => $paramval)
  6836. {
  6837. // Set focus on field
  6838. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  6839. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  6840. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  6841. }
  6842. }
  6843. }
  6844. }
  6845. if (!empty($user->default_values[$relativepathstring]['mandatory']))
  6846. {
  6847. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval)
  6848. {
  6849. $qualified = 0;
  6850. if ($defkey != '_noquery_')
  6851. {
  6852. $tmpqueryarraytohave = explode('&', $defkey);
  6853. $foundintru = 0;
  6854. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  6855. {
  6856. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  6857. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  6858. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  6859. }
  6860. if (!$foundintru) $qualified = 1;
  6861. //var_dump($defkey.'-'.$qualified);
  6862. } else $qualified = 1;
  6863. if ($qualified)
  6864. {
  6865. foreach ($defval as $paramkey => $paramval)
  6866. {
  6867. // Add property 'required' on input
  6868. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6869. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6870. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
  6871. }
  6872. }
  6873. }
  6874. }
  6875. }
  6876. print '});'."\n";
  6877. // End of tuning
  6878. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO))
  6879. {
  6880. print "\n";
  6881. print "/* JS CODE TO ENABLE to add memory info */\n";
  6882. print 'window.console && console.log("';
  6883. if (!empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  6884. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  6885. if (!empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  6886. {
  6887. $micro_end_time = microtime(true);
  6888. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  6889. }
  6890. if (function_exists("memory_get_usage")) {
  6891. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  6892. }
  6893. if (function_exists("memory_get_peak_usage")) {
  6894. print ' - Real mem peak: '.memory_get_peak_usage(true);
  6895. }
  6896. if (function_exists("zend_loader_file_encoded"))
  6897. {
  6898. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  6899. }
  6900. print '");'."\n";
  6901. }
  6902. print "\n".'</script>'."\n";
  6903. // Google Analytics
  6904. // TODO Add a hook here
  6905. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID))
  6906. {
  6907. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  6908. foreach ($tmptagarray as $tmptag) {
  6909. print "\n";
  6910. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  6911. print "
  6912. <!-- Global site tag (gtag.js) - Google Analytics -->
  6913. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  6914. <script>
  6915. window.dataLayer = window.dataLayer || [];
  6916. function gtag(){dataLayer.push(arguments);}
  6917. gtag('js', new Date());
  6918. gtag('config', '".trim($tmptag)."');
  6919. </script>";
  6920. print "\n";
  6921. }
  6922. }
  6923. }
  6924. // Add Xdebug coverage of code
  6925. if (defined('XDEBUGCOVERAGE'))
  6926. {
  6927. print_r(xdebug_get_code_coverage());
  6928. }
  6929. // Add DebugBar data
  6930. if (!empty($user->rights->debugbar->read) && is_object($debugbar))
  6931. {
  6932. $debugbar['time']->stopMeasure('pageaftermaster');
  6933. print '<!-- Output debugbar data -->'."\n";
  6934. $renderer = $debugbar->getRenderer();
  6935. print $debugbar->getRenderer()->render();
  6936. } elseif (count($conf->logbuffer)) // If there is some logs in buffer to show
  6937. {
  6938. print "\n";
  6939. print "<!-- Start of log output\n";
  6940. //print '<div class="hidden">'."\n";
  6941. foreach ($conf->logbuffer as $logline)
  6942. {
  6943. print $logline."<br>\n";
  6944. }
  6945. //print '</div>'."\n";
  6946. print "End of log output -->\n";
  6947. }
  6948. }
  6949. }
  6950. /**
  6951. * Split a string with 2 keys into key array.
  6952. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  6953. *
  6954. * @param string $string String to explode
  6955. * @param string $delimiter Delimiter between each couple of data
  6956. * @param string $kv Delimiter between key and value
  6957. * @return array Array of data exploded
  6958. */
  6959. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  6960. {
  6961. if ($a = explode($delimiter, $string))
  6962. {
  6963. $ka = array();
  6964. foreach ($a as $s) { // each part
  6965. if ($s) {
  6966. if ($pos = strpos($s, $kv)) { // key/value delimiter
  6967. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  6968. } else { // key delimiter not found
  6969. $ka[] = trim($s);
  6970. }
  6971. }
  6972. }
  6973. return $ka;
  6974. }
  6975. return array();
  6976. }
  6977. /**
  6978. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  6979. *
  6980. * @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.
  6981. * @return string HTML code to set focus
  6982. */
  6983. function dol_set_focus($selector)
  6984. {
  6985. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  6986. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  6987. }
  6988. /**
  6989. * Return getmypid() or random PID when function is disabled
  6990. * Some web hosts disable this php function for security reasons
  6991. * and sometimes we can't redeclare function
  6992. *
  6993. * @return int
  6994. */
  6995. function dol_getmypid()
  6996. {
  6997. if (!function_exists('getmypid')) {
  6998. return mt_rand(1, 32768);
  6999. } else {
  7000. return getmypid();
  7001. }
  7002. }
  7003. /**
  7004. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  7005. *
  7006. * @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")
  7007. * @param string $value The value to look for.
  7008. * If param $mode is 0, can contains several keywords separated with a space or |
  7009. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  7010. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  7011. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  7012. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  7013. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  7014. * @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')
  7015. * 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'
  7016. * @param integer $nofirstand 1=Do not output the first 'AND'
  7017. * @return string $res The statement to append to the SQL query
  7018. */
  7019. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  7020. {
  7021. global $db, $langs;
  7022. $value = trim($value);
  7023. if ($mode == 0)
  7024. {
  7025. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  7026. }
  7027. if ($mode == 1)
  7028. {
  7029. $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
  7030. }
  7031. $value = preg_replace('/\s*\|\s*/', '|', $value);
  7032. $crits = explode(' ', $value);
  7033. $res = '';
  7034. if (!is_array($fields)) $fields = array($fields);
  7035. $j = 0;
  7036. foreach ($crits as $crit)
  7037. {
  7038. $crit = trim($crit);
  7039. $i = 0; $i2 = 0;
  7040. $newres = '';
  7041. foreach ($fields as $field)
  7042. {
  7043. if ($mode == 1)
  7044. {
  7045. $operator = '=';
  7046. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  7047. $reg = array();
  7048. preg_match('/([<>=]+)/', $crit, $reg);
  7049. if ($reg[1])
  7050. {
  7051. $operator = $reg[1];
  7052. }
  7053. if ($newcrit != '')
  7054. {
  7055. $numnewcrit = price2num($newcrit);
  7056. if (is_numeric($numnewcrit))
  7057. {
  7058. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric
  7059. } else {
  7060. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  7061. }
  7062. $i2++; // a criteria was added to string
  7063. }
  7064. } elseif ($mode == 2 || $mode == -2)
  7065. {
  7066. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  7067. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  7068. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  7069. if ($mode == -2) $newres .= ' OR '.$field.' IS NULL';
  7070. $i2++; // a criteria was added to string
  7071. } elseif ($mode == 3 || $mode == -3)
  7072. {
  7073. $tmparray = explode(',', $crit);
  7074. if (count($tmparray))
  7075. {
  7076. $listofcodes = '';
  7077. foreach ($tmparray as $val)
  7078. {
  7079. $val = trim($val);
  7080. if ($val)
  7081. {
  7082. $listofcodes .= ($listofcodes ? ',' : '');
  7083. $listofcodes .= "'".$db->escape($val)."'";
  7084. }
  7085. }
  7086. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes).")";
  7087. $i2++; // a criteria was added to string
  7088. }
  7089. if ($mode == -3) $newres .= ' OR '.$field.' IS NULL';
  7090. } elseif ($mode == 4)
  7091. {
  7092. $tmparray = explode(',', $crit);
  7093. if (count($tmparray))
  7094. {
  7095. $listofcodes = '';
  7096. foreach ($tmparray as $val)
  7097. {
  7098. $val = trim($val);
  7099. if ($val)
  7100. {
  7101. $newres .= ($i2 > 0 ? ' OR (' : '(').$field.' LIKE \''.$db->escape($val).',%\'';
  7102. $newres .= ' OR '.$field.' = \''.$db->escape($val).'\'';
  7103. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).'\'';
  7104. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).',%\'';
  7105. $newres .= ')';
  7106. $i2++;
  7107. }
  7108. }
  7109. }
  7110. } else // $mode=0
  7111. {
  7112. $tmpcrits = explode('|', $crit);
  7113. $i3 = 0;
  7114. foreach ($tmpcrits as $tmpcrit)
  7115. {
  7116. if ($tmpcrit !== '0' && empty($tmpcrit)) continue;
  7117. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  7118. if (preg_match('/\.(id|rowid)$/', $field)) // Special case for rowid that is sometimes a ref so used as a search field
  7119. {
  7120. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ?trim($tmpcrit) : '0');
  7121. } else {
  7122. $newres .= $field." LIKE '";
  7123. $tmpcrit = trim($tmpcrit);
  7124. $tmpcrit2 = $tmpcrit;
  7125. $tmpbefore = '%'; $tmpafter = '%';
  7126. if (preg_match('/^[\^\$]/', $tmpcrit))
  7127. {
  7128. $tmpbefore = '';
  7129. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  7130. }
  7131. if (preg_match('/[\^\$]$/', $tmpcrit))
  7132. {
  7133. $tmpafter = '';
  7134. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  7135. }
  7136. $newres .= $tmpbefore;
  7137. $newres .= $db->escape($tmpcrit2);
  7138. $newres .= $tmpafter;
  7139. $newres .= "'";
  7140. if ($tmpcrit2 == '')
  7141. {
  7142. $newres .= ' OR '.$field." IS NULL";
  7143. }
  7144. }
  7145. $i3++;
  7146. }
  7147. $i2++; // a criteria was added to string
  7148. }
  7149. $i++;
  7150. }
  7151. if ($newres) $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  7152. $j++;
  7153. }
  7154. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  7155. //print 'xx'.$res.'yy';
  7156. return $res;
  7157. }
  7158. /**
  7159. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  7160. *
  7161. * @param Object $object Object
  7162. * @return string Url string
  7163. */
  7164. function showDirectDownloadLink($object)
  7165. {
  7166. global $conf, $langs;
  7167. $out = '';
  7168. $url = $object->getLastMainDocLink($object->element);
  7169. if ($url)
  7170. {
  7171. $out .= img_picto('', 'globe').' '.$langs->trans("DirectDownloadLink").'<br>';
  7172. $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
  7173. $out .= ajax_autoselect("directdownloadlink", 0);
  7174. }
  7175. return $out;
  7176. }
  7177. /**
  7178. * Return the filename of file to get the thumbs
  7179. *
  7180. * @param string $file Original filename (full or relative path)
  7181. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  7182. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  7183. * @return string New file name (full or relative path, including the thumbs/)
  7184. */
  7185. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  7186. {
  7187. $dirName = dirname($file);
  7188. if ($dirName == '.') $dirName = '';
  7189. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  7190. $fileName = basename($fileName);
  7191. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  7192. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  7193. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  7194. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  7195. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  7196. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  7197. if (!$extImgTarget) return $file;
  7198. $subdir = '';
  7199. if ($extName) $subdir = 'thumbs/';
  7200. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  7201. }
  7202. /**
  7203. * Return URL we can use for advanced preview links
  7204. *
  7205. * @param string $modulepart propal, facture, facture_fourn, ...
  7206. * @param string $relativepath Relative path of docs.
  7207. * @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)
  7208. * @param string $param More param on http links
  7209. * @return string|array Output string with href link or array with all components of link
  7210. */
  7211. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  7212. {
  7213. global $conf, $langs;
  7214. if (empty($conf->use_javascript_ajax)) return '';
  7215. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  7216. if ($alldata == 1)
  7217. {
  7218. 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));
  7219. else return array();
  7220. }
  7221. // old behavior, return a string
  7222. 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')).'\')';
  7223. else return '';
  7224. }
  7225. /**
  7226. * Make content of an input box selected when we click into input field.
  7227. *
  7228. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  7229. * @param string $addlink Add a 'link to' after
  7230. * @return string
  7231. */
  7232. function ajax_autoselect($htmlname, $addlink = '')
  7233. {
  7234. global $langs;
  7235. $out = '<script>
  7236. jQuery(document).ready(function () {
  7237. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  7238. });
  7239. </script>';
  7240. if ($addlink) $out .= ' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  7241. return $out;
  7242. }
  7243. /**
  7244. * Return if a file is qualified for preview
  7245. *
  7246. * @param string $file Filename we looking for information
  7247. * @return int 1 If allowed, 0 otherwise
  7248. * @see dol_mimetype(), image_format_supported() from images.lib.php
  7249. */
  7250. function dolIsAllowedForPreview($file)
  7251. {
  7252. global $conf;
  7253. // Check .noexe extension in filename
  7254. if (preg_match('/\.noexe$/i', $file)) return 0;
  7255. // Check mime types
  7256. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  7257. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) $mime_preview[] = 'svg+xml';
  7258. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  7259. //$mime_preview[]='archive';
  7260. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  7261. if ($num_mime !== false) return 1;
  7262. // By default, not allowed for preview
  7263. return 0;
  7264. }
  7265. /**
  7266. * Return mime type of a file
  7267. *
  7268. * @param string $file Filename we looking for MIME type
  7269. * @param string $default Default mime type if extension not found in known list
  7270. * @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
  7271. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  7272. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  7273. */
  7274. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  7275. {
  7276. $mime = $default;
  7277. $imgmime = 'other.png';
  7278. $famime = 'file-o';
  7279. $srclang = '';
  7280. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  7281. // Plain text files
  7282. if (preg_match('/\.txt$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7283. if (preg_match('/\.rtx$/i', $tmpfile)) { $mime = 'text/richtext'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7284. if (preg_match('/\.csv$/i', $tmpfile)) { $mime = 'text/csv'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7285. if (preg_match('/\.tsv$/i', $tmpfile)) { $mime = 'text/tab-separated-values'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7286. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7287. if (preg_match('/\.ini$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'ini'; $famime = 'file-text-o'; }
  7288. if (preg_match('/\.md$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'md'; $famime = 'file-text-o'; }
  7289. if (preg_match('/\.css$/i', $tmpfile)) { $mime = 'text/css'; $imgmime = 'css.png'; $srclang = 'css'; $famime = 'file-text-o'; }
  7290. if (preg_match('/\.lang$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'lang'; $famime = 'file-text-o'; }
  7291. // Certificate files
  7292. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7293. // XML based (HTML/XML/XAML)
  7294. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { $mime = 'text/html'; $imgmime = 'html.png'; $srclang = 'html'; $famime = 'file-text-o'; }
  7295. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xml'; $famime = 'file-text-o'; }
  7296. if (preg_match('/\.xaml$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xaml'; $famime = 'file-text-o'; }
  7297. // Languages
  7298. if (preg_match('/\.bas$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'bas'; $famime = 'file-code-o'; }
  7299. if (preg_match('/\.(c)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'c'; $famime = 'file-code-o'; }
  7300. if (preg_match('/\.(cpp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cpp'; $famime = 'file-code-o'; }
  7301. if (preg_match('/\.cs$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cs'; $famime = 'file-code-o'; }
  7302. if (preg_match('/\.(h)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'h'; $famime = 'file-code-o'; }
  7303. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'java'; $famime = 'file-code-o'; }
  7304. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7305. if (preg_match('/\.phtml$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7306. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'pl.png'; $srclang = 'perl'; $famime = 'file-code-o'; }
  7307. if (preg_match('/\.sql$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'sql'; $famime = 'file-code-o'; }
  7308. if (preg_match('/\.js$/i', $tmpfile)) { $mime = 'text/x-javascript'; $imgmime = 'jscript.png'; $srclang = 'js'; $famime = 'file-code-o'; }
  7309. // Open office
  7310. if (preg_match('/\.odp$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.presentation'; $imgmime = 'ooffice.png'; $famime = 'file-powerpoint-o'; }
  7311. if (preg_match('/\.ods$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.spreadsheet'; $imgmime = 'ooffice.png'; $famime = 'file-excel-o'; }
  7312. if (preg_match('/\.odt$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.text'; $imgmime = 'ooffice.png'; $famime = 'file-word-o'; }
  7313. // MS Office
  7314. if (preg_match('/\.mdb$/i', $tmpfile)) { $mime = 'application/msaccess'; $imgmime = 'mdb.png'; $famime = 'file-o'; }
  7315. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7316. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7317. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7318. if (preg_match('/\.xla(m)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7319. if (preg_match('/\.xls$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7320. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) { $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7321. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-powerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7322. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) { $mime = 'application/x-mspowerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7323. // Other
  7324. if (preg_match('/\.pdf$/i', $tmpfile)) { $mime = 'application/pdf'; $imgmime = 'pdf.png'; $famime = 'file-pdf-o'; }
  7325. // Scripts
  7326. if (preg_match('/\.bat$/i', $tmpfile)) { $mime = 'text/x-bat'; $imgmime = 'script.png'; $srclang = 'dos'; $famime = 'file-code-o'; }
  7327. if (preg_match('/\.sh$/i', $tmpfile)) { $mime = 'text/x-sh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7328. if (preg_match('/\.ksh$/i', $tmpfile)) { $mime = 'text/x-ksh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7329. if (preg_match('/\.bash$/i', $tmpfile)) { $mime = 'text/x-bash'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7330. // Images
  7331. if (preg_match('/\.ico$/i', $tmpfile)) { $mime = 'image/x-icon'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7332. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) { $mime = 'image/jpeg'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7333. if (preg_match('/\.png$/i', $tmpfile)) { $mime = 'image/png'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7334. if (preg_match('/\.gif$/i', $tmpfile)) { $mime = 'image/gif'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7335. if (preg_match('/\.bmp$/i', $tmpfile)) { $mime = 'image/bmp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7336. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) { $mime = 'image/tiff'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7337. if (preg_match('/\.svg$/i', $tmpfile)) { $mime = 'image/svg+xml'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7338. if (preg_match('/\.webp$/i', $tmpfile)) { $mime = 'image/webp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7339. // Calendar
  7340. if (preg_match('/\.vcs$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7341. if (preg_match('/\.ics$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7342. // Other
  7343. if (preg_match('/\.torrent$/i', $tmpfile)) { $mime = 'application/x-bittorrent'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7344. // Audio
  7345. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { $mime = 'audio'; $imgmime = 'audio.png'; $famime = 'file-audio-o'; }
  7346. // Video
  7347. if (preg_match('/\.ogv$/i', $tmpfile)) { $mime = 'video/ogg'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7348. if (preg_match('/\.webm$/i', $tmpfile)) { $mime = 'video/webm'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7349. if (preg_match('/\.avi$/i', $tmpfile)) { $mime = 'video/x-msvideo'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7350. if (preg_match('/\.divx$/i', $tmpfile)) { $mime = 'video/divx'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7351. if (preg_match('/\.xvid$/i', $tmpfile)) { $mime = 'video/xvid'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7352. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) { $mime = 'video'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7353. // Archive
  7354. 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, ...
  7355. // Exe
  7356. if (preg_match('/\.(exe|com)$/i', $tmpfile)) { $mime = 'application/octet-stream'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7357. // Lib
  7358. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { $mime = 'library'; $imgmime = 'library.png'; $famime = 'file-o'; }
  7359. // Err
  7360. if (preg_match('/\.err$/i', $tmpfile)) { $mime = 'error'; $imgmime = 'error.png'; $famime = 'file-text-o'; }
  7361. // Return string
  7362. if ($mode == 1)
  7363. {
  7364. $tmp = explode('/', $mime);
  7365. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  7366. }
  7367. if ($mode == 2)
  7368. {
  7369. return $imgmime;
  7370. }
  7371. if ($mode == 3)
  7372. {
  7373. return $srclang;
  7374. }
  7375. if ($mode == 4)
  7376. {
  7377. return $famime;
  7378. }
  7379. return $mime;
  7380. }
  7381. /**
  7382. * Return value from dictionary
  7383. *
  7384. * @param string $tablename name of dictionary
  7385. * @param string $field the value to return
  7386. * @param int $id id of line
  7387. * @param bool $checkentity add filter on entity
  7388. * @param string $rowidfield name of the column rowid
  7389. * @return string
  7390. */
  7391. function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  7392. {
  7393. global $dictvalues, $db, $langs;
  7394. if (!isset($dictvalues[$tablename]))
  7395. {
  7396. $dictvalues[$tablename] = array();
  7397. $sql = 'SELECT * FROM '.$tablename.' WHERE 1'; // Here select * is allowed as it is generic code and we don't have list of fields
  7398. if ($checkentity) $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  7399. $resql = $db->query($sql);
  7400. if ($resql)
  7401. {
  7402. while ($obj = $db->fetch_object($resql))
  7403. {
  7404. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  7405. }
  7406. } else {
  7407. dol_print_error($db);
  7408. }
  7409. }
  7410. if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
  7411. else // Not found
  7412. {
  7413. if ($id > 0) return $id;
  7414. return '';
  7415. }
  7416. }
  7417. /**
  7418. * Return true if the color is light
  7419. *
  7420. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  7421. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  7422. */
  7423. function colorIsLight($stringcolor)
  7424. {
  7425. $stringcolor = str_replace('#', '', $stringcolor);
  7426. $res = -1;
  7427. if (!empty($stringcolor))
  7428. {
  7429. $res = 0;
  7430. $tmp = explode(',', $stringcolor);
  7431. if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
  7432. {
  7433. $r = $tmp[0];
  7434. $g = $tmp[1];
  7435. $b = $tmp[2];
  7436. } else {
  7437. $hexr = $stringcolor[0].$stringcolor[1];
  7438. $hexg = $stringcolor[2].$stringcolor[3];
  7439. $hexb = $stringcolor[4].$stringcolor[5];
  7440. $r = hexdec($hexr);
  7441. $g = hexdec($hexg);
  7442. $b = hexdec($hexb);
  7443. }
  7444. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  7445. if ($bright > 0.6) $res = 1;
  7446. }
  7447. return $res;
  7448. }
  7449. /**
  7450. * Function to test if an entry is enabled or not
  7451. *
  7452. * @param string $type_user 0=We test for internal user, 1=We test for external user
  7453. * @param array $menuentry Array for feature entry to test
  7454. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  7455. * @return int 0=Hide, 1=Show, 2=Show gray
  7456. */
  7457. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  7458. {
  7459. global $conf;
  7460. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  7461. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  7462. if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
  7463. if ($type_user && $menuentry['module'])
  7464. {
  7465. $tmploops = explode('|', $menuentry['module']);
  7466. $found = 0;
  7467. foreach ($tmploops as $tmploop)
  7468. {
  7469. if (in_array($tmploop, $listofmodulesforexternal)) {
  7470. $found++; break;
  7471. }
  7472. }
  7473. if (!$found) return 0; // Entry is for menus all excluded to external users
  7474. }
  7475. if (!$menuentry['perms'] && $type_user) return 0; // No permissions and user is external
  7476. 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
  7477. if (!$menuentry['perms']) return 2; // No permissions and user is external
  7478. return 1;
  7479. }
  7480. /**
  7481. * Round to next multiple.
  7482. *
  7483. * @param double $n Number to round up
  7484. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  7485. * @return integer Value rounded.
  7486. */
  7487. function roundUpToNextMultiple($n, $x = 5)
  7488. {
  7489. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  7490. }
  7491. /**
  7492. * Function dolGetBadge
  7493. *
  7494. * @param string $label label of badge no html : use in alt attribute for accessibility
  7495. * @param string $html optional : label of badge with html
  7496. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  7497. * @param string $mode default '' , 'pill', 'dot'
  7498. * @param string $url the url for link
  7499. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  7500. * @return string Html badge
  7501. */
  7502. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  7503. {
  7504. $attr = array(
  7505. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  7506. );
  7507. if (empty($html)) {
  7508. $html = $label;
  7509. }
  7510. if (!empty($url)) {
  7511. $attr['href'] = $url;
  7512. }
  7513. if ($mode === 'dot') {
  7514. $attr['class'] .= ' classfortooltip';
  7515. $attr['title'] = $html;
  7516. $attr['aria-label'] = $label;
  7517. $html = '';
  7518. }
  7519. // Override attr
  7520. if (!empty($params['attr']) && is_array($params['attr'])) {
  7521. foreach ($params['attr']as $key => $value) {
  7522. if ($key == 'class') {
  7523. $attr['class'] .= ' '.$value;
  7524. } elseif ($key == 'classOverride') {
  7525. $attr['class'] = $value;
  7526. } else {
  7527. $attr[$key] = $value;
  7528. }
  7529. }
  7530. }
  7531. // TODO: add hook
  7532. // escape all attribute
  7533. $attr = array_map('dol_escape_htmltag', $attr);
  7534. $TCompiledAttr = array();
  7535. foreach ($attr as $key => $value) {
  7536. $TCompiledAttr[] = $key.'="'.$value.'"';
  7537. }
  7538. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7539. $tag = !empty($url) ? 'a' : 'span';
  7540. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  7541. }
  7542. /**
  7543. * Function dolGetStatus
  7544. *
  7545. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  7546. * @param string $statusLabelShort Short label of badge no html
  7547. * @param string $html Optional : label of badge with html
  7548. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  7549. * @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
  7550. * @param string $url The url for link
  7551. * @param array $params Various params for future : recommended rather than adding more function arguments
  7552. * @return string Html status string
  7553. */
  7554. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  7555. {
  7556. global $conf;
  7557. $return = '';
  7558. $dolGetBadgeParams = array();
  7559. if (!empty($params['badgeParams'])) {
  7560. $dolGetBadgeParams = $params['badgeParams'];
  7561. }
  7562. // TODO : add a hook
  7563. if ($displayMode == 0) {
  7564. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  7565. } elseif ($displayMode == 1) {
  7566. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7567. } // Use status with images (for backward compatibility)
  7568. elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  7569. $return = '';
  7570. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  7571. $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>' : '');
  7572. // For small screen, we always use the short label instead of long label.
  7573. if (!empty($conf->dol_optimize_smallscreen))
  7574. {
  7575. if ($displayMode == 0) $displayMode = 1;
  7576. elseif ($displayMode == 4) $displayMode = 2;
  7577. elseif ($displayMode == 6) $displayMode = 5;
  7578. }
  7579. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  7580. $statusImg = array(
  7581. 'status0' => 'statut0',
  7582. 'status1' => 'statut1',
  7583. 'status2' => 'statut2',
  7584. 'status3' => 'statut3',
  7585. 'status4' => 'statut4',
  7586. 'status5' => 'statut5',
  7587. 'status6' => 'statut6',
  7588. 'status7' => 'statut7',
  7589. 'status8' => 'statut8',
  7590. 'status9' => 'statut9'
  7591. );
  7592. if (!empty($statusImg[$statusType])) {
  7593. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  7594. } else {
  7595. $htmlImg = img_picto($statusLabel, $statusType);
  7596. }
  7597. if ($displayMode === 2) {
  7598. $return = $htmlImg.' '.$htmlLabelShort;
  7599. } elseif ($displayMode === 3) {
  7600. $return = $htmlImg;
  7601. } elseif ($displayMode === 4) {
  7602. $return = $htmlImg.' '.$htmlLabel;
  7603. } elseif ($displayMode === 5) {
  7604. $return = $htmlLabelShort.' '.$htmlImg;
  7605. } else { // $displayMode >= 6
  7606. $return = $htmlLabel.' '.$htmlImg;
  7607. }
  7608. } // Use new badge
  7609. elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  7610. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7611. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  7612. $dolGetBadgeParams['attr']['title'] = $statusLabel;
  7613. if ($displayMode == 3) {
  7614. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  7615. } elseif ($displayMode === 5) {
  7616. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  7617. } else {
  7618. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  7619. }
  7620. }
  7621. return $return;
  7622. }
  7623. /**
  7624. * Function dolGetButtonAction
  7625. *
  7626. * @param string $label label of button no html : use in alt attribute for accessibility $html is not empty
  7627. * @param string $html optional : content with html
  7628. * @param string $actionType default, delete, danger
  7629. * @param string $url the url for link
  7630. * @param string $id attribute id of button
  7631. * @param int $userRight user action right
  7632. * @param array $params various params for future : recommended rather than adding more function arguments
  7633. * @return string html button
  7634. */
  7635. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  7636. {
  7637. $class = 'butAction';
  7638. if ($actionType == 'danger' || $actionType == 'delete') {
  7639. $class = 'butActionDelete';
  7640. }
  7641. $attr = array(
  7642. 'class' => $class
  7643. ,'href' => empty($url) ? '' : $url
  7644. );
  7645. if (empty($html)) {
  7646. $html = $label;
  7647. } else {
  7648. $attr['aria-label'] = $label;
  7649. }
  7650. if (empty($userRight)) {
  7651. $attr['class'] = 'butActionRefused';
  7652. $attr['href'] = '';
  7653. }
  7654. if (!empty($id)) {
  7655. $attr['id'] = $id;
  7656. }
  7657. // Override attr
  7658. if (!empty($params['attr']) && is_array($params['attr'])) {
  7659. foreach ($params['attr'] as $key => $value) {
  7660. if ($key == 'class') {
  7661. $attr['class'] .= ' '.$value;
  7662. } elseif ($key == 'classOverride') {
  7663. $attr['class'] = $value;
  7664. } else {
  7665. $attr[$key] = $value;
  7666. }
  7667. }
  7668. }
  7669. if (isset($attr['href']) && empty($attr['href'])) {
  7670. unset($attr['href']);
  7671. }
  7672. // TODO : add a hook
  7673. // escape all attribute
  7674. $attr = array_map('dol_escape_htmltag', $attr);
  7675. $TCompiledAttr = array();
  7676. foreach ($attr as $key => $value) {
  7677. $TCompiledAttr[] = $key.'="'.$value.'"';
  7678. }
  7679. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7680. $tag = !empty($attr['href']) ? 'a' : 'span';
  7681. return '<div class="inline-block divButAction"><'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'></div>';
  7682. }
  7683. /**
  7684. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  7685. *
  7686. * @param string $label label of button
  7687. * @param string $helpText optional : content for help tooltip
  7688. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  7689. * @param string $url the url for link
  7690. * @param string $id attribute id of button
  7691. * @param int $status 0 no user rights, 1 active, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  7692. * @param array $params various params for future : recommended rather than adding more function arguments
  7693. * @return string html button
  7694. */
  7695. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  7696. {
  7697. global $langs, $conf, $user;
  7698. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  7699. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  7700. return '';
  7701. }
  7702. $class = 'btnTitle';
  7703. if ($iconClass == 'fa fa-plus-circle') $class .= ' btnTitlePlus';
  7704. $useclassfortooltip = 1;
  7705. if (!empty($params['morecss'])) $class .= ' '.$params['morecss'];
  7706. $attr = array(
  7707. 'class' => $class,
  7708. 'href' => empty($url) ? '' : $url
  7709. );
  7710. if (!empty($helpText)) {
  7711. $attr['title'] = dol_escape_htmltag($helpText);
  7712. } elseif (empty($attr['title']) && $label) {
  7713. $attr['title'] = $label;
  7714. $useclassfortooltip = 0;
  7715. }
  7716. if ($status <= 0) {
  7717. $attr['class'] .= ' refused';
  7718. $attr['href'] = '';
  7719. if ($status == -1) { // disable
  7720. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  7721. } elseif ($status == 0) { // Not enough permissions
  7722. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  7723. }
  7724. }
  7725. if (!empty($attr['title']) && $useclassfortooltip) {
  7726. $attr['class'] .= ' classfortooltip';
  7727. }
  7728. if (!empty($id)) {
  7729. $attr['id'] = $id;
  7730. }
  7731. // Override attr
  7732. if (!empty($params['attr']) && is_array($params['attr'])) {
  7733. foreach ($params['attr'] as $key => $value) {
  7734. if ($key == 'class') {
  7735. $attr['class'] .= ' '.$value;
  7736. } elseif ($key == 'classOverride') {
  7737. $attr['class'] = $value;
  7738. } else {
  7739. $attr[$key] = $value;
  7740. }
  7741. }
  7742. }
  7743. if (isset($attr['href']) && empty($attr['href'])) {
  7744. unset($attr['href']);
  7745. }
  7746. // TODO : add a hook
  7747. // escape all attribute
  7748. $attr = array_map('dol_escape_htmltag', $attr);
  7749. $TCompiledAttr = array();
  7750. foreach ($attr as $key => $value) {
  7751. $TCompiledAttr[] = $key.'="'.$value.'"';
  7752. }
  7753. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  7754. $tag = (empty($attr['href']) ? 'span' : 'a');
  7755. $button = '<'.$tag.' '.$compiledAttributes.'>';
  7756. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  7757. if (!empty($params['forcenohideoftext'])) {
  7758. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  7759. }
  7760. $button .= '</'.$tag.'>';
  7761. return $button;
  7762. }
  7763. /**
  7764. * Get an array with properties of an element.
  7765. * Called by fetchObjectByElement.
  7766. *
  7767. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  7768. * @return array (module, classpath, element, subelement, classfile, classname)
  7769. */
  7770. function getElementProperties($element_type)
  7771. {
  7772. $regs = array();
  7773. $classfile = $classname = $classpath = '';
  7774. // Parse element/subelement (ex: project_task)
  7775. $module = $element_type;
  7776. $element = $element_type;
  7777. $subelement = $element_type;
  7778. // If we ask an resource form external module (instead of default path)
  7779. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  7780. $element = $subelement = $regs[1];
  7781. $module = $regs[2];
  7782. }
  7783. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  7784. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  7785. $module = $element = $regs[1];
  7786. $subelement = $regs[2];
  7787. }
  7788. // For compat
  7789. if ($element_type == "action") {
  7790. $classpath = 'comm/action/class';
  7791. $subelement = 'Actioncomm';
  7792. $module = 'agenda';
  7793. }
  7794. // To work with non standard path
  7795. if ($element_type == 'facture' || $element_type == 'invoice') {
  7796. $classpath = 'compta/facture/class';
  7797. $module = 'facture';
  7798. $subelement = 'facture';
  7799. }
  7800. if ($element_type == 'commande' || $element_type == 'order') {
  7801. $classpath = 'commande/class';
  7802. $module = 'commande';
  7803. $subelement = 'commande';
  7804. }
  7805. if ($element_type == 'propal') {
  7806. $classpath = 'comm/propal/class';
  7807. }
  7808. if ($element_type == 'supplier_proposal') {
  7809. $classpath = 'supplier_proposal/class';
  7810. }
  7811. if ($element_type == 'shipping') {
  7812. $classpath = 'expedition/class';
  7813. $subelement = 'expedition';
  7814. $module = 'expedition_bon';
  7815. }
  7816. if ($element_type == 'delivery') {
  7817. $classpath = 'delivery/class';
  7818. $subelement = 'delivery';
  7819. $module = 'livraison_bon';
  7820. }
  7821. if ($element_type == 'contract') {
  7822. $classpath = 'contrat/class';
  7823. $module = 'contrat';
  7824. $subelement = 'contrat';
  7825. }
  7826. if ($element_type == 'member') {
  7827. $classpath = 'adherents/class';
  7828. $module = 'adherent';
  7829. $subelement = 'adherent';
  7830. }
  7831. if ($element_type == 'cabinetmed_cons') {
  7832. $classpath = 'cabinetmed/class';
  7833. $module = 'cabinetmed';
  7834. $subelement = 'cabinetmedcons';
  7835. }
  7836. if ($element_type == 'fichinter') {
  7837. $classpath = 'fichinter/class';
  7838. $module = 'ficheinter';
  7839. $subelement = 'fichinter';
  7840. }
  7841. if ($element_type == 'dolresource' || $element_type == 'resource') {
  7842. $classpath = 'resource/class';
  7843. $module = 'resource';
  7844. $subelement = 'dolresource';
  7845. }
  7846. if ($element_type == 'propaldet') {
  7847. $classpath = 'comm/propal/class';
  7848. $module = 'propal';
  7849. $subelement = 'propaleligne';
  7850. }
  7851. if ($element_type == 'order_supplier') {
  7852. $classpath = 'fourn/class';
  7853. $module = 'fournisseur';
  7854. $subelement = 'commandefournisseur';
  7855. $classfile = 'fournisseur.commande';
  7856. }
  7857. if ($element_type == 'invoice_supplier') {
  7858. $classpath = 'fourn/class';
  7859. $module = 'fournisseur';
  7860. $subelement = 'facturefournisseur';
  7861. $classfile = 'fournisseur.facture';
  7862. }
  7863. if ($element_type == "service") {
  7864. $classpath = 'product/class';
  7865. $subelement = 'product';
  7866. }
  7867. if (empty($classfile)) $classfile = strtolower($subelement);
  7868. if (empty($classname)) $classname = ucfirst($subelement);
  7869. if (empty($classpath)) $classpath = $module.'/class';
  7870. $element_properties = array(
  7871. 'module' => $module,
  7872. 'classpath' => $classpath,
  7873. 'element' => $element,
  7874. 'subelement' => $subelement,
  7875. 'classfile' => $classfile,
  7876. 'classname' => $classname
  7877. );
  7878. return $element_properties;
  7879. }
  7880. /**
  7881. * Fetch an object from its id and element_type
  7882. * Inclusion of classes is automatic
  7883. *
  7884. * @param int $element_id Element id
  7885. * @param string $element_type Element type
  7886. * @param string $element_ref Element ref (Use this or element_id but not both)
  7887. * @return int|object object || 0 || -1 if error
  7888. */
  7889. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  7890. {
  7891. global $conf, $db;
  7892. $element_prop = getElementProperties($element_type);
  7893. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
  7894. {
  7895. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  7896. $objecttmp = new $element_prop['classname']($db);
  7897. $ret = $objecttmp->fetch($element_id, $element_ref);
  7898. if ($ret >= 0)
  7899. {
  7900. return $objecttmp;
  7901. }
  7902. }
  7903. return 0;
  7904. }
  7905. /**
  7906. * Return if a file can contains executable content
  7907. *
  7908. * @param string $filename File name to test
  7909. * @return boolean True if yes, False if no
  7910. */
  7911. function isAFileWithExecutableContent($filename)
  7912. {
  7913. 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))
  7914. {
  7915. return true;
  7916. }
  7917. return false;
  7918. }
  7919. /**
  7920. * Return the value of token currently saved into session with name 'newtoken'.
  7921. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  7922. *
  7923. * @return string
  7924. */
  7925. function newToken()
  7926. {
  7927. return $_SESSION['newtoken'];
  7928. }
  7929. /**
  7930. * Return the value of token currently saved into session with name 'token'.
  7931. *
  7932. * @return string
  7933. */
  7934. function currentToken()
  7935. {
  7936. return $_SESSION['token'];
  7937. }
  7938. /**
  7939. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  7940. *
  7941. * @param string $header The first left header of the table (automatic translated)
  7942. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  7943. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  7944. * @param integer $emptyRows (optional) The count of empty rows after the first header
  7945. * @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"
  7946. * @return void
  7947. *
  7948. * @see finishSimpleTable()
  7949. */
  7950. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  7951. {
  7952. global $langs;
  7953. print '<div class="div-table-responsive-no-min">';
  7954. print '<table class="noborder centpercent">';
  7955. print '<tr class="liste_titre">';
  7956. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  7957. print $langs->trans($header);
  7958. // extra space between the first header and the number
  7959. if ($number > -1) {
  7960. print ' ';
  7961. }
  7962. if (!empty($link)) {
  7963. if (!empty($arguments)) {
  7964. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  7965. } else {
  7966. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  7967. }
  7968. }
  7969. if ($number > -1) {
  7970. print '<span class="badge">'.$number.'</span>';
  7971. }
  7972. if (!empty($link)) {
  7973. print '</a>';
  7974. }
  7975. print '</th>';
  7976. if ($number < 0 && !empty($link)) {
  7977. print '<th class="right">';
  7978. if (!empty($arguments)) {
  7979. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  7980. } else {
  7981. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  7982. }
  7983. print $langs->trans("FullList");
  7984. print '</a>';
  7985. print '</th>';
  7986. }
  7987. print '</tr>';
  7988. }
  7989. /**
  7990. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  7991. *
  7992. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  7993. * @return void
  7994. *
  7995. * @see startSimpleTable()
  7996. */
  7997. function finishSimpleTable($addLineBreak = false)
  7998. {
  7999. print '</table>';
  8000. print '</div>';
  8001. if ($addLineBreak) {
  8002. print '<br>';
  8003. }
  8004. }
  8005. /**
  8006. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  8007. *
  8008. * @param integer $tableColumnCount The complete count columns of the table
  8009. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  8010. * @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)
  8011. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  8012. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  8013. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  8014. * @return void
  8015. */
  8016. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  8017. {
  8018. global $langs;
  8019. if ($num === 0) {
  8020. print '<tr class="oddeven">';
  8021. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  8022. print '</tr>';
  8023. return;
  8024. }
  8025. if ($nbofloop === 0)
  8026. {
  8027. // don't show a summary line
  8028. return;
  8029. }
  8030. if ($num === 0) {
  8031. $colspan = $tableColumnCount;
  8032. }
  8033. elseif ($num > $nbofloop) {
  8034. $colspan = $tableColumnCount;
  8035. } else {
  8036. $colspan = $tableColumnCount - 1;
  8037. }
  8038. if ($extraRightColumn) {
  8039. $colspan--;
  8040. }
  8041. print '<tr class="liste_total">';
  8042. if ($nbofloop > 0 && $num > $nbofloop) {
  8043. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  8044. } else {
  8045. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  8046. print '<td class="right" width="100">'.price($total).'</td>';
  8047. }
  8048. if ($extraRightColumn) {
  8049. print '<td></td>';
  8050. }
  8051. print '</tr>';
  8052. }
  8053. /**
  8054. * Return a file on output using a lo memory.
  8055. * It can return very large files with no need of memory.
  8056. * WARNING: This close output buffers.
  8057. *
  8058. * @param string $fullpath_original_file_osencoded Full path of file to return.
  8059. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  8060. * @return void
  8061. */
  8062. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  8063. {
  8064. global $conf;
  8065. if ($method == -1) {
  8066. $method = 0;
  8067. if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1;
  8068. if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2;
  8069. }
  8070. // Be sure we don't have output buffering enabled to have readfile working correctly
  8071. while (ob_get_level()) ob_end_flush();
  8072. // Solution 0
  8073. if ($method == 0) {
  8074. readfile($fullpath_original_file_osencoded);
  8075. }
  8076. // Solution 1
  8077. elseif ($method == 1) {
  8078. $handle = fopen($fullpath_original_file_osencoded, "rb");
  8079. while (!feof($handle)) {
  8080. print fread($handle, 8192);
  8081. }
  8082. fclose($handle);
  8083. }
  8084. // Solution 2
  8085. elseif ($method == 2) {
  8086. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  8087. $handle2 = fopen("php://output", "wb");
  8088. stream_copy_to_stream($handle1, $handle2);
  8089. fclose($handle1);
  8090. fclose($handle2);
  8091. }
  8092. }