functions.lib.php 440 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
  21. *
  22. * This program is free software; you can redistribute it and/or modify
  23. * it under the terms of the GNU General Public License as published by
  24. * the Free Software Foundation; either version 3 of the License, or
  25. * (at your option) any later version.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU General Public License
  33. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  34. * or see https://www.gnu.org/
  35. */
  36. /**
  37. * \file htdocs/core/lib/functions.lib.php
  38. * \brief A set of functions for Dolibarr
  39. * This file contains all frequently used functions.
  40. */
  41. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  42. /**
  43. * Return dolibarr global constant string value
  44. * @param string $key key to return value, return '' if not set
  45. * @param string $default value to return
  46. * @return string
  47. */
  48. function getDolGlobalString($key, $default = '')
  49. {
  50. global $conf;
  51. // return $conf->global->$key ?? $default;
  52. return (string) (empty($conf->global->$key) ? $default : $conf->global->$key);
  53. }
  54. /**
  55. * Return dolibarr global constant int value
  56. * @param string $key key to return value, return 0 if not set
  57. * @param int $default value to return
  58. * @return int
  59. */
  60. function getDolGlobalInt($key, $default = 0)
  61. {
  62. global $conf;
  63. // return $conf->global->$key ?? $default;
  64. return (int) (empty($conf->global->$key) ? $default : $conf->global->$key);
  65. }
  66. /**
  67. * Return a DoliDB instance (database handler).
  68. *
  69. * @param string $type Type of database (mysql, pgsql...)
  70. * @param string $host Address of database server
  71. * @param string $user Authorized username
  72. * @param string $pass Password
  73. * @param string $name Name of database
  74. * @param int $port Port of database server
  75. * @return DoliDB A DoliDB instance
  76. */
  77. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  78. {
  79. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  80. $class = 'DoliDB'.ucfirst($type);
  81. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  82. return $dolidb;
  83. }
  84. /**
  85. * Get list of entity id to use.
  86. *
  87. * @param string $element Current element
  88. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  89. * 'product', 'productprice', 'stock', 'bom', 'mo',
  90. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  91. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  92. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  93. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  94. * 'email_template', 'event', 'donation'
  95. * 'c_paiement', 'c_payment_term', ...
  96. * @param int $shared 0=Return id of current entity only,
  97. * 1=Return id of current entity + shared entities (default)
  98. * @param object $currentobject Current object if needed
  99. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  100. */
  101. function getEntity($element, $shared = 1, $currentobject = null)
  102. {
  103. global $conf, $mc, $hookmanager, $object, $action, $db;
  104. if (! is_object($hookmanager)) {
  105. $hookmanager = new HookManager($db);
  106. }
  107. // fix different element names (France to English)
  108. switch ($element) {
  109. case 'contrat':
  110. $element = 'contract';
  111. break; // "/contrat/class/contrat.class.php"
  112. case 'order_supplier':
  113. $element = 'supplier_order';
  114. break; // "/fourn/class/fournisseur.commande.class.php"
  115. }
  116. if (is_object($mc)) {
  117. $out = $mc->getEntity($element, $shared, $currentobject);
  118. } else {
  119. $out = '';
  120. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  121. if (in_array($element, $addzero)) {
  122. $out .= '0,';
  123. }
  124. $out .= ((int) $conf->entity);
  125. }
  126. // Manipulate entities to query on the fly
  127. $parameters = array(
  128. 'element' => $element,
  129. 'shared' => $shared,
  130. 'object' => $object,
  131. 'currentobject' => $currentobject,
  132. 'out' => $out
  133. );
  134. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  135. if (is_numeric($reshook)) {
  136. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  137. $out .= ','.$hookmanager->resPrint; // add
  138. } elseif ($reshook == 1) {
  139. $out = $hookmanager->resPrint; // replace
  140. }
  141. }
  142. return $out;
  143. }
  144. /**
  145. * Set entity id to use when to create an object
  146. *
  147. * @param object $currentobject Current object
  148. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  149. */
  150. function setEntity($currentobject)
  151. {
  152. global $conf, $mc;
  153. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  154. return $mc->setEntity($currentobject);
  155. } else {
  156. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  157. }
  158. }
  159. /**
  160. * Return if string has a name dedicated to store a secret
  161. *
  162. * @param string $keyname Name of key to test
  163. * @return boolean True if key is used to store a secret
  164. */
  165. function isASecretKey($keyname)
  166. {
  167. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  168. }
  169. /**
  170. * Return information about user browser
  171. *
  172. * Returns array with the following format:
  173. * array(
  174. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  175. * 'browserversion' => Browser version. Empty if unknown
  176. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  177. * 'layout' => (tablet|phone|classic)
  178. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  179. * 'tablet' => true/false
  180. * )
  181. *
  182. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  183. * @return array Check function documentation
  184. */
  185. function getBrowserInfo($user_agent)
  186. {
  187. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  188. $name = 'unknown';
  189. $version = '';
  190. $os = 'unknown';
  191. $phone = '';
  192. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  193. $detectmobile = new Mobile_Detect(null, $user_agent);
  194. $tablet = $detectmobile->isTablet();
  195. if ($detectmobile->isMobile()) {
  196. $phone = 'unknown';
  197. // If phone/smartphone, we set phone os name.
  198. if ($detectmobile->is('AndroidOS')) {
  199. $os = $phone = 'android';
  200. } elseif ($detectmobile->is('BlackBerryOS')) {
  201. $os = $phone = 'blackberry';
  202. } elseif ($detectmobile->is('iOS')) {
  203. $os = 'ios';
  204. $phone = 'iphone';
  205. } elseif ($detectmobile->is('PalmOS')) {
  206. $os = $phone = 'palm';
  207. } elseif ($detectmobile->is('SymbianOS')) {
  208. $os = 'symbian';
  209. } elseif ($detectmobile->is('webOS')) {
  210. $os = 'webos';
  211. } elseif ($detectmobile->is('MaemoOS')) {
  212. $os = 'maemo';
  213. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  214. $os = 'windows';
  215. }
  216. }
  217. // OS
  218. if (preg_match('/linux/i', $user_agent)) {
  219. $os = 'linux';
  220. } elseif (preg_match('/macintosh/i', $user_agent)) {
  221. $os = 'macintosh';
  222. } elseif (preg_match('/windows/i', $user_agent)) {
  223. $os = 'windows';
  224. }
  225. // Name
  226. $reg = array();
  227. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  228. $name = 'firefox';
  229. $version = $reg[2];
  230. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  231. $name = 'edge';
  232. $version = $reg[2];
  233. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  234. $name = 'chrome';
  235. $version = $reg[2];
  236. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  237. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  238. $name = 'chrome';
  239. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  240. $name = 'iceweasel';
  241. } elseif (preg_match('/epiphany/i', $user_agent)) {
  242. $name = 'epiphany';
  243. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  244. $name = 'safari';
  245. $version = $reg[2];
  246. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  247. // Safari is often present in string for mobile but its not.
  248. $name = 'opera';
  249. $version = $reg[2];
  250. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  251. $name = 'ie';
  252. $version = end($reg);
  253. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  254. // MS products at end
  255. $name = 'ie';
  256. $version = end($reg);
  257. } elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  258. // MS products at end
  259. $name = 'lynxlinks';
  260. $version = $reg[4];
  261. }
  262. if ($tablet) {
  263. $layout = 'tablet';
  264. } elseif ($phone) {
  265. $layout = 'phone';
  266. } else {
  267. $layout = 'classic';
  268. }
  269. return array(
  270. 'browsername' => $name,
  271. 'browserversion' => $version,
  272. 'browseros' => $os,
  273. 'layout' => $layout,
  274. 'phone' => $phone,
  275. 'tablet' => $tablet
  276. );
  277. }
  278. /**
  279. * Function called at end of web php process
  280. *
  281. * @return void
  282. */
  283. function dol_shutdown()
  284. {
  285. global $conf, $user, $langs, $db;
  286. $disconnectdone = false;
  287. $depth = 0;
  288. if (is_object($db) && !empty($db->connected)) {
  289. $depth = $db->transaction_opened;
  290. $disconnectdone = $db->close();
  291. }
  292. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  293. }
  294. /**
  295. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  296. *
  297. * @param string $paramname Name or parameter to test
  298. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  299. */
  300. function GETPOSTISSET($paramname)
  301. {
  302. $isset = false;
  303. $relativepathstring = $_SERVER["PHP_SELF"];
  304. // Clean $relativepathstring
  305. if (constant('DOL_URL_ROOT')) {
  306. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  307. }
  308. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  309. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  310. //var_dump($relativepathstring);
  311. //var_dump($user->default_values);
  312. // Code for search criteria persistence.
  313. // Retrieve values if restore_lastsearch_values
  314. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  315. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  316. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  317. if (is_array($tmp)) {
  318. foreach ($tmp as $key => $val) {
  319. if ($key == $paramname) { // We are on the requested parameter
  320. $isset = true;
  321. break;
  322. }
  323. }
  324. }
  325. }
  326. // If there is saved contextpage, limit, page or mode
  327. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  328. $isset = true;
  329. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  330. $isset = true;
  331. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  332. $isset = true;
  333. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  334. $isset = true;
  335. }
  336. } else {
  337. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  338. }
  339. return $isset;
  340. }
  341. /**
  342. * Return value of a param into GET or POST supervariable.
  343. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  344. * Note: The property $user->default_values is loaded by main.php when loading the user.
  345. *
  346. * @param string $paramname Name of parameter to found
  347. * @param string $check Type of check
  348. * ''=no check (deprecated)
  349. * 'none'=no check (only for param that should have very rich content like passwords)
  350. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  351. * 'int'=check it's numeric (integer or float)
  352. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  353. * 'alpha'=Same than alphanohtml since v13
  354. * 'alphawithlgt'=alpha with lgt
  355. * 'alphanohtml'=check there is no html content and no " and no ../
  356. * 'aZ'=check it's a-z only
  357. * 'aZ09'=check it's simple alpha string (recommended for keys)
  358. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  359. * 'nohtml'=check there is no html content and no " and no ../
  360. * 'restricthtml'=check html content is restricted to some tags only
  361. * 'custom'= custom filter specify $filter and $options)
  362. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  363. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  364. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  365. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  366. * @return string|array Value found (string or array), or '' if check fails
  367. */
  368. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  369. {
  370. global $mysoc, $user, $conf;
  371. if (empty($paramname)) {
  372. return 'BadFirstParameterForGETPOST';
  373. }
  374. if (empty($check)) {
  375. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  376. // Enable this line to know who call the GETPOST with '' $check parameter.
  377. //var_dump(debug_backtrace()[0]);
  378. }
  379. if (empty($method)) {
  380. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  381. } elseif ($method == 1) {
  382. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  383. } elseif ($method == 2) {
  384. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  385. } elseif ($method == 3) {
  386. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  387. } else {
  388. return 'BadThirdParameterForGETPOST';
  389. }
  390. if (empty($method) || $method == 3 || $method == 4) {
  391. $relativepathstring = $_SERVER["PHP_SELF"];
  392. // Clean $relativepathstring
  393. if (constant('DOL_URL_ROOT')) {
  394. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  395. }
  396. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  397. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  398. //var_dump($relativepathstring);
  399. //var_dump($user->default_values);
  400. // Code for search criteria persistence.
  401. // Retrieve values if restore_lastsearch_values
  402. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  403. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  404. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  405. if (is_array($tmp)) {
  406. foreach ($tmp as $key => $val) {
  407. if ($key == $paramname) { // We are on the requested parameter
  408. $out = $val;
  409. break;
  410. }
  411. }
  412. }
  413. }
  414. // If there is saved contextpage, page or limit
  415. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  416. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  417. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  418. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  419. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  420. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  421. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  422. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  423. }
  424. } elseif (!isset($_GET['sortfield'])) {
  425. // Else, retrieve default values if we are not doing a sort
  426. // 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
  427. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  428. // Search default value from $object->field
  429. global $object;
  430. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  431. $out = $object->fields[$paramname]['default'];
  432. }
  433. }
  434. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  435. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  436. // Now search in setup to overwrite default values
  437. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  438. if (isset($user->default_values[$relativepathstring]['createform'])) {
  439. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  440. $qualified = 0;
  441. if ($defkey != '_noquery_') {
  442. $tmpqueryarraytohave = explode('&', $defkey);
  443. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  444. $foundintru = 0;
  445. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  446. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  447. $foundintru = 1;
  448. }
  449. }
  450. if (!$foundintru) {
  451. $qualified = 1;
  452. }
  453. //var_dump($defkey.'-'.$qualified);
  454. } else {
  455. $qualified = 1;
  456. }
  457. if ($qualified) {
  458. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  459. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  460. break;
  461. }
  462. }
  463. }
  464. }
  465. }
  466. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  467. // Management of default search_filters and sort order
  468. if (!empty($user->default_values)) {
  469. // $user->default_values defined from menu 'Setup - Default values'
  470. //var_dump($user->default_values[$relativepathstring]);
  471. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  472. // Sorted on which fields ? ASC or DESC ?
  473. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  474. // Even if paramname is sortfield, data are stored into ['sortorder...']
  475. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  476. $qualified = 0;
  477. if ($defkey != '_noquery_') {
  478. $tmpqueryarraytohave = explode('&', $defkey);
  479. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  480. $foundintru = 0;
  481. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  482. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  483. $foundintru = 1;
  484. }
  485. }
  486. if (!$foundintru) {
  487. $qualified = 1;
  488. }
  489. //var_dump($defkey.'-'.$qualified);
  490. } else {
  491. $qualified = 1;
  492. }
  493. if ($qualified) {
  494. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  495. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  496. if ($out) {
  497. $out .= ', ';
  498. }
  499. if ($paramname == 'sortfield') {
  500. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  501. }
  502. if ($paramname == 'sortorder') {
  503. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  504. }
  505. }
  506. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  507. }
  508. }
  509. }
  510. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  511. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  512. $qualified = 0;
  513. if ($defkey != '_noquery_') {
  514. $tmpqueryarraytohave = explode('&', $defkey);
  515. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  516. $foundintru = 0;
  517. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  518. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  519. $foundintru = 1;
  520. }
  521. }
  522. if (!$foundintru) {
  523. $qualified = 1;
  524. }
  525. //var_dump($defkey.'-'.$qualified);
  526. } else {
  527. $qualified = 1;
  528. }
  529. if ($qualified) {
  530. // We must keep $_POST and $_GET here
  531. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  532. // We made a search from quick search menu, do we still use default filter ?
  533. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  534. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  535. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  536. }
  537. } else {
  538. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  539. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  540. }
  541. break;
  542. }
  543. }
  544. }
  545. }
  546. }
  547. }
  548. }
  549. }
  550. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  551. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  552. // 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.
  553. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  554. $reg = array();
  555. $maxloop = 20;
  556. $loopnb = 0; // Protection against infinite loop
  557. 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.
  558. $loopnb++;
  559. $newout = '';
  560. if ($reg[1] == 'DAY') {
  561. $tmp = dol_getdate(dol_now(), true);
  562. $newout = $tmp['mday'];
  563. } elseif ($reg[1] == 'MONTH') {
  564. $tmp = dol_getdate(dol_now(), true);
  565. $newout = $tmp['mon'];
  566. } elseif ($reg[1] == 'YEAR') {
  567. $tmp = dol_getdate(dol_now(), true);
  568. $newout = $tmp['year'];
  569. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  570. $tmp = dol_getdate(dol_now(), true);
  571. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  572. $newout = $tmp2['day'];
  573. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  574. $tmp = dol_getdate(dol_now(), true);
  575. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  576. $newout = $tmp2['month'];
  577. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  578. $tmp = dol_getdate(dol_now(), true);
  579. $newout = ($tmp['year'] - 1);
  580. } elseif ($reg[1] == 'NEXT_DAY') {
  581. $tmp = dol_getdate(dol_now(), true);
  582. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  583. $newout = $tmp2['day'];
  584. } elseif ($reg[1] == 'NEXT_MONTH') {
  585. $tmp = dol_getdate(dol_now(), true);
  586. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  587. $newout = $tmp2['month'];
  588. } elseif ($reg[1] == 'NEXT_YEAR') {
  589. $tmp = dol_getdate(dol_now(), true);
  590. $newout = ($tmp['year'] + 1);
  591. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  592. $newout = $mysoc->country_id;
  593. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  594. $newout = $user->id;
  595. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  596. $newout = $user->fk_user;
  597. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  598. $newout = $conf->entity;
  599. } else {
  600. $newout = ''; // Key not found, we replace with empty string
  601. }
  602. //var_dump('__'.$reg[1].'__ -> '.$newout);
  603. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  604. }
  605. }
  606. // Check rule
  607. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  608. if (!is_array($out) || empty($out)) {
  609. $out = array();
  610. } else {
  611. $tmparray = explode(':', $check);
  612. if (!empty($tmparray[1])) {
  613. $tmpcheck = $tmparray[1];
  614. } else {
  615. $tmpcheck = 'alphanohtml';
  616. }
  617. foreach ($out as $outkey => $outval) {
  618. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  619. }
  620. }
  621. } else {
  622. $out = checkVal($out, $check, $filter, $options);
  623. }
  624. // Sanitizing for special parameters.
  625. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  626. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  627. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  628. $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
  629. do {
  630. $oldstringtoclean = $out;
  631. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  632. $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
  633. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  634. } while ($oldstringtoclean != $out);
  635. }
  636. // Code for search criteria persistence.
  637. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  638. if (empty($method) || $method == 3 || $method == 4) {
  639. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  640. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  641. // We save search key only if $out not empty that means:
  642. // - posted value not empty, or
  643. // - 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).
  644. if ($out != '') { // $out = '0' or 'abc', it is a search criteria to keep
  645. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  646. }
  647. }
  648. }
  649. return $out;
  650. }
  651. /**
  652. * Return value of a param into GET or POST supervariable.
  653. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  654. * Note: The property $user->default_values is loaded by main.php when loading the user.
  655. *
  656. * @param string $paramname Name of parameter to found
  657. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  658. * @return int Value found (int)
  659. */
  660. function GETPOSTINT($paramname, $method = 0)
  661. {
  662. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  663. }
  664. /**
  665. * Return a value after checking on a rule. A sanitization may also have been done.
  666. *
  667. * @param string|array $out Value to check/clear.
  668. * @param string $check Type of check/sanitizing
  669. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  670. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  671. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  672. */
  673. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  674. {
  675. global $conf;
  676. // Check is done after replacement
  677. switch ($check) {
  678. case 'none':
  679. break;
  680. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  681. if (!is_numeric($out)) {
  682. $out = '';
  683. }
  684. break;
  685. case 'intcomma':
  686. if (preg_match('/[^0-9,-]+/i', $out)) {
  687. $out = '';
  688. }
  689. break;
  690. case 'san_alpha':
  691. $out = filter_var($out, FILTER_SANITIZE_STRING);
  692. break;
  693. case 'email':
  694. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  695. break;
  696. case 'aZ':
  697. if (!is_array($out)) {
  698. $out = trim($out);
  699. if (preg_match('/[^a-z]+/i', $out)) {
  700. $out = '';
  701. }
  702. }
  703. break;
  704. case 'aZ09':
  705. if (!is_array($out)) {
  706. $out = trim($out);
  707. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  708. $out = '';
  709. }
  710. }
  711. break;
  712. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  713. if (!is_array($out)) {
  714. $out = trim($out);
  715. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  716. $out = '';
  717. }
  718. }
  719. break;
  720. case 'nohtml': // No html
  721. $out = dol_string_nohtmltag($out, 0);
  722. break;
  723. case 'alpha': // No html and no ../ and "
  724. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  725. if (!is_array($out)) {
  726. $out = trim($out);
  727. do {
  728. $oldstringtoclean = $out;
  729. // Remove html tags
  730. $out = dol_string_nohtmltag($out, 0);
  731. // Remove also other dangerous string sequences
  732. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  733. // '../' or '..\' is dangerous because it allows dir transversals
  734. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  735. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  736. } while ($oldstringtoclean != $out);
  737. // keep lines feed
  738. }
  739. break;
  740. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
  741. if (!is_array($out)) {
  742. $out = trim($out);
  743. do {
  744. $oldstringtoclean = $out;
  745. // Remove html tags
  746. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  747. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  748. // '../' or '..\' is dangerous because it allows dir transversals
  749. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  750. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  751. } while ($oldstringtoclean != $out);
  752. }
  753. break;
  754. case 'restricthtml': // Recommended for most html textarea
  755. case 'restricthtmlallowunvalid':
  756. do {
  757. $oldstringtoclean = $out;
  758. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  759. try {
  760. $dom = new DOMDocument;
  761. // Add a trick to solve pb with text without parent tag
  762. // like '<h1>Foo</h1><p>bar</p>' that ends up with '<h1>Foo<p>bar</p></h1>'
  763. // like 'abc' that ends up with '<p>abc</p>'
  764. $out = '<div class="tricktoremove">'.$out.'</div>';
  765. $dom->loadHTML($out, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  766. $out = trim($dom->saveHTML());
  767. // Remove the trick added to solve pb with text without parent tag
  768. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  769. $out = preg_replace('/<\/div>$/', '', $out);
  770. } catch (Exception $e) {
  771. //print $e->getMessage();
  772. return 'InvalidHTMLString';
  773. }
  774. }
  775. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  776. // encoded using text entities) so we can then exclude all numeric entities.
  777. $out = preg_replace('/&#39;/i', '&apos;', $out);
  778. // We replace chars from a/A to z/Z encoded with numeric HTML entities with the real char so we won't loose the chars at the next step (preg_replace).
  779. // No need to use a loop here, this step is not to sanitize (this is done at next step, this is to try to save chars, even if they are
  780. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  781. //$out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', 'realCharForNumericEntities', $out);
  782. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  783. return realCharForNumericEntities($m); }, $out);
  784. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  785. $out = preg_replace('/&#x?[0-9]+/i', '', $out); // For example if we have j&#x61vascript with an entities without the ; to hide the 'a' of 'javascript'.
  786. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  787. // We should also exclude non expected HTML attributes and clean content of some attributes.
  788. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  789. // Warning, the function may add a LF so we are forced to trim to compare with old $out without having always a difference and an infinit loop.
  790. $out = dol_string_onlythesehtmlattributes($out);
  791. }
  792. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  793. $out = preg_replace('/&apos;/i', "&#39;", $out);
  794. } while ($oldstringtoclean != $out);
  795. break;
  796. case 'custom':
  797. if (empty($filter)) {
  798. return 'BadFourthParameterForGETPOST';
  799. }
  800. $out = filter_var($out, $filter, $options);
  801. break;
  802. }
  803. return $out;
  804. }
  805. if (!function_exists('dol_getprefix')) {
  806. /**
  807. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  808. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  809. * or two instances in same virtual servers.
  810. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  811. *
  812. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  813. * @return string A calculated prefix
  814. */
  815. function dol_getprefix($mode = '')
  816. {
  817. // If prefix is for email (we need to have $conf already loaded for this case)
  818. if ($mode == 'email') {
  819. global $conf;
  820. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  821. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  822. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  823. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  824. return $_SERVER["SERVER_NAME"];
  825. }
  826. }
  827. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  828. if (!empty($conf->file->instance_unique_id)) {
  829. return sha1('dolibarr'.$conf->file->instance_unique_id);
  830. }
  831. // For backward compatibility when instance_unique_id is not set
  832. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  833. }
  834. // If prefix is for session (no need to have $conf loaded)
  835. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  836. $tmp_instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance
  837. // The recommended value (may be not defined for old versions)
  838. if (!empty($tmp_instance_unique_id)) {
  839. return sha1('dolibarr'.$tmp_instance_unique_id);
  840. }
  841. // For backward compatibility when instance_unique_id is not set
  842. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  843. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  844. } else {
  845. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  846. }
  847. }
  848. }
  849. /**
  850. * Make an include_once using default root and alternate root if it fails.
  851. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  852. * To link to a module file from a module file, use include './mymodulefile';
  853. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  854. *
  855. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  856. * @param string $classname Class name (deprecated)
  857. * @return bool True if load is a success, False if it fails
  858. */
  859. function dol_include_once($relpath, $classname = '')
  860. {
  861. global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retrieved with $GLOBALS['var']
  862. $fullpath = dol_buildpath($relpath);
  863. if (!file_exists($fullpath)) {
  864. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  865. return false;
  866. }
  867. if (!empty($classname) && !class_exists($classname)) {
  868. return include $fullpath;
  869. } else {
  870. return include_once $fullpath;
  871. }
  872. }
  873. /**
  874. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  875. *
  876. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  877. * @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)
  878. * @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)
  879. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  880. * 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
  881. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  882. */
  883. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  884. {
  885. global $conf;
  886. $path = preg_replace('/^\//', '', $path);
  887. if (empty($type)) { // For a filesystem path
  888. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  889. if (is_array($conf->file->dol_document_root)) {
  890. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  891. if ($key == 'main') {
  892. continue;
  893. }
  894. if (file_exists($dirroot.'/'.$path)) {
  895. $res = $dirroot.'/'.$path;
  896. return $res;
  897. }
  898. }
  899. }
  900. if ($returnemptyifnotfound) {
  901. // Not found into alternate dir
  902. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  903. return '';
  904. }
  905. }
  906. } else {
  907. // For an url path
  908. // We try to get local path of file on filesystem from url
  909. // Note that trying to know if a file on disk exist by forging path on disk from url
  910. // works only for some web server and some setup. This is bugged when
  911. // using proxy, rewriting, virtual path, etc...
  912. $res = '';
  913. if ($type == 1) {
  914. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  915. }
  916. if ($type == 2) {
  917. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  918. }
  919. if ($type == 3) {
  920. $res = DOL_URL_ROOT.'/'.$path;
  921. }
  922. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  923. if ($key == 'main') {
  924. if ($type == 3) {
  925. global $dolibarr_main_url_root;
  926. // Define $urlwithroot
  927. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  928. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  929. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  930. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  931. }
  932. continue;
  933. }
  934. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  935. if (!empty($regs[1])) {
  936. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  937. if (file_exists($dirroot.'/'.$regs[1])) {
  938. if ($type == 1) {
  939. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  940. }
  941. if ($type == 2) {
  942. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  943. }
  944. if ($type == 3) {
  945. global $dolibarr_main_url_root;
  946. // Define $urlwithroot
  947. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  948. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  949. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  950. $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
  951. }
  952. break;
  953. }
  954. }
  955. }
  956. }
  957. return $res;
  958. }
  959. /**
  960. * Create a clone of instance of object (new instance with same value for properties)
  961. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  962. * 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.
  963. *
  964. * @param object $object Object to clone
  965. * @param int $native 0=Full isolation method, 1=Native PHP method
  966. * @return object Clone object
  967. * @see https://php.net/manual/language.oop5.cloning.php
  968. */
  969. function dol_clone($object, $native = 0)
  970. {
  971. if (empty($native)) {
  972. $myclone = unserialize(serialize($object)); // serialize then unserialize is hack to be sure to have a new object for all fields
  973. } else {
  974. $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep the reference (refering to the same target/variable)
  975. }
  976. return $myclone;
  977. }
  978. /**
  979. * Optimize a size for some browsers (phone, smarphone, ...)
  980. *
  981. * @param int $size Size we want
  982. * @param string $type Type of optimizing:
  983. * '' = function used to define a size for truncation
  984. * 'width' = function is used to define a width
  985. * @return int New size after optimizing
  986. */
  987. function dol_size($size, $type = '')
  988. {
  989. global $conf;
  990. if (empty($conf->dol_optimize_smallscreen)) {
  991. return $size;
  992. }
  993. if ($type == 'width' && $size > 250) {
  994. return 250;
  995. } else {
  996. return 10;
  997. }
  998. }
  999. /**
  1000. * Clean a string to use it as a file name.
  1001. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1002. *
  1003. * @param string $str String to clean
  1004. * @param string $newstr String to replace bad chars with.
  1005. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1006. * @return string String cleaned (a-zA-Z_)
  1007. *
  1008. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1009. */
  1010. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1011. {
  1012. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1013. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1014. // Char '/' and '\' are file delimiters.
  1015. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1016. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1017. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1018. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1019. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1020. $tmp = str_replace('..', '', $tmp);
  1021. return $tmp;
  1022. }
  1023. /**
  1024. * Clean a string to use it as a path name.
  1025. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1026. *
  1027. * @param string $str String to clean
  1028. * @param string $newstr String to replace bad chars with
  1029. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1030. * @return string String cleaned (a-zA-Z_)
  1031. *
  1032. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1033. */
  1034. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1035. {
  1036. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1037. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1038. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1039. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1040. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1041. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1042. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1043. $tmp = str_replace('..', '', $tmp);
  1044. return $tmp;
  1045. }
  1046. /**
  1047. * Clean a string to use it as an URL (into a href or src attribute)
  1048. *
  1049. * @param string $stringtoclean String to clean
  1050. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1051. * @return string Escaped string.
  1052. */
  1053. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1054. {
  1055. // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char)
  1056. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1057. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1058. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1059. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1060. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1061. if ($type == 1) {
  1062. // removing : should disable links to external url like http:aaa)
  1063. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1064. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1065. }
  1066. do {
  1067. $oldstringtoclean = $stringtoclean;
  1068. // removing '&colon' should disable links to external url like http:aaa)
  1069. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1070. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1071. } while ($oldstringtoclean != $stringtoclean);
  1072. if ($type == 1) {
  1073. // removing '//' should disable links to external url like //aaa or http//)
  1074. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1075. }
  1076. return $stringtoclean;
  1077. }
  1078. /**
  1079. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1080. *
  1081. * @param string $str String to clean
  1082. * @return string Cleaned string
  1083. *
  1084. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1085. */
  1086. function dol_string_unaccent($str)
  1087. {
  1088. global $conf;
  1089. if (utf8_check($str)) {
  1090. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1091. $transliterator = \Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', \Transliterator::FORWARD);
  1092. return $transliterator->transliterate($str);
  1093. }
  1094. // See http://www.utf8-chartable.de/
  1095. $string = rawurlencode($str);
  1096. $replacements = array(
  1097. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1098. '%C3%87' => 'C',
  1099. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1100. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1101. '%C3%91' => 'N',
  1102. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1103. '%C5%A0' => 'S',
  1104. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1105. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1106. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1107. '%C3%A7' => 'c',
  1108. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1109. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1110. '%C3%B1' => 'n',
  1111. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1112. '%C5%A1' => 's',
  1113. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1114. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1115. );
  1116. $string = strtr($string, $replacements);
  1117. return rawurldecode($string);
  1118. } else {
  1119. // See http://www.ascii-code.com/
  1120. $string = strtr(
  1121. $str,
  1122. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1123. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1124. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1125. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1126. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1127. \xF9\xFA\xFB\xFC\xFD\xFF",
  1128. "AAAAAAC
  1129. EEEEIIIIDN
  1130. OOOOOUUUY
  1131. aaaaaaceeee
  1132. iiiidnooooo
  1133. uuuuyy"
  1134. );
  1135. $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"));
  1136. return $string;
  1137. }
  1138. }
  1139. /**
  1140. * Clean a string from all punctuation characters to use it as a ref or login.
  1141. * This is a more complete function than dol_sanitizeFileName.
  1142. *
  1143. * @param string $str String to clean
  1144. * @param string $newstr String to replace forbidden chars with
  1145. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1146. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1147. * @return string Cleaned string
  1148. *
  1149. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1150. */
  1151. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1152. {
  1153. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1154. $forbidden_chars_to_remove = array();
  1155. //$forbidden_chars_to_remove=array("(",")");
  1156. if (is_array($badcharstoreplace)) {
  1157. $forbidden_chars_to_replace = $badcharstoreplace;
  1158. }
  1159. if (is_array($badcharstoremove)) {
  1160. $forbidden_chars_to_remove = $badcharstoremove;
  1161. }
  1162. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1163. }
  1164. /**
  1165. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1166. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1167. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1168. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1169. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1170. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1171. * @param string $str String to clean
  1172. * @param int $removetabcrlf Remove also CR-LF
  1173. * @return string Cleaned string
  1174. *
  1175. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1176. */
  1177. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1178. {
  1179. if ($removetabcrlf) {
  1180. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1181. } else {
  1182. return preg_replace('/[\x00-\x08\x11-\x12\x14-\x1F\x7F]/u', '', $str); // /u operator should make UTF8 valid characters being ignored so are not included into the replace
  1183. }
  1184. }
  1185. /**
  1186. * Returns text escaped for inclusion into javascript code
  1187. *
  1188. * @param string $stringtoescape String to escape
  1189. * @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 \
  1190. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1191. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1192. */
  1193. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1194. {
  1195. // escape quotes and backslashes, newlines, etc.
  1196. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1197. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1198. if (empty($noescapebackslashn)) {
  1199. $substitjs["\n"] = '\\n';
  1200. $substitjs['\\'] = '\\\\';
  1201. }
  1202. if (empty($mode)) {
  1203. $substitjs["'"] = "\\'";
  1204. $substitjs['"'] = "\\'";
  1205. } elseif ($mode == 1) {
  1206. $substitjs["'"] = "\\'";
  1207. } elseif ($mode == 2) {
  1208. $substitjs['"'] = '\\"';
  1209. } elseif ($mode == 3) {
  1210. $substitjs["'"] = "\\'";
  1211. $substitjs['"'] = "\\\"";
  1212. }
  1213. return strtr($stringtoescape, $substitjs);
  1214. }
  1215. /**
  1216. * Returns text escaped for inclusion into javascript code
  1217. *
  1218. * @param string $stringtoescape String to escape
  1219. * @return string Escaped string for json content.
  1220. */
  1221. function dol_escape_json($stringtoescape)
  1222. {
  1223. return str_replace('"', '\"', $stringtoescape);
  1224. }
  1225. /**
  1226. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1227. *
  1228. * @param string $stringtoescape String to escape
  1229. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1230. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1231. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes to tag.
  1232. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1233. * @return string Escaped string
  1234. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1235. */
  1236. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1237. {
  1238. if ($noescapetags == 'common') {
  1239. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1240. }
  1241. // escape quotes and backslashes, newlines, etc.
  1242. if ($escapeonlyhtmltags) {
  1243. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1244. } else {
  1245. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1246. }
  1247. if (!$keepb) {
  1248. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1249. }
  1250. if (!$keepn) {
  1251. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1252. }
  1253. if ($escapeonlyhtmltags) {
  1254. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1255. } else {
  1256. // Escape tags to keep
  1257. // TODO Does not works yet when there is attributes to tag
  1258. $tmparrayoftags = array();
  1259. if ($noescapetags) {
  1260. $tmparrayoftags = explode(',', $noescapetags);
  1261. }
  1262. if (count($tmparrayoftags)) {
  1263. foreach ($tmparrayoftags as $tagtoreplace) {
  1264. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1265. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1266. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1267. }
  1268. }
  1269. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1270. if (count($tmparrayoftags)) {
  1271. foreach ($tmparrayoftags as $tagtoreplace) {
  1272. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1273. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1274. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1275. }
  1276. }
  1277. return $result;
  1278. }
  1279. }
  1280. /**
  1281. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1282. *
  1283. * @param string $string String to encode
  1284. * @param string $encoding Character set encoding
  1285. * @return string String converted
  1286. */
  1287. function dol_strtolower($string, $encoding = "UTF-8")
  1288. {
  1289. if (function_exists('mb_strtolower')) {
  1290. return mb_strtolower($string, $encoding);
  1291. } else {
  1292. return strtolower($string);
  1293. }
  1294. }
  1295. /**
  1296. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1297. *
  1298. * @param string $string String to encode
  1299. * @param string $encoding Character set encoding
  1300. * @return string String converted
  1301. */
  1302. function dol_strtoupper($string, $encoding = "UTF-8")
  1303. {
  1304. if (function_exists('mb_strtoupper')) {
  1305. return mb_strtoupper($string, $encoding);
  1306. } else {
  1307. return strtoupper($string);
  1308. }
  1309. }
  1310. /**
  1311. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1312. *
  1313. * @param string $string String to encode
  1314. * @param string $encoding Character set encodign
  1315. * @return string String converted
  1316. */
  1317. function dol_ucfirst($string, $encoding = "UTF-8")
  1318. {
  1319. if (function_exists('mb_substr')) {
  1320. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1321. } else {
  1322. return ucfirst($string);
  1323. }
  1324. }
  1325. /**
  1326. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1327. *
  1328. * @param string $string String to encode
  1329. * @param string $encoding Character set encodign
  1330. * @return string String converted
  1331. */
  1332. function dol_ucwords($string, $encoding = "UTF-8")
  1333. {
  1334. if (function_exists('mb_convert_case')) {
  1335. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1336. } else {
  1337. return ucwords($string);
  1338. }
  1339. }
  1340. /**
  1341. * Write log message into outputs. Possible outputs can be:
  1342. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1343. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1344. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1345. * this, use logging to files instead of syslog (see setup of module).
  1346. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1347. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1348. * This function works only if syslog module is enabled.
  1349. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1350. *
  1351. * @param string $message Line to log. ''=Show nothing
  1352. * @param int $level Log level
  1353. * 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
  1354. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1355. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1356. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1357. * @param string $restricttologhandler Force output of log only to this log handler
  1358. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1359. * @return void
  1360. */
  1361. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1362. {
  1363. global $conf, $user, $debugbar;
  1364. // If syslog module enabled
  1365. if (empty($conf->syslog->enabled)) {
  1366. return;
  1367. }
  1368. // Check if we are into execution of code of a website
  1369. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1370. global $website, $websitekey;
  1371. if (is_object($website) && !empty($website->ref)) {
  1372. $suffixinfilename .= '_website_'.$website->ref;
  1373. } elseif (!empty($websitekey)) {
  1374. $suffixinfilename .= '_website_'.$websitekey;
  1375. }
  1376. }
  1377. if ($ident < 0) {
  1378. foreach ($conf->loghandlers as $loghandlerinstance) {
  1379. $loghandlerinstance->setIdent($ident);
  1380. }
  1381. }
  1382. if (!empty($message)) {
  1383. // Test log level
  1384. $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');
  1385. if (!array_key_exists($level, $logLevels)) {
  1386. throw new Exception('Incorrect log level');
  1387. }
  1388. if ($level > $conf->global->SYSLOG_LEVEL) {
  1389. return;
  1390. }
  1391. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1392. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1393. }
  1394. // If adding log inside HTML page is required
  1395. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1396. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1397. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1398. }
  1399. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1400. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1401. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1402. print "\n\n<!-- Log start\n";
  1403. print dol_escape_htmltag($message)."\n";
  1404. print "Log end -->\n";
  1405. }
  1406. $data = array(
  1407. 'message' => $message,
  1408. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1409. 'level' => $level,
  1410. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1411. 'ip' => false
  1412. );
  1413. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1414. if (!empty($remoteip)) {
  1415. $data['ip'] = $remoteip;
  1416. // This is when server run behind a reverse proxy
  1417. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1418. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1419. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1420. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1421. }
  1422. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1423. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1424. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1425. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1426. // 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).
  1427. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1428. } elseif (!empty($_SERVER['LOGNAME'])) {
  1429. // 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).
  1430. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1431. }
  1432. // Loop on each log handler and send output
  1433. foreach ($conf->loghandlers as $loghandlerinstance) {
  1434. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1435. continue;
  1436. }
  1437. $loghandlerinstance->export($data, $suffixinfilename);
  1438. }
  1439. unset($data);
  1440. }
  1441. if ($ident > 0) {
  1442. foreach ($conf->loghandlers as $loghandlerinstance) {
  1443. $loghandlerinstance->setIdent($ident);
  1444. }
  1445. }
  1446. }
  1447. /**
  1448. * Return HTML code to output a button to open a dialog popup box.
  1449. * Such buttons must be included inside a HTML form.
  1450. *
  1451. * @param string $name A name for the html component
  1452. * @param string $label Label of button
  1453. * @param string $buttonstring button string
  1454. * @param string $url Url to open
  1455. * @param string $disabled Disabled text
  1456. * @return string HTML component with button
  1457. */
  1458. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1459. {
  1460. if (strpos($url, '?') > 0) {
  1461. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1462. } else {
  1463. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1464. }
  1465. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1466. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1467. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1468. $out .= '<script type="text/javascript">
  1469. jQuery(document).ready(function () {
  1470. jQuery(".button_'.$name.'").click(function () {
  1471. console.log("Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'")
  1472. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1473. .dialog({
  1474. autoOpen: false,
  1475. modal: true,
  1476. height: (window.innerHeight - 150),
  1477. width: \'80%\',
  1478. title: "'.dol_escape_js($label).'"
  1479. });
  1480. $dialog.dialog(\'open\');
  1481. });
  1482. });
  1483. </script>';
  1484. return $out;
  1485. }
  1486. /**
  1487. * Show tab header of a card
  1488. *
  1489. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1490. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1491. * @param string $title Title
  1492. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1493. * @param string $picto Add a picto on tab title
  1494. * @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.
  1495. * @param string $morehtmlright Add more html content on right of tabs title
  1496. * @param string $morecss More Css
  1497. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1498. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1499. * @return void
  1500. * @deprecated Use print dol_get_fiche_head() instead
  1501. */
  1502. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1503. {
  1504. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1505. }
  1506. /**
  1507. * Show tabs of a record
  1508. *
  1509. * @param array $links Array of tabs. Note that label into $links[$i][1] must be already HTML escaped.
  1510. * @param string $active Active tab name
  1511. * @param string $title Title
  1512. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1513. * @param string $picto Add a picto on tab title
  1514. * @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.
  1515. * @param string $morehtmlright Add more html content on right of tabs title
  1516. * @param string $morecss More CSS on the link <a>
  1517. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1518. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1519. * @return string
  1520. */
  1521. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1522. {
  1523. global $conf, $langs, $hookmanager;
  1524. // Show title
  1525. $showtitle = 1;
  1526. if (!empty($conf->dol_optimize_smallscreen)) {
  1527. $showtitle = 0;
  1528. }
  1529. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1530. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1531. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1532. }
  1533. // Show right part
  1534. if ($morehtmlright) {
  1535. $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.
  1536. }
  1537. // Show title
  1538. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1539. $limittitle = 30;
  1540. $out .= '<a class="tabTitle">';
  1541. if ($picto) {
  1542. $noprefix = $pictoisfullpath;
  1543. if (strpos($picto, 'fontawesome_') !== false) {
  1544. $noprefix = 1;
  1545. }
  1546. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1547. }
  1548. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1549. $out .= '</a>';
  1550. }
  1551. // Show tabs
  1552. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1553. $maxkey = -1;
  1554. if (is_array($links) && !empty($links)) {
  1555. $keys = array_keys($links);
  1556. if (count($keys)) {
  1557. $maxkey = max($keys);
  1558. }
  1559. }
  1560. // Show tabs
  1561. // if =0 we don't use the feature
  1562. if (empty($limittoshow)) {
  1563. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1564. }
  1565. if (!empty($conf->dol_optimize_smallscreen)) {
  1566. $limittoshow = 2;
  1567. }
  1568. $displaytab = 0;
  1569. $nbintab = 0;
  1570. $popuptab = 0;
  1571. $outmore = '';
  1572. for ($i = 0; $i <= $maxkey; $i++) {
  1573. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1574. // If active tab is already present
  1575. if ($i >= $limittoshow) {
  1576. $limittoshow--;
  1577. }
  1578. }
  1579. }
  1580. for ($i = 0; $i <= $maxkey; $i++) {
  1581. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1582. $isactive = true;
  1583. } else {
  1584. $isactive = false;
  1585. }
  1586. if ($i < $limittoshow || $isactive) {
  1587. // Output entry with a visible tab
  1588. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
  1589. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1590. if (!empty($links[$i][0])) {
  1591. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1592. } else {
  1593. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1594. }
  1595. } elseif (!empty($links[$i][1])) {
  1596. //print "x $i $active ".$links[$i][2]." z";
  1597. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1598. if (!empty($links[$i][0])) {
  1599. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1600. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  1601. }
  1602. $out .= $links[$i][1];
  1603. if (!empty($links[$i][0])) {
  1604. $out .= '</a>'."\n";
  1605. }
  1606. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1607. $out .= '</div>';
  1608. }
  1609. $out .= '</div>';
  1610. } else {
  1611. // Add entry into the combo popup with the other tabs
  1612. if (!$popuptab) {
  1613. $popuptab = 1;
  1614. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1615. }
  1616. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1617. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1618. if (!empty($links[$i][0])) {
  1619. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1620. } else {
  1621. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1622. }
  1623. } elseif (!empty($links[$i][1])) {
  1624. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1625. $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.
  1626. $outmore .= '</a>'."\n";
  1627. }
  1628. $outmore .= '</div>';
  1629. $nbintab++;
  1630. }
  1631. $displaytab = $i;
  1632. }
  1633. if ($popuptab) {
  1634. $outmore .= '</div>';
  1635. }
  1636. if ($popuptab) { // If there is some tabs not shown
  1637. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1638. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1639. $widthofpopup = 200;
  1640. $tabsname = $moretabssuffix;
  1641. if (empty($tabsname)) {
  1642. $tabsname = str_replace("@", "", $picto);
  1643. }
  1644. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1645. $out .= '<div class="tab"><a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
  1646. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1647. $out .= $outmore;
  1648. $out .= '</div>';
  1649. $out .= '<div></div>';
  1650. $out .= "</div>\n";
  1651. $out .= "<script>";
  1652. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1653. var x = this.offsetLeft, y = this.offsetTop;
  1654. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1655. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1656. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1657. }
  1658. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1659. });
  1660. ";
  1661. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1662. $out .= "</script>";
  1663. }
  1664. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1665. $out .= "</div>\n";
  1666. }
  1667. if (!$notab || $notab == -1 || $notab == -2) {
  1668. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1669. }
  1670. $parameters = array('tabname' => $active, 'out' => $out);
  1671. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1672. if ($reshook > 0) {
  1673. $out = $hookmanager->resPrint;
  1674. }
  1675. return $out;
  1676. }
  1677. /**
  1678. * Show tab footer of a card
  1679. *
  1680. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1681. * @return void
  1682. * @deprecated Use print dol_get_fiche_end() instead
  1683. */
  1684. function dol_fiche_end($notab = 0)
  1685. {
  1686. print dol_get_fiche_end($notab);
  1687. }
  1688. /**
  1689. * Return tab footer of a card
  1690. *
  1691. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1692. * @return string
  1693. */
  1694. function dol_get_fiche_end($notab = 0)
  1695. {
  1696. if (!$notab || $notab == -1) {
  1697. return "\n</div>\n";
  1698. } else {
  1699. return '';
  1700. }
  1701. }
  1702. /**
  1703. * Show tab footer of a card.
  1704. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1705. *
  1706. * @param Object $object Object to show
  1707. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1708. * @param string $morehtml More html content to output just before the nav bar
  1709. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1710. * @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.
  1711. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1712. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1713. * @param string $moreparam More param to add in nav link url.
  1714. * @param int $nodbprefix Do not include DB prefix to forge table name
  1715. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1716. * @param string $morehtmlstatus More html code to show under navigation arrows
  1717. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1718. * @param string $morehtmlright More html code to show before navigation arrows
  1719. * @return void
  1720. */
  1721. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1722. {
  1723. global $conf, $form, $user, $langs, $hookmanager, $action;
  1724. $error = 0;
  1725. $maxvisiblephotos = 1;
  1726. $showimage = 1;
  1727. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1728. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1729. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1730. $showbarcode = 0;
  1731. }
  1732. $modulepart = 'unknown';
  1733. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1734. $modulepart = $object->element;
  1735. } elseif ($object->element == 'member') {
  1736. $modulepart = 'memberphoto';
  1737. } elseif ($object->element == 'user') {
  1738. $modulepart = 'userphoto';
  1739. }
  1740. if (class_exists("Imagick")) {
  1741. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1742. $modulepart = $object->element;
  1743. } elseif ($object->element == 'fichinter') {
  1744. $modulepart = 'ficheinter';
  1745. } elseif ($object->element == 'contrat') {
  1746. $modulepart = 'contract';
  1747. } elseif ($object->element == 'order_supplier') {
  1748. $modulepart = 'supplier_order';
  1749. } elseif ($object->element == 'invoice_supplier') {
  1750. $modulepart = 'supplier_invoice';
  1751. }
  1752. }
  1753. if ($object->element == 'product') {
  1754. $width = 80;
  1755. $cssclass = 'photowithmargin photoref';
  1756. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1757. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1758. if ($conf->browser->layout == 'phone') {
  1759. $maxvisiblephotos = 1;
  1760. }
  1761. if ($showimage) {
  1762. $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>';
  1763. } else {
  1764. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1765. $nophoto = '';
  1766. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1767. } else { // Show no photo link
  1768. $nophoto = '/public/theme/common/nophoto.png';
  1769. $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>';
  1770. }
  1771. }
  1772. } elseif ($object->element == 'ticket') {
  1773. $width = 80;
  1774. $cssclass = 'photoref';
  1775. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1776. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1777. if ($conf->browser->layout == 'phone') {
  1778. $maxvisiblephotos = 1;
  1779. }
  1780. if ($showimage) {
  1781. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1782. if ($object->nbphoto > 0) {
  1783. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1784. } else {
  1785. $showimage = 0;
  1786. }
  1787. }
  1788. if (!$showimage) {
  1789. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1790. $nophoto = '';
  1791. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1792. } else { // Show no photo link
  1793. $nophoto = img_picto('No photo', 'object_ticket');
  1794. $morehtmlleft .= '<!-- No photo to show -->';
  1795. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1796. $morehtmlleft .= $nophoto;
  1797. $morehtmlleft .= '</div></div>';
  1798. }
  1799. }
  1800. } else {
  1801. if ($showimage) {
  1802. if ($modulepart != 'unknown') {
  1803. $phototoshow = '';
  1804. // Check if a preview file is available
  1805. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1806. $objectref = dol_sanitizeFileName($object->ref);
  1807. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1808. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1809. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1810. $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
  1811. } else {
  1812. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1813. }
  1814. if (empty($subdir)) {
  1815. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1816. }
  1817. $filepath = $dir_output.$subdir."/";
  1818. $filepdf = $filepath.$objectref.".pdf";
  1819. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1820. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1821. $fileimage = $filepdf.'_preview.png';
  1822. $relativepathimage = $relativepath.'_preview.png';
  1823. $pdfexists = file_exists($filepdf);
  1824. // If PDF file exists
  1825. if ($pdfexists) {
  1826. // Conversion du PDF en image png si fichier png non existant
  1827. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1828. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1829. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1830. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1831. if ($ret < 0) {
  1832. $error++;
  1833. }
  1834. }
  1835. }
  1836. }
  1837. if ($pdfexists && !$error) {
  1838. $heightforphotref = 80;
  1839. if (!empty($conf->dol_optimize_smallscreen)) {
  1840. $heightforphotref = 60;
  1841. }
  1842. // If the preview file is found
  1843. if (file_exists($fileimage)) {
  1844. $phototoshow = '<div class="photoref">';
  1845. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1846. $phototoshow .= '</div>';
  1847. }
  1848. }
  1849. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1850. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  1851. }
  1852. if ($phototoshow) {
  1853. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1854. $morehtmlleft .= $phototoshow;
  1855. $morehtmlleft .= '</div>';
  1856. }
  1857. }
  1858. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1859. if ($object->element == 'action') {
  1860. $width = 80;
  1861. $cssclass = 'photorefcenter';
  1862. $nophoto = img_picto('No photo', 'title_agenda');
  1863. } else {
  1864. $width = 14;
  1865. $cssclass = 'photorefcenter';
  1866. $picto = $object->picto;
  1867. $prefix = 'object_';
  1868. if ($object->element == 'project' && !$object->public) {
  1869. $picto = 'project'; // instead of projectpub
  1870. }
  1871. if (strpos($picto, 'fontawesome_') !== false) {
  1872. $prefix = '';
  1873. }
  1874. $nophoto = img_picto('No photo', $prefix.$picto);
  1875. }
  1876. $morehtmlleft .= '<!-- No photo to show -->';
  1877. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1878. $morehtmlleft .= $nophoto;
  1879. $morehtmlleft .= '</div></div>';
  1880. }
  1881. }
  1882. }
  1883. if ($showbarcode) {
  1884. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref').'</div>';
  1885. }
  1886. if ($object->element == 'societe') {
  1887. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1888. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1889. } else {
  1890. $morehtmlstatus .= $object->getLibStatut(6);
  1891. }
  1892. } elseif ($object->element == 'product') {
  1893. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1894. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1895. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1896. } else {
  1897. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1898. }
  1899. $morehtmlstatus .= ' &nbsp; ';
  1900. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1901. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1902. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1903. } else {
  1904. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1905. }
  1906. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  1907. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1908. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1909. $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1910. }
  1911. $morehtmlstatus .= $tmptxt;
  1912. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  1913. if ($object->statut == 0) {
  1914. $morehtmlstatus .= $object->getLibStatut(5);
  1915. } else {
  1916. $morehtmlstatus .= $object->getLibStatut(4);
  1917. }
  1918. } elseif ($object->element == 'facturerec') {
  1919. if ($object->frequency == 0) {
  1920. $morehtmlstatus .= $object->getLibStatut(2);
  1921. } else {
  1922. $morehtmlstatus .= $object->getLibStatut(5);
  1923. }
  1924. } elseif ($object->element == 'project_task') {
  1925. $object->fk_statut = 1;
  1926. if ($object->progress > 0) {
  1927. $object->fk_statut = 2;
  1928. }
  1929. if ($object->progress >= 100) {
  1930. $object->fk_statut = 3;
  1931. }
  1932. $tmptxt = $object->getLibStatut(5);
  1933. $morehtmlstatus .= $tmptxt; // No status on task
  1934. } else { // Generic case
  1935. $tmptxt = $object->getLibStatut(6);
  1936. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1937. $tmptxt = $object->getLibStatut(5);
  1938. }
  1939. $morehtmlstatus .= $tmptxt;
  1940. }
  1941. // Add if object was dispatched "into accountancy"
  1942. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  1943. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  1944. if (method_exists($object, 'getVentilExportCompta')) {
  1945. $accounted = $object->getVentilExportCompta();
  1946. $langs->load("accountancy");
  1947. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1948. }
  1949. }
  1950. // Add alias for thirdparty
  1951. if (!empty($object->name_alias)) {
  1952. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1953. }
  1954. // Add label
  1955. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  1956. if (!empty($object->label)) {
  1957. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1958. }
  1959. }
  1960. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  1961. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1962. if ($moreaddress) {
  1963. $morehtmlref .= '<div class="refidno">';
  1964. $morehtmlref .= $moreaddress;
  1965. $morehtmlref .= '</div>';
  1966. }
  1967. }
  1968. 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)) {
  1969. $morehtmlref .= '<div style="clear: both;"></div>';
  1970. $morehtmlref .= '<div class="refidno">';
  1971. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1972. $morehtmlref .= '</div>';
  1973. }
  1974. $parameters=array('morehtmlref'=>$morehtmlref);
  1975. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  1976. if ($reshook < 0) {
  1977. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1978. } elseif (empty($reshook)) {
  1979. $morehtmlref .= $hookmanager->resPrint;
  1980. } elseif ($reshook > 0) {
  1981. $morehtmlref = $hookmanager->resPrint;
  1982. }
  1983. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1984. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1985. print '</div>';
  1986. print '<div class="underrefbanner clearboth"></div>';
  1987. }
  1988. /**
  1989. * Show a string with the label tag dedicated to the HTML edit field.
  1990. *
  1991. * @param string $langkey Translation key
  1992. * @param string $fieldkey Key of the html select field the text refers to
  1993. * @param int $fieldrequired 1=Field is mandatory
  1994. * @return string
  1995. * @deprecated Form::editfieldkey
  1996. */
  1997. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1998. {
  1999. global $langs;
  2000. $ret = '';
  2001. if ($fieldrequired) {
  2002. $ret .= '<span class="fieldrequired">';
  2003. }
  2004. $ret .= '<label for="'.$fieldkey.'">';
  2005. $ret .= $langs->trans($langkey);
  2006. $ret .= '</label>';
  2007. if ($fieldrequired) {
  2008. $ret .= '</span>';
  2009. }
  2010. return $ret;
  2011. }
  2012. /**
  2013. * Return string to add class property on html element with pair/impair.
  2014. *
  2015. * @param string $var 0 or 1
  2016. * @param string $moreclass More class to add
  2017. * @return string String to add class onto HTML element
  2018. */
  2019. function dol_bc($var, $moreclass = '')
  2020. {
  2021. global $bc;
  2022. $ret = ' '.$bc[$var];
  2023. if ($moreclass) {
  2024. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2025. }
  2026. return $ret;
  2027. }
  2028. /**
  2029. * Return a formated address (part address/zip/town/state) according to country rules.
  2030. * See https://en.wikipedia.org/wiki/Address
  2031. *
  2032. * @param Object $object A company or contact object
  2033. * @param int $withcountry 1=Add country into address string
  2034. * @param string $sep Separator to use to build string
  2035. * @param Translate $outputlangs Object lang that contains language for text translation.
  2036. * @param int $mode 0=Standard output, 1=Remove address
  2037. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2038. * @return string Formated string
  2039. * @see dol_print_address()
  2040. */
  2041. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2042. {
  2043. global $conf, $langs;
  2044. $ret = '';
  2045. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2046. $sep = "\n";
  2047. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2048. // Address
  2049. if (empty($mode)) {
  2050. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2051. }
  2052. // Zip/Town/State
  2053. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2054. // US: title firstname name \n address lines \n town, state, zip \n country
  2055. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2056. $ret .= (($ret && $town) ? $sep : '').$town;
  2057. if (!empty($object->state)) {
  2058. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2059. }
  2060. if (!empty($object->zip)) {
  2061. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2062. }
  2063. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2064. // UK: title firstname name \n address lines \n town state \n zip \n country
  2065. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2066. $ret .= ($ret ? $sep : '').$town;
  2067. if (!empty($object->state)) {
  2068. $ret .= ($ret ? ", " : '').$object->state;
  2069. }
  2070. if (!empty($object->zip)) {
  2071. $ret .= ($ret ? $sep : '').$object->zip;
  2072. }
  2073. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2074. // ES: title firstname name \n address lines \n zip town \n state \n country
  2075. $ret .= ($ret ? $sep : '').$object->zip;
  2076. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2077. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2078. if (!empty($object->state)) {
  2079. $ret .= "\n".$object->state;
  2080. }
  2081. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2082. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2083. // See https://www.sljfaq.org/afaq/addresses.html
  2084. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2085. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2086. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2087. // IT: title firstname name\n address lines \n zip town state_code \n country
  2088. $ret .= ($ret ? $sep : '').$object->zip;
  2089. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2090. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2091. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2092. } else {
  2093. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2094. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2095. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2096. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2097. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2098. $ret .= ($ret ? ", " : '').$object->state;
  2099. }
  2100. }
  2101. if (!is_object($outputlangs)) {
  2102. $outputlangs = $langs;
  2103. }
  2104. if ($withcountry) {
  2105. $langs->load("dict");
  2106. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2107. }
  2108. return $ret;
  2109. }
  2110. /**
  2111. * Format a string.
  2112. *
  2113. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2114. * @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)
  2115. * @param int $is_gmt See comment of timestamp parameter
  2116. * @return string A formatted string
  2117. */
  2118. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2119. {
  2120. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2121. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2122. } else {
  2123. return 'Error date into a not supported range';
  2124. }
  2125. }
  2126. /**
  2127. * Output date in a string format according to outputlangs (or langs if not defined).
  2128. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2129. *
  2130. * @param int $time GM Timestamps date
  2131. * @param string $format Output date format (tag of strftime function)
  2132. * "%d %b %Y",
  2133. * "%d/%m/%Y %H:%M",
  2134. * "%d/%m/%Y %H:%M:%S",
  2135. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2136. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2137. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2138. * false or 'tzserver' => output string is for local PHP server TZ usage
  2139. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2140. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  2141. * @param Translate $outputlangs Object lang that contains language for text translation.
  2142. * @param boolean $encodetooutput false=no convert into output pagecode
  2143. * @return string Formated date or '' if time is null
  2144. *
  2145. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2146. */
  2147. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2148. {
  2149. global $conf, $langs;
  2150. // If date undefined or "", we return ""
  2151. if (dol_strlen($time) == 0) {
  2152. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2153. }
  2154. if ($tzoutput === 'auto') {
  2155. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2156. }
  2157. // Clean parameters
  2158. $to_gmt = false;
  2159. $offsettz = $offsetdst = 0;
  2160. if ($tzoutput) {
  2161. $to_gmt = true; // For backward compatibility
  2162. if (is_string($tzoutput)) {
  2163. if ($tzoutput == 'tzserver') {
  2164. $to_gmt = false;
  2165. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2166. $offsettz = 0; // Timezone offset with server timezone, so 0
  2167. $offsetdst = 0; // Dst offset with server timezone, so 0
  2168. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2169. $to_gmt = true;
  2170. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2171. if (class_exists('DateTimeZone')) {
  2172. $user_date_tz = new DateTimeZone($offsettzstring);
  2173. $user_dt = new DateTime();
  2174. $user_dt->setTimezone($user_date_tz);
  2175. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2176. $offsettz = $user_dt->getOffset();
  2177. } else { // old method (The 'tzuser' was processed like the 'tzuserrel')
  2178. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2179. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2180. }
  2181. }
  2182. }
  2183. }
  2184. if (!is_object($outputlangs)) {
  2185. $outputlangs = $langs;
  2186. }
  2187. if (!$format) {
  2188. $format = 'daytextshort';
  2189. }
  2190. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2191. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2192. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2193. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2194. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2195. if ($formatwithoutreduce != $format) {
  2196. $format = $formatwithoutreduce;
  2197. $reduceformat = 1;
  2198. } // so format 'dayreduceformat' is processed like day
  2199. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2200. // TODO Add format daysmallyear and dayhoursmallyear
  2201. if ($format == 'day') {
  2202. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2203. } elseif ($format == 'hour') {
  2204. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2205. } elseif ($format == 'hourduration') {
  2206. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2207. } elseif ($format == 'daytext') {
  2208. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2209. } elseif ($format == 'daytextshort') {
  2210. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2211. } elseif ($format == 'dayhour') {
  2212. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2213. } elseif ($format == 'dayhoursec') {
  2214. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2215. } elseif ($format == 'dayhourtext') {
  2216. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2217. } elseif ($format == 'dayhourtextshort') {
  2218. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2219. } elseif ($format == 'dayhourlog') {
  2220. // Format not sensitive to language
  2221. $format = '%Y%m%d%H%M%S';
  2222. } elseif ($format == 'dayhourldap') {
  2223. $format = '%Y%m%d%H%M%SZ';
  2224. } elseif ($format == 'dayhourxcard') {
  2225. $format = '%Y%m%dT%H%M%SZ';
  2226. } elseif ($format == 'dayxcard') {
  2227. $format = '%Y%m%d';
  2228. } elseif ($format == 'dayrfc') {
  2229. $format = '%Y-%m-%d'; // DATE_RFC3339
  2230. } elseif ($format == 'dayhourrfc') {
  2231. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2232. } elseif ($format == 'standard') {
  2233. $format = '%Y-%m-%d %H:%M:%S';
  2234. }
  2235. if ($reduceformat) {
  2236. $format = str_replace('%Y', '%y', $format);
  2237. $format = str_replace('yyyy', 'yy', $format);
  2238. }
  2239. // Clean format
  2240. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2241. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2242. $format = str_replace('%b', '__b__', $format);
  2243. $format = str_replace('%B', '__B__', $format);
  2244. }
  2245. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2246. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2247. $format = str_replace('%a', '__a__', $format);
  2248. $format = str_replace('%A', '__A__', $format);
  2249. }
  2250. // Analyze date
  2251. $reg = array();
  2252. 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
  2253. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2254. return '';
  2255. } 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
  2256. // This part of code should not be used anymore.
  2257. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2258. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2259. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2260. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2261. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2262. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2263. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2264. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2265. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2266. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2267. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2268. } else {
  2269. // Date is a timestamps
  2270. if ($time < 100000000000) { // Protection against bad date values
  2271. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2272. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2273. } else {
  2274. $ret = 'Bad value '.$time.' for date';
  2275. }
  2276. }
  2277. if (preg_match('/__b__/i', $format)) {
  2278. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2279. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2280. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2281. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2282. if ($encodetooutput) {
  2283. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2284. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2285. } else {
  2286. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2287. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2288. }
  2289. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2290. $ret = str_replace('__b__', $monthtextshort, $ret);
  2291. $ret = str_replace('__B__', $monthtext, $ret);
  2292. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2293. //return $ret;
  2294. }
  2295. if (preg_match('/__a__/i', $format)) {
  2296. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2297. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2298. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2299. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2300. $ret = str_replace('__A__', $dayweek, $ret);
  2301. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2302. }
  2303. return $ret;
  2304. }
  2305. /**
  2306. * Return an array with locale date info.
  2307. * WARNING: This function use PHP server timezone by default to return locale informations.
  2308. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2309. *
  2310. * @param int $timestamp Timestamp
  2311. * @param boolean $fast Fast mode. deprecated.
  2312. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2313. * @return array Array of informations
  2314. * 'seconds' => $secs,
  2315. * 'minutes' => $min,
  2316. * 'hours' => $hour,
  2317. * 'mday' => $day,
  2318. * 'wday' => $dow, 0=sunday, 6=saturday
  2319. * 'mon' => $month,
  2320. * 'year' => $year,
  2321. * 'yday' => floor($secsInYear/$_day_power)
  2322. * '0' => original timestamp
  2323. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2324. */
  2325. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2326. {
  2327. //$datetimeobj = new DateTime('@'.$timestamp);
  2328. $datetimeobj = new DateTime();
  2329. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2330. if ($forcetimezone) {
  2331. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2332. }
  2333. $arrayinfo = array(
  2334. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2335. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2336. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2337. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2338. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2339. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2340. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2341. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2342. '0'=>$timestamp
  2343. );
  2344. return $arrayinfo;
  2345. }
  2346. /**
  2347. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2348. * Replace function mktime not available under Windows if year < 1970
  2349. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2350. *
  2351. * @param int $hour Hour (can be -1 for undefined)
  2352. * @param int $minute Minute (can be -1 for undefined)
  2353. * @param int $second Second (can be -1 for undefined)
  2354. * @param int $month Month (1 to 12)
  2355. * @param int $day Day (1 to 31)
  2356. * @param int $year Year
  2357. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2358. * False or 0 or 'tzserver' = local to server TZ
  2359. * 'auto'
  2360. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2361. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user into a GMT date.
  2362. * 'tz,TimeZone' = use specified timezone
  2363. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2364. * @return int|string Date as a timestamp, '' or false if error
  2365. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2366. */
  2367. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2368. {
  2369. global $conf;
  2370. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2371. if ($gm === 'auto') {
  2372. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2373. }
  2374. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2375. // Clean parameters
  2376. if ($hour == -1 || empty($hour)) {
  2377. $hour = 0;
  2378. }
  2379. if ($minute == -1 || empty($minute)) {
  2380. $minute = 0;
  2381. }
  2382. if ($second == -1 || empty($second)) {
  2383. $second = 0;
  2384. }
  2385. // Check parameters
  2386. if ($check) {
  2387. if (!$month || !$day) {
  2388. return '';
  2389. }
  2390. if ($day > 31) {
  2391. return '';
  2392. }
  2393. if ($month > 12) {
  2394. return '';
  2395. }
  2396. if ($hour < 0 || $hour > 24) {
  2397. return '';
  2398. }
  2399. if ($minute < 0 || $minute > 60) {
  2400. return '';
  2401. }
  2402. if ($second < 0 || $second > 60) {
  2403. return '';
  2404. }
  2405. }
  2406. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2407. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2408. $localtz = new DateTimeZone($default_timezone);
  2409. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2410. // We use dol_tz_string first because it is more reliable.
  2411. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2412. try {
  2413. $localtz = new DateTimeZone($default_timezone);
  2414. } catch (Exception $e) {
  2415. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2416. $default_timezone = @date_default_timezone_get();
  2417. }
  2418. } elseif (strrpos($gm, "tz,") !== false) {
  2419. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2420. try {
  2421. $localtz = new DateTimeZone($timezone);
  2422. } catch (Exception $e) {
  2423. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2424. }
  2425. }
  2426. if (empty($localtz)) {
  2427. $localtz = new DateTimeZone('UTC');
  2428. }
  2429. //var_dump($localtz);
  2430. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2431. $dt = new DateTime(null, $localtz);
  2432. $dt->setDate((int) $year, (int) $month, (int) $day);
  2433. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2434. $date = $dt->getTimestamp(); // should include daylight saving time
  2435. //var_dump($date);
  2436. return $date;
  2437. }
  2438. /**
  2439. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2440. *
  2441. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2442. * 'gmt' => we return GMT timestamp,
  2443. * 'tzserver' => we add the PHP server timezone
  2444. * 'tzref' => we add the company timezone. Not implemented.
  2445. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2446. * @return int $date Timestamp
  2447. */
  2448. function dol_now($mode = 'auto')
  2449. {
  2450. $ret = 0;
  2451. if ($mode === 'auto') {
  2452. $mode = 'gmt';
  2453. }
  2454. if ($mode == 'gmt') {
  2455. $ret = time(); // Time for now at greenwich.
  2456. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2457. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2458. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2459. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2460. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2461. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2462. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2463. // $ret=dol_now('gmt')+($tzsecond*3600);
  2464. //}
  2465. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2466. // Time for now with user timezone added
  2467. //print 'time: '.time();
  2468. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2469. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2470. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2471. }
  2472. return $ret;
  2473. }
  2474. /**
  2475. * Return string with formated size
  2476. *
  2477. * @param int $size Size to print
  2478. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2479. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2480. * @return string Link
  2481. */
  2482. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2483. {
  2484. global $conf, $langs;
  2485. $level = 1024;
  2486. if (!empty($conf->dol_optimize_smallscreen)) {
  2487. $shortunit = 1;
  2488. }
  2489. // Set value text
  2490. if (empty($shortvalue) || $size < ($level * 10)) {
  2491. $ret = $size;
  2492. $textunitshort = $langs->trans("b");
  2493. $textunitlong = $langs->trans("Bytes");
  2494. } else {
  2495. $ret = round($size / $level, 0);
  2496. $textunitshort = $langs->trans("Kb");
  2497. $textunitlong = $langs->trans("KiloBytes");
  2498. }
  2499. // Use long or short text unit
  2500. if (empty($shortunit)) {
  2501. $ret .= ' '.$textunitlong;
  2502. } else {
  2503. $ret .= ' '.$textunitshort;
  2504. }
  2505. return $ret;
  2506. }
  2507. /**
  2508. * Show Url link
  2509. *
  2510. * @param string $url Url to show
  2511. * @param string $target Target for link
  2512. * @param int $max Max number of characters to show
  2513. * @param int $withpicto With picto
  2514. * @return string HTML Link
  2515. */
  2516. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2517. {
  2518. global $langs;
  2519. if (empty($url)) {
  2520. return '';
  2521. }
  2522. $link = '<a href="';
  2523. if (!preg_match('/^http/i', $url)) {
  2524. $link .= 'http://';
  2525. }
  2526. $link .= $url;
  2527. $link .= '"';
  2528. if ($target) {
  2529. $link .= ' target="'.$target.'"';
  2530. }
  2531. $link .= '>';
  2532. if (!preg_match('/^http/i', $url)) {
  2533. $link .= 'http://';
  2534. }
  2535. $link .= dol_trunc($url, $max);
  2536. $link .= '</a>';
  2537. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2538. }
  2539. /**
  2540. * Show EMail link formatted for HTML output.
  2541. *
  2542. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2543. * @param int $cid Id of contact if known
  2544. * @param int $socid Id of third party if known
  2545. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2546. * @param int $max Max number of characters to show
  2547. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2548. * @param int|string $withpicto Show picto
  2549. * @return string HTML Link
  2550. */
  2551. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2552. {
  2553. global $conf, $user, $langs, $hookmanager;
  2554. $newemail = dol_escape_htmltag($email);
  2555. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2556. $withpicto = 0;
  2557. }
  2558. if (empty($email)) {
  2559. return '&nbsp;';
  2560. }
  2561. if (!empty($addlink)) {
  2562. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2563. if (!preg_match('/^mailto:/i', $email)) {
  2564. $newemail .= 'mailto:';
  2565. }
  2566. $newemail .= $email;
  2567. $newemail .= '">';
  2568. $newemail .= dol_trunc($email, $max);
  2569. $newemail .= '</a>';
  2570. if ($showinvalid && !isValidEmail($email)) {
  2571. $langs->load("errors");
  2572. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2573. }
  2574. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2575. $type = 'AC_EMAIL';
  2576. $link = '';
  2577. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2578. $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>';
  2579. }
  2580. if ($link) {
  2581. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2582. }
  2583. }
  2584. } else {
  2585. if ($showinvalid && !isValidEmail($email)) {
  2586. $langs->load("errors");
  2587. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2588. }
  2589. }
  2590. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2591. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  2592. //$rep .= '</div>';
  2593. if ($hookmanager) {
  2594. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2595. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2596. if ($reshook > 0) {
  2597. $rep = '';
  2598. }
  2599. $rep .= $hookmanager->resPrint;
  2600. }
  2601. return $rep;
  2602. }
  2603. /**
  2604. * Get array of social network dictionary
  2605. *
  2606. * @return array Array of Social Networks Dictionary
  2607. */
  2608. function getArrayOfSocialNetworks()
  2609. {
  2610. global $conf, $db;
  2611. $socialnetworks = array();
  2612. // Enable caching of array
  2613. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2614. $cachekey = 'socialnetworks_' . $conf->entity;
  2615. $dataretrieved = dol_getcache($cachekey);
  2616. if (!is_null($dataretrieved)) {
  2617. $socialnetworks = $dataretrieved;
  2618. } else {
  2619. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2620. $sql .= " WHERE entity=".$conf->entity;
  2621. $resql = $db->query($sql);
  2622. if ($resql) {
  2623. while ($obj = $db->fetch_object($resql)) {
  2624. $socialnetworks[$obj->code] = array(
  2625. 'rowid' => $obj->rowid,
  2626. 'label' => $obj->label,
  2627. 'url' => $obj->url,
  2628. 'icon' => $obj->icon,
  2629. 'active' => $obj->active,
  2630. );
  2631. }
  2632. }
  2633. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2634. }
  2635. return $socialnetworks;
  2636. }
  2637. /**
  2638. * Show social network link
  2639. *
  2640. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2641. * @param int $cid Id of contact if known
  2642. * @param int $socid Id of third party if known
  2643. * @param string $type 'skype','facebook',...
  2644. * @param array $dictsocialnetworks socialnetworks availables
  2645. * @return string HTML Link
  2646. */
  2647. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2648. {
  2649. global $conf, $user, $langs;
  2650. $htmllink = $value;
  2651. if (empty($value)) {
  2652. return '&nbsp;';
  2653. }
  2654. if (!empty($type)) {
  2655. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2656. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2657. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2658. if ($type == 'skype') {
  2659. $htmllink .= dol_escape_htmltag($value);
  2660. $htmllink .= '&nbsp;';
  2661. $htmllink .= '<a href="skype:';
  2662. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2663. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  2664. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2665. $htmllink .= '</a><a href="skype:';
  2666. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2667. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  2668. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2669. $htmllink .= '</a>';
  2670. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2671. $addlink = 'AC_SKYPE';
  2672. $link = '';
  2673. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2674. $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>';
  2675. }
  2676. $htmllink .= ($link ? ' '.$link : '');
  2677. }
  2678. } else {
  2679. if (!empty($dictsocialnetworks[$type]['url'])) {
  2680. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2681. $htmllink .= '&nbsp;<a href="'.$link.'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  2682. } else {
  2683. $htmllink .= dol_escape_htmltag($value);
  2684. }
  2685. }
  2686. $htmllink .= '</div>';
  2687. } else {
  2688. $langs->load("errors");
  2689. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2690. }
  2691. return $htmllink;
  2692. }
  2693. /**
  2694. * Format profIDs according to country
  2695. *
  2696. * @param string $profID Value of profID to format
  2697. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  2698. * @param string $countrycode Country code to use for formatting
  2699. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  2700. * @param string $separ Separation between numbers for a better visibility example : xxx xxx xxx xxxxx
  2701. * @return string Formated profID
  2702. */
  2703. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
  2704. {
  2705. global $mysoc;
  2706. if (empty($profID) || empty($profIDtype)) {
  2707. return '';
  2708. }
  2709. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2710. $newProfID = $profID;
  2711. $id = substr($profIDtype, -1);
  2712. $ret = '';
  2713. if (strtoupper($countrycode) == 'FR') {
  2714. // France
  2715. if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
  2716. if ($id == 2 && dol_strlen($newProfID) == 14) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3).$separ.substr($newProfID, 9, 5);
  2717. if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) $newProfID = substr($newProfID, 0, 4).$separ.substr($newProfID, 4, 3).$separ.substr($newProfID, 7, 3).$separ.substr($newProfID, 10, 3);
  2718. }
  2719. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  2720. else $ret = $newProfID;
  2721. return $ret;
  2722. }
  2723. /**
  2724. * Format phone numbers according to country
  2725. *
  2726. * @param string $phone Phone number to format
  2727. * @param string $countrycode Country code to use for formatting
  2728. * @param int $cid Id of contact if known
  2729. * @param int $socid Id of third party if known
  2730. * @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)
  2731. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2732. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2733. * @param string $titlealt Text to show on alt
  2734. * @param int $adddivfloat Add div float around phone.
  2735. * @return string Formated phone number
  2736. */
  2737. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2738. {
  2739. global $conf, $user, $langs, $mysoc, $hookmanager;
  2740. // Clean phone parameter
  2741. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2742. if (empty($phone)) {
  2743. return '';
  2744. }
  2745. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2746. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2747. }
  2748. if (empty($countrycode)) {
  2749. $countrycode = $mysoc->country_code;
  2750. }
  2751. // Short format for small screens
  2752. if ($conf->dol_optimize_smallscreen) {
  2753. $separ = '';
  2754. }
  2755. $newphone = $phone;
  2756. if (strtoupper($countrycode) == "FR") {
  2757. // France
  2758. if (dol_strlen($phone) == 10) {
  2759. $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);
  2760. } elseif (dol_strlen($phone) == 7) {
  2761. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2762. } elseif (dol_strlen($phone) == 9) {
  2763. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2764. } elseif (dol_strlen($phone) == 11) {
  2765. $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);
  2766. } elseif (dol_strlen($phone) == 12) {
  2767. $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);
  2768. }
  2769. } elseif (strtoupper($countrycode) == "CA") {
  2770. if (dol_strlen($phone) == 10) {
  2771. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2772. }
  2773. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2774. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2775. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2776. }
  2777. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2778. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2779. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2780. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2781. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2782. }
  2783. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2784. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2785. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2786. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2787. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2788. }
  2789. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2790. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2791. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2792. }
  2793. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2794. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2795. $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);
  2796. }
  2797. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2798. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2799. $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);
  2800. }
  2801. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2802. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2803. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2804. }
  2805. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2806. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2807. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2808. }
  2809. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2810. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2811. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2812. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2813. $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);
  2814. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2815. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2816. }
  2817. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2818. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2819. $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);
  2820. }
  2821. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2822. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2823. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2824. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2825. $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);
  2826. }
  2827. } elseif (strtoupper($countrycode) == "MU") {
  2828. //Maurice
  2829. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  2830. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2831. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  2832. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2833. }
  2834. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  2835. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  2836. $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);
  2837. }
  2838. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  2839. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  2840. $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);
  2841. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  2842. $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);
  2843. }
  2844. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  2845. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  2846. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2847. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  2848. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2849. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  2850. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2851. }
  2852. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  2853. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  2854. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2855. }
  2856. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  2857. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  2858. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2859. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  2860. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2861. }
  2862. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  2863. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  2864. $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);
  2865. }
  2866. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  2867. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  2868. $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);
  2869. }
  2870. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  2871. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  2872. $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);
  2873. }
  2874. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  2875. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  2876. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2877. }
  2878. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  2879. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
  2880. $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);
  2881. }
  2882. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  2883. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  2884. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2885. }
  2886. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  2887. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  2888. $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);
  2889. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  2890. $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);
  2891. }
  2892. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  2893. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  2894. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2895. }
  2896. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  2897. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2898. $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);
  2899. }
  2900. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  2901. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2902. $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);
  2903. }
  2904. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  2905. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2906. $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);
  2907. }
  2908. } elseif (strtoupper($countrycode) == "IT") {//Italie
  2909. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  2910. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2911. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  2912. $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);
  2913. }
  2914. } elseif (strtoupper($countrycode) == "AU") {
  2915. //Australie
  2916. if (dol_strlen($phone) == 12) {
  2917. //ex: +61_A_BCDE_FGHI
  2918. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2919. }
  2920. }
  2921. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2922. 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
  2923. $newphoneform = $newphone;
  2924. $newphone = '<a href="tel:'.$phone.'"';
  2925. $newphone .= '>'.$newphoneform.'</a>';
  2926. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  2927. if (empty($user->clicktodial_loaded)) {
  2928. $user->fetch_clicktodial();
  2929. }
  2930. // Define urlmask
  2931. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2932. if (!empty($conf->global->CLICKTODIAL_URL)) {
  2933. $urlmask = $conf->global->CLICKTODIAL_URL;
  2934. }
  2935. if (!empty($user->clicktodial_url)) {
  2936. $urlmask = $user->clicktodial_url;
  2937. }
  2938. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2939. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2940. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2941. // This line is for backward compatibility
  2942. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2943. // Thoose lines are for substitution
  2944. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2945. '__PHONETO__'=>urlencode($phone),
  2946. '__LOGIN__'=>$clicktodial_login,
  2947. '__PASS__'=>$clicktodial_password);
  2948. $url = make_substitutions($url, $substitarray);
  2949. $newphonesav = $newphone;
  2950. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  2951. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  2952. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  2953. $newphone .= '>'.$newphonesav.'</a>';
  2954. } else {
  2955. // Old method
  2956. $newphone = '<a href="'.$url.'"';
  2957. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  2958. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  2959. }
  2960. $newphone .= '>'.$newphonesav.'</a>';
  2961. }
  2962. }
  2963. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2964. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2965. $type = 'AC_TEL';
  2966. $link = '';
  2967. if ($addlink == 'AC_FAX') {
  2968. $type = 'AC_FAX';
  2969. }
  2970. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  2971. $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>';
  2972. }
  2973. if ($link) {
  2974. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2975. }
  2976. }
  2977. }
  2978. if (empty($titlealt)) {
  2979. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2980. }
  2981. $rep = '';
  2982. if ($hookmanager) {
  2983. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2984. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2985. $rep .= $hookmanager->resPrint;
  2986. }
  2987. if (empty($reshook)) {
  2988. $picto = '';
  2989. if ($withpicto) {
  2990. if ($withpicto == 'fax') {
  2991. $picto = 'phoning_fax';
  2992. } elseif ($withpicto == 'phone') {
  2993. $picto = 'phoning';
  2994. } elseif ($withpicto == 'mobile') {
  2995. $picto = 'phoning_mobile';
  2996. } else {
  2997. $picto = '';
  2998. }
  2999. }
  3000. if ($adddivfloat) {
  3001. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3002. } else {
  3003. $rep .= '<span style="margin-right: 10px;">';
  3004. }
  3005. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  3006. if ($adddivfloat) {
  3007. $rep .= '</div>';
  3008. } else {
  3009. $rep .= '</span>';
  3010. }
  3011. }
  3012. return $rep;
  3013. }
  3014. /**
  3015. * Return an IP formated to be shown on screen
  3016. *
  3017. * @param string $ip IP
  3018. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3019. * @return string Formated IP, with country if GeoIP module is enabled
  3020. */
  3021. function dol_print_ip($ip, $mode = 0)
  3022. {
  3023. global $conf, $langs;
  3024. $ret = '';
  3025. if (empty($mode)) {
  3026. $ret .= $ip;
  3027. }
  3028. if ($mode != 2) {
  3029. $countrycode = dolGetCountryCodeFromIp($ip);
  3030. if ($countrycode) { // If success, countrycode is us, fr, ...
  3031. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3032. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3033. } else {
  3034. $ret .= ' ('.$countrycode.')';
  3035. }
  3036. } else {
  3037. // Nothing
  3038. }
  3039. }
  3040. return $ret;
  3041. }
  3042. /**
  3043. * Return the IP of remote user.
  3044. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3045. * Then HTTP_CLIENT_IP if defined (rare)
  3046. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3047. *
  3048. * @return string Ip of remote user.
  3049. */
  3050. function getUserRemoteIP()
  3051. {
  3052. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3053. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3054. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3055. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3056. } else {
  3057. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3058. }
  3059. } else {
  3060. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3061. }
  3062. } else {
  3063. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3064. }
  3065. return $ip;
  3066. }
  3067. /**
  3068. * Return if we are using a HTTPS connexion
  3069. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3070. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3071. * Then HTTP_X_FORWARDED_SSL
  3072. *
  3073. * @return boolean True if user is using HTTPS
  3074. */
  3075. function isHTTPS()
  3076. {
  3077. $isSecure = false;
  3078. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3079. $isSecure = true;
  3080. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
  3081. $isSecure = true;
  3082. }
  3083. return $isSecure;
  3084. }
  3085. /**
  3086. * Return a country code from IP. Empty string if not found.
  3087. *
  3088. * @param string $ip IP
  3089. * @return string Country code ('us', 'fr', ...)
  3090. */
  3091. function dolGetCountryCodeFromIp($ip)
  3092. {
  3093. global $conf;
  3094. $countrycode = '';
  3095. if (!empty($conf->geoipmaxmind->enabled)) {
  3096. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3097. //$ip='24.24.24.24';
  3098. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3099. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3100. $geoip = new DolGeoIP('country', $datafile);
  3101. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3102. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3103. }
  3104. return $countrycode;
  3105. }
  3106. /**
  3107. * Return country code for current user.
  3108. * If software is used inside a local network, detection may fails (we need a public ip)
  3109. *
  3110. * @return string Country code (fr, es, it, us, ...)
  3111. */
  3112. function dol_user_country()
  3113. {
  3114. global $conf, $langs, $user;
  3115. //$ret=$user->xxx;
  3116. $ret = '';
  3117. if (!empty($conf->geoipmaxmind->enabled)) {
  3118. $ip = getUserRemoteIP();
  3119. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3120. //$ip='24.24.24.24';
  3121. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3122. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3123. $geoip = new DolGeoIP('country', $datafile);
  3124. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3125. $ret = $countrycode;
  3126. }
  3127. return $ret;
  3128. }
  3129. /**
  3130. * Format address string
  3131. *
  3132. * @param string $address Address string, already formatted with dol_format_address()
  3133. * @param int $htmlid Html ID (for example 'gmap')
  3134. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3135. * @param int $id Id of object
  3136. * @param int $noprint No output. Result is the function return
  3137. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3138. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3139. * @see dol_format_address()
  3140. */
  3141. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3142. {
  3143. global $conf, $user, $langs, $hookmanager;
  3144. $out = '';
  3145. if ($address) {
  3146. if ($hookmanager) {
  3147. $parameters = array('element' => $element, 'id' => $id);
  3148. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3149. $out .= $hookmanager->resPrint;
  3150. }
  3151. if (empty($reshook)) {
  3152. if (empty($charfornl)) {
  3153. $out .= nl2br($address);
  3154. } else {
  3155. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3156. }
  3157. // TODO Remove this block, we can add this using the hook now
  3158. $showgmap = $showomap = 0;
  3159. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3160. $showgmap = 1;
  3161. }
  3162. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3163. $showgmap = 1;
  3164. }
  3165. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3166. $showgmap = 1;
  3167. }
  3168. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3169. $showomap = 1;
  3170. }
  3171. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3172. $showomap = 1;
  3173. }
  3174. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3175. $showomap = 1;
  3176. }
  3177. if ($showgmap) {
  3178. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3179. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3180. }
  3181. if ($showomap) {
  3182. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3183. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3184. }
  3185. }
  3186. }
  3187. if ($noprint) {
  3188. return $out;
  3189. } else {
  3190. print $out;
  3191. }
  3192. }
  3193. /**
  3194. * Return true if email syntax is ok.
  3195. *
  3196. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3197. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3198. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3199. * @return boolean true if email syntax is OK, false if KO or empty string
  3200. * @see isValidMXRecord()
  3201. */
  3202. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3203. {
  3204. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3205. return true;
  3206. }
  3207. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3208. return true;
  3209. }
  3210. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3211. return true;
  3212. }
  3213. return false;
  3214. }
  3215. /**
  3216. * Return if the domain name has a valid MX record.
  3217. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3218. *
  3219. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3220. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3221. * @see isValidEmail()
  3222. */
  3223. function isValidMXRecord($domain)
  3224. {
  3225. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3226. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3227. return 0;
  3228. }
  3229. if (function_exists('getmxrr')) {
  3230. $mxhosts = array();
  3231. $weight = array();
  3232. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3233. if (count($mxhosts) > 1) {
  3234. return 1;
  3235. }
  3236. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3237. return 1;
  3238. }
  3239. return 0;
  3240. }
  3241. }
  3242. return -1;
  3243. }
  3244. /**
  3245. * Return true if phone number syntax is ok
  3246. * TODO Decide what to do with this
  3247. *
  3248. * @param string $phone phone (Ex: "0601010101")
  3249. * @return boolean true if phone syntax is OK, false if KO or empty string
  3250. */
  3251. function isValidPhone($phone)
  3252. {
  3253. return true;
  3254. }
  3255. /**
  3256. * Make a strlen call. Works even if mbstring module not enabled
  3257. *
  3258. * @param string $string String to calculate length
  3259. * @param string $stringencoding Encoding of string
  3260. * @return int Length of string
  3261. */
  3262. function dol_strlen($string, $stringencoding = 'UTF-8')
  3263. {
  3264. if (function_exists('mb_strlen')) {
  3265. return mb_strlen($string, $stringencoding);
  3266. } else {
  3267. return strlen($string);
  3268. }
  3269. }
  3270. /**
  3271. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3272. *
  3273. * @param string $string String to scan
  3274. * @param string $start Start position
  3275. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3276. * @param string $stringencoding Page code used for input string encoding
  3277. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3278. * @return string substring
  3279. */
  3280. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3281. {
  3282. global $langs;
  3283. if (empty($stringencoding)) {
  3284. $stringencoding = $langs->charset_output;
  3285. }
  3286. $ret = '';
  3287. if (empty($trunconbytes)) {
  3288. if (function_exists('mb_substr')) {
  3289. $ret = mb_substr($string, $start, $length, $stringencoding);
  3290. } else {
  3291. $ret = substr($string, $start, $length);
  3292. }
  3293. } else {
  3294. if (function_exists('mb_strcut')) {
  3295. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3296. } else {
  3297. $ret = substr($string, $start, $length);
  3298. }
  3299. }
  3300. return $ret;
  3301. }
  3302. /**
  3303. * Truncate a string to a particular length adding '…' if string larger than length.
  3304. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3305. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3306. *
  3307. * @param string $string String to truncate
  3308. * @param int $size Max string size visible (excluding …). 0 for no limit. WARNING: Final string size can have 3 more chars (if we added …, or if size was max+1 so it does not worse to replace with ...)
  3309. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3310. * @param string $stringencoding Tell what is source string encoding
  3311. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3312. * @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)
  3313. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3314. */
  3315. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3316. {
  3317. global $conf;
  3318. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3319. return $string;
  3320. }
  3321. if (empty($stringencoding)) {
  3322. $stringencoding = 'UTF-8';
  3323. }
  3324. // reduce for small screen
  3325. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3326. $size = round($size / 3);
  3327. }
  3328. // We go always here
  3329. if ($trunc == 'right') {
  3330. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3331. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3332. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3333. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3334. } else {
  3335. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3336. return $string;
  3337. }
  3338. } elseif ($trunc == 'middle') {
  3339. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3340. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3341. $size1 = round($size / 2);
  3342. $size2 = round($size / 2);
  3343. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3344. } else {
  3345. return $string;
  3346. }
  3347. } elseif ($trunc == 'left') {
  3348. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3349. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3350. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3351. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3352. } else {
  3353. return $string;
  3354. }
  3355. } elseif ($trunc == 'wrap') {
  3356. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3357. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3358. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3359. } else {
  3360. return $string;
  3361. }
  3362. } else {
  3363. return 'BadParam3CallingDolTrunc';
  3364. }
  3365. }
  3366. /**
  3367. * Show picto whatever it's its name (generic function)
  3368. *
  3369. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3370. * @param string $picto Name of image file to show ('filenew', ...)
  3371. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3372. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3373. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3374. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3375. * Example: fontawesome_envelope-open-text_fas_red_1em if you want to use fontaweseome icons: fontawesome_<icon-name>_<style>_<color>_<size> (only icon-name is mandatory)
  3376. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3377. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3378. * @param int $srconly Return only content of the src attribute of img.
  3379. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3380. * @param string $alt Force alt for bind people
  3381. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3382. * @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.
  3383. * @return string Return img tag
  3384. * @see img_object(), img_picto_common()
  3385. */
  3386. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3387. {
  3388. global $conf, $langs;
  3389. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3390. $url = DOL_URL_ROOT;
  3391. $theme = isset($conf->theme) ? $conf->theme : null;
  3392. $path = 'theme/'.$theme;
  3393. // Define fullpathpicto to use into src
  3394. if ($pictoisfullpath) {
  3395. // Clean parameters
  3396. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3397. $picto .= '.png';
  3398. }
  3399. $fullpathpicto = $picto;
  3400. $reg = array();
  3401. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3402. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3403. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3404. }
  3405. } else {
  3406. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3407. if (strpos($pictowithouttext, 'fontawesome_') !== false) {
  3408. $pictowithouttext = explode('_', $pictowithouttext);
  3409. $marginleftonlyshort = 0;
  3410. $fakey = 'fa-'.$pictowithouttext[1];
  3411. $fa = $pictowithouttext[2] ? $pictowithouttext[2] : 'fa';
  3412. $facolor = $pictowithouttext[3] ? $pictowithouttext[3] : '';
  3413. $fasize = $pictowithouttext[4] ? $pictowithouttext[4] : '';
  3414. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3415. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3416. $morestyle = '';
  3417. $reg = array();
  3418. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3419. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3420. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3421. }
  3422. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3423. $morestyle = $reg[1];
  3424. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3425. }
  3426. $moreatt = trim($moreatt);
  3427. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3428. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3429. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3430. $enabledisablehtml .= $titlealt;
  3431. }*/
  3432. $enabledisablehtml .= '</span>';
  3433. return $enabledisablehtml;
  3434. }
  3435. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3436. if (empty($srconly) && in_array($pictowithouttext, array(
  3437. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3438. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3439. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  3440. 'card', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3441. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3442. 'currency', 'multicurrency',
  3443. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3444. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3445. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3446. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3447. 'help', 'holiday',
  3448. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3449. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3450. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3451. 'off', 'on', 'order',
  3452. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'puce',
  3453. 'stock', 'resize', 'service', 'stats', 'trip',
  3454. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3455. 'github', 'google', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3456. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3457. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3458. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3459. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3460. 'technic', 'ticket',
  3461. 'error', 'warning',
  3462. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource', 'recurring',
  3463. 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3464. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3465. 'uncheck', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation',
  3466. 'conferenceorbooth', 'eventorganization'
  3467. ))) {
  3468. $fakey = $pictowithouttext;
  3469. $facolor = '';
  3470. $fasize = '';
  3471. $fa = 'fas';
  3472. if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3473. $fa = 'far';
  3474. }
  3475. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3476. $fa = 'fab';
  3477. }
  3478. $arrayconvpictotofa = array(
  3479. 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  3480. 'bank_account'=>'university',
  3481. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3482. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3483. 'bom'=>'shapes',
  3484. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3485. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3486. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3487. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3488. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3489. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3490. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3491. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3492. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3493. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  3494. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3495. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3496. 'sign-out'=>'sign-out-alt',
  3497. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3498. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3499. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3500. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'currency'=>'dollar-sign', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3501. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3502. 'other'=>'square',
  3503. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3504. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
  3505. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3506. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3507. 'refresh'=>'redo', 'region'=>'map-marked', 'resource'=>'laptop-house', 'recurring'=>'history',
  3508. 'service'=>'concierge-bell',
  3509. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3510. 'supplier'=>'building', 'technic'=>'cogs',
  3511. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3512. 'title_agenda'=>'calendar-alt',
  3513. 'uncheck'=>'times', 'uparrow'=>'share', 'vat'=>'money-check-alt', 'vcard'=>'address-card',
  3514. 'jabber'=>'comment-o',
  3515. 'website'=>'globe-americas', 'workstation'=>'pallet',
  3516. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3517. );
  3518. if ($pictowithouttext == 'off') {
  3519. $fakey = 'fa-square';
  3520. $fasize = '1.3em';
  3521. } elseif ($pictowithouttext == 'on') {
  3522. $fakey = 'fa-check-square';
  3523. $fasize = '1.3em';
  3524. } elseif ($pictowithouttext == 'listlight') {
  3525. $fakey = 'fa-download';
  3526. $marginleftonlyshort = 1;
  3527. } elseif ($pictowithouttext == 'printer') {
  3528. $fakey = 'fa-print';
  3529. $fasize = '1.2em';
  3530. } elseif ($pictowithouttext == 'note') {
  3531. $fakey = 'fa-sticky-note';
  3532. $marginleftonlyshort = 1;
  3533. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3534. $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');
  3535. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3536. if (preg_match('/selected/', $pictowithouttext)) {
  3537. $facolor = '#888';
  3538. }
  3539. $marginleftonlyshort = 1;
  3540. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3541. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3542. } else {
  3543. $fakey = 'fa-'.$pictowithouttext;
  3544. }
  3545. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3546. $morecss .= ' em092';
  3547. }
  3548. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3549. $morecss .= ' em088';
  3550. }
  3551. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3552. $morecss .= ' em080';
  3553. }
  3554. // Define $marginleftonlyshort
  3555. $arrayconvpictotomarginleftonly = array(
  3556. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3557. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3558. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3559. );
  3560. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3561. $marginleftonlyshort = 0;
  3562. }
  3563. // Add CSS
  3564. $arrayconvpictotomorcess = array(
  3565. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3566. 'bank_account'=>'bg-infobox-bank_account',
  3567. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3568. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3569. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3570. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3571. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3572. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3573. 'incoterm'=>'infobox-supplier_proposal',
  3574. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  3575. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3576. 'order'=>'infobox-commande',
  3577. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3578. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_red'=>'font-status8',
  3579. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3580. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3581. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  3582. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3583. 'resource'=>'infobox-action',
  3584. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3585. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3586. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3587. 'vat'=>'infobox-bank_account',
  3588. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3589. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3590. );
  3591. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3592. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3593. }
  3594. // Define $color
  3595. $arrayconvpictotocolor = array(
  3596. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3597. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3598. 'dynamicprice'=>'#a69944',
  3599. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3600. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3601. 'lot'=>'#a69944',
  3602. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3603. 'other'=>'#ddd',
  3604. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3605. //'shipment'=>'#a69944',
  3606. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3607. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3608. 'website'=>'#304', 'workstation'=>'#a69944'
  3609. );
  3610. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3611. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3612. }
  3613. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3614. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3615. $morestyle = '';
  3616. $reg = array();
  3617. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3618. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3619. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3620. }
  3621. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3622. $morestyle = $reg[1];
  3623. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3624. }
  3625. $moreatt = trim($moreatt);
  3626. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3627. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3628. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3629. $enabledisablehtml .= $titlealt;
  3630. }*/
  3631. $enabledisablehtml .= '</span>';
  3632. return $enabledisablehtml;
  3633. }
  3634. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3635. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3636. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3637. $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
  3638. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3639. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3640. }
  3641. // If we ask an image into $url/$mymodule/img (instead of default path)
  3642. $regs = array();
  3643. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3644. $picto = $regs[1];
  3645. $path = $regs[2]; // $path is $mymodule
  3646. }
  3647. // Clean parameters
  3648. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3649. $picto .= '.png';
  3650. }
  3651. // If alt path are defined, define url where img file is, according to physical path
  3652. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3653. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3654. if ($type == 'main') {
  3655. continue;
  3656. }
  3657. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3658. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3659. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3660. break;
  3661. }
  3662. }
  3663. // $url is '' or '/custom', $path is current theme or
  3664. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3665. }
  3666. if ($srconly) {
  3667. return $fullpathpicto;
  3668. }
  3669. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3670. return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dol_escape_htmltag($alt).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
  3671. }
  3672. /**
  3673. * Show a picto called object_picto (generic function)
  3674. *
  3675. * @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.
  3676. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3677. * For external modules use imagename@mymodule to search into directory "img" of module.
  3678. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3679. * @param int $pictoisfullpath If 1, image path is a full path
  3680. * @param int $srconly Return only content of the src attribute of img.
  3681. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3682. * @return string Return img tag
  3683. * @see img_picto(), img_picto_common()
  3684. */
  3685. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3686. {
  3687. if (strpos($picto, '^') === 0) {
  3688. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3689. } else {
  3690. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3691. }
  3692. }
  3693. /**
  3694. * Show weather picto
  3695. *
  3696. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3697. * @param string|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).
  3698. * @param string $moreatt Add more attribute on img tag
  3699. * @param int $pictoisfullpath If 1, image path is a full path
  3700. * @param string $morecss More CSS
  3701. * @return string Return img tag
  3702. * @see img_object(), img_picto()
  3703. */
  3704. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3705. {
  3706. global $conf;
  3707. if (is_numeric($picto)) {
  3708. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3709. //$picto = $leveltopicto[$picto];
  3710. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3711. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3712. $picto .= '.png';
  3713. }
  3714. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3715. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3716. }
  3717. /**
  3718. * Show picto (generic function)
  3719. *
  3720. * @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.
  3721. * @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.
  3722. * @param string $moreatt Add more attribute on img tag
  3723. * @param int $pictoisfullpath If 1, image path is a full path
  3724. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3725. * @return string Return img tag
  3726. * @see img_object(), img_picto()
  3727. */
  3728. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  3729. {
  3730. global $conf;
  3731. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3732. $picto .= '.png';
  3733. }
  3734. if ($pictoisfullpath) {
  3735. $path = $picto;
  3736. } else {
  3737. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3738. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3739. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3740. if (file_exists($themepath)) {
  3741. $path = $themepath;
  3742. }
  3743. }
  3744. }
  3745. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  3746. }
  3747. /**
  3748. * Show logo action
  3749. *
  3750. * @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.
  3751. * @param string $numaction Action id or code to show
  3752. * @param string $picto Name of image file to show ('filenew', ...)
  3753. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3754. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3755. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3756. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3757. * @return string Return an img tag
  3758. */
  3759. function img_action($titlealt, $numaction, $picto = '')
  3760. {
  3761. global $langs;
  3762. if (empty($titlealt) || $titlealt == 'default') {
  3763. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3764. $numaction = -1;
  3765. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3766. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3767. $numaction = 0;
  3768. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3769. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3770. $numaction = 1;
  3771. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3772. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3773. $numaction = 2;
  3774. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3775. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3776. $numaction = 3;
  3777. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3778. } else {
  3779. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3780. $numaction = 0;
  3781. }
  3782. }
  3783. if (!is_numeric($numaction)) {
  3784. $numaction = 0;
  3785. }
  3786. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3787. }
  3788. /**
  3789. * Show pdf logo
  3790. *
  3791. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3792. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3793. * @return string Retourne tag img
  3794. */
  3795. function img_pdf($titlealt = 'default', $size = 3)
  3796. {
  3797. global $langs;
  3798. if ($titlealt == 'default') {
  3799. $titlealt = $langs->trans('Show');
  3800. }
  3801. return img_picto($titlealt, 'pdf'.$size.'.png');
  3802. }
  3803. /**
  3804. * Show logo +
  3805. *
  3806. * @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.
  3807. * @param string $other Add more attributes on img
  3808. * @return string Return tag img
  3809. */
  3810. function img_edit_add($titlealt = 'default', $other = '')
  3811. {
  3812. global $langs;
  3813. if ($titlealt == 'default') {
  3814. $titlealt = $langs->trans('Add');
  3815. }
  3816. return img_picto($titlealt, 'edit_add.png', $other);
  3817. }
  3818. /**
  3819. * Show logo -
  3820. *
  3821. * @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.
  3822. * @param string $other Add more attributes on img
  3823. * @return string Return tag img
  3824. */
  3825. function img_edit_remove($titlealt = 'default', $other = '')
  3826. {
  3827. global $langs;
  3828. if ($titlealt == 'default') {
  3829. $titlealt = $langs->trans('Remove');
  3830. }
  3831. return img_picto($titlealt, 'edit_remove.png', $other);
  3832. }
  3833. /**
  3834. * Show logo editer/modifier fiche
  3835. *
  3836. * @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.
  3837. * @param integer $float If you have to put the style "float: right"
  3838. * @param string $other Add more attributes on img
  3839. * @return string Return tag img
  3840. */
  3841. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3842. {
  3843. global $langs;
  3844. if ($titlealt == 'default') {
  3845. $titlealt = $langs->trans('Modify');
  3846. }
  3847. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3848. }
  3849. /**
  3850. * Show logo view card
  3851. *
  3852. * @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.
  3853. * @param integer $float If you have to put the style "float: right"
  3854. * @param string $other Add more attributes on img
  3855. * @return string Return tag img
  3856. */
  3857. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  3858. {
  3859. global $langs;
  3860. if ($titlealt == 'default') {
  3861. $titlealt = $langs->trans('View');
  3862. }
  3863. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3864. return img_picto($titlealt, 'view.png', $moreatt);
  3865. }
  3866. /**
  3867. * Show delete logo
  3868. *
  3869. * @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.
  3870. * @param string $other Add more attributes on img
  3871. * @param string $morecss More CSS
  3872. * @return string Retourne tag img
  3873. */
  3874. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3875. {
  3876. global $langs;
  3877. if ($titlealt == 'default') {
  3878. $titlealt = $langs->trans('Delete');
  3879. }
  3880. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3881. }
  3882. /**
  3883. * Show printer logo
  3884. *
  3885. * @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.
  3886. * @param string $other Add more attributes on img
  3887. * @return string Retourne tag img
  3888. */
  3889. function img_printer($titlealt = "default", $other = '')
  3890. {
  3891. global $langs;
  3892. if ($titlealt == "default") {
  3893. $titlealt = $langs->trans("Print");
  3894. }
  3895. return img_picto($titlealt, 'printer.png', $other);
  3896. }
  3897. /**
  3898. * Show split logo
  3899. *
  3900. * @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.
  3901. * @param string $other Add more attributes on img
  3902. * @return string Retourne tag img
  3903. */
  3904. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3905. {
  3906. global $langs;
  3907. if ($titlealt == 'default') {
  3908. $titlealt = $langs->trans('Split');
  3909. }
  3910. return img_picto($titlealt, 'split.png', $other);
  3911. }
  3912. /**
  3913. * Show help logo with cursor "?"
  3914. *
  3915. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3916. * @param int|string $usealttitle Text to use as alt title
  3917. * @return string Return tag img
  3918. */
  3919. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3920. {
  3921. global $langs;
  3922. if ($usealttitle) {
  3923. if (is_string($usealttitle)) {
  3924. $usealttitle = dol_escape_htmltag($usealttitle);
  3925. } else {
  3926. $usealttitle = $langs->trans('Info');
  3927. }
  3928. }
  3929. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3930. }
  3931. /**
  3932. * Show info logo
  3933. *
  3934. * @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.
  3935. * @return string Return img tag
  3936. */
  3937. function img_info($titlealt = 'default')
  3938. {
  3939. global $langs;
  3940. if ($titlealt == 'default') {
  3941. $titlealt = $langs->trans('Informations');
  3942. }
  3943. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3944. }
  3945. /**
  3946. * Show warning logo
  3947. *
  3948. * @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.
  3949. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3950. * @param string $morecss Add more CSS
  3951. * @return string Return img tag
  3952. */
  3953. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3954. {
  3955. global $langs;
  3956. if ($titlealt == 'default') {
  3957. $titlealt = $langs->trans('Warning');
  3958. }
  3959. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3960. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3961. }
  3962. /**
  3963. * Show error logo
  3964. *
  3965. * @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.
  3966. * @return string Return img tag
  3967. */
  3968. function img_error($titlealt = 'default')
  3969. {
  3970. global $langs;
  3971. if ($titlealt == 'default') {
  3972. $titlealt = $langs->trans('Error');
  3973. }
  3974. return img_picto($titlealt, 'error.png');
  3975. }
  3976. /**
  3977. * Show next logo
  3978. *
  3979. * @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.
  3980. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3981. * @return string Return img tag
  3982. */
  3983. function img_next($titlealt = 'default', $moreatt = '')
  3984. {
  3985. global $langs;
  3986. if ($titlealt == 'default') {
  3987. $titlealt = $langs->trans('Next');
  3988. }
  3989. //return img_picto($titlealt, 'next.png', $moreatt);
  3990. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3991. }
  3992. /**
  3993. * Show previous logo
  3994. *
  3995. * @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.
  3996. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3997. * @return string Return img tag
  3998. */
  3999. function img_previous($titlealt = 'default', $moreatt = '')
  4000. {
  4001. global $langs;
  4002. if ($titlealt == 'default') {
  4003. $titlealt = $langs->trans('Previous');
  4004. }
  4005. //return img_picto($titlealt, 'previous.png', $moreatt);
  4006. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4007. }
  4008. /**
  4009. * Show down arrow logo
  4010. *
  4011. * @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.
  4012. * @param int $selected Selected
  4013. * @param string $moreclass Add more CSS classes
  4014. * @return string Return img tag
  4015. */
  4016. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4017. {
  4018. global $langs;
  4019. if ($titlealt == 'default') {
  4020. $titlealt = $langs->trans('Down');
  4021. }
  4022. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4023. }
  4024. /**
  4025. * Show top arrow logo
  4026. *
  4027. * @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.
  4028. * @param int $selected Selected
  4029. * @param string $moreclass Add more CSS classes
  4030. * @return string Return img tag
  4031. */
  4032. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4033. {
  4034. global $langs;
  4035. if ($titlealt == 'default') {
  4036. $titlealt = $langs->trans('Up');
  4037. }
  4038. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4039. }
  4040. /**
  4041. * Show left arrow logo
  4042. *
  4043. * @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.
  4044. * @param int $selected Selected
  4045. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4046. * @return string Return img tag
  4047. */
  4048. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4049. {
  4050. global $langs;
  4051. if ($titlealt == 'default') {
  4052. $titlealt = $langs->trans('Left');
  4053. }
  4054. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4055. }
  4056. /**
  4057. * Show right arrow logo
  4058. *
  4059. * @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.
  4060. * @param int $selected Selected
  4061. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4062. * @return string Return img tag
  4063. */
  4064. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4065. {
  4066. global $langs;
  4067. if ($titlealt == 'default') {
  4068. $titlealt = $langs->trans('Right');
  4069. }
  4070. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4071. }
  4072. /**
  4073. * Show tick logo if allowed
  4074. *
  4075. * @param string $allow Allow
  4076. * @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.
  4077. * @return string Return img tag
  4078. */
  4079. function img_allow($allow, $titlealt = 'default')
  4080. {
  4081. global $langs;
  4082. if ($titlealt == 'default') {
  4083. $titlealt = $langs->trans('Active');
  4084. }
  4085. if ($allow == 1) {
  4086. return img_picto($titlealt, 'tick.png');
  4087. }
  4088. return '-';
  4089. }
  4090. /**
  4091. * Return image of a credit card according to its brand name
  4092. *
  4093. * @param string $brand Brand name of credit card
  4094. * @param string $morecss More CSS
  4095. * @return string Return img tag
  4096. */
  4097. function img_credit_card($brand, $morecss = null)
  4098. {
  4099. if (is_null($morecss)) {
  4100. $morecss = 'fa-2x';
  4101. }
  4102. if ($brand == 'visa' || $brand == 'Visa') {
  4103. $brand = 'cc-visa';
  4104. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4105. $brand = 'cc-mastercard';
  4106. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4107. $brand = 'cc-amex';
  4108. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4109. $brand = 'cc-discover';
  4110. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4111. $brand = 'cc-jcb';
  4112. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4113. $brand = 'cc-diners-club';
  4114. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4115. $brand = 'credit-card';
  4116. }
  4117. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4118. }
  4119. /**
  4120. * Show MIME img of a file
  4121. *
  4122. * @param string $file Filename
  4123. * @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.
  4124. * @param string $morecss More css
  4125. * @return string Return img tag
  4126. */
  4127. function img_mime($file, $titlealt = '', $morecss = '')
  4128. {
  4129. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4130. $mimetype = dol_mimetype($file, '', 1);
  4131. $mimeimg = dol_mimetype($file, '', 2);
  4132. $mimefa = dol_mimetype($file, '', 4);
  4133. if (empty($titlealt)) {
  4134. $titlealt = 'Mime type: '.$mimetype;
  4135. }
  4136. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4137. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4138. }
  4139. /**
  4140. * Show search logo
  4141. *
  4142. * @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.
  4143. * @param string $other Add more attributes on img
  4144. * @return string Retourne tag img
  4145. */
  4146. function img_search($titlealt = 'default', $other = '')
  4147. {
  4148. global $conf, $langs;
  4149. if ($titlealt == 'default') {
  4150. $titlealt = $langs->trans('Search');
  4151. }
  4152. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4153. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4154. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4155. return $input;
  4156. }
  4157. /**
  4158. * Show search logo
  4159. *
  4160. * @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.
  4161. * @param string $other Add more attributes on img
  4162. * @return string Retourne tag img
  4163. */
  4164. function img_searchclear($titlealt = 'default', $other = '')
  4165. {
  4166. global $conf, $langs;
  4167. if ($titlealt == 'default') {
  4168. $titlealt = $langs->trans('Search');
  4169. }
  4170. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4171. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4172. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4173. return $input;
  4174. }
  4175. /**
  4176. * Show information for admin users or standard users
  4177. *
  4178. * @param string $text Text info
  4179. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4180. * @param int $nodiv No div
  4181. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4182. * @param string $morecss More CSS ('', 'warning', 'error')
  4183. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4184. * @return string String with info text
  4185. */
  4186. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4187. {
  4188. global $conf, $langs;
  4189. if ($infoonimgalt) {
  4190. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4191. } else {
  4192. if (empty($conf->use_javascript_ajax)) {
  4193. $textfordropdown = '';
  4194. }
  4195. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4196. $result = ($nodiv ? '' : '<div class="'.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  4197. if ($textfordropdown) {
  4198. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4199. $tmpresult .= '<script type="text/javascript">
  4200. jQuery(document).ready(function() {
  4201. jQuery(".'.$class.'text").click(function() {
  4202. console.log("toggle text");
  4203. jQuery(".'.$class.'").toggle();
  4204. });
  4205. });
  4206. </script>';
  4207. $result = $tmpresult.$result;
  4208. }
  4209. }
  4210. return $result;
  4211. }
  4212. /**
  4213. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4214. * This function must be called when a blocking technical error is encountered.
  4215. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4216. *
  4217. * @param DoliDB|string $db Database handler
  4218. * @param string|string[] $error String or array of errors strings to show
  4219. * @param array $errors Array of errors
  4220. * @return void
  4221. * @see dol_htmloutput_errors()
  4222. */
  4223. function dol_print_error($db = '', $error = '', $errors = null)
  4224. {
  4225. global $conf, $langs, $argv;
  4226. global $dolibarr_main_prod;
  4227. $out = '';
  4228. $syslog = '';
  4229. // If error occurs before the $lang object was loaded
  4230. if (!$langs) {
  4231. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4232. $langs = new Translate('', $conf);
  4233. $langs->load("main");
  4234. }
  4235. // Load translation files required by the error messages
  4236. $langs->loadLangs(array('main', 'errors'));
  4237. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4238. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4239. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4240. $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";
  4241. }
  4242. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4243. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4244. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4245. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4246. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4247. }
  4248. if (function_exists("phpversion")) {
  4249. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4250. }
  4251. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4252. if (function_exists("php_uname")) {
  4253. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4254. }
  4255. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4256. $out .= "<br>\n";
  4257. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4258. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4259. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4260. $out .= "<br>\n";
  4261. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4262. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4263. } else // Mode CLI
  4264. {
  4265. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4266. $syslog .= "pid=".dol_getmypid();
  4267. }
  4268. if (!empty($conf->modules)) {
  4269. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4270. }
  4271. if (is_object($db)) {
  4272. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4273. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4274. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4275. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4276. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4277. $out .= "<br>\n";
  4278. } else // Mode CLI
  4279. {
  4280. // No dol_escape_htmltag for output, we are in CLI mode
  4281. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4282. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4283. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4284. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4285. }
  4286. $syslog .= ", sql=".$db->lastquery();
  4287. $syslog .= ", db_error=".$db->lasterror();
  4288. }
  4289. if ($error || $errors) {
  4290. $langs->load("errors");
  4291. // Merge all into $errors array
  4292. if (is_array($error) && is_array($errors)) {
  4293. $errors = array_merge($error, $errors);
  4294. } elseif (is_array($error)) {
  4295. $errors = $error;
  4296. } elseif (is_array($errors)) {
  4297. $errors = array_merge(array($error), $errors);
  4298. } else {
  4299. $errors = array_merge(array($error));
  4300. }
  4301. foreach ($errors as $msg) {
  4302. if (empty($msg)) {
  4303. continue;
  4304. }
  4305. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4306. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4307. } else // Mode CLI
  4308. {
  4309. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4310. }
  4311. $syslog .= ", msg=".$msg;
  4312. }
  4313. }
  4314. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4315. xdebug_print_function_stack();
  4316. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4317. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4318. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4319. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4320. $out .= "<br>\n";
  4321. }
  4322. // Return a http error code if possible
  4323. if (!headers_sent()) {
  4324. http_response_code(500);
  4325. }
  4326. if (empty($dolibarr_main_prod)) {
  4327. print $out;
  4328. } else {
  4329. if (empty($langs->defaultlang)) {
  4330. $langs->setDefaultLang();
  4331. }
  4332. $langs->loadLangs(array("main", "errors")); // Reload main because language may have been set only on previous line so we have to reload files we need.
  4333. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4334. print 'This website or feature is currently temporarly not available or failed after a technical error.<br><br>This may be due to a maintenance operation. Current status of operation ('.dol_print_date(dol_now(), 'dayhourrfc').') are on next line...<br><br>'."\n";
  4335. print $langs->trans("DolibarrHasDetectedError").'. ';
  4336. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4337. define("MAIN_CORE_ERROR", 1);
  4338. }
  4339. dol_syslog("Error ".$syslog, LOG_ERR);
  4340. }
  4341. /**
  4342. * Show a public email and error code to contact if technical error
  4343. *
  4344. * @param string $prefixcode Prefix of public error code
  4345. * @param string $errormessage Complete error message
  4346. * @param array $errormessages Array of error messages
  4347. * @param string $morecss More css
  4348. * @param string $email Email
  4349. * @return void
  4350. */
  4351. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4352. {
  4353. global $langs, $conf;
  4354. if (empty($email)) {
  4355. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4356. }
  4357. $langs->load("errors");
  4358. $now = dol_now();
  4359. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4360. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4361. if ($errormessage) {
  4362. print '<br><br>'.$errormessage;
  4363. }
  4364. if (is_array($errormessages) && count($errormessages)) {
  4365. foreach ($errormessages as $mesgtoshow) {
  4366. print '<br><br>'.$mesgtoshow;
  4367. }
  4368. }
  4369. print '</div></div>';
  4370. }
  4371. /**
  4372. * Show title line of an array
  4373. *
  4374. * @param string $name Label of field
  4375. * @param string $file Url used when we click on sort picto
  4376. * @param string $field Field to use for new sorting
  4377. * @param string $begin ("" by defaut)
  4378. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4379. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  4380. * @param string $sortfield Current field used to sort
  4381. * @param string $sortorder Current sort order
  4382. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4383. * @param string $tooltip Tooltip
  4384. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4385. * @return void
  4386. */
  4387. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4388. {
  4389. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4390. }
  4391. /**
  4392. * Get title line of an array
  4393. *
  4394. * @param string $name Translation key of field to show or complete HTML string to show
  4395. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4396. * @param string $file Url used when we click on sort picto
  4397. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4398. * @param string $begin ("" by defaut)
  4399. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4400. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  4401. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4402. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4403. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4404. * @param string $disablesortlink 1=Disable sort link
  4405. * @param string $tooltip Tooltip
  4406. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4407. * @return string
  4408. */
  4409. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4410. {
  4411. global $conf, $langs, $form;
  4412. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4413. if ($moreattrib == 'class="right"') {
  4414. $prefix .= 'right '; // For backward compatibility
  4415. }
  4416. $sortorder = strtoupper($sortorder);
  4417. $out = '';
  4418. $sortimg = '';
  4419. $tag = 'th';
  4420. if ($thead == 2) {
  4421. $tag = 'div';
  4422. }
  4423. $tmpsortfield = explode(',', $sortfield);
  4424. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4425. $tmpfield = explode(',', $field);
  4426. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4427. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4428. $prefix = 'wrapcolumntitle '.$prefix;
  4429. }
  4430. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4431. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4432. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4433. $liste_titre = 'liste_titre';
  4434. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4435. $liste_titre = 'liste_titre_sel';
  4436. }
  4437. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4438. //$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)).'"' : '');
  4439. $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4440. $out .= '>';
  4441. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4442. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4443. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4444. $options = preg_replace('/&+/i', '&', $options);
  4445. if (!preg_match('/^&/', $options)) {
  4446. $options = '&'.$options;
  4447. }
  4448. $sortordertouseinlink = '';
  4449. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4450. if (preg_match('/^DESC/i', $sortorder)) {
  4451. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4452. } else // We reverse the var $sortordertouseinlink
  4453. {
  4454. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4455. }
  4456. } else // We are on field that is the first current sorting criteria
  4457. {
  4458. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4459. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4460. } else {
  4461. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4462. }
  4463. }
  4464. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4465. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4466. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4467. $out .= '>';
  4468. }
  4469. if ($tooltip) {
  4470. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4471. $tmptooltip = explode(':', $tooltip);
  4472. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4473. } else {
  4474. $out .= $langs->trans($name);
  4475. }
  4476. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4477. $out .= '</a>';
  4478. }
  4479. if (empty($thead) && $field) { // If this is a sort field
  4480. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4481. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4482. $options = preg_replace('/&+/i', '&', $options);
  4483. if (!preg_match('/^&/', $options)) {
  4484. $options = '&'.$options;
  4485. }
  4486. if (!$sortorder || $field1 != $sortfield1) {
  4487. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4488. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4489. } else {
  4490. if (preg_match('/^DESC/', $sortorder)) {
  4491. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4492. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4493. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  4494. }
  4495. if (preg_match('/^ASC/', $sortorder)) {
  4496. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4497. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4498. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  4499. }
  4500. }
  4501. }
  4502. $out .= $sortimg;
  4503. $out .= '</'.$tag.'>';
  4504. return $out;
  4505. }
  4506. /**
  4507. * Show a title.
  4508. *
  4509. * @param string $title Title to show
  4510. * @return void
  4511. * @deprecated Use load_fiche_titre instead
  4512. * @see load_fiche_titre()
  4513. */
  4514. function print_titre($title)
  4515. {
  4516. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4517. print '<div class="titre">'.$title.'</div>';
  4518. }
  4519. /**
  4520. * Show a title with picto
  4521. *
  4522. * @param string $title Title to show
  4523. * @param string $mesg Added message to show on right
  4524. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4525. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4526. * @param int $id To force an id on html objects
  4527. * @return void
  4528. * @deprecated Use print load_fiche_titre instead
  4529. */
  4530. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4531. {
  4532. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4533. }
  4534. /**
  4535. * Load a title with picto
  4536. *
  4537. * @param string $titre Title to show
  4538. * @param string $morehtmlright Added message to show on right
  4539. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4540. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4541. * @param string $id To force an id on html objects
  4542. * @param string $morecssontable More css on table
  4543. * @param string $morehtmlcenter Added message to show on center
  4544. * @return string
  4545. * @see print_barre_liste()
  4546. */
  4547. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4548. {
  4549. global $conf;
  4550. $return = '';
  4551. if ($picto == 'setup') {
  4552. $picto = 'generic';
  4553. }
  4554. $return .= "\n";
  4555. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4556. $return .= '<tr class="titre">';
  4557. if ($picto) {
  4558. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4559. }
  4560. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4561. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4562. $return .= '</td>';
  4563. if (dol_strlen($morehtmlcenter)) {
  4564. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4565. }
  4566. if (dol_strlen($morehtmlright)) {
  4567. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4568. }
  4569. $return .= '</tr></table>'."\n";
  4570. return $return;
  4571. }
  4572. /**
  4573. * Print a title with navigation controls for pagination
  4574. *
  4575. * @param string $titre Title to show (required)
  4576. * @param int $page Numero of page to show in navigation links (required)
  4577. * @param string $file Url of page (required)
  4578. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4579. * @param string $sortfield Field to sort on ('' by default)
  4580. * @param string $sortorder Order to sort ('' by default)
  4581. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4582. * @param int $num Number of records found by select with limit+1
  4583. * @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.
  4584. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4585. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4586. * @param string $morehtmlright More html to show (after arrows)
  4587. * @param string $morecss More css to the table
  4588. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4589. * @param int $hideselectlimit Force to hide select limit
  4590. * @param int $hidenavigation Force to hide all navigation tools
  4591. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4592. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4593. * @return void
  4594. */
  4595. 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 = '')
  4596. {
  4597. global $conf, $langs;
  4598. $savlimit = $limit;
  4599. $savtotalnboflines = $totalnboflines;
  4600. $totalnboflines = abs((int) $totalnboflines);
  4601. if ($picto == 'setup') {
  4602. $picto = 'title_setup.png';
  4603. }
  4604. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4605. $picto = 'title.gif';
  4606. }
  4607. if ($limit < 0) {
  4608. $limit = $conf->liste_limit;
  4609. }
  4610. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4611. $nextpage = 1;
  4612. } else {
  4613. $nextpage = 0;
  4614. }
  4615. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4616. print "\n";
  4617. print "<!-- Begin title -->\n";
  4618. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4619. // Left
  4620. if ($picto && $titre) {
  4621. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4622. }
  4623. print '<td class="nobordernopadding valignmiddle col-title">';
  4624. print '<div class="titre inline-block">'.$titre;
  4625. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4626. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4627. }
  4628. print '</div></td>';
  4629. // Center
  4630. if ($morehtmlcenter) {
  4631. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4632. }
  4633. // Right
  4634. print '<td class="nobordernopadding valignmiddle right">';
  4635. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4636. if ($sortfield) {
  4637. $options .= "&sortfield=".urlencode($sortfield);
  4638. }
  4639. if ($sortorder) {
  4640. $options .= "&sortorder=".urlencode($sortorder);
  4641. }
  4642. // Show navigation bar
  4643. $pagelist = '';
  4644. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4645. if ($totalnboflines) { // If we know total nb of lines
  4646. // Define nb of extra page links before and after selected page + ... + first or last
  4647. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4648. if ($limit > 0) {
  4649. $nbpages = ceil($totalnboflines / $limit);
  4650. } else {
  4651. $nbpages = 1;
  4652. }
  4653. $cpt = ($page - $maxnbofpage);
  4654. if ($cpt < 0) {
  4655. $cpt = 0;
  4656. }
  4657. if ($cpt >= 1) {
  4658. if (empty($pagenavastextinput)) {
  4659. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4660. if ($cpt > 2) {
  4661. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4662. } elseif ($cpt == 2) {
  4663. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4664. }
  4665. }
  4666. }
  4667. do {
  4668. if ($pagenavastextinput) {
  4669. if ($cpt == $page) {
  4670. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4671. $pagelist .= '/';
  4672. }
  4673. } else {
  4674. if ($cpt == $page) {
  4675. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4676. } else {
  4677. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4678. }
  4679. }
  4680. $cpt++;
  4681. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4682. if (empty($pagenavastextinput)) {
  4683. if ($cpt < $nbpages) {
  4684. if ($cpt < $nbpages - 2) {
  4685. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4686. } elseif ($cpt == $nbpages - 2) {
  4687. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4688. }
  4689. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4690. }
  4691. } else {
  4692. //var_dump($page.' '.$cpt.' '.$nbpages);
  4693. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4694. }
  4695. } else {
  4696. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4697. }
  4698. }
  4699. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4700. 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
  4701. }
  4702. // js to autoselect page field on focus
  4703. if ($pagenavastextinput) {
  4704. print ajax_autoselect('.pageplusone');
  4705. }
  4706. print '</td>';
  4707. print '</tr></table>'."\n";
  4708. print "<!-- End title -->\n\n";
  4709. }
  4710. /**
  4711. * Function to show navigation arrows into lists
  4712. *
  4713. * @param int $page Number of page
  4714. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4715. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4716. * @param integer $nextpage Do we show a next page button
  4717. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4718. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4719. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4720. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4721. * @param int $hideselectlimit Force to hide select limit
  4722. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4723. * @return void
  4724. */
  4725. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4726. {
  4727. global $conf, $langs;
  4728. print '<div class="pagination"><ul>';
  4729. if ($beforearrows) {
  4730. print '<li class="paginationbeforearrows">';
  4731. print $beforearrows;
  4732. print '</li>';
  4733. }
  4734. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4735. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000,25000:25000';
  4736. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4737. //$pagesizechoices.=',2:2';
  4738. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4739. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4740. }
  4741. print '<li class="pagination">';
  4742. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4743. $tmpchoice = explode(',', $pagesizechoices);
  4744. $tmpkey = $limit.':'.$limit;
  4745. if (!in_array($tmpkey, $tmpchoice)) {
  4746. $tmpchoice[] = $tmpkey;
  4747. }
  4748. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4749. if (!in_array($tmpkey, $tmpchoice)) {
  4750. $tmpchoice[] = $tmpkey;
  4751. }
  4752. asort($tmpchoice, SORT_NUMERIC);
  4753. foreach ($tmpchoice as $val) {
  4754. $selected = '';
  4755. $tmp = explode(':', $val);
  4756. $key = $tmp[0];
  4757. $val = $tmp[1];
  4758. if ($key != '' && $val != '') {
  4759. if ((int) $key == (int) $limit) {
  4760. $selected = ' selected="selected"';
  4761. }
  4762. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4763. }
  4764. }
  4765. print '</select>';
  4766. if ($conf->use_javascript_ajax) {
  4767. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4768. <script>
  4769. jQuery(document).ready(function () {
  4770. jQuery(".selectlimit").change(function() {
  4771. console.log("Change limit. Send submit");
  4772. $(this).parents(\'form:first\').submit();
  4773. });
  4774. });
  4775. </script>
  4776. ';
  4777. }
  4778. print '</li>';
  4779. }
  4780. if ($page > 0) {
  4781. 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>';
  4782. }
  4783. if ($betweenarrows) {
  4784. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4785. print $betweenarrows;
  4786. print '<!--</div>-->';
  4787. }
  4788. if ($nextpage > 0) {
  4789. 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>';
  4790. }
  4791. if ($afterarrows) {
  4792. print '<li class="paginationafterarrows">';
  4793. print $afterarrows;
  4794. print '</li>';
  4795. }
  4796. print '</ul></div>'."\n";
  4797. }
  4798. /**
  4799. * Return a string with VAT rate label formated for view output
  4800. * Used into pdf and HTML pages
  4801. *
  4802. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4803. * @param boolean $addpercent Add a percent % sign in output
  4804. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4805. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4806. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4807. */
  4808. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4809. {
  4810. $morelabel = '';
  4811. if (preg_match('/%/', $rate)) {
  4812. $rate = str_replace('%', '', $rate);
  4813. $addpercent = true;
  4814. }
  4815. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  4816. $morelabel = ' ('.$reg[1].')';
  4817. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4818. }
  4819. if (preg_match('/\*/', $rate)) {
  4820. $rate = str_replace('*', '', $rate);
  4821. $info_bits |= 1;
  4822. }
  4823. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4824. if (!preg_match('/\//', $rate)) {
  4825. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4826. } else {
  4827. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4828. $ret = $rate.($addpercent ? '%' : '');
  4829. }
  4830. if (($info_bits & 1) && $usestarfornpr >= 0) {
  4831. $ret .= ' *';
  4832. }
  4833. $ret .= $morelabel;
  4834. return $ret;
  4835. }
  4836. /**
  4837. * Function to format a value into an amount for visual output
  4838. * Function used into PDF and HTML pages
  4839. *
  4840. * @param float $amount Amount to format
  4841. * @param integer $form Type of format, HTML or not (not by default)
  4842. * @param Translate|string $outlangs Object langs for output
  4843. * @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.
  4844. * @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)
  4845. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4846. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4847. * @return string String with formated amount
  4848. *
  4849. * @see price2num() Revert function of price
  4850. */
  4851. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4852. {
  4853. global $langs, $conf;
  4854. // Clean parameters
  4855. if (empty($amount)) {
  4856. $amount = 0; // To have a numeric value if amount not defined or = ''
  4857. }
  4858. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4859. if ($rounding < 0) {
  4860. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4861. }
  4862. $nbdecimal = $rounding;
  4863. // Output separators by default (french)
  4864. $dec = ',';
  4865. $thousand = ' ';
  4866. // If $outlangs not forced, we use use language
  4867. if (!is_object($outlangs)) {
  4868. $outlangs = $langs;
  4869. }
  4870. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4871. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4872. }
  4873. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4874. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4875. }
  4876. if ($thousand == 'None') {
  4877. $thousand = '';
  4878. } elseif ($thousand == 'Space') {
  4879. $thousand = ' ';
  4880. }
  4881. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4882. //print "amount=".$amount."-";
  4883. $amount = str_replace(',', '.', $amount); // should be useless
  4884. //print $amount."-";
  4885. $datas = explode('.', $amount);
  4886. $decpart = isset($datas[1]) ? $datas[1] : '';
  4887. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4888. //print "decpart=".$decpart."<br>";
  4889. $end = '';
  4890. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4891. if (dol_strlen($decpart) > $nbdecimal) {
  4892. $nbdecimal = dol_strlen($decpart);
  4893. }
  4894. // Si on depasse max
  4895. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  4896. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4897. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  4898. // Si un affichage est tronque, on montre des ...
  4899. $end = '...';
  4900. }
  4901. }
  4902. // If force rounding
  4903. if ($forcerounding >= 0) {
  4904. $nbdecimal = $forcerounding;
  4905. }
  4906. // Format number
  4907. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4908. if ($form) {
  4909. $output = preg_replace('/\s/', '&nbsp;', $output);
  4910. $output = preg_replace('/\'/', '&#039;', $output);
  4911. }
  4912. // Add symbol of currency if requested
  4913. $cursymbolbefore = $cursymbolafter = '';
  4914. if ($currency_code) {
  4915. if ($currency_code == 'auto') {
  4916. $currency_code = $conf->currency;
  4917. }
  4918. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4919. $listoflanguagesbefore = array('nl_NL');
  4920. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  4921. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4922. } else {
  4923. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4924. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4925. }
  4926. }
  4927. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4928. return $output;
  4929. }
  4930. /**
  4931. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4932. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4933. * should be roundtext2num().
  4934. *
  4935. * @param string|float $amount Amount to convert/clean or round
  4936. * @param string|int $rounding ''=No rounding
  4937. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4938. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4939. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4940. * 'CU'=Round to Max unit price of foreign currency accuracy
  4941. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  4942. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  4943. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4944. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  4945. * @return string Amount with universal numeric format (Example: '99.99999').
  4946. * If conversion fails to return a numeric, it returns:
  4947. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  4948. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  4949. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  4950. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  4951. *
  4952. * @see price() Opposite function of price2num
  4953. */
  4954. function price2num($amount, $rounding = '', $option = 0)
  4955. {
  4956. global $langs, $conf;
  4957. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4958. // Numbers must be '1234.56'
  4959. // Decimal delimiter for PHP and database SQL requests must be '.'
  4960. $dec = ',';
  4961. $thousand = ' ';
  4962. if (is_null($langs)) { // $langs is not defined, we use english values.
  4963. $dec = '.';
  4964. $thousand = ',';
  4965. } else {
  4966. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4967. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4968. }
  4969. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4970. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4971. }
  4972. }
  4973. if ($thousand == 'None') {
  4974. $thousand = '';
  4975. } elseif ($thousand == 'Space') {
  4976. $thousand = ' ';
  4977. }
  4978. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4979. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4980. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4981. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4982. if (!is_numeric($amount)) {
  4983. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  4984. }
  4985. if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come from input data, so 1.123 is 1123
  4986. $amount = str_replace($thousand, '', $amount);
  4987. }
  4988. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4989. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4990. // So if number was already a good number, it is converted into local Dolibarr setup.
  4991. if (is_numeric($amount)) {
  4992. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4993. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4994. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4995. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4996. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4997. }
  4998. //print "QQ".$amount."<br>\n";
  4999. // Now make replace (the main goal of function)
  5000. if ($thousand != ',' && $thousand != '.') {
  5001. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5002. }
  5003. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5004. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5005. $amount = str_replace($dec, '.', $amount);
  5006. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5007. }
  5008. //print ' XX'.$amount.' '.$rounding;
  5009. // Now, $amount is a real PHP float number. We make a rounding if required.
  5010. if ($rounding) {
  5011. $nbofdectoround = '';
  5012. if ($rounding == 'MU') {
  5013. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5014. } elseif ($rounding == 'MT') {
  5015. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5016. } elseif ($rounding == 'MS') {
  5017. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5018. } elseif ($rounding == 'CU') {
  5019. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5020. } elseif ($rounding == 'CT') {
  5021. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5022. } elseif (is_numeric($rounding)) {
  5023. $nbofdectoround = (int) $rounding;
  5024. }
  5025. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5026. if (dol_strlen($nbofdectoround)) {
  5027. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5028. } else {
  5029. return 'ErrorBadParameterProvidedToFunction';
  5030. }
  5031. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5032. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5033. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5034. if (is_numeric($amount)) {
  5035. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5036. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5037. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5038. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5039. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5040. }
  5041. //print "TT".$amount.'<br>';
  5042. // Always make replace because each math function (like round) replace
  5043. // with local values and we want a number that has a SQL string format x.y
  5044. if ($thousand != ',' && $thousand != '.') {
  5045. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5046. }
  5047. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5048. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5049. $amount = str_replace($dec, '.', $amount);
  5050. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5051. }
  5052. return $amount;
  5053. }
  5054. /**
  5055. * Output a dimension with best unit
  5056. *
  5057. * @param float $dimension Dimension
  5058. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5059. * @param string $type 'weight', 'volume', ...
  5060. * @param Translate $outputlangs Translate language object
  5061. * @param int $round -1 = non rounding, x = number of decimal
  5062. * @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)
  5063. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5064. * @return string String to show dimensions
  5065. */
  5066. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5067. {
  5068. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5069. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5070. $dimension = $dimension * 1000000;
  5071. $unit = $unit - 6;
  5072. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5073. $dimension = $dimension * 1000;
  5074. $unit = $unit - 3;
  5075. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5076. $dimension = $dimension / 1000000;
  5077. $unit = $unit + 6;
  5078. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5079. $dimension = $dimension / 1000;
  5080. $unit = $unit + 3;
  5081. }
  5082. // Special case when we want output unit into pound or ounce
  5083. /* TODO
  5084. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5085. {
  5086. $dimension = // convert dimension from standard unit into ounce or pound
  5087. $unit = $forceunitoutput;
  5088. }
  5089. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5090. {
  5091. $dimension = // convert dimension from standard unit into ounce or pound
  5092. $unit = $forceunitoutput;
  5093. }*/
  5094. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5095. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5096. return $ret;
  5097. }
  5098. /**
  5099. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5100. * Note: This function applies same rules than get_default_tva
  5101. *
  5102. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5103. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5104. * @param Societe $thirdparty_buyer Object of buying third party
  5105. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5106. * @param int $vatnpr If vat rate is NPR or not
  5107. * @return mixed 0 if not found, localtax rate if found
  5108. * @see get_default_tva()
  5109. */
  5110. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5111. {
  5112. global $db, $conf, $mysoc;
  5113. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5114. $thirdparty_seller = $mysoc;
  5115. }
  5116. 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);
  5117. $vatratecleaned = $vatrate;
  5118. $reg = array();
  5119. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5120. $vatratecleaned = trim($reg[1]);
  5121. $vatratecode = $reg[2];
  5122. }
  5123. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5124. {
  5125. return 0;
  5126. }*/
  5127. // Some test to guess with no need to make database access
  5128. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5129. if ($local == 1) {
  5130. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5131. return 0;
  5132. }
  5133. if ($thirdparty_seller->id == $mysoc->id) {
  5134. if (!$thirdparty_buyer->localtax1_assuj) {
  5135. return 0;
  5136. }
  5137. } else {
  5138. if (!$thirdparty_seller->localtax1_assuj) {
  5139. return 0;
  5140. }
  5141. }
  5142. }
  5143. if ($local == 2) {
  5144. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5145. if (!$mysoc->localtax2_assuj) {
  5146. return 0; // If main vat is 0, IRPF may be different than 0.
  5147. }
  5148. if ($thirdparty_seller->id == $mysoc->id) {
  5149. if (!$thirdparty_buyer->localtax2_assuj) {
  5150. return 0;
  5151. }
  5152. } else {
  5153. if (!$thirdparty_seller->localtax2_assuj) {
  5154. return 0;
  5155. }
  5156. }
  5157. }
  5158. } else {
  5159. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5160. return 0;
  5161. }
  5162. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5163. return 0;
  5164. }
  5165. }
  5166. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5167. if (in_array($mysoc->country_code, array('ES'))) {
  5168. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5169. }
  5170. // Search local taxes
  5171. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5172. if ($local == 1) {
  5173. if ($thirdparty_seller != $mysoc) {
  5174. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5175. return $thirdparty_seller->localtax1_value;
  5176. }
  5177. } else { // i am the seller
  5178. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5179. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5180. }
  5181. }
  5182. }
  5183. if ($local == 2) {
  5184. if ($thirdparty_seller != $mysoc) {
  5185. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5186. // TODO We should also return value defined on thirdparty only if defined
  5187. return $thirdparty_seller->localtax2_value;
  5188. }
  5189. } else { // i am the seller
  5190. if (in_array($mysoc->country_code, array('ES'))) {
  5191. return $thirdparty_buyer->localtax2_value;
  5192. } else {
  5193. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5194. }
  5195. }
  5196. }
  5197. }
  5198. // By default, search value of local tax on line of common tax
  5199. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5200. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5201. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5202. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5203. if (!empty($vatratecode)) {
  5204. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5205. } else {
  5206. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5207. }
  5208. $resql = $db->query($sql);
  5209. if ($resql) {
  5210. $obj = $db->fetch_object($resql);
  5211. if ($obj) {
  5212. if ($local == 1) {
  5213. return $obj->localtax1;
  5214. } elseif ($local == 2) {
  5215. return $obj->localtax2;
  5216. }
  5217. }
  5218. }
  5219. return 0;
  5220. }
  5221. /**
  5222. * Return true if LocalTax (1 or 2) is unique.
  5223. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5224. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5225. *
  5226. * @param int $local Local tax to test (1 or 2)
  5227. * @return boolean True if LocalTax have multiple values, False if not
  5228. */
  5229. function isOnlyOneLocalTax($local)
  5230. {
  5231. $tax = get_localtax_by_third($local);
  5232. $valors = explode(":", $tax);
  5233. if (count($valors) > 1) {
  5234. return false;
  5235. } else {
  5236. return true;
  5237. }
  5238. }
  5239. /**
  5240. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5241. *
  5242. * @param int $local LocalTax to get
  5243. * @return number Values of localtax
  5244. */
  5245. function get_localtax_by_third($local)
  5246. {
  5247. global $db, $mysoc;
  5248. $sql = "SELECT t.localtax1, t.localtax2 ";
  5249. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5250. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5251. $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";
  5252. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5253. $sql .= " )";
  5254. $resql = $db->query($sql);
  5255. if ($resql) {
  5256. $obj = $db->fetch_object($resql);
  5257. if ($local == 1) {
  5258. return $obj->localtax1;
  5259. } elseif ($local == 2) {
  5260. return $obj->localtax2;
  5261. }
  5262. }
  5263. return 0;
  5264. }
  5265. /**
  5266. * Get tax (VAT) main information from Id.
  5267. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5268. *
  5269. * @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.
  5270. * @param Societe $buyer Company object
  5271. * @param Societe $seller Company object
  5272. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5273. * @return array array('rowid'=> , 'code'=> ...)
  5274. * @see getLocalTaxesFromRate()
  5275. */
  5276. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5277. {
  5278. global $db, $mysoc;
  5279. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5280. // Search local taxes
  5281. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5282. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5283. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5284. if ($firstparamisid) {
  5285. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5286. } else {
  5287. $vatratecleaned = $vatrate;
  5288. $vatratecode = '';
  5289. $reg = array();
  5290. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5291. $vatratecleaned = $reg[1];
  5292. $vatratecode = $reg[2];
  5293. }
  5294. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5295. /*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 ??
  5296. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5297. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5298. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5299. if ($vatratecode) {
  5300. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5301. }
  5302. }
  5303. $resql = $db->query($sql);
  5304. if ($resql) {
  5305. $obj = $db->fetch_object($resql);
  5306. if ($obj) {
  5307. return array(
  5308. 'rowid'=>$obj->rowid,
  5309. 'code'=>$obj->code,
  5310. 'rate'=>$obj->rate,
  5311. 'localtax1'=>$obj->localtax1,
  5312. 'localtax1_type'=>$obj->localtax1_type,
  5313. 'localtax2'=>$obj->localtax2,
  5314. 'localtax2_type'=>$obj->localtax2_type,
  5315. 'npr'=>$obj->npr,
  5316. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5317. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5318. );
  5319. } else {
  5320. return array();
  5321. }
  5322. } else {
  5323. dol_print_error($db);
  5324. }
  5325. return array();
  5326. }
  5327. /**
  5328. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5329. * This does not take into account the seller setup if subject to vat or not, only country.
  5330. *
  5331. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5332. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5333. * provide the selected value to the function calcul_price_total.
  5334. *
  5335. * @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.
  5336. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5337. * @param Societe $buyer Company object
  5338. * @param Societe $seller Company object
  5339. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5340. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5341. * @see getTaxesFromId()
  5342. */
  5343. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5344. {
  5345. global $db, $mysoc;
  5346. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5347. // Search local taxes
  5348. $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";
  5349. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5350. if ($firstparamisid) {
  5351. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5352. } else {
  5353. $vatratecleaned = $vatrate;
  5354. $vatratecode = '';
  5355. $reg = array();
  5356. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5357. $vatratecleaned = $reg[1];
  5358. $vatratecode = $reg[2];
  5359. }
  5360. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5361. if ($mysoc->country_code == 'ES') {
  5362. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5363. } else {
  5364. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5365. }
  5366. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5367. if ($vatratecode) {
  5368. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5369. }
  5370. }
  5371. $resql = $db->query($sql);
  5372. if ($resql) {
  5373. $obj = $db->fetch_object($resql);
  5374. if ($obj) {
  5375. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5376. if ($local == 1) {
  5377. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5378. } elseif ($local == 2) {
  5379. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5380. } else {
  5381. 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);
  5382. }
  5383. }
  5384. }
  5385. return array();
  5386. }
  5387. /**
  5388. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5389. * Function called by get_default_tva().
  5390. *
  5391. * @param int $idprod Id of product or 0 if not a predefined product
  5392. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5393. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5394. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5395. * @see get_product_localtax_for_country()
  5396. */
  5397. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5398. {
  5399. global $db, $conf, $mysoc;
  5400. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5401. $ret = 0;
  5402. $found = 0;
  5403. if ($idprod > 0) {
  5404. // Load product
  5405. $product = new Product($db);
  5406. $result = $product->fetch($idprod);
  5407. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5408. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5409. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5410. $ret = $product->vatrate_supplier;
  5411. if ($product->default_vat_code) {
  5412. $ret .= ' ('.$product->default_vat_code.')';
  5413. }
  5414. } else {
  5415. $ret = $product->tva_tx; // Default vat of product we defined
  5416. if ($product->default_vat_code) {
  5417. $ret .= ' ('.$product->default_vat_code.')';
  5418. }
  5419. }
  5420. $found = 1;
  5421. } else {
  5422. // TODO Read default product vat according to product and another countrycode.
  5423. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5424. }
  5425. }
  5426. if (!$found) {
  5427. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5428. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5429. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5430. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5431. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5432. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5433. $sql .= $db->plimit(1);
  5434. $resql = $db->query($sql);
  5435. if ($resql) {
  5436. $obj = $db->fetch_object($resql);
  5437. if ($obj) {
  5438. $ret = $obj->vat_rate;
  5439. if ($obj->default_vat_code) {
  5440. $ret .= ' ('.$obj->default_vat_code.')';
  5441. }
  5442. }
  5443. $db->free($resql);
  5444. } else {
  5445. dol_print_error($db);
  5446. }
  5447. } else {
  5448. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5449. }
  5450. }
  5451. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5452. return $ret;
  5453. }
  5454. /**
  5455. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5456. *
  5457. * @param int $idprod Id of product
  5458. * @param int $local 1 for localtax1, 2 for localtax 2
  5459. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5460. * @return int <0 if KO, Vat rate if OK
  5461. * @see get_product_vat_for_country()
  5462. */
  5463. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5464. {
  5465. global $db, $mysoc;
  5466. if (!class_exists('Product')) {
  5467. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5468. }
  5469. $ret = 0;
  5470. $found = 0;
  5471. if ($idprod > 0) {
  5472. // Load product
  5473. $product = new Product($db);
  5474. $result = $product->fetch($idprod);
  5475. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5476. /* Not defined yet, so we don't use this
  5477. if ($local==1) $ret=$product->localtax1_tx;
  5478. elseif ($local==2) $ret=$product->localtax2_tx;
  5479. $found=1;
  5480. */
  5481. } else {
  5482. // TODO Read default product vat according to product and another countrycode.
  5483. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5484. }
  5485. }
  5486. if (!$found) {
  5487. // If vat of product for the country not found or not defined, we return higher vat of country.
  5488. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5489. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5490. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5491. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5492. $sql .= $db->plimit(1);
  5493. $resql = $db->query($sql);
  5494. if ($resql) {
  5495. $obj = $db->fetch_object($resql);
  5496. if ($obj) {
  5497. if ($local == 1) {
  5498. $ret = $obj->localtax1;
  5499. } elseif ($local == 2) {
  5500. $ret = $obj->localtax2;
  5501. }
  5502. }
  5503. } else {
  5504. dol_print_error($db);
  5505. }
  5506. }
  5507. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5508. return $ret;
  5509. }
  5510. /**
  5511. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5512. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5513. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5514. * VATRULE 3: Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  5515. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5516. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5517. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5518. *
  5519. * @param Societe $thirdparty_seller Objet societe vendeuse
  5520. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5521. * @param int $idprod Id product
  5522. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5523. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5524. * @see get_default_npr(), get_default_localtax()
  5525. */
  5526. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5527. {
  5528. global $conf;
  5529. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5530. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5531. $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;
  5532. $seller_country_code = $thirdparty_seller->country_code;
  5533. $seller_in_cee = isInEEC($thirdparty_seller);
  5534. $buyer_country_code = $thirdparty_buyer->country_code;
  5535. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5536. 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 : ''));
  5537. // 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)
  5538. // we use the buyer VAT.
  5539. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5540. if ($seller_in_cee && $buyer_in_cee) {
  5541. $isacompany = $thirdparty_buyer->isACompany();
  5542. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5543. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5544. if (!isValidVATID($thirdparty_buyer)) {
  5545. $isacompany = 0;
  5546. }
  5547. }
  5548. if (!$isacompany) {
  5549. //print 'VATRULE 0';
  5550. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5551. }
  5552. }
  5553. }
  5554. // If seller does not use VAT
  5555. if (!$seller_use_vat) {
  5556. //print 'VATRULE 1';
  5557. return 0;
  5558. }
  5559. // 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.
  5560. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5561. if (($seller_country_code == $buyer_country_code)
  5562. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5563. //print 'VATRULE 2';
  5564. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5565. }
  5566. // 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.
  5567. // 'VATRULE 3' - Not supported
  5568. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5569. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5570. if (($seller_in_cee && $buyer_in_cee)) {
  5571. $isacompany = $thirdparty_buyer->isACompany();
  5572. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5573. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5574. if (!isValidVATID($thirdparty_buyer)) {
  5575. $isacompany = 0;
  5576. }
  5577. }
  5578. if (!$isacompany) {
  5579. //print 'VATRULE 4';
  5580. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5581. } else {
  5582. //print 'VATRULE 5';
  5583. return 0;
  5584. }
  5585. }
  5586. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5587. // I don't see any use case that need this rule.
  5588. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5589. $isacompany = $thirdparty_buyer->isACompany();
  5590. if (!$isacompany) {
  5591. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5592. //print 'VATRULE extra';
  5593. }
  5594. }
  5595. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5596. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5597. //print 'VATRULE 6';
  5598. return 0;
  5599. }
  5600. /**
  5601. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5602. *
  5603. * @param Societe $thirdparty_seller Thirdparty seller
  5604. * @param Societe $thirdparty_buyer Thirdparty buyer
  5605. * @param int $idprod Id product
  5606. * @param int $idprodfournprice Id supplier price for product
  5607. * @return float 0 or 1
  5608. * @see get_default_tva(), get_default_localtax()
  5609. */
  5610. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5611. {
  5612. global $db;
  5613. if ($idprodfournprice > 0) {
  5614. if (!class_exists('ProductFournisseur')) {
  5615. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5616. }
  5617. $prodprice = new ProductFournisseur($db);
  5618. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5619. return $prodprice->fourn_tva_npr;
  5620. } elseif ($idprod > 0) {
  5621. if (!class_exists('Product')) {
  5622. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5623. }
  5624. $prod = new Product($db);
  5625. $prod->fetch($idprod);
  5626. return $prod->tva_npr;
  5627. }
  5628. return 0;
  5629. }
  5630. /**
  5631. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5632. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5633. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5634. * Sinon TVA proposee par defaut=0. Fin de regle.
  5635. *
  5636. * @param Societe $thirdparty_seller Thirdparty seller
  5637. * @param Societe $thirdparty_buyer Thirdparty buyer
  5638. * @param int $local Localtax to process (1 or 2)
  5639. * @param int $idprod Id product
  5640. * @return integer localtax, -1 si ne peut etre determine
  5641. * @see get_default_tva(), get_default_npr()
  5642. */
  5643. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5644. {
  5645. global $mysoc;
  5646. if (!is_object($thirdparty_seller)) {
  5647. return -1;
  5648. }
  5649. if (!is_object($thirdparty_buyer)) {
  5650. return -1;
  5651. }
  5652. if ($local == 1) { // Localtax 1
  5653. if ($mysoc->country_code == 'ES') {
  5654. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5655. return 0;
  5656. }
  5657. } else {
  5658. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5659. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5660. return 0;
  5661. }
  5662. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5663. return 0;
  5664. }
  5665. }
  5666. } elseif ($local == 2) { //I Localtax 2
  5667. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5668. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5669. return 0;
  5670. }
  5671. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5672. return 0;
  5673. }
  5674. }
  5675. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5676. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5677. }
  5678. return 0;
  5679. }
  5680. /**
  5681. * Return yes or no in current language
  5682. *
  5683. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5684. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5685. * @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.
  5686. * @return string HTML string
  5687. */
  5688. function yn($yesno, $case = 1, $color = 0)
  5689. {
  5690. global $langs;
  5691. $result = 'unknown';
  5692. $classname = '';
  5693. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5694. $result = $langs->trans('yes');
  5695. if ($case == 1 || $case == 3) {
  5696. $result = $langs->trans("Yes");
  5697. }
  5698. if ($case == 2) {
  5699. $result = '<input type="checkbox" value="1" checked disabled>';
  5700. }
  5701. if ($case == 3) {
  5702. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5703. }
  5704. $classname = 'ok';
  5705. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5706. $result = $langs->trans("no");
  5707. if ($case == 1 || $case == 3) {
  5708. $result = $langs->trans("No");
  5709. }
  5710. if ($case == 2) {
  5711. $result = '<input type="checkbox" value="0" disabled>';
  5712. }
  5713. if ($case == 3) {
  5714. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5715. }
  5716. if ($color == 2) {
  5717. $classname = 'ok';
  5718. } else {
  5719. $classname = 'error';
  5720. }
  5721. }
  5722. if ($color) {
  5723. return '<span class="'.$classname.'">'.$result.'</span>';
  5724. }
  5725. return $result;
  5726. }
  5727. /**
  5728. * Return a path to have a the directory according to object where files are stored.
  5729. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5730. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5731. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5732. * Example out with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  5733. *
  5734. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5735. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5736. * @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)
  5737. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5738. * @param Object $object Object to use to get ref to forge the path.
  5739. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5740. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5741. */
  5742. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5743. {
  5744. global $conf;
  5745. if (empty($modulepart) && !empty($object->module)) {
  5746. $modulepart = $object->module;
  5747. }
  5748. $path = '';
  5749. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5750. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5751. $arrayforoldpath[] = 'product';
  5752. }
  5753. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5754. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5755. if (empty($alpha)) {
  5756. $num = preg_replace('/([^0-9])/i', '', $num);
  5757. } else {
  5758. $num = preg_replace('/^.*\-/i', '', $num);
  5759. }
  5760. $num = substr("000".$num, -$level);
  5761. if ($level == 1) {
  5762. $path = substr($num, 0, 1);
  5763. }
  5764. if ($level == 2) {
  5765. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5766. }
  5767. if ($level == 3) {
  5768. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5769. }
  5770. } else {
  5771. // We will enhance here a common way of forging path for document storage.
  5772. // In a future, we may distribute directories on several levels depending on setup and object.
  5773. // Here, $object->id, $object->ref and $modulepart are required.
  5774. //var_dump($modulepart);
  5775. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5776. }
  5777. if (empty($withoutslash) && !empty($path)) {
  5778. $path .= '/';
  5779. }
  5780. return $path;
  5781. }
  5782. /**
  5783. * Creation of a directory (this can create recursive subdir)
  5784. *
  5785. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5786. * @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)
  5787. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5788. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5789. */
  5790. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5791. {
  5792. global $conf;
  5793. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5794. $dir_osencoded = dol_osencode($dir);
  5795. if (@is_dir($dir_osencoded)) {
  5796. return 0;
  5797. }
  5798. $nberr = 0;
  5799. $nbcreated = 0;
  5800. $ccdir = '';
  5801. if (!empty($dataroot)) {
  5802. // Remove data root from loop
  5803. $dir = str_replace($dataroot.'/', '', $dir);
  5804. $ccdir = $dataroot.'/';
  5805. }
  5806. $cdir = explode("/", $dir);
  5807. $num = count($cdir);
  5808. for ($i = 0; $i < $num; $i++) {
  5809. if ($i > 0) {
  5810. $ccdir .= '/'.$cdir[$i];
  5811. } else {
  5812. $ccdir .= $cdir[$i];
  5813. }
  5814. if (preg_match("/^.:$/", $ccdir, $regs)) {
  5815. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5816. }
  5817. // Attention, le is_dir() peut echouer bien que le rep existe.
  5818. // (ex selon config de open_basedir)
  5819. if ($ccdir) {
  5820. $ccdir_osencoded = dol_osencode($ccdir);
  5821. if (!@is_dir($ccdir_osencoded)) {
  5822. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5823. umask(0);
  5824. $dirmaskdec = octdec($newmask);
  5825. if (empty($newmask)) {
  5826. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5827. }
  5828. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5829. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  5830. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5831. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5832. $nberr++;
  5833. } else {
  5834. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5835. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5836. $nbcreated++;
  5837. }
  5838. } else {
  5839. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5840. }
  5841. }
  5842. }
  5843. return ($nberr ? -$nberr : $nbcreated);
  5844. }
  5845. /**
  5846. * Return picto saying a field is required
  5847. *
  5848. * @return string Chaine avec picto obligatoire
  5849. */
  5850. function picto_required()
  5851. {
  5852. return '<span class="fieldrequired">*</span>';
  5853. }
  5854. /**
  5855. * Clean a string from all HTML tags and entities.
  5856. * This function differs from strip_tags because:
  5857. * - <br> are replaced with \n if removelinefeed=0 or 1
  5858. * - if entities are found, they are decoded BEFORE the strip
  5859. * - you can decide to convert line feed into a space
  5860. *
  5861. * @param string $stringtoclean String to clean
  5862. * @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..."
  5863. * @param string $pagecodeto Encoding of input/output string
  5864. * @param integer $strip_tags 0=Use internal strip, 1=Use strip_tags() php function (bugged when text contains a < char that is not for a html tag or when tags is not closed like '<img onload=aaa')
  5865. * @param integer $removedoublespaces Replace double space into one space
  5866. * @return string String cleaned
  5867. *
  5868. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5869. */
  5870. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5871. {
  5872. if ($removelinefeed == 2) {
  5873. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5874. }
  5875. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5876. // We remove entities BEFORE stripping (in case of an open separator char that is entity encoded and not the closing other, the strip will fails)
  5877. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5878. $temp = str_replace('< ', '__ltspace__', $temp);
  5879. if ($strip_tags) {
  5880. $temp = strip_tags($temp);
  5881. } else {
  5882. $temp = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  5883. $pattern = "/<[^<>]+>/";
  5884. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5885. $temp = preg_replace($pattern, "", $temp); // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5886. $temp = preg_replace($pattern, "", $temp); // pass 2 - $temp after pass 2: 0000-021
  5887. // Remove '<' into remainging, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
  5888. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  5889. }
  5890. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5891. // Remove also carriage returns
  5892. if ($removelinefeed == 1) {
  5893. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5894. }
  5895. // And double quotes
  5896. if ($removedoublespaces) {
  5897. while (strpos($temp, " ")) {
  5898. $temp = str_replace(" ", " ", $temp);
  5899. }
  5900. }
  5901. $temp = str_replace('__ltspace__', '< ', $temp);
  5902. return trim($temp);
  5903. }
  5904. /**
  5905. * Clean a string to keep only desirable HTML tags.
  5906. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  5907. *
  5908. * @param string $stringtoclean String to clean
  5909. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5910. * @param int $removeclassattribute 1=Remove the class attribute from tags
  5911. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  5912. * @param int $allowiframe Allow iframe tags.
  5913. * @return string String cleaned
  5914. *
  5915. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5916. */
  5917. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  5918. {
  5919. $allowed_tags = array(
  5920. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5921. "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",
  5922. "comment" // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  5923. );
  5924. if ($allowiframe) {
  5925. $allowed_tags[] = "iframe";
  5926. }
  5927. $allowed_tags_string = join("><", $allowed_tags);
  5928. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5929. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  5930. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5931. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  5932. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  5933. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5934. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  5935. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  5936. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </> changing string obfuscated with </> that pass injection detection into harmfull string
  5937. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5938. $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $temp); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless
  5939. }
  5940. if ($removeclassattribute) { // Clean for remaining html tags
  5941. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5942. }
  5943. // Remove 'javascript:' that we should not find into a text with
  5944. // Warning: This is not reliable to fight against obfuscated javascript, there is a lot of other solution to include js into a common html tag (only filtered by a GETPOST(.., powerfullfilter)).
  5945. if ($cleanalsojavascript) {
  5946. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5947. }
  5948. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  5949. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  5950. return $temp;
  5951. }
  5952. /**
  5953. * Clean a string from some undesirable HTML tags.
  5954. * Note: Complementary to dol_string_onlythesehtmltags().
  5955. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  5956. *
  5957. * @param string $stringtoclean String to clean
  5958. * @param array $allowed_attributes Array of tags not allowed
  5959. * @return string String cleaned
  5960. *
  5961. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  5962. */
  5963. function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = array("allow", "allowfullscreen", "alt", "class", "contenteditable", "data-html", "frameborder", "height", "href", "id", "name", "src", "style", "target", "title", "width"))
  5964. {
  5965. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  5966. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  5967. $dom = new DOMDocument(null, 'UTF-8');
  5968. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  5969. if (is_object($dom)) {
  5970. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  5971. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  5972. //var_dump($attrs->item($ii));
  5973. if (! empty($attrs->item($ii)->name)) {
  5974. // Delete attribute if not into allowed_attributes
  5975. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  5976. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  5977. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  5978. $valuetoclean = $attrs->item($ii)->value;
  5979. if (isset($valuetoclean)) {
  5980. do {
  5981. $oldvaluetoclean = $valuetoclean;
  5982. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  5983. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  5984. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  5985. $valuetoclean = preg_replace('/display\s*://m', '', $valuetoclean);
  5986. $valuetoclean = preg_replace('/z-index\s*://m', '', $valuetoclean);
  5987. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*://m', '', $valuetoclean);
  5988. }
  5989. } while ($oldvaluetoclean != $valuetoclean);
  5990. }
  5991. $attrs->item($ii)->value = $valuetoclean;
  5992. }
  5993. }
  5994. }
  5995. }
  5996. }
  5997. $return = $dom->saveHTML();
  5998. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  5999. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6000. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6001. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6002. return trim($return);
  6003. } else {
  6004. return $stringtoclean;
  6005. }
  6006. }
  6007. /**
  6008. * Clean a string from some undesirable HTML tags.
  6009. * Note. Not as secured as dol_string_onlythesehtmltags().
  6010. *
  6011. * @param string $stringtoclean String to clean
  6012. * @param array $disallowed_tags Array of tags not allowed
  6013. * @param string $cleanalsosomestyles Clean also some tags
  6014. * @return string String cleaned
  6015. *
  6016. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6017. */
  6018. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6019. {
  6020. $temp = $stringtoclean;
  6021. foreach ($disallowed_tags as $tagtoremove) {
  6022. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6023. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6024. }
  6025. if ($cleanalsosomestyles) {
  6026. $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
  6027. }
  6028. return $temp;
  6029. }
  6030. /**
  6031. * Return first line of text. Cut will depends if content is HTML or not.
  6032. *
  6033. * @param string $text Input text
  6034. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6035. * @param string $charset Charset of $text string (UTF-8 by default)
  6036. * @return string Output text
  6037. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6038. */
  6039. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6040. {
  6041. if ($nboflines == 1) {
  6042. if (dol_textishtml($text)) {
  6043. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6044. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6045. } else {
  6046. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6047. }
  6048. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  6049. } else {
  6050. $ishtml = 0;
  6051. if (dol_textishtml($text)) {
  6052. $text = preg_replace('/\n/', '', $text);
  6053. $ishtml = 1;
  6054. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6055. } else {
  6056. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6057. }
  6058. $text = strtr($text, $repTable);
  6059. if ($charset == 'UTF-8') {
  6060. $pattern = '/(<br[^>]*>)/Uu';
  6061. } else {
  6062. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6063. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6064. }
  6065. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6066. $firstline = '';
  6067. $i = 0;
  6068. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  6069. while (($i < $nba) && ($i < ($nboflines * 2))) {
  6070. if ($i % 2 == 0) {
  6071. $firstline .= $a[$i];
  6072. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  6073. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6074. }
  6075. $i++;
  6076. }
  6077. unset($a);
  6078. return $firstline.(($i < $nba) ? '...' : '');
  6079. }
  6080. }
  6081. /**
  6082. * Replace CRLF in string with a HTML BR tag.
  6083. * 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.
  6084. *
  6085. * @param string $stringtoencode String to encode
  6086. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6087. * @param bool $forxml false=Use <br>, true=Use <br />
  6088. * @return string String encoded
  6089. * @see dol_nboflines(), dolGetFirstLineOfText()
  6090. */
  6091. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6092. {
  6093. if (!$nl2brmode) {
  6094. return nl2br($stringtoencode, $forxml);
  6095. } else {
  6096. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6097. return $ret;
  6098. }
  6099. }
  6100. /**
  6101. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6102. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6103. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6104. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6105. * For PDF usage, you can show text by 2 ways:
  6106. * - writeHTMLCell -> param must be encoded into HTML.
  6107. * - MultiCell -> param must not be encoded into HTML.
  6108. * Because writeHTMLCell convert also \n into <br>, if function
  6109. * is used to build PDF, nl2brmode must be 1.
  6110. *
  6111. * @param string $stringtoencode String to encode
  6112. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6113. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6114. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6115. * @return string String encoded
  6116. */
  6117. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6118. {
  6119. $newstring = $stringtoencode;
  6120. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6121. $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.
  6122. if ($removelasteolbr) {
  6123. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6124. }
  6125. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6126. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6127. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6128. } else {
  6129. if ($removelasteolbr) {
  6130. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6131. }
  6132. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6133. }
  6134. // Other substitutions that htmlentities does not do
  6135. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6136. return $newstring;
  6137. }
  6138. /**
  6139. * This function is called to decode a HTML string (it decodes entities and br tags)
  6140. *
  6141. * @param string $stringtodecode String to decode
  6142. * @param string $pagecodeto Page code for result
  6143. * @return string String decoded
  6144. */
  6145. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6146. {
  6147. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6148. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6149. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6150. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6151. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6152. return $ret;
  6153. }
  6154. /**
  6155. * This function remove all ending \n and br at end
  6156. *
  6157. * @param string $stringtodecode String to decode
  6158. * @return string String decoded
  6159. */
  6160. function dol_htmlcleanlastbr($stringtodecode)
  6161. {
  6162. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6163. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6164. return $ret;
  6165. }
  6166. /**
  6167. * Replace html_entity_decode functions to manage errors
  6168. *
  6169. * @param string $a Operand a
  6170. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6171. * @param string $c Operand c
  6172. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6173. * @return string String decoded
  6174. */
  6175. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6176. {
  6177. $newstring = $a;
  6178. if ($keepsomeentities) {
  6179. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6180. }
  6181. $newstring = html_entity_decode($newstring, $b, $c);
  6182. if ($keepsomeentities) {
  6183. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6184. }
  6185. return $newstring;
  6186. }
  6187. /**
  6188. * Replace htmlentities functions.
  6189. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6190. *
  6191. * @param string $string The input string to encode
  6192. * @param int $flags Flags (see PHP doc above)
  6193. * @param string $encoding Encoding page code
  6194. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6195. * @return string $ret Encoded string
  6196. */
  6197. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6198. {
  6199. return htmlentities($string, $flags, $encoding, $double_encode);
  6200. }
  6201. /**
  6202. * Check if a string is a correct iso string
  6203. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6204. * Example, if string contains euro symbol that has ascii code 128
  6205. *
  6206. * @param string $s String to check
  6207. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6208. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6209. */
  6210. function dol_string_is_good_iso($s, $clean = 0)
  6211. {
  6212. $len = dol_strlen($s);
  6213. $out = '';
  6214. $ok = 1;
  6215. for ($scursor = 0; $scursor < $len; $scursor++) {
  6216. $ordchar = ord($s[$scursor]);
  6217. //print $scursor.'-'.$ordchar.'<br>';
  6218. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6219. $ok = 0;
  6220. break;
  6221. } elseif ($ordchar > 126 && $ordchar < 160) {
  6222. $ok = 0;
  6223. break;
  6224. } elseif ($clean) {
  6225. $out .= $s[$scursor];
  6226. }
  6227. }
  6228. if ($clean) {
  6229. return $out;
  6230. }
  6231. return $ok;
  6232. }
  6233. /**
  6234. * Return nb of lines of a clear text
  6235. *
  6236. * @param string $s String to check
  6237. * @param int $maxchar Not yet used
  6238. * @return int Number of lines
  6239. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6240. */
  6241. function dol_nboflines($s, $maxchar = 0)
  6242. {
  6243. if ($s == '') {
  6244. return 0;
  6245. }
  6246. $arraystring = explode("\n", $s);
  6247. $nb = count($arraystring);
  6248. return $nb;
  6249. }
  6250. /**
  6251. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6252. *
  6253. * @param string $text Text
  6254. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6255. * @param string $charset Give the charset used to encode the $text variable in memory.
  6256. * @return int Number of lines
  6257. * @see dol_nboflines(), dolGetFirstLineOfText()
  6258. */
  6259. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6260. {
  6261. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6262. if (dol_textishtml($text)) {
  6263. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6264. }
  6265. $text = strtr($text, $repTable);
  6266. if ($charset == 'UTF-8') {
  6267. $pattern = '/(<br[^>]*>)/Uu';
  6268. } else {
  6269. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6270. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6271. }
  6272. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6273. $nblines = (int) floor((count($a) + 1) / 2);
  6274. // count possible auto line breaks
  6275. if ($maxlinesize) {
  6276. foreach ($a as $line) {
  6277. if (dol_strlen($line) > $maxlinesize) {
  6278. //$line_dec = html_entity_decode(strip_tags($line));
  6279. $line_dec = html_entity_decode($line);
  6280. if (dol_strlen($line_dec) > $maxlinesize) {
  6281. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6282. $nblines += substr_count($line_dec, '\n');
  6283. }
  6284. }
  6285. }
  6286. }
  6287. unset($a);
  6288. return $nblines;
  6289. }
  6290. /**
  6291. * Return if a text is a html content
  6292. *
  6293. * @param string $msg Content to check
  6294. * @param int $option 0=Full detection, 1=Fast check
  6295. * @return boolean true/false
  6296. * @see dol_concatdesc()
  6297. */
  6298. function dol_textishtml($msg, $option = 0)
  6299. {
  6300. if ($option == 1) {
  6301. if (preg_match('/<html/i', $msg)) {
  6302. return true;
  6303. } elseif (preg_match('/<body/i', $msg)) {
  6304. return true;
  6305. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6306. return true;
  6307. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6308. return true;
  6309. } elseif (preg_match('/<br/i', $msg)) {
  6310. return true;
  6311. }
  6312. return false;
  6313. } else {
  6314. if (preg_match('/<html/i', $msg)) {
  6315. return true;
  6316. } elseif (preg_match('/<body/i', $msg)) {
  6317. return true;
  6318. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6319. return true;
  6320. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6321. return true;
  6322. } elseif (preg_match('/<br\/>/i', $msg)) {
  6323. return true;
  6324. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6325. return true;
  6326. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6327. return true;
  6328. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6329. return true; // must accept <img src="http://example.com/aaa.png" />
  6330. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6331. return true; // must accept <a href="http://example.com/aaa.png" />
  6332. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6333. return true;
  6334. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6335. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6336. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6337. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6338. }
  6339. return false;
  6340. }
  6341. }
  6342. /**
  6343. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6344. * text1 html + text2 html => text1 + '<br>' + text2
  6345. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6346. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6347. * text1 txt + text2 txt => text1 + '\n' + text2
  6348. *
  6349. * @param string $text1 Text 1
  6350. * @param string $text2 Text 2
  6351. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6352. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6353. * @return string Text 1 + new line + Text2
  6354. * @see dol_textishtml()
  6355. */
  6356. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6357. {
  6358. if (!empty($invert)) {
  6359. $tmp = $text1;
  6360. $text1 = $text2;
  6361. $text2 = $tmp;
  6362. }
  6363. $ret = '';
  6364. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6365. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6366. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6367. return $ret;
  6368. }
  6369. /**
  6370. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6371. *
  6372. * @param Translate $outputlangs Output language
  6373. * @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)
  6374. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6375. * @param Object $object Object for keys on object
  6376. * @return array Array of substitutions
  6377. * @see setSubstitFromObject()
  6378. */
  6379. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6380. {
  6381. global $db, $conf, $mysoc, $user, $extrafields;
  6382. $substitutionarray = array();
  6383. if (empty($exclude) || !in_array('user', $exclude)) {
  6384. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6385. // this will include signature content first and then replace var found into content of signature
  6386. $signature = $user->signature;
  6387. $substitutionarray = array_merge($substitutionarray, array(
  6388. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6389. ));
  6390. if (is_object($user)) {
  6391. $substitutionarray = array_merge($substitutionarray, array(
  6392. '__USER_ID__' => (string) $user->id,
  6393. '__USER_LOGIN__' => (string) $user->login,
  6394. '__USER_EMAIL__' => (string) $user->email,
  6395. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone),
  6396. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile),
  6397. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile),
  6398. '__USER_FAX__' => (string) $user->office_fax,
  6399. '__USER_LASTNAME__' => (string) $user->lastname,
  6400. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6401. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6402. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6403. '__USER_JOB__' => (string) $user->job,
  6404. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6405. ));
  6406. }
  6407. }
  6408. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6409. $substitutionarray = array_merge($substitutionarray, array(
  6410. '__MYCOMPANY_NAME__' => $mysoc->name,
  6411. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6412. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone),
  6413. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax),
  6414. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6415. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6416. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6417. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6418. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6419. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6420. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6421. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6422. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6423. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6424. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6425. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6426. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6427. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6428. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6429. ));
  6430. }
  6431. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6432. if ($onlykey) {
  6433. $substitutionarray['__ID__'] = '__ID__';
  6434. $substitutionarray['__REF__'] = '__REF__';
  6435. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6436. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6437. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6438. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6439. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6440. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6441. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6442. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6443. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6444. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6445. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6446. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6447. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6448. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6449. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6450. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6451. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6452. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6453. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6454. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6455. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6456. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6457. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6458. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6459. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6460. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6461. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6462. }
  6463. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6464. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6465. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6466. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6467. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6468. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6469. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6470. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6471. }
  6472. // add variables subtitutions ticket
  6473. if (!empty($conf->ticket->enabled) && (!is_object($object) || $object->element == 'ticket')) {
  6474. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  6475. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  6476. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  6477. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  6478. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  6479. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  6480. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  6481. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  6482. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  6483. }
  6484. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'recruitmentcandidature')) {
  6485. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6486. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6487. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6488. }
  6489. if (!empty($conf->projet->enabled)) { // Most objects
  6490. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6491. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6492. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6493. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6494. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6495. }
  6496. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6497. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6498. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6499. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6500. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6501. }
  6502. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6503. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6504. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6505. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6506. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6507. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6508. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  6509. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6510. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6511. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6512. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6513. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6514. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6515. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6516. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6517. }
  6518. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6519. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6520. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6521. }
  6522. } else {
  6523. $substitutionarray['__ID__'] = $object->id;
  6524. $substitutionarray['__REF__'] = $object->ref;
  6525. $substitutionarray['__NEWREF__'] = $object->newref;
  6526. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6527. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6528. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6529. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6530. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6531. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6532. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6533. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6534. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6535. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6536. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6537. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6538. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6539. // For backward compatibility
  6540. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6541. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6542. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6543. $substitutionarray['__SUPPLIER_ORDER_DELAY_DELIVERY__'] = (isset($object->availability_code) ? ($outputlangs->transnoentities("AvailabilityType".$object->availability_code) != ('AvailabilityType'.$object->availability_code) ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : '')) : '');
  6544. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6545. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6546. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6547. if (method_exists($object, 'getCivilityLabel')) {
  6548. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6549. }
  6550. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6551. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6552. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6553. if (method_exists($object, 'getFullName')) {
  6554. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6555. }
  6556. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6557. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6558. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6559. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6560. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6561. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6562. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6563. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6564. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6565. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6566. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  6567. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  6568. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  6569. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6570. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6571. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  6572. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  6573. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6574. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6575. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6576. }
  6577. if (is_object($object) && $object->element == 'societe') {
  6578. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6579. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6580. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6581. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6582. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6583. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6584. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  6585. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  6586. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6587. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6588. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6589. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6590. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6591. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6592. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6593. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6594. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6595. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6596. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6597. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6598. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6599. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6600. } elseif (is_object($object->thirdparty)) {
  6601. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6602. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6603. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6604. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6605. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6606. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6607. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  6608. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  6609. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6610. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6611. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6612. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6613. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6614. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6615. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6616. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6617. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6618. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6619. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6620. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6621. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6622. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6623. }
  6624. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6625. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6626. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  6627. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  6628. }
  6629. if (is_object($object->project)) {
  6630. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6631. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6632. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6633. }
  6634. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6635. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6636. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6637. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6638. }
  6639. if (is_object($object) && $object->element == 'shipping') {
  6640. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6641. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6642. }
  6643. if (is_object($object) && $object->element == 'reception') {
  6644. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6645. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6646. }
  6647. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6648. $dateplannedstart = '';
  6649. $datenextexpiration = '';
  6650. foreach ($object->lines as $line) {
  6651. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6652. $dateplannedstart = $line->date_ouverture_prevue;
  6653. }
  6654. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6655. $datenextexpiration = $line->date_fin_prevue;
  6656. }
  6657. }
  6658. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6659. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6660. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6661. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6662. }
  6663. // add substition variable for ticket
  6664. if (is_object($object) && $object->element == 'ticket') {
  6665. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  6666. $substitutionarray['__REF__'] = $object->ref;
  6667. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  6668. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  6669. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  6670. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  6671. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  6672. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  6673. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  6674. $userstat = new User($db);
  6675. if ($object->fk_user_assign > 0) {
  6676. $userstat->fetch($object->fk_user_assign);
  6677. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  6678. }
  6679. if ($object->fk_user_create > 0) {
  6680. $userstat->fetch($object->fk_user_create);
  6681. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  6682. }
  6683. }
  6684. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6685. if ($object->table_element && $object->id > 0) {
  6686. if (!is_object($extrafields)) {
  6687. $extrafields = new ExtraFields($db);
  6688. }
  6689. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6690. if ($object->fetch_optionals() > 0) {
  6691. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6692. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6693. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6694. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6695. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6696. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6697. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6698. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6699. $datetime = $object->array_options['options_'.$key];
  6700. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6701. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6702. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6703. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6704. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  6705. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  6706. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  6707. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6708. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  6709. }
  6710. }
  6711. }
  6712. }
  6713. }
  6714. // Complete substitution array with the url to make online payment
  6715. $paymenturl = '';
  6716. if (empty($substitutionarray['__REF__'])) {
  6717. $paymenturl = '';
  6718. } else {
  6719. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6720. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6721. $outputlangs->loadLangs(array('paypal', 'other'));
  6722. $typeforonlinepayment = 'free';
  6723. if (is_object($object) && $object->element == 'commande') {
  6724. $typeforonlinepayment = 'order';
  6725. }
  6726. if (is_object($object) && $object->element == 'facture') {
  6727. $typeforonlinepayment = 'invoice';
  6728. }
  6729. if (is_object($object) && $object->element == 'member') {
  6730. $typeforonlinepayment = 'member';
  6731. }
  6732. if (is_object($object) && $object->element == 'contrat') {
  6733. $typeforonlinepayment = 'contract';
  6734. }
  6735. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6736. $paymenturl = $url;
  6737. }
  6738. if ($object->id > 0) {
  6739. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6740. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6741. if (is_object($object) && $object->element == 'propal') {
  6742. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  6743. }
  6744. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6745. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6746. } else {
  6747. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6748. }
  6749. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6750. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6751. } else {
  6752. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6753. }
  6754. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6755. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6756. } else {
  6757. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6758. }
  6759. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6760. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6761. } else {
  6762. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6763. }
  6764. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6765. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6766. } else {
  6767. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6768. }
  6769. if (is_object($object) && $object->element == 'propal') {
  6770. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6771. }
  6772. if (is_object($object) && $object->element == 'commande') {
  6773. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6774. }
  6775. if (is_object($object) && $object->element == 'facture') {
  6776. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6777. }
  6778. if (is_object($object) && $object->element == 'contrat') {
  6779. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6780. }
  6781. if (is_object($object) && $object->element == 'supplier_proposal') {
  6782. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6783. }
  6784. if (is_object($object) && $object->element == 'shipping') {
  6785. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  6786. }
  6787. }
  6788. if (is_object($object) && $object->element == 'action') {
  6789. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6790. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  6791. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  6792. }
  6793. }
  6794. }
  6795. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  6796. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  6797. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  6798. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  6799. $already_payed_all = 0;
  6800. if (is_object($object) && ($object instanceof Facture)) {
  6801. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  6802. }
  6803. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  6804. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  6805. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  6806. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  6807. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? $object->total_ttc - $already_payed_all : '';
  6808. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6809. $substitutionarray['__AMOUNT_VAT_TEXT__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, '', true) : dol_convertToWord($object->total_tva, $outputlangs, '', true)) : '';
  6810. $substitutionarray['__AMOUNT_VAT_TEXTCURRENCY__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, $conf->currency, true) : dol_convertToWord($object->total_tva, $outputlangs, $conf->currency, true)) : '';
  6811. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6812. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  6813. }
  6814. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6815. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  6816. }
  6817. // Amount keys formated in a currency
  6818. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6819. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6820. $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc - $already_payed_all, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6821. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? (isset($object->total_vat) ? price($object->total_vat, 0, $outputlangs, 0, -1, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, -1, -1, $conf->currency) : null)) : '';
  6822. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6823. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6824. }
  6825. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6826. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6827. }
  6828. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  6829. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  6830. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  6831. // TODO Add other keys for foreign multicurrency
  6832. // For backward compatibility
  6833. if ($onlykey != 2) {
  6834. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  6835. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  6836. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6837. }
  6838. }
  6839. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  6840. if (empty($exclude) || !in_array('date', $exclude)) {
  6841. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6842. $tmp = dol_getdate(dol_now(), true);
  6843. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6844. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  6845. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6846. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  6847. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  6848. $substitutionarray = array_merge($substitutionarray, array(
  6849. '__DAY__' => (string) $tmp['mday'],
  6850. '__DAY_TEXT__' => $daytext, // Monday
  6851. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  6852. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  6853. '__MONTH__' => (string) $tmp['mon'],
  6854. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  6855. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  6856. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  6857. '__YEAR__' => (string) $tmp['year'],
  6858. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  6859. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  6860. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  6861. '__NEXT_DAY__' => (string) $tmp4['day'],
  6862. '__NEXT_MONTH__' => (string) $tmp5['month'],
  6863. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  6864. ));
  6865. }
  6866. if (!empty($conf->multicompany->enabled)) {
  6867. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  6868. }
  6869. if (empty($exclude) || !in_array('system', $exclude)) {
  6870. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  6871. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  6872. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  6873. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  6874. }
  6875. return $substitutionarray;
  6876. }
  6877. /**
  6878. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  6879. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  6880. * Example of usage:
  6881. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  6882. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  6883. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  6884. *
  6885. * @param string $text Source string in which we must do substitution
  6886. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  6887. * @param Translate $outputlangs Output language
  6888. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  6889. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  6890. * @return string Output string after substitutions
  6891. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  6892. */
  6893. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  6894. {
  6895. global $conf, $langs;
  6896. if (!is_array($substitutionarray)) {
  6897. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  6898. }
  6899. if (empty($outputlangs)) {
  6900. $outputlangs = $langs;
  6901. }
  6902. // Is initial text HTML or simple text ?
  6903. $msgishtml = 0;
  6904. if (dol_textishtml($text, 1)) {
  6905. $msgishtml = 1;
  6906. }
  6907. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  6908. if (is_object($outputlangs)) {
  6909. $reg = array();
  6910. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  6911. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  6912. $tmp = explode('|', $reg[1]);
  6913. if (!empty($tmp[1])) {
  6914. $outputlangs->load($tmp[1]);
  6915. }
  6916. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  6917. if (empty($converttextinhtmlifnecessary)) {
  6918. // convert $newval into HTML is necessary
  6919. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6920. } else {
  6921. if (! $msgishtml) {
  6922. $valueishtml = dol_textishtml($value, 1);
  6923. if ($valueishtml) {
  6924. $text = dol_htmlentitiesbr($text);
  6925. $msgishtml = 1;
  6926. }
  6927. } else {
  6928. $value = dol_nl2br("$value");
  6929. }
  6930. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  6931. }
  6932. }
  6933. }
  6934. // Make substitution for constant keys.
  6935. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  6936. $reg = array();
  6937. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  6938. $keyfound = $reg[1];
  6939. if (isASecretKey($keyfound)) {
  6940. $value = '*****forbidden*****';
  6941. } else {
  6942. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  6943. }
  6944. if (empty($converttextinhtmlifnecessary)) {
  6945. // convert $newval into HTML is necessary
  6946. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6947. } else {
  6948. if (! $msgishtml) {
  6949. $valueishtml = dol_textishtml($value, 1);
  6950. if ($valueishtml) {
  6951. $text = dol_htmlentitiesbr($text);
  6952. $msgishtml = 1;
  6953. }
  6954. } else {
  6955. $value = dol_nl2br("$value");
  6956. }
  6957. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  6958. }
  6959. }
  6960. // Make substitition for array $substitutionarray
  6961. foreach ($substitutionarray as $key => $value) {
  6962. if (!isset($value)) {
  6963. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  6964. }
  6965. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  6966. $value = ''; // Protection
  6967. }
  6968. if (empty($converttextinhtmlifnecessary)) {
  6969. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6970. } else {
  6971. if (! $msgishtml) {
  6972. $valueishtml = dol_textishtml($value, 1);
  6973. if ($valueishtml) {
  6974. $text = dol_htmlentitiesbr($text);
  6975. $msgishtml = 1;
  6976. }
  6977. } else {
  6978. $value = dol_nl2br("$value");
  6979. }
  6980. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6981. }
  6982. }
  6983. return $text;
  6984. }
  6985. /**
  6986. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6987. * In this case, method completesubstitutionarray provided by module is called.
  6988. *
  6989. * @param array $substitutionarray Array substitution old value => new value value
  6990. * @param Translate $outputlangs Output language
  6991. * @param Object $object Source object
  6992. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6993. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6994. * @return void
  6995. * @see make_substitutions()
  6996. */
  6997. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6998. {
  6999. global $conf, $user;
  7000. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7001. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7002. // Check if there is external substitution to do, requested by plugins
  7003. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7004. foreach ($dirsubstitutions as $reldir) {
  7005. $dir = dol_buildpath($reldir, 0);
  7006. // Check if directory exists
  7007. if (!dol_is_dir($dir)) {
  7008. continue;
  7009. }
  7010. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7011. foreach ($substitfiles as $substitfile) {
  7012. $reg = array();
  7013. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7014. $module = $reg[1];
  7015. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7016. // Include the user's functions file
  7017. require_once $dir.$substitfile['name'];
  7018. // Call the user's function, and only if it is defined
  7019. $function_name = $module."_".$callfunc;
  7020. if (function_exists($function_name)) {
  7021. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7022. }
  7023. }
  7024. }
  7025. }
  7026. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7027. // to list all tags in odt template
  7028. $tags = '';
  7029. foreach ($substitutionarray as $key => $value) {
  7030. $tags .= '{'.$key.'} => '.$value."\n";
  7031. }
  7032. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7033. }
  7034. }
  7035. /**
  7036. * Format output for start and end date
  7037. *
  7038. * @param int $date_start Start date
  7039. * @param int $date_end End date
  7040. * @param string $format Output format
  7041. * @param Translate $outputlangs Output language
  7042. * @return void
  7043. */
  7044. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7045. {
  7046. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7047. }
  7048. /**
  7049. * Format output for start and end date
  7050. *
  7051. * @param int $date_start Start date
  7052. * @param int $date_end End date
  7053. * @param string $format Output format
  7054. * @param Translate $outputlangs Output language
  7055. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7056. * @return string String
  7057. */
  7058. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7059. {
  7060. global $langs;
  7061. $out = '';
  7062. if (!is_object($outputlangs)) {
  7063. $outputlangs = $langs;
  7064. }
  7065. if ($date_start && $date_end) {
  7066. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7067. }
  7068. if ($date_start && !$date_end) {
  7069. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7070. }
  7071. if (!$date_start && $date_end) {
  7072. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7073. }
  7074. return $out;
  7075. }
  7076. /**
  7077. * Return firstname and lastname in correct order
  7078. *
  7079. * @param string $firstname Firstname
  7080. * @param string $lastname Lastname
  7081. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  7082. * @return string Firstname + lastname or Lastname + firstname
  7083. */
  7084. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7085. {
  7086. global $conf;
  7087. $ret = '';
  7088. // If order not defined, we use the setup
  7089. if ($nameorder < 0) {
  7090. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7091. }
  7092. if ($nameorder == 1) {
  7093. $ret .= $firstname;
  7094. if ($firstname && $lastname) {
  7095. $ret .= ' ';
  7096. }
  7097. $ret .= $lastname;
  7098. } elseif ($nameorder == 2 || $nameorder == 3) {
  7099. $ret .= $firstname;
  7100. if (empty($ret) && $nameorder == 3) {
  7101. $ret .= $lastname;
  7102. }
  7103. } else { // 0, 4 or 5
  7104. $ret .= $lastname;
  7105. if (empty($ret) && $nameorder == 5) {
  7106. $ret .= $firstname;
  7107. }
  7108. if ($nameorder == 0) {
  7109. if ($firstname && $lastname) {
  7110. $ret .= ' ';
  7111. }
  7112. $ret .= $firstname;
  7113. }
  7114. }
  7115. return $ret;
  7116. }
  7117. /**
  7118. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  7119. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7120. * Note: Prefer to use setEventMessages instead.
  7121. *
  7122. * @param string|string[] $mesgs Message string or array
  7123. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7124. * @return void
  7125. * @see dol_htmloutput_events()
  7126. */
  7127. function setEventMessage($mesgs, $style = 'mesgs')
  7128. {
  7129. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  7130. if (!is_array($mesgs)) {
  7131. // If mesgs is a string
  7132. if ($mesgs) {
  7133. $_SESSION['dol_events'][$style][] = $mesgs;
  7134. }
  7135. } else {
  7136. // If mesgs is an array
  7137. foreach ($mesgs as $mesg) {
  7138. if ($mesg) {
  7139. $_SESSION['dol_events'][$style][] = $mesg;
  7140. }
  7141. }
  7142. }
  7143. }
  7144. /**
  7145. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7146. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7147. *
  7148. * @param string $mesg Message string
  7149. * @param array $mesgs Message array
  7150. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7151. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7152. * @return void
  7153. * @see dol_htmloutput_events()
  7154. */
  7155. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  7156. {
  7157. if (empty($mesg) && empty($mesgs)) {
  7158. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  7159. } else {
  7160. if ($messagekey) {
  7161. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7162. // TODO
  7163. $mesg .= '';
  7164. }
  7165. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7166. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7167. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7168. }
  7169. if (empty($mesgs)) {
  7170. setEventMessage($mesg, $style);
  7171. } else {
  7172. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7173. setEventMessage($mesg, $style); // Add message string if not already into array
  7174. }
  7175. setEventMessage($mesgs, $style);
  7176. }
  7177. }
  7178. }
  7179. }
  7180. /**
  7181. * Print formated messages to output (Used to show messages on html output).
  7182. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7183. * no need to call it explicitely.
  7184. *
  7185. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7186. * @return void
  7187. * @see dol_htmloutput_mesg()
  7188. */
  7189. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7190. {
  7191. // Show mesgs
  7192. if (isset($_SESSION['dol_events']['mesgs'])) {
  7193. if (empty($disabledoutputofmessages)) {
  7194. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7195. }
  7196. unset($_SESSION['dol_events']['mesgs']);
  7197. }
  7198. // Show errors
  7199. if (isset($_SESSION['dol_events']['errors'])) {
  7200. if (empty($disabledoutputofmessages)) {
  7201. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7202. }
  7203. unset($_SESSION['dol_events']['errors']);
  7204. }
  7205. // Show warnings
  7206. if (isset($_SESSION['dol_events']['warnings'])) {
  7207. if (empty($disabledoutputofmessages)) {
  7208. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7209. }
  7210. unset($_SESSION['dol_events']['warnings']);
  7211. }
  7212. }
  7213. /**
  7214. * Get formated messages to output (Used to show messages on html output).
  7215. * This include also the translation of the message key.
  7216. *
  7217. * @param string $mesgstring Message string or message key
  7218. * @param string[] $mesgarray Array of message strings or message keys
  7219. * @param string $style Style of message output ('ok' or 'error')
  7220. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7221. * @return string Return html output
  7222. *
  7223. * @see dol_print_error()
  7224. * @see dol_htmloutput_errors()
  7225. * @see setEventMessages()
  7226. */
  7227. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7228. {
  7229. global $conf, $langs;
  7230. $ret = 0;
  7231. $return = '';
  7232. $out = '';
  7233. $divstart = $divend = '';
  7234. // If inline message with no format, we add it.
  7235. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7236. $divstart = '<div class="'.$style.' clearboth">';
  7237. $divend = '</div>';
  7238. }
  7239. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7240. $langs->load("errors");
  7241. $out .= $divstart;
  7242. if (is_array($mesgarray) && count($mesgarray)) {
  7243. foreach ($mesgarray as $message) {
  7244. $ret++;
  7245. $out .= $langs->trans($message);
  7246. if ($ret < count($mesgarray)) {
  7247. $out .= "<br>\n";
  7248. }
  7249. }
  7250. }
  7251. if ($mesgstring) {
  7252. $langs->load("errors");
  7253. $ret++;
  7254. $out .= $langs->trans($mesgstring);
  7255. }
  7256. $out .= $divend;
  7257. }
  7258. if ($out) {
  7259. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7260. $return = '<script>
  7261. $(document).ready(function() {
  7262. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7263. if (block) {
  7264. $.dolEventValid("","'.dol_escape_js($out).'");
  7265. } else {
  7266. /* jnotify(message, preset of message type, keepmessage) */
  7267. $.jnotify("'.dol_escape_js($out).'",
  7268. "'.($style == "ok" ? 3000 : $style).'",
  7269. '.($style == "ok" ? "false" : "true").',
  7270. { remove: function (){} } );
  7271. }
  7272. });
  7273. </script>';
  7274. } else {
  7275. $return = $out;
  7276. }
  7277. }
  7278. return $return;
  7279. }
  7280. /**
  7281. * Get formated error messages to output (Used to show messages on html output).
  7282. *
  7283. * @param string $mesgstring Error message
  7284. * @param array $mesgarray Error messages array
  7285. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7286. * @return string Return html output
  7287. *
  7288. * @see dol_print_error()
  7289. * @see dol_htmloutput_mesg()
  7290. */
  7291. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7292. {
  7293. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7294. }
  7295. /**
  7296. * Print formated messages to output (Used to show messages on html output).
  7297. *
  7298. * @param string $mesgstring Message string or message key
  7299. * @param string[] $mesgarray Array of message strings or message keys
  7300. * @param string $style Which style to use ('ok', 'warning', 'error')
  7301. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7302. * @return void
  7303. *
  7304. * @see dol_print_error()
  7305. * @see dol_htmloutput_errors()
  7306. * @see setEventMessages()
  7307. */
  7308. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7309. {
  7310. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7311. return;
  7312. }
  7313. $iserror = 0;
  7314. $iswarning = 0;
  7315. if (is_array($mesgarray)) {
  7316. foreach ($mesgarray as $val) {
  7317. if ($val && preg_match('/class="error"/i', $val)) {
  7318. $iserror++;
  7319. break;
  7320. }
  7321. if ($val && preg_match('/class="warning"/i', $val)) {
  7322. $iswarning++;
  7323. break;
  7324. }
  7325. }
  7326. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7327. $iserror++;
  7328. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7329. $iswarning++;
  7330. }
  7331. if ($style == 'error') {
  7332. $iserror++;
  7333. }
  7334. if ($style == 'warning') {
  7335. $iswarning++;
  7336. }
  7337. if ($iserror || $iswarning) {
  7338. // Remove div from texts
  7339. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7340. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7341. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7342. // Remove div from texts array
  7343. if (is_array($mesgarray)) {
  7344. $newmesgarray = array();
  7345. foreach ($mesgarray as $val) {
  7346. if (is_string($val)) {
  7347. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7348. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7349. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7350. $newmesgarray[] = $tmpmesgstring;
  7351. } else {
  7352. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7353. }
  7354. }
  7355. $mesgarray = $newmesgarray;
  7356. }
  7357. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7358. } else {
  7359. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7360. }
  7361. }
  7362. /**
  7363. * Print formated error messages to output (Used to show messages on html output).
  7364. *
  7365. * @param string $mesgstring Error message
  7366. * @param array $mesgarray Error messages array
  7367. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7368. * @return void
  7369. *
  7370. * @see dol_print_error()
  7371. * @see dol_htmloutput_mesg()
  7372. */
  7373. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7374. {
  7375. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7376. }
  7377. /**
  7378. * Advanced sort array by second index function, which produces ascending (default)
  7379. * or descending output and uses optionally natural case insensitive sorting (which
  7380. * can be optionally case sensitive as well).
  7381. *
  7382. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7383. * @param string $index Key in array to use for sorting criteria
  7384. * @param int $order Sort order ('asc' or 'desc')
  7385. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7386. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7387. * @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.
  7388. * @return array Sorted array
  7389. */
  7390. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7391. {
  7392. // Clean parameters
  7393. $order = strtolower($order);
  7394. if (is_array($array)) {
  7395. $sizearray = count($array);
  7396. if ($sizearray > 0) {
  7397. $temp = array();
  7398. foreach (array_keys($array) as $key) {
  7399. if (is_object($array[$key])) {
  7400. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7401. } else {
  7402. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7403. }
  7404. }
  7405. if (!$natsort) {
  7406. if ($order == 'asc') {
  7407. asort($temp);
  7408. } else {
  7409. arsort($temp);
  7410. }
  7411. } else {
  7412. if ($case_sensitive) {
  7413. natsort($temp);
  7414. } else {
  7415. natcasesort($temp); // natecasesort is not sensible to case
  7416. }
  7417. if ($order != 'asc') {
  7418. $temp = array_reverse($temp, true);
  7419. }
  7420. }
  7421. $sorted = array();
  7422. foreach (array_keys($temp) as $key) {
  7423. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7424. }
  7425. return $sorted;
  7426. }
  7427. }
  7428. return $array;
  7429. }
  7430. /**
  7431. * Check if a string is in UTF8
  7432. *
  7433. * @param string $str String to check
  7434. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7435. */
  7436. function utf8_check($str)
  7437. {
  7438. $str = (string) $str; // Sometimes string is an int.
  7439. // We must use here a binary strlen function (so not dol_strlen)
  7440. $strLength = dol_strlen($str);
  7441. for ($i = 0; $i < $strLength; $i++) {
  7442. if (ord($str[$i]) < 0x80) {
  7443. continue; // 0bbbbbbb
  7444. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7445. $n = 1; // 110bbbbb
  7446. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7447. $n = 2; // 1110bbbb
  7448. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7449. $n = 3; // 11110bbb
  7450. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7451. $n = 4; // 111110bb
  7452. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7453. $n = 5; // 1111110b
  7454. } else {
  7455. return false; // Does not match any model
  7456. }
  7457. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7458. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7459. return false;
  7460. }
  7461. }
  7462. }
  7463. return true;
  7464. }
  7465. /**
  7466. * Check if a string is in ASCII
  7467. *
  7468. * @param string $str String to check
  7469. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7470. */
  7471. function ascii_check($str)
  7472. {
  7473. if (function_exists('mb_check_encoding')) {
  7474. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7475. if (!mb_check_encoding($str, 'ASCII')) {
  7476. return false;
  7477. }
  7478. } else {
  7479. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7480. return false; // Contains a byte > 7f
  7481. }
  7482. }
  7483. return true;
  7484. }
  7485. /**
  7486. * Return a string encoded into OS filesystem encoding. This function is used to define
  7487. * value to pass to filesystem PHP functions.
  7488. *
  7489. * @param string $str String to encode (UTF-8)
  7490. * @return string Encoded string (UTF-8, ISO-8859-1)
  7491. */
  7492. function dol_osencode($str)
  7493. {
  7494. global $conf;
  7495. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7496. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7497. $tmp = 'iso-8859-1'; // By default for windows
  7498. }
  7499. if (empty($tmp)) {
  7500. $tmp = 'utf-8'; // By default for other
  7501. }
  7502. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7503. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7504. }
  7505. if ($tmp == 'iso-8859-1') {
  7506. return utf8_decode($str);
  7507. }
  7508. return $str;
  7509. }
  7510. /**
  7511. * Return an id or code from a code or id.
  7512. * Store also Code-Id into a cache to speed up next request on same key.
  7513. *
  7514. * @param DoliDB $db Database handler
  7515. * @param string $key Code or Id to get Id or Code
  7516. * @param string $tablename Table name without prefix
  7517. * @param string $fieldkey Field to search the key into
  7518. * @param string $fieldid Field to get
  7519. * @param int $entityfilter Filter by entity
  7520. * @return int <0 if KO, Id of code if OK
  7521. * @see $langs->getLabelFromKey
  7522. */
  7523. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  7524. {
  7525. global $cache_codes;
  7526. // If key empty
  7527. if ($key == '') {
  7528. return '';
  7529. }
  7530. // Check in cache
  7531. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7532. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7533. }
  7534. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7535. $sql = "SELECT ".$fieldid." as valuetoget";
  7536. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7537. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7538. if (!empty($entityfilter)) {
  7539. $sql .= " AND entity IN (".getEntity($tablename).")";
  7540. }
  7541. $resql = $db->query($sql);
  7542. if ($resql) {
  7543. $obj = $db->fetch_object($resql);
  7544. if ($obj) {
  7545. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7546. } else {
  7547. $cache_codes[$tablename][$key][$fieldid] = '';
  7548. }
  7549. $db->free($resql);
  7550. return $cache_codes[$tablename][$key][$fieldid];
  7551. } else {
  7552. return -1;
  7553. }
  7554. }
  7555. /**
  7556. * Verify if condition in string is ok or not
  7557. *
  7558. * @param string $strToEvaluate String with condition to check
  7559. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  7560. */
  7561. function verifCond($strToEvaluate)
  7562. {
  7563. global $user, $conf, $langs;
  7564. global $leftmenu;
  7565. global $rights; // To export to dol_eval function
  7566. //print $strToEvaluate."<br>\n";
  7567. $rights = true;
  7568. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  7569. //$str = 'if(!('.$strToEvaluate.')) $rights = false;';
  7570. //dol_eval($str, 0, 1, '2'); // The dol_eval must contains all the global $xxx used into a condition
  7571. //var_dump($strToEvaluate);
  7572. $rep = dol_eval($strToEvaluate, 1, 1, '1'); // The dol_eval must contains all the global $xxx for all variables $xxx found into the string condition
  7573. $rights = (($rep && strpos($rep, 'Bad string syntax to evaluate') === false) ? true : false);
  7574. //var_dump($rights);
  7575. }
  7576. return $rights;
  7577. }
  7578. /**
  7579. * Replace eval function to add more security.
  7580. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7581. *
  7582. * @param string $s String to evaluate
  7583. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7584. * @param int $hideerrors 1=Hide errors
  7585. * @param string $onlysimplestring 0=Accept all chars, 1=Accept only simple string with char 'a-z0-9\s^$_+-.*\/>&|=!?():"\',/';', 2=Accept also ';[]'
  7586. * @return mixed Nothing or return result of eval
  7587. */
  7588. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  7589. {
  7590. // Only global variables can be changed by eval function and returned to caller
  7591. global $db, $langs, $user, $conf, $website, $websitepage;
  7592. global $action, $mainmenu, $leftmenu;
  7593. global $rights;
  7594. global $object;
  7595. global $mysoc;
  7596. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7597. global $soc; // For backward compatibility
  7598. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  7599. if ($onlysimplestring == '1') {
  7600. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL'
  7601. // We must accept: '$conf->barcode->enabled && preg_match(\'/^(AAA|BBB)/\',$leftmenu)'
  7602. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/', '/').']/i', $s)) {
  7603. if ($returnvalue) {
  7604. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  7605. } else {
  7606. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  7607. return '';
  7608. }
  7609. // TODO We can exclude all () that is not '($db)' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match('
  7610. // ...
  7611. }
  7612. } elseif ($onlysimplestring == '2') {
  7613. // We must accept: (($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"
  7614. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/;[]', '/').']/i', $s)) {
  7615. if ($returnvalue) {
  7616. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  7617. } else {
  7618. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  7619. return '';
  7620. }
  7621. }
  7622. }
  7623. if (strpos($s, '::') !== false) {
  7624. if ($returnvalue) {
  7625. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  7626. } else {
  7627. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  7628. return '';
  7629. }
  7630. }
  7631. if (strpos($s, '`') !== false) {
  7632. if ($returnvalue) {
  7633. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  7634. } else {
  7635. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  7636. return '';
  7637. }
  7638. }
  7639. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  7640. if ($returnvalue) {
  7641. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  7642. } else {
  7643. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  7644. return '';
  7645. }
  7646. }
  7647. // We block use of php exec or php file functions
  7648. $forbiddenphpstrings = array('$$');
  7649. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7650. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI", 'verifCond');
  7651. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  7652. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  7653. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  7654. do {
  7655. $oldstringtoclean = $s;
  7656. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7657. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  7658. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7659. } while ($oldstringtoclean != $s);
  7660. if (strpos($s, '__forbiddenstring__') !== false) {
  7661. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7662. if ($returnvalue) {
  7663. return 'Bad string syntax to evaluate: '.$s;
  7664. } else {
  7665. dol_syslog('Bad string syntax to evaluate: '.$s);
  7666. return '';
  7667. }
  7668. }
  7669. //print $s."<br>\n";
  7670. if ($returnvalue) {
  7671. if ($hideerrors) {
  7672. return @eval('return '.$s.';');
  7673. } else {
  7674. return eval('return '.$s.';');
  7675. }
  7676. } else {
  7677. if ($hideerrors) {
  7678. @eval($s);
  7679. } else {
  7680. eval($s);
  7681. }
  7682. }
  7683. }
  7684. /**
  7685. * Return if var element is ok
  7686. *
  7687. * @param string $element Variable to check
  7688. * @return boolean Return true of variable is not empty
  7689. */
  7690. function dol_validElement($element)
  7691. {
  7692. return (trim($element) != '');
  7693. }
  7694. /**
  7695. * Return img flag of country for a language code or country code.
  7696. *
  7697. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7698. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7699. * @param int $notitlealt No title alt
  7700. * @return string HTML img string with flag.
  7701. */
  7702. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  7703. {
  7704. if (empty($codelang)) {
  7705. return '';
  7706. }
  7707. if ($codelang == 'auto') {
  7708. return '<span class="fa fa-language"></span>';
  7709. }
  7710. $langtocountryflag = array(
  7711. 'ar_AR' => '',
  7712. 'ca_ES' => 'catalonia',
  7713. 'da_DA' => 'dk',
  7714. 'fr_CA' => 'mq',
  7715. 'sv_SV' => 'se',
  7716. 'sw_SW' => 'unknown',
  7717. 'AQ' => 'unknown',
  7718. 'CW' => 'unknown',
  7719. 'IM' => 'unknown',
  7720. 'JE' => 'unknown',
  7721. 'MF' => 'unknown',
  7722. 'BL' => 'unknown',
  7723. 'SX' => 'unknown'
  7724. );
  7725. if (isset($langtocountryflag[$codelang])) {
  7726. $flagImage = $langtocountryflag[$codelang];
  7727. } else {
  7728. $tmparray = explode('_', $codelang);
  7729. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7730. }
  7731. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  7732. }
  7733. /**
  7734. * Return default language from country code.
  7735. * Return null if not found.
  7736. *
  7737. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  7738. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  7739. */
  7740. function getLanguageCodeFromCountryCode($countrycode)
  7741. {
  7742. global $mysoc;
  7743. if (empty($countrycode)) {
  7744. return null;
  7745. }
  7746. if (strtoupper($countrycode) == 'MQ') {
  7747. return 'fr_CA';
  7748. }
  7749. if (strtoupper($countrycode) == 'SE') {
  7750. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7751. }
  7752. if (strtoupper($countrycode) == 'CH') {
  7753. if ($mysoc->country_code == 'FR') {
  7754. return 'fr_CH';
  7755. }
  7756. if ($mysoc->country_code == 'DE') {
  7757. return 'de_CH';
  7758. }
  7759. if ($mysoc->country_code == 'IT') {
  7760. return 'it_CH';
  7761. }
  7762. }
  7763. // Locale list taken from:
  7764. // http://stackoverflow.com/questions/3191664/
  7765. // list-of-all-locales-and-their-short-codes
  7766. $locales = array(
  7767. 'af-ZA',
  7768. 'am-ET',
  7769. 'ar-AE',
  7770. 'ar-BH',
  7771. 'ar-DZ',
  7772. 'ar-EG',
  7773. 'ar-IQ',
  7774. 'ar-JO',
  7775. 'ar-KW',
  7776. 'ar-LB',
  7777. 'ar-LY',
  7778. 'ar-MA',
  7779. 'ar-OM',
  7780. 'ar-QA',
  7781. 'ar-SA',
  7782. 'ar-SY',
  7783. 'ar-TN',
  7784. 'ar-YE',
  7785. //'as-IN', // Moved after en-IN
  7786. 'ba-RU',
  7787. 'be-BY',
  7788. 'bg-BG',
  7789. 'bn-BD',
  7790. //'bn-IN', // Moved after en-IN
  7791. 'bo-CN',
  7792. 'br-FR',
  7793. 'ca-ES',
  7794. 'co-FR',
  7795. 'cs-CZ',
  7796. 'cy-GB',
  7797. 'da-DK',
  7798. 'de-AT',
  7799. 'de-CH',
  7800. 'de-DE',
  7801. 'de-LI',
  7802. 'de-LU',
  7803. 'dv-MV',
  7804. 'el-GR',
  7805. 'en-AU',
  7806. 'en-BZ',
  7807. 'en-CA',
  7808. 'en-GB',
  7809. 'en-IE',
  7810. 'en-IN',
  7811. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  7812. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  7813. 'en-JM',
  7814. 'en-MY',
  7815. 'en-NZ',
  7816. 'en-PH',
  7817. 'en-SG',
  7818. 'en-TT',
  7819. 'en-US',
  7820. 'en-ZA',
  7821. 'en-ZW',
  7822. 'es-AR',
  7823. 'es-BO',
  7824. 'es-CL',
  7825. 'es-CO',
  7826. 'es-CR',
  7827. 'es-DO',
  7828. 'es-EC',
  7829. 'es-ES',
  7830. 'es-GT',
  7831. 'es-HN',
  7832. 'es-MX',
  7833. 'es-NI',
  7834. 'es-PA',
  7835. 'es-PE',
  7836. 'es-PR',
  7837. 'es-PY',
  7838. 'es-SV',
  7839. 'es-US',
  7840. 'es-UY',
  7841. 'es-VE',
  7842. 'et-EE',
  7843. 'eu-ES',
  7844. 'fa-IR',
  7845. 'fi-FI',
  7846. 'fo-FO',
  7847. 'fr-BE',
  7848. 'fr-CA',
  7849. 'fr-CH',
  7850. 'fr-FR',
  7851. 'fr-LU',
  7852. 'fr-MC',
  7853. 'fy-NL',
  7854. 'ga-IE',
  7855. 'gd-GB',
  7856. 'gl-ES',
  7857. 'gu-IN',
  7858. 'he-IL',
  7859. 'hi-IN',
  7860. 'hr-BA',
  7861. 'hr-HR',
  7862. 'hu-HU',
  7863. 'hy-AM',
  7864. 'id-ID',
  7865. 'ig-NG',
  7866. 'ii-CN',
  7867. 'is-IS',
  7868. 'it-CH',
  7869. 'it-IT',
  7870. 'ja-JP',
  7871. 'ka-GE',
  7872. 'kk-KZ',
  7873. 'kl-GL',
  7874. 'km-KH',
  7875. 'kn-IN',
  7876. 'ko-KR',
  7877. 'ky-KG',
  7878. 'lb-LU',
  7879. 'lo-LA',
  7880. 'lt-LT',
  7881. 'lv-LV',
  7882. 'mi-NZ',
  7883. 'mk-MK',
  7884. 'ml-IN',
  7885. 'mn-MN',
  7886. 'mr-IN',
  7887. 'ms-BN',
  7888. 'ms-MY',
  7889. 'mt-MT',
  7890. 'nb-NO',
  7891. 'ne-NP',
  7892. 'nl-BE',
  7893. 'nl-NL',
  7894. 'nn-NO',
  7895. 'oc-FR',
  7896. 'or-IN',
  7897. 'pa-IN',
  7898. 'pl-PL',
  7899. 'ps-AF',
  7900. 'pt-BR',
  7901. 'pt-PT',
  7902. 'rm-CH',
  7903. 'ro-MD',
  7904. 'ro-RO',
  7905. 'ru-RU',
  7906. 'rw-RW',
  7907. 'sa-IN',
  7908. 'se-FI',
  7909. 'se-NO',
  7910. 'se-SE',
  7911. 'si-LK',
  7912. 'sk-SK',
  7913. 'sl-SI',
  7914. 'sq-AL',
  7915. 'sv-FI',
  7916. 'sv-SE',
  7917. 'sw-KE',
  7918. 'ta-IN',
  7919. 'te-IN',
  7920. 'th-TH',
  7921. 'tk-TM',
  7922. 'tn-ZA',
  7923. 'tr-TR',
  7924. 'tt-RU',
  7925. 'ug-CN',
  7926. 'uk-UA',
  7927. 'ur-PK',
  7928. 'vi-VN',
  7929. 'wo-SN',
  7930. 'xh-ZA',
  7931. 'yo-NG',
  7932. 'zh-CN',
  7933. 'zh-HK',
  7934. 'zh-MO',
  7935. 'zh-SG',
  7936. 'zh-TW',
  7937. 'zu-ZA',
  7938. );
  7939. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  7940. if (in_array($buildprimarykeytotest, $locales)) {
  7941. return strtolower($countrycode).'_'.strtoupper($countrycode);
  7942. }
  7943. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  7944. foreach ($locales as $locale) {
  7945. $locale_language = locale_get_primary_language($locale);
  7946. $locale_region = locale_get_region($locale);
  7947. if (strtoupper($countrycode) == $locale_region) {
  7948. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  7949. return strtolower($locale_language).'_'.strtoupper($locale_region);
  7950. }
  7951. }
  7952. } else {
  7953. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  7954. }
  7955. return null;
  7956. }
  7957. /**
  7958. * Complete or removed entries into a head array (used to build tabs).
  7959. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  7960. * Or by change using hook completeTabsHead
  7961. *
  7962. * @param Conf $conf Object conf
  7963. * @param Translate $langs Object langs
  7964. * @param object|null $object Object object
  7965. * @param array $head Object head
  7966. * @param int $h New position to fill
  7967. * @param string $type Value for object where objectvalue can be
  7968. * 'thirdparty' to add a tab in third party view
  7969. * 'intervention' to add a tab in intervention view
  7970. * 'supplier_order' to add a tab in supplier order view
  7971. * 'supplier_invoice' to add a tab in supplier invoice view
  7972. * 'invoice' to add a tab in customer invoice view
  7973. * 'order' to add a tab in customer order view
  7974. * 'contract' to add a tabl in contract view
  7975. * 'product' to add a tab in product view
  7976. * 'propal' to add a tab in propal view
  7977. * 'user' to add a tab in user view
  7978. * 'group' to add a tab in group view
  7979. * 'member' to add a tab in fundation member view
  7980. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  7981. * 'ecm' to add a tab for another ecm view
  7982. * 'stock' to add a tab for warehouse view
  7983. * @param string $mode 'add' to complete head, 'remove' to remove entries
  7984. * @return void
  7985. */
  7986. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  7987. {
  7988. global $hookmanager, $db;
  7989. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  7990. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  7991. $values = explode(':', $value);
  7992. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  7993. if (count($values) == 6) { // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  7994. if ($values[0] != $type) {
  7995. continue;
  7996. }
  7997. if (verifCond($values[4])) {
  7998. if ($values[3]) {
  7999. $langs->load($values[3]);
  8000. }
  8001. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8002. $substitutionarray = array();
  8003. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8004. $label = make_substitutions($reg[1], $substitutionarray);
  8005. } else {
  8006. $labeltemp = explode(':', $values[2]);
  8007. $label = $langs->trans($labeltemp[0]);
  8008. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  8009. dol_include_once($labeltemp[2]);
  8010. $classtoload = $labeltemp[1];
  8011. if (class_exists($classtoload)) {
  8012. $obj = new $classtoload($db);
  8013. $function = $labeltemp[3];
  8014. if ($obj && $function && method_exists($obj, $function)) {
  8015. $nbrec = $obj->$function($object->id, $obj);
  8016. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  8017. }
  8018. }
  8019. }
  8020. }
  8021. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  8022. $head[$h][1] = $label;
  8023. $head[$h][2] = str_replace('+', '', $values[1]);
  8024. $h++;
  8025. }
  8026. } elseif (count($values) == 5) { // deprecated
  8027. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  8028. if ($values[0] != $type) {
  8029. continue;
  8030. }
  8031. if ($values[3]) {
  8032. $langs->load($values[3]);
  8033. }
  8034. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8035. $substitutionarray = array();
  8036. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8037. $label = make_substitutions($reg[1], $substitutionarray);
  8038. } else {
  8039. $label = $langs->trans($values[2]);
  8040. }
  8041. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  8042. $head[$h][1] = $label;
  8043. $head[$h][2] = str_replace('+', '', $values[1]);
  8044. $h++;
  8045. }
  8046. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  8047. if ($values[0] != $type) {
  8048. continue;
  8049. }
  8050. $tabname = str_replace('-', '', $values[1]);
  8051. foreach ($head as $key => $val) {
  8052. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  8053. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  8054. if ($head[$key][2] == $tabname && $condition) {
  8055. unset($head[$key]);
  8056. break;
  8057. }
  8058. }
  8059. }
  8060. }
  8061. }
  8062. // No need to make a return $head. Var is modified as a reference
  8063. if (!empty($hookmanager)) {
  8064. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  8065. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  8066. if ($reshook > 0) { // Hook ask to replace completely the array
  8067. $head = $hookmanager->resArray;
  8068. } else { // Hook
  8069. $head = array_merge($head, $hookmanager->resArray);
  8070. }
  8071. $h = count($head);
  8072. }
  8073. }
  8074. /**
  8075. * Print common footer :
  8076. * conf->global->MAIN_HTML_FOOTER
  8077. * js for switch of menu hider
  8078. * js for conf->global->MAIN_GOOGLE_AN_ID
  8079. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  8080. * js for conf->logbuffer
  8081. *
  8082. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  8083. * @return void
  8084. */
  8085. function printCommonFooter($zone = 'private')
  8086. {
  8087. global $conf, $hookmanager, $user, $debugbar;
  8088. global $action;
  8089. global $micro_start_time;
  8090. if ($zone == 'private') {
  8091. print "\n".'<!-- Common footer for private page -->'."\n";
  8092. } else {
  8093. print "\n".'<!-- Common footer for public page -->'."\n";
  8094. }
  8095. // A div to store page_y POST parameter so we can read it using javascript
  8096. print "\n<!-- A div to store page_y POST parameter -->\n";
  8097. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  8098. $parameters = array();
  8099. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  8100. if (empty($reshook)) {
  8101. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  8102. print $conf->global->MAIN_HTML_FOOTER."\n";
  8103. }
  8104. print "\n";
  8105. if (!empty($conf->use_javascript_ajax)) {
  8106. print '<script>'."\n";
  8107. print 'jQuery(document).ready(function() {'."\n";
  8108. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  8109. print "\n";
  8110. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  8111. print 'jQuery("li.menuhider").click(function(event) {';
  8112. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  8113. print ' console.log("We click on .menuhider");'."\n";
  8114. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  8115. print '});'."\n";
  8116. }
  8117. // Management of focus and mandatory for fields
  8118. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  8119. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  8120. $relativepathstring = $_SERVER["PHP_SELF"];
  8121. // Clean $relativepathstring
  8122. if (constant('DOL_URL_ROOT')) {
  8123. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  8124. }
  8125. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  8126. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  8127. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  8128. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  8129. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  8130. $qualified = 0;
  8131. if ($defkey != '_noquery_') {
  8132. $tmpqueryarraytohave = explode('&', $defkey);
  8133. $foundintru = 0;
  8134. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8135. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8136. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8137. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8138. $foundintru = 1;
  8139. }
  8140. }
  8141. if (!$foundintru) {
  8142. $qualified = 1;
  8143. }
  8144. //var_dump($defkey.'-'.$qualified);
  8145. } else {
  8146. $qualified = 1;
  8147. }
  8148. if ($qualified) {
  8149. foreach ($defval as $paramkey => $paramval) {
  8150. // Set focus on field
  8151. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  8152. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  8153. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  8154. }
  8155. }
  8156. }
  8157. }
  8158. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  8159. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  8160. $qualified = 0;
  8161. if ($defkey != '_noquery_') {
  8162. $tmpqueryarraytohave = explode('&', $defkey);
  8163. $foundintru = 0;
  8164. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8165. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8166. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8167. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8168. $foundintru = 1;
  8169. }
  8170. }
  8171. if (!$foundintru) {
  8172. $qualified = 1;
  8173. }
  8174. //var_dump($defkey.'-'.$qualified);
  8175. } else {
  8176. $qualified = 1;
  8177. }
  8178. if ($qualified) {
  8179. foreach ($defval as $paramkey => $paramval) {
  8180. // Add property 'required' on input
  8181. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8182. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8183. print '// required on a select works only if key is "", so we add the required attributes but also we reset the key -1 or 0 to an empty string'."\n";
  8184. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8185. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  8186. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  8187. // Add 'field required' class on closest td for all input elements : input, textarea and select
  8188. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  8189. }
  8190. }
  8191. }
  8192. }
  8193. }
  8194. print '});'."\n";
  8195. // End of tuning
  8196. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  8197. print "\n";
  8198. print "/* JS CODE TO ENABLE to add memory info */\n";
  8199. print 'window.console && console.log("';
  8200. if (!empty($conf->global->MEMCACHED_SERVER)) {
  8201. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  8202. }
  8203. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  8204. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  8205. $micro_end_time = microtime(true);
  8206. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  8207. }
  8208. if (function_exists("memory_get_usage")) {
  8209. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  8210. }
  8211. if (function_exists("memory_get_peak_usage")) {
  8212. print ' - Real mem peak: '.memory_get_peak_usage(true);
  8213. }
  8214. if (function_exists("zend_loader_file_encoded")) {
  8215. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8216. }
  8217. print '");'."\n";
  8218. }
  8219. print "\n".'</script>'."\n";
  8220. // Google Analytics
  8221. // TODO Add a hook here
  8222. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8223. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8224. foreach ($tmptagarray as $tmptag) {
  8225. print "\n";
  8226. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8227. print "
  8228. <!-- Global site tag (gtag.js) - Google Analytics -->
  8229. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  8230. <script>
  8231. window.dataLayer = window.dataLayer || [];
  8232. function gtag(){dataLayer.push(arguments);}
  8233. gtag('js', new Date());
  8234. gtag('config', '".trim($tmptag)."');
  8235. </script>";
  8236. print "\n";
  8237. }
  8238. }
  8239. }
  8240. // Add Xdebug coverage of code
  8241. if (defined('XDEBUGCOVERAGE')) {
  8242. print_r(xdebug_get_code_coverage());
  8243. }
  8244. // Add DebugBar data
  8245. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8246. $debugbar['time']->stopMeasure('pageaftermaster');
  8247. print '<!-- Output debugbar data -->'."\n";
  8248. $renderer = $debugbar->getRenderer();
  8249. print $debugbar->getRenderer()->render();
  8250. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8251. print "\n";
  8252. print "<!-- Start of log output\n";
  8253. //print '<div class="hidden">'."\n";
  8254. foreach ($conf->logbuffer as $logline) {
  8255. print $logline."<br>\n";
  8256. }
  8257. //print '</div>'."\n";
  8258. print "End of log output -->\n";
  8259. }
  8260. }
  8261. }
  8262. /**
  8263. * Split a string with 2 keys into key array.
  8264. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8265. *
  8266. * @param string $string String to explode
  8267. * @param string $delimiter Delimiter between each couple of data
  8268. * @param string $kv Delimiter between key and value
  8269. * @return array Array of data exploded
  8270. */
  8271. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8272. {
  8273. if ($a = explode($delimiter, $string)) {
  8274. $ka = array();
  8275. foreach ($a as $s) { // each part
  8276. if ($s) {
  8277. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8278. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8279. } else { // key delimiter not found
  8280. $ka[] = trim($s);
  8281. }
  8282. }
  8283. }
  8284. return $ka;
  8285. }
  8286. return array();
  8287. }
  8288. /**
  8289. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  8290. *
  8291. * @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.
  8292. * @return void
  8293. */
  8294. function dol_set_focus($selector)
  8295. {
  8296. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8297. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8298. }
  8299. /**
  8300. * Return getmypid() or random PID when function is disabled
  8301. * Some web hosts disable this php function for security reasons
  8302. * and sometimes we can't redeclare function
  8303. *
  8304. * @return int
  8305. */
  8306. function dol_getmypid()
  8307. {
  8308. if (!function_exists('getmypid')) {
  8309. return mt_rand(1, 32768);
  8310. } else {
  8311. return getmypid();
  8312. }
  8313. }
  8314. /**
  8315. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8316. *
  8317. * @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")
  8318. * @param string $value The value to look for.
  8319. * If param $mode is 0, can contains several keywords separated with a space or |
  8320. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8321. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8322. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8323. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8324. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8325. * @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')
  8326. * 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'
  8327. * @param integer $nofirstand 1=Do not output the first 'AND'
  8328. * @return string $res The statement to append to the SQL query
  8329. * @see dolSqlDateFilter()
  8330. */
  8331. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8332. {
  8333. global $db, $langs;
  8334. $value = trim($value);
  8335. if ($mode == 0) {
  8336. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8337. }
  8338. if ($mode == 1) {
  8339. $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
  8340. }
  8341. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8342. $crits = explode(' ', $value);
  8343. $res = '';
  8344. if (!is_array($fields)) {
  8345. $fields = array($fields);
  8346. }
  8347. $j = 0;
  8348. foreach ($crits as $crit) {
  8349. $crit = trim($crit);
  8350. $i = 0;
  8351. $i2 = 0;
  8352. $newres = '';
  8353. foreach ($fields as $field) {
  8354. if ($mode == 1) {
  8355. $operator = '=';
  8356. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8357. $reg = array();
  8358. preg_match('/([<>=]+)/', $crit, $reg);
  8359. if ($reg[1]) {
  8360. $operator = $reg[1];
  8361. }
  8362. if ($newcrit != '') {
  8363. $numnewcrit = price2num($newcrit);
  8364. if (is_numeric($numnewcrit)) {
  8365. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  8366. } else {
  8367. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8368. }
  8369. $i2++; // a criteria was added to string
  8370. }
  8371. } elseif ($mode == 2 || $mode == -2) {
  8372. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8373. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8374. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8375. if ($mode == -2) {
  8376. $newres .= ' OR '.$field.' IS NULL';
  8377. }
  8378. $i2++; // a criteria was added to string
  8379. } elseif ($mode == 3 || $mode == -3) {
  8380. $tmparray = explode(',', $crit);
  8381. if (count($tmparray)) {
  8382. $listofcodes = '';
  8383. foreach ($tmparray as $val) {
  8384. $val = trim($val);
  8385. if ($val) {
  8386. $listofcodes .= ($listofcodes ? ',' : '');
  8387. $listofcodes .= "'".$db->escape($val)."'";
  8388. }
  8389. }
  8390. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8391. $i2++; // a criteria was added to string
  8392. }
  8393. if ($mode == -3) {
  8394. $newres .= ' OR '.$field.' IS NULL';
  8395. }
  8396. } elseif ($mode == 4) {
  8397. $tmparray = explode(',', $crit);
  8398. if (count($tmparray)) {
  8399. $listofcodes = '';
  8400. foreach ($tmparray as $val) {
  8401. $val = trim($val);
  8402. if ($val) {
  8403. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8404. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8405. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8406. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8407. $newres .= ')';
  8408. $i2++;
  8409. }
  8410. }
  8411. }
  8412. } else // $mode=0
  8413. {
  8414. $tmpcrits = explode('|', $crit);
  8415. $i3 = 0;
  8416. foreach ($tmpcrits as $tmpcrit) {
  8417. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8418. continue;
  8419. }
  8420. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8421. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8422. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? ((float) trim($tmpcrit)) : '0');
  8423. } else {
  8424. $tmpcrit = trim($tmpcrit);
  8425. $tmpcrit2 = $tmpcrit;
  8426. $tmpbefore = '%';
  8427. $tmpafter = '%';
  8428. if (preg_match('/^!/', $tmpcrit)) {
  8429. $newres .= $field." NOT LIKE '"; // ! as exclude character
  8430. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  8431. } else $newres .= $field." LIKE '";
  8432. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8433. $tmpbefore = '';
  8434. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8435. }
  8436. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8437. $tmpafter = '';
  8438. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8439. }
  8440. $newres .= $tmpbefore;
  8441. $newres .= $db->escape($tmpcrit2);
  8442. $newres .= $tmpafter;
  8443. $newres .= "'";
  8444. if ($tmpcrit2 == '') {
  8445. $newres .= " OR ".$field." IS NULL";
  8446. }
  8447. }
  8448. $i3++;
  8449. }
  8450. $i2++; // a criteria was added to string
  8451. }
  8452. $i++;
  8453. }
  8454. if ($newres) {
  8455. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8456. }
  8457. $j++;
  8458. }
  8459. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8460. //print 'xx'.$res.'yy';
  8461. return $res;
  8462. }
  8463. /**
  8464. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8465. *
  8466. * @param Object $object Object
  8467. * @return string Url string
  8468. */
  8469. function showDirectDownloadLink($object)
  8470. {
  8471. global $conf, $langs;
  8472. $out = '';
  8473. $url = $object->getLastMainDocLink($object->element);
  8474. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8475. if ($url) {
  8476. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8477. $out .= ajax_autoselect("directdownloadlink", 0);
  8478. } else {
  8479. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8480. }
  8481. return $out;
  8482. }
  8483. /**
  8484. * Return the filename of file to get the thumbs
  8485. *
  8486. * @param string $file Original filename (full or relative path)
  8487. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8488. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8489. * @return string New file name (full or relative path, including the thumbs/)
  8490. */
  8491. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8492. {
  8493. $dirName = dirname($file);
  8494. if ($dirName == '.') {
  8495. $dirName = '';
  8496. }
  8497. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8498. $fileName = basename($fileName);
  8499. if (empty($extImgTarget)) {
  8500. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8501. }
  8502. if (empty($extImgTarget)) {
  8503. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8504. }
  8505. if (empty($extImgTarget)) {
  8506. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8507. }
  8508. if (empty($extImgTarget)) {
  8509. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8510. }
  8511. if (empty($extImgTarget)) {
  8512. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8513. }
  8514. if (empty($extImgTarget)) {
  8515. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8516. }
  8517. if (!$extImgTarget) {
  8518. return $file;
  8519. }
  8520. $subdir = '';
  8521. if ($extName) {
  8522. $subdir = 'thumbs/';
  8523. }
  8524. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8525. }
  8526. /**
  8527. * Return URL we can use for advanced preview links
  8528. *
  8529. * @param string $modulepart propal, facture, facture_fourn, ...
  8530. * @param string $relativepath Relative path of docs.
  8531. * @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)
  8532. * @param string $param More param on http links
  8533. * @return string|array Output string with href link or array with all components of link
  8534. */
  8535. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8536. {
  8537. global $conf, $langs;
  8538. if (empty($conf->use_javascript_ajax)) {
  8539. return '';
  8540. }
  8541. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8542. if ($alldata == 1) {
  8543. if ($isAllowedForPreview) {
  8544. 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));
  8545. } else {
  8546. return array();
  8547. }
  8548. }
  8549. // old behavior, return a string
  8550. if ($isAllowedForPreview) {
  8551. 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')).'\')';
  8552. } else {
  8553. return '';
  8554. }
  8555. }
  8556. /**
  8557. * Make content of an input box selected when we click into input field.
  8558. *
  8559. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8560. * @param string $addlink Add a 'link to' after
  8561. * @param string $textonlink Text to show on link or 'image'
  8562. * @return string
  8563. */
  8564. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  8565. {
  8566. global $langs;
  8567. $out = '<script>
  8568. jQuery(document).ready(function () {
  8569. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8570. });
  8571. </script>';
  8572. if ($addlink) {
  8573. if ($textonlink === 'image') {
  8574. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  8575. } else {
  8576. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  8577. }
  8578. }
  8579. return $out;
  8580. }
  8581. /**
  8582. * Return if a file is qualified for preview
  8583. *
  8584. * @param string $file Filename we looking for information
  8585. * @return int 1 If allowed, 0 otherwise
  8586. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8587. */
  8588. function dolIsAllowedForPreview($file)
  8589. {
  8590. global $conf;
  8591. // Check .noexe extension in filename
  8592. if (preg_match('/\.noexe$/i', $file)) {
  8593. return 0;
  8594. }
  8595. // Check mime types
  8596. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8597. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8598. $mime_preview[] = 'svg+xml';
  8599. }
  8600. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8601. //$mime_preview[]='archive';
  8602. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8603. if ($num_mime !== false) {
  8604. return 1;
  8605. }
  8606. // By default, not allowed for preview
  8607. return 0;
  8608. }
  8609. /**
  8610. * Return MIME type of a file from its name with extension.
  8611. *
  8612. * @param string $file Filename we looking for MIME type
  8613. * @param string $default Default mime type if extension not found in known list
  8614. * @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
  8615. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8616. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8617. */
  8618. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8619. {
  8620. $mime = $default;
  8621. $imgmime = 'other.png';
  8622. $famime = 'file-o';
  8623. $srclang = '';
  8624. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8625. // Plain text files
  8626. if (preg_match('/\.txt$/i', $tmpfile)) {
  8627. $mime = 'text/plain';
  8628. $imgmime = 'text.png';
  8629. $famime = 'file-text-o';
  8630. }
  8631. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8632. $mime = 'text/richtext';
  8633. $imgmime = 'text.png';
  8634. $famime = 'file-text-o';
  8635. }
  8636. if (preg_match('/\.csv$/i', $tmpfile)) {
  8637. $mime = 'text/csv';
  8638. $imgmime = 'text.png';
  8639. $famime = 'file-text-o';
  8640. }
  8641. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8642. $mime = 'text/tab-separated-values';
  8643. $imgmime = 'text.png';
  8644. $famime = 'file-text-o';
  8645. }
  8646. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8647. $mime = 'text/plain';
  8648. $imgmime = 'text.png';
  8649. $famime = 'file-text-o';
  8650. }
  8651. if (preg_match('/\.ini$/i', $tmpfile)) {
  8652. $mime = 'text/plain';
  8653. $imgmime = 'text.png';
  8654. $srclang = 'ini';
  8655. $famime = 'file-text-o';
  8656. }
  8657. if (preg_match('/\.md$/i', $tmpfile)) {
  8658. $mime = 'text/plain';
  8659. $imgmime = 'text.png';
  8660. $srclang = 'md';
  8661. $famime = 'file-text-o';
  8662. }
  8663. if (preg_match('/\.css$/i', $tmpfile)) {
  8664. $mime = 'text/css';
  8665. $imgmime = 'css.png';
  8666. $srclang = 'css';
  8667. $famime = 'file-text-o';
  8668. }
  8669. if (preg_match('/\.lang$/i', $tmpfile)) {
  8670. $mime = 'text/plain';
  8671. $imgmime = 'text.png';
  8672. $srclang = 'lang';
  8673. $famime = 'file-text-o';
  8674. }
  8675. // Certificate files
  8676. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8677. $mime = 'text/plain';
  8678. $imgmime = 'text.png';
  8679. $famime = 'file-text-o';
  8680. }
  8681. // XML based (HTML/XML/XAML)
  8682. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8683. $mime = 'text/html';
  8684. $imgmime = 'html.png';
  8685. $srclang = 'html';
  8686. $famime = 'file-text-o';
  8687. }
  8688. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8689. $mime = 'text/xml';
  8690. $imgmime = 'other.png';
  8691. $srclang = 'xml';
  8692. $famime = 'file-text-o';
  8693. }
  8694. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8695. $mime = 'text/xml';
  8696. $imgmime = 'other.png';
  8697. $srclang = 'xaml';
  8698. $famime = 'file-text-o';
  8699. }
  8700. // Languages
  8701. if (preg_match('/\.bas$/i', $tmpfile)) {
  8702. $mime = 'text/plain';
  8703. $imgmime = 'text.png';
  8704. $srclang = 'bas';
  8705. $famime = 'file-code-o';
  8706. }
  8707. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8708. $mime = 'text/plain';
  8709. $imgmime = 'text.png';
  8710. $srclang = 'c';
  8711. $famime = 'file-code-o';
  8712. }
  8713. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8714. $mime = 'text/plain';
  8715. $imgmime = 'text.png';
  8716. $srclang = 'cpp';
  8717. $famime = 'file-code-o';
  8718. }
  8719. if (preg_match('/\.cs$/i', $tmpfile)) {
  8720. $mime = 'text/plain';
  8721. $imgmime = 'text.png';
  8722. $srclang = 'cs';
  8723. $famime = 'file-code-o';
  8724. }
  8725. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8726. $mime = 'text/plain';
  8727. $imgmime = 'text.png';
  8728. $srclang = 'h';
  8729. $famime = 'file-code-o';
  8730. }
  8731. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8732. $mime = 'text/plain';
  8733. $imgmime = 'text.png';
  8734. $srclang = 'java';
  8735. $famime = 'file-code-o';
  8736. }
  8737. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8738. $mime = 'text/plain';
  8739. $imgmime = 'php.png';
  8740. $srclang = 'php';
  8741. $famime = 'file-code-o';
  8742. }
  8743. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8744. $mime = 'text/plain';
  8745. $imgmime = 'php.png';
  8746. $srclang = 'php';
  8747. $famime = 'file-code-o';
  8748. }
  8749. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8750. $mime = 'text/plain';
  8751. $imgmime = 'pl.png';
  8752. $srclang = 'perl';
  8753. $famime = 'file-code-o';
  8754. }
  8755. if (preg_match('/\.sql$/i', $tmpfile)) {
  8756. $mime = 'text/plain';
  8757. $imgmime = 'text.png';
  8758. $srclang = 'sql';
  8759. $famime = 'file-code-o';
  8760. }
  8761. if (preg_match('/\.js$/i', $tmpfile)) {
  8762. $mime = 'text/x-javascript';
  8763. $imgmime = 'jscript.png';
  8764. $srclang = 'js';
  8765. $famime = 'file-code-o';
  8766. }
  8767. // Open office
  8768. if (preg_match('/\.odp$/i', $tmpfile)) {
  8769. $mime = 'application/vnd.oasis.opendocument.presentation';
  8770. $imgmime = 'ooffice.png';
  8771. $famime = 'file-powerpoint-o';
  8772. }
  8773. if (preg_match('/\.ods$/i', $tmpfile)) {
  8774. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8775. $imgmime = 'ooffice.png';
  8776. $famime = 'file-excel-o';
  8777. }
  8778. if (preg_match('/\.odt$/i', $tmpfile)) {
  8779. $mime = 'application/vnd.oasis.opendocument.text';
  8780. $imgmime = 'ooffice.png';
  8781. $famime = 'file-word-o';
  8782. }
  8783. // MS Office
  8784. if (preg_match('/\.mdb$/i', $tmpfile)) {
  8785. $mime = 'application/msaccess';
  8786. $imgmime = 'mdb.png';
  8787. $famime = 'file-o';
  8788. }
  8789. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  8790. $mime = 'application/msword';
  8791. $imgmime = 'doc.png';
  8792. $famime = 'file-word-o';
  8793. }
  8794. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  8795. $mime = 'application/msword';
  8796. $imgmime = 'doc.png';
  8797. $famime = 'file-word-o';
  8798. }
  8799. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  8800. $mime = 'application/vnd.ms-excel';
  8801. $imgmime = 'xls.png';
  8802. $famime = 'file-excel-o';
  8803. }
  8804. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  8805. $mime = 'application/vnd.ms-excel';
  8806. $imgmime = 'xls.png';
  8807. $famime = 'file-excel-o';
  8808. }
  8809. if (preg_match('/\.xls$/i', $tmpfile)) {
  8810. $mime = 'application/vnd.ms-excel';
  8811. $imgmime = 'xls.png';
  8812. $famime = 'file-excel-o';
  8813. }
  8814. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  8815. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  8816. $imgmime = 'xls.png';
  8817. $famime = 'file-excel-o';
  8818. }
  8819. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  8820. $mime = 'application/vnd.ms-powerpoint';
  8821. $imgmime = 'ppt.png';
  8822. $famime = 'file-powerpoint-o';
  8823. }
  8824. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  8825. $mime = 'application/x-mspowerpoint';
  8826. $imgmime = 'ppt.png';
  8827. $famime = 'file-powerpoint-o';
  8828. }
  8829. // Other
  8830. if (preg_match('/\.pdf$/i', $tmpfile)) {
  8831. $mime = 'application/pdf';
  8832. $imgmime = 'pdf.png';
  8833. $famime = 'file-pdf-o';
  8834. }
  8835. // Scripts
  8836. if (preg_match('/\.bat$/i', $tmpfile)) {
  8837. $mime = 'text/x-bat';
  8838. $imgmime = 'script.png';
  8839. $srclang = 'dos';
  8840. $famime = 'file-code-o';
  8841. }
  8842. if (preg_match('/\.sh$/i', $tmpfile)) {
  8843. $mime = 'text/x-sh';
  8844. $imgmime = 'script.png';
  8845. $srclang = 'bash';
  8846. $famime = 'file-code-o';
  8847. }
  8848. if (preg_match('/\.ksh$/i', $tmpfile)) {
  8849. $mime = 'text/x-ksh';
  8850. $imgmime = 'script.png';
  8851. $srclang = 'bash';
  8852. $famime = 'file-code-o';
  8853. }
  8854. if (preg_match('/\.bash$/i', $tmpfile)) {
  8855. $mime = 'text/x-bash';
  8856. $imgmime = 'script.png';
  8857. $srclang = 'bash';
  8858. $famime = 'file-code-o';
  8859. }
  8860. // Images
  8861. if (preg_match('/\.ico$/i', $tmpfile)) {
  8862. $mime = 'image/x-icon';
  8863. $imgmime = 'image.png';
  8864. $famime = 'file-image-o';
  8865. }
  8866. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  8867. $mime = 'image/jpeg';
  8868. $imgmime = 'image.png';
  8869. $famime = 'file-image-o';
  8870. }
  8871. if (preg_match('/\.png$/i', $tmpfile)) {
  8872. $mime = 'image/png';
  8873. $imgmime = 'image.png';
  8874. $famime = 'file-image-o';
  8875. }
  8876. if (preg_match('/\.gif$/i', $tmpfile)) {
  8877. $mime = 'image/gif';
  8878. $imgmime = 'image.png';
  8879. $famime = 'file-image-o';
  8880. }
  8881. if (preg_match('/\.bmp$/i', $tmpfile)) {
  8882. $mime = 'image/bmp';
  8883. $imgmime = 'image.png';
  8884. $famime = 'file-image-o';
  8885. }
  8886. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  8887. $mime = 'image/tiff';
  8888. $imgmime = 'image.png';
  8889. $famime = 'file-image-o';
  8890. }
  8891. if (preg_match('/\.svg$/i', $tmpfile)) {
  8892. $mime = 'image/svg+xml';
  8893. $imgmime = 'image.png';
  8894. $famime = 'file-image-o';
  8895. }
  8896. if (preg_match('/\.webp$/i', $tmpfile)) {
  8897. $mime = 'image/webp';
  8898. $imgmime = 'image.png';
  8899. $famime = 'file-image-o';
  8900. }
  8901. // Calendar
  8902. if (preg_match('/\.vcs$/i', $tmpfile)) {
  8903. $mime = 'text/calendar';
  8904. $imgmime = 'other.png';
  8905. $famime = 'file-text-o';
  8906. }
  8907. if (preg_match('/\.ics$/i', $tmpfile)) {
  8908. $mime = 'text/calendar';
  8909. $imgmime = 'other.png';
  8910. $famime = 'file-text-o';
  8911. }
  8912. // Other
  8913. if (preg_match('/\.torrent$/i', $tmpfile)) {
  8914. $mime = 'application/x-bittorrent';
  8915. $imgmime = 'other.png';
  8916. $famime = 'file-o';
  8917. }
  8918. // Audio
  8919. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  8920. $mime = 'audio';
  8921. $imgmime = 'audio.png';
  8922. $famime = 'file-audio-o';
  8923. }
  8924. // Video
  8925. if (preg_match('/\.mp4$/i', $tmpfile)) {
  8926. $mime = 'video/mp4';
  8927. $imgmime = 'video.png';
  8928. $famime = 'file-video-o';
  8929. }
  8930. if (preg_match('/\.ogv$/i', $tmpfile)) {
  8931. $mime = 'video/ogg';
  8932. $imgmime = 'video.png';
  8933. $famime = 'file-video-o';
  8934. }
  8935. if (preg_match('/\.webm$/i', $tmpfile)) {
  8936. $mime = 'video/webm';
  8937. $imgmime = 'video.png';
  8938. $famime = 'file-video-o';
  8939. }
  8940. if (preg_match('/\.avi$/i', $tmpfile)) {
  8941. $mime = 'video/x-msvideo';
  8942. $imgmime = 'video.png';
  8943. $famime = 'file-video-o';
  8944. }
  8945. if (preg_match('/\.divx$/i', $tmpfile)) {
  8946. $mime = 'video/divx';
  8947. $imgmime = 'video.png';
  8948. $famime = 'file-video-o';
  8949. }
  8950. if (preg_match('/\.xvid$/i', $tmpfile)) {
  8951. $mime = 'video/xvid';
  8952. $imgmime = 'video.png';
  8953. $famime = 'file-video-o';
  8954. }
  8955. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  8956. $mime = 'video';
  8957. $imgmime = 'video.png';
  8958. $famime = 'file-video-o';
  8959. }
  8960. // Archive
  8961. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  8962. $mime = 'archive';
  8963. $imgmime = 'archive.png';
  8964. $famime = 'file-archive-o';
  8965. } // application/xxx where zzz is zip, ...
  8966. // Exe
  8967. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  8968. $mime = 'application/octet-stream';
  8969. $imgmime = 'other.png';
  8970. $famime = 'file-o';
  8971. }
  8972. // Lib
  8973. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  8974. $mime = 'library';
  8975. $imgmime = 'library.png';
  8976. $famime = 'file-o';
  8977. }
  8978. // Err
  8979. if (preg_match('/\.err$/i', $tmpfile)) {
  8980. $mime = 'error';
  8981. $imgmime = 'error.png';
  8982. $famime = 'file-text-o';
  8983. }
  8984. // Return string
  8985. if ($mode == 1) {
  8986. $tmp = explode('/', $mime);
  8987. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  8988. }
  8989. if ($mode == 2) {
  8990. return $imgmime;
  8991. }
  8992. if ($mode == 3) {
  8993. return $srclang;
  8994. }
  8995. if ($mode == 4) {
  8996. return $famime;
  8997. }
  8998. return $mime;
  8999. }
  9000. /**
  9001. * Return the value of a filed into a dictionary for the record $id.
  9002. * This also set all the values into a cache for a next search.
  9003. *
  9004. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  9005. * @param string $field The name of field where to find the value to return
  9006. * @param int $id Id of line record
  9007. * @param bool $checkentity Add filter on entity
  9008. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  9009. * @return string The value of field $field. This also set $dictvalues cache.
  9010. */
  9011. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  9012. {
  9013. global $conf, $db;
  9014. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  9015. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  9016. if (is_null($dictvalues)) {
  9017. $dictvalues = array();
  9018. $sql = "SELECT * FROM ".MAIN_DB_PREFIX.$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  9019. if ($checkentity) {
  9020. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  9021. }
  9022. $resql = $db->query($sql);
  9023. if ($resql) {
  9024. while ($obj = $db->fetch_object($resql)) {
  9025. $dictvalues[$obj->{$rowidfield}] = $obj;
  9026. }
  9027. } else {
  9028. dol_print_error($db);
  9029. }
  9030. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  9031. }
  9032. if (!empty($dictvalues[$id])) {
  9033. // Found
  9034. return $dictvalues[$id]->{$field};
  9035. } else {
  9036. // Not found
  9037. return '';
  9038. }
  9039. }
  9040. /**
  9041. * Return true if the color is light
  9042. *
  9043. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  9044. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  9045. */
  9046. function colorIsLight($stringcolor)
  9047. {
  9048. $stringcolor = str_replace('#', '', $stringcolor);
  9049. $res = -1;
  9050. if (!empty($stringcolor)) {
  9051. $res = 0;
  9052. $tmp = explode(',', $stringcolor);
  9053. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  9054. $r = $tmp[0];
  9055. $g = $tmp[1];
  9056. $b = $tmp[2];
  9057. } else {
  9058. $hexr = $stringcolor[0].$stringcolor[1];
  9059. $hexg = $stringcolor[2].$stringcolor[3];
  9060. $hexb = $stringcolor[4].$stringcolor[5];
  9061. $r = hexdec($hexr);
  9062. $g = hexdec($hexg);
  9063. $b = hexdec($hexb);
  9064. }
  9065. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  9066. if ($bright > 0.6) {
  9067. $res = 1;
  9068. }
  9069. }
  9070. return $res;
  9071. }
  9072. /**
  9073. * Function to test if an entry is enabled or not
  9074. *
  9075. * @param string $type_user 0=We test for internal user, 1=We test for external user
  9076. * @param array $menuentry Array for feature entry to test
  9077. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  9078. * @return int 0=Hide, 1=Show, 2=Show gray
  9079. */
  9080. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  9081. {
  9082. global $conf;
  9083. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  9084. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  9085. if (empty($menuentry['enabled'])) {
  9086. return 0; // Entry disabled by condition
  9087. }
  9088. if ($type_user && $menuentry['module']) {
  9089. $tmploops = explode('|', $menuentry['module']);
  9090. $found = 0;
  9091. foreach ($tmploops as $tmploop) {
  9092. if (in_array($tmploop, $listofmodulesforexternal)) {
  9093. $found++;
  9094. break;
  9095. }
  9096. }
  9097. if (!$found) {
  9098. return 0; // Entry is for menus all excluded to external users
  9099. }
  9100. }
  9101. if (!$menuentry['perms'] && $type_user) {
  9102. return 0; // No permissions and user is external
  9103. }
  9104. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  9105. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  9106. }
  9107. if (!$menuentry['perms']) {
  9108. return 2; // No permissions and user is external
  9109. }
  9110. return 1;
  9111. }
  9112. /**
  9113. * Round to next multiple.
  9114. *
  9115. * @param double $n Number to round up
  9116. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  9117. * @return integer Value rounded.
  9118. */
  9119. function roundUpToNextMultiple($n, $x = 5)
  9120. {
  9121. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  9122. }
  9123. /**
  9124. * Function dolGetBadge
  9125. *
  9126. * @param string $label label of badge no html : use in alt attribute for accessibility
  9127. * @param string $html optional : label of badge with html
  9128. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  9129. * @param string $mode default '' , 'pill', 'dot'
  9130. * @param string $url the url for link
  9131. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  9132. * @return string Html badge
  9133. */
  9134. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  9135. {
  9136. $attr = array(
  9137. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  9138. );
  9139. if (empty($html)) {
  9140. $html = $label;
  9141. }
  9142. if (!empty($url)) {
  9143. $attr['href'] = $url;
  9144. }
  9145. if ($mode === 'dot') {
  9146. $attr['class'] .= ' classfortooltip';
  9147. $attr['title'] = $html;
  9148. $attr['aria-label'] = $label;
  9149. $html = '';
  9150. }
  9151. // Override attr
  9152. if (!empty($params['attr']) && is_array($params['attr'])) {
  9153. foreach ($params['attr'] as $key => $value) {
  9154. if ($key == 'class') {
  9155. $attr['class'] .= ' '.$value;
  9156. } elseif ($key == 'classOverride') {
  9157. $attr['class'] = $value;
  9158. } else {
  9159. $attr[$key] = $value;
  9160. }
  9161. }
  9162. }
  9163. // TODO: add hook
  9164. // escape all attribute
  9165. $attr = array_map('dol_escape_htmltag', $attr);
  9166. $TCompiledAttr = array();
  9167. foreach ($attr as $key => $value) {
  9168. $TCompiledAttr[] = $key.'="'.$value.'"';
  9169. }
  9170. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9171. $tag = !empty($url) ? 'a' : 'span';
  9172. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  9173. }
  9174. /**
  9175. * Output the badge of a status.
  9176. *
  9177. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  9178. * @param string $statusLabelShort Short label of badge no html
  9179. * @param string $html Optional : label of badge with html
  9180. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  9181. * @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
  9182. * @param string $url The url for link
  9183. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  9184. * @return string Html status string
  9185. */
  9186. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  9187. {
  9188. global $conf;
  9189. $return = '';
  9190. $dolGetBadgeParams = array();
  9191. if (!empty($params['badgeParams'])) {
  9192. $dolGetBadgeParams = $params['badgeParams'];
  9193. }
  9194. // TODO : add a hook
  9195. if ($displayMode == 0) {
  9196. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  9197. } elseif ($displayMode == 1) {
  9198. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9199. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  9200. // Use status with images (for backward compatibility)
  9201. $return = '';
  9202. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  9203. $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>' : '');
  9204. // For small screen, we always use the short label instead of long label.
  9205. if (!empty($conf->dol_optimize_smallscreen)) {
  9206. if ($displayMode == 0) {
  9207. $displayMode = 1;
  9208. } elseif ($displayMode == 4) {
  9209. $displayMode = 2;
  9210. } elseif ($displayMode == 6) {
  9211. $displayMode = 5;
  9212. }
  9213. }
  9214. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  9215. $statusImg = array(
  9216. 'status0' => 'statut0',
  9217. 'status1' => 'statut1',
  9218. 'status2' => 'statut2',
  9219. 'status3' => 'statut3',
  9220. 'status4' => 'statut4',
  9221. 'status5' => 'statut5',
  9222. 'status6' => 'statut6',
  9223. 'status7' => 'statut7',
  9224. 'status8' => 'statut8',
  9225. 'status9' => 'statut9'
  9226. );
  9227. if (!empty($statusImg[$statusType])) {
  9228. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  9229. } else {
  9230. $htmlImg = img_picto($statusLabel, $statusType);
  9231. }
  9232. if ($displayMode === 2) {
  9233. $return = $htmlImg.' '.$htmlLabelShort;
  9234. } elseif ($displayMode === 3) {
  9235. $return = $htmlImg;
  9236. } elseif ($displayMode === 4) {
  9237. $return = $htmlImg.' '.$htmlLabel;
  9238. } elseif ($displayMode === 5) {
  9239. $return = $htmlLabelShort.' '.$htmlImg;
  9240. } else { // $displayMode >= 6
  9241. $return = $htmlLabel.' '.$htmlImg;
  9242. }
  9243. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9244. // Use new badge
  9245. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9246. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9247. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9248. if ($displayMode == 3) {
  9249. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9250. } elseif ($displayMode === 5) {
  9251. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9252. } else {
  9253. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9254. }
  9255. }
  9256. return $return;
  9257. }
  9258. /**
  9259. * Function dolGetButtonAction
  9260. *
  9261. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  9262. * @param string $html optional : content with html
  9263. * @param string $actionType default, delete, danger
  9264. * @param string $url the url for link
  9265. * @param string $id attribute id of button
  9266. * @param int $userRight user action right
  9267. * // phpcs:disable
  9268. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  9269. * 'attr' => [ // to add or override button attributes
  9270. * 'xxxxx' => '', // your xxxxx attribute you want
  9271. * 'class' => '', // to add more css class to the button class attribute
  9272. * 'classOverride' => '' // to replace class attribute of the button
  9273. * ],
  9274. * 'confirm' => [
  9275. * 'url' => 'http://', // Overide Url to go when user click on action btn, if empty default url is $url.?confirm=yes, for no js compatibility use $url for fallback confirm.
  9276. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  9277. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  9278. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  9279. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  9280. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  9281. * ],
  9282. * ]
  9283. * // phpcs:enable
  9284. * @return string html button
  9285. */
  9286. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  9287. {
  9288. global $hookmanager, $action, $object, $langs;
  9289. $class = 'butAction';
  9290. if ($actionType == 'danger' || $actionType == 'delete') {
  9291. $class = 'butActionDelete';
  9292. if (!empty($url) && strpos($url, 'token=') === false) $url .= '&token='.newToken();
  9293. }
  9294. $attr = array(
  9295. 'class' => $class,
  9296. 'href' => empty($url) ? '' : $url,
  9297. 'title' => $label
  9298. );
  9299. if (empty($html)) {
  9300. $html = $label;
  9301. $attr['title'] = ''; // if html not set, leave label on title is redundant
  9302. } else {
  9303. $attr['aria-label'] = $label;
  9304. }
  9305. if (empty($userRight)) {
  9306. $attr['class'] = 'butActionRefused';
  9307. $attr['href'] = '';
  9308. }
  9309. if (!empty($id)) {
  9310. $attr['id'] = $id;
  9311. }
  9312. // Override attr
  9313. if (!empty($params['attr']) && is_array($params['attr'])) {
  9314. foreach ($params['attr'] as $key => $value) {
  9315. if ($key == 'class') {
  9316. $attr['class'] .= ' '.$value;
  9317. } elseif ($key == 'classOverride') {
  9318. $attr['class'] = $value;
  9319. } else {
  9320. $attr[$key] = $value;
  9321. }
  9322. }
  9323. }
  9324. // automatic add tooltip when title is detected
  9325. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  9326. $attr['class'].= ' classfortooltip';
  9327. }
  9328. // Js Confirm button
  9329. if ($userRight && !empty($params['confirm'])) {
  9330. if (!is_array($params['confirm'])) {
  9331. $params['confirm'] = array(
  9332. 'url' => $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes'
  9333. );
  9334. }
  9335. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9336. $attr['data-confirm-url'] = $params['confirm']['url'];
  9337. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9338. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9339. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9340. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9341. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9342. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9343. $attr['class'].= ' butActionConfirm';
  9344. }
  9345. if (isset($attr['href']) && empty($attr['href'])) {
  9346. unset($attr['href']);
  9347. }
  9348. // escape all attribute
  9349. $attr = array_map('dol_escape_htmltag', $attr);
  9350. $TCompiledAttr = array();
  9351. foreach ($attr as $key => $value) {
  9352. $TCompiledAttr[] = $key.'="'.$value.'"';
  9353. }
  9354. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9355. $tag = !empty($attr['href']) ? 'a' : 'span';
  9356. $parameters = array(
  9357. 'TCompiledAttr' => $TCompiledAttr,
  9358. 'compiledAttributes' => $compiledAttributes,
  9359. 'attr' => $attr,
  9360. 'tag' => $tag,
  9361. 'label' => $label,
  9362. 'html' => $html,
  9363. 'actionType' => $actionType,
  9364. 'url' => $url,
  9365. 'id' => $id,
  9366. 'userRight' => $userRight,
  9367. 'params' => $params
  9368. );
  9369. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9370. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9371. if (empty($reshook)) {
  9372. return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
  9373. } else {
  9374. return $hookmanager->resPrint;
  9375. }
  9376. }
  9377. /**
  9378. * Add space between dolGetButtonTitle
  9379. *
  9380. * @param string $moreClass more css class label
  9381. * @return string html of title separator
  9382. */
  9383. function dolGetButtonTitleSeparator($moreClass = "")
  9384. {
  9385. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9386. }
  9387. /**
  9388. * get field error icon
  9389. *
  9390. * @param string $fieldValidationErrorMsg message to add in tooltip
  9391. * @return string html output
  9392. */
  9393. function getFieldErrorIcon($fieldValidationErrorMsg)
  9394. {
  9395. $out = '';
  9396. if (!empty($fieldValidationErrorMsg)) {
  9397. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9398. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9399. $out.= '</span>';
  9400. }
  9401. return $out;
  9402. }
  9403. /**
  9404. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9405. *
  9406. * @param string $label label of button
  9407. * @param string $helpText optional : content for help tooltip
  9408. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9409. * @param string $url the url for link
  9410. * @param string $id attribute id of button
  9411. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  9412. * @param array $params various params for future : recommended rather than adding more function arguments
  9413. * @return string html button
  9414. */
  9415. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9416. {
  9417. global $langs, $conf, $user;
  9418. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9419. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9420. return '';
  9421. }
  9422. $class = 'btnTitle';
  9423. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots'))) {
  9424. $class .= ' btnTitlePlus';
  9425. }
  9426. $useclassfortooltip = 1;
  9427. if (!empty($params['morecss'])) {
  9428. $class .= ' '.$params['morecss'];
  9429. }
  9430. $attr = array(
  9431. 'class' => $class,
  9432. 'href' => empty($url) ? '' : $url
  9433. );
  9434. if (!empty($helpText)) {
  9435. $attr['title'] = dol_escape_htmltag($helpText);
  9436. } elseif (empty($attr['title']) && $label) {
  9437. $attr['title'] = $label;
  9438. $useclassfortooltip = 0;
  9439. }
  9440. if ($status == 2) {
  9441. $attr['class'] .= ' btnTitleSelected';
  9442. } elseif ($status <= 0) {
  9443. $attr['class'] .= ' refused';
  9444. $attr['href'] = '';
  9445. if ($status == -1) { // disable
  9446. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9447. } elseif ($status == 0) { // Not enough permissions
  9448. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9449. }
  9450. }
  9451. if (!empty($attr['title']) && $useclassfortooltip) {
  9452. $attr['class'] .= ' classfortooltip';
  9453. }
  9454. if (!empty($id)) {
  9455. $attr['id'] = $id;
  9456. }
  9457. // Override attr
  9458. if (!empty($params['attr']) && is_array($params['attr'])) {
  9459. foreach ($params['attr'] as $key => $value) {
  9460. if ($key == 'class') {
  9461. $attr['class'] .= ' '.$value;
  9462. } elseif ($key == 'classOverride') {
  9463. $attr['class'] = $value;
  9464. } else {
  9465. $attr[$key] = $value;
  9466. }
  9467. }
  9468. }
  9469. if (isset($attr['href']) && empty($attr['href'])) {
  9470. unset($attr['href']);
  9471. }
  9472. // TODO : add a hook
  9473. // escape all attribute
  9474. $attr = array_map('dol_escape_htmltag', $attr);
  9475. $TCompiledAttr = array();
  9476. foreach ($attr as $key => $value) {
  9477. $TCompiledAttr[] = $key.'="'.$value.'"';
  9478. }
  9479. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9480. $tag = (empty($attr['href']) ? 'span' : 'a');
  9481. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9482. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9483. if (!empty($params['forcenohideoftext'])) {
  9484. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9485. }
  9486. $button .= '</'.$tag.'>';
  9487. return $button;
  9488. }
  9489. /**
  9490. * Get an array with properties of an element.
  9491. * Called by fetchObjectByElement.
  9492. *
  9493. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9494. * @return array (module, classpath, element, subelement, classfile, classname)
  9495. */
  9496. function getElementProperties($element_type)
  9497. {
  9498. $regs = array();
  9499. $classfile = $classname = $classpath = '';
  9500. // Parse element/subelement (ex: project_task)
  9501. $module = $element_type;
  9502. $element = $element_type;
  9503. $subelement = $element_type;
  9504. // If we ask an resource form external module (instead of default path)
  9505. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9506. $element = $subelement = $regs[1];
  9507. $module = $regs[2];
  9508. }
  9509. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9510. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9511. $module = $element = $regs[1];
  9512. $subelement = $regs[2];
  9513. }
  9514. // For compat
  9515. if ($element_type == "action") {
  9516. $classpath = 'comm/action/class';
  9517. $subelement = 'Actioncomm';
  9518. $module = 'agenda';
  9519. }
  9520. // To work with non standard path
  9521. if ($element_type == 'facture' || $element_type == 'invoice') {
  9522. $classpath = 'compta/facture/class';
  9523. $module = 'facture';
  9524. $subelement = 'facture';
  9525. }
  9526. if ($element_type == 'commande' || $element_type == 'order') {
  9527. $classpath = 'commande/class';
  9528. $module = 'commande';
  9529. $subelement = 'commande';
  9530. }
  9531. if ($element_type == 'propal') {
  9532. $classpath = 'comm/propal/class';
  9533. }
  9534. if ($element_type == 'supplier_proposal') {
  9535. $classpath = 'supplier_proposal/class';
  9536. }
  9537. if ($element_type == 'shipping') {
  9538. $classpath = 'expedition/class';
  9539. $subelement = 'expedition';
  9540. $module = 'expedition_bon';
  9541. }
  9542. if ($element_type == 'delivery') {
  9543. $classpath = 'delivery/class';
  9544. $subelement = 'delivery';
  9545. $module = 'delivery_note';
  9546. }
  9547. if ($element_type == 'contract') {
  9548. $classpath = 'contrat/class';
  9549. $module = 'contrat';
  9550. $subelement = 'contrat';
  9551. }
  9552. if ($element_type == 'member') {
  9553. $classpath = 'adherents/class';
  9554. $module = 'adherent';
  9555. $subelement = 'adherent';
  9556. }
  9557. if ($element_type == 'cabinetmed_cons') {
  9558. $classpath = 'cabinetmed/class';
  9559. $module = 'cabinetmed';
  9560. $subelement = 'cabinetmedcons';
  9561. }
  9562. if ($element_type == 'fichinter') {
  9563. $classpath = 'fichinter/class';
  9564. $module = 'ficheinter';
  9565. $subelement = 'fichinter';
  9566. }
  9567. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9568. $classpath = 'resource/class';
  9569. $module = 'resource';
  9570. $subelement = 'dolresource';
  9571. }
  9572. if ($element_type == 'propaldet') {
  9573. $classpath = 'comm/propal/class';
  9574. $module = 'propal';
  9575. $subelement = 'propaleligne';
  9576. }
  9577. if ($element_type == 'order_supplier') {
  9578. $classpath = 'fourn/class';
  9579. $module = 'fournisseur';
  9580. $subelement = 'commandefournisseur';
  9581. $classfile = 'fournisseur.commande';
  9582. }
  9583. if ($element_type == 'invoice_supplier') {
  9584. $classpath = 'fourn/class';
  9585. $module = 'fournisseur';
  9586. $subelement = 'facturefournisseur';
  9587. $classfile = 'fournisseur.facture';
  9588. }
  9589. if ($element_type == "service") {
  9590. $classpath = 'product/class';
  9591. $subelement = 'product';
  9592. }
  9593. if (empty($classfile)) {
  9594. $classfile = strtolower($subelement);
  9595. }
  9596. if (empty($classname)) {
  9597. $classname = ucfirst($subelement);
  9598. }
  9599. if (empty($classpath)) {
  9600. $classpath = $module.'/class';
  9601. }
  9602. $element_properties = array(
  9603. 'module' => $module,
  9604. 'classpath' => $classpath,
  9605. 'element' => $element,
  9606. 'subelement' => $subelement,
  9607. 'classfile' => $classfile,
  9608. 'classname' => $classname
  9609. );
  9610. return $element_properties;
  9611. }
  9612. /**
  9613. * Fetch an object from its id and element_type
  9614. * Inclusion of classes is automatic
  9615. *
  9616. * @param int $element_id Element id
  9617. * @param string $element_type Element type
  9618. * @param string $element_ref Element ref (Use this or element_id but not both)
  9619. * @return int|object object || 0 || -1 if error
  9620. */
  9621. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9622. {
  9623. global $conf, $db;
  9624. $element_prop = getElementProperties($element_type);
  9625. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9626. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9627. $objecttmp = new $element_prop['classname']($db);
  9628. $ret = $objecttmp->fetch($element_id, $element_ref);
  9629. if ($ret >= 0) {
  9630. return $objecttmp;
  9631. }
  9632. }
  9633. return 0;
  9634. }
  9635. /**
  9636. * Return if a file can contains executable content
  9637. *
  9638. * @param string $filename File name to test
  9639. * @return boolean True if yes, False if no
  9640. */
  9641. function isAFileWithExecutableContent($filename)
  9642. {
  9643. 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)) {
  9644. return true;
  9645. }
  9646. return false;
  9647. }
  9648. /**
  9649. * Return the value of token currently saved into session with name 'newtoken'.
  9650. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9651. *
  9652. * @return string
  9653. */
  9654. function newToken()
  9655. {
  9656. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  9657. }
  9658. /**
  9659. * Return the value of token currently saved into session with name 'token'.
  9660. * For ajax call, you must use this token as a parameter of the call into the js calling script (the called ajax php page must also set constant NOTOKENRENEWAL).
  9661. *
  9662. * @return string
  9663. */
  9664. function currentToken()
  9665. {
  9666. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  9667. }
  9668. /**
  9669. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9670. *
  9671. * @param string $header The first left header of the table (automatic translated)
  9672. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9673. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9674. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9675. * @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"
  9676. * @return void
  9677. *
  9678. * @see finishSimpleTable()
  9679. */
  9680. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9681. {
  9682. global $langs;
  9683. print '<div class="div-table-responsive-no-min">';
  9684. print '<table class="noborder centpercent">';
  9685. print '<tr class="liste_titre">';
  9686. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9687. print $langs->trans($header);
  9688. // extra space between the first header and the number
  9689. if ($number > -1) {
  9690. print ' ';
  9691. }
  9692. if (!empty($link)) {
  9693. if (!empty($arguments)) {
  9694. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9695. } else {
  9696. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9697. }
  9698. }
  9699. if ($number > -1) {
  9700. print '<span class="badge">'.$number.'</span>';
  9701. }
  9702. if (!empty($link)) {
  9703. print '</a>';
  9704. }
  9705. print '</th>';
  9706. if ($number < 0 && !empty($link)) {
  9707. print '<th class="right">';
  9708. if (!empty($arguments)) {
  9709. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9710. } else {
  9711. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9712. }
  9713. print $langs->trans("FullList");
  9714. print '</a>';
  9715. print '</th>';
  9716. }
  9717. print '</tr>';
  9718. }
  9719. /**
  9720. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9721. *
  9722. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9723. * @return void
  9724. *
  9725. * @see startSimpleTable()
  9726. */
  9727. function finishSimpleTable($addLineBreak = false)
  9728. {
  9729. print '</table>';
  9730. print '</div>';
  9731. if ($addLineBreak) {
  9732. print '<br>';
  9733. }
  9734. }
  9735. /**
  9736. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9737. *
  9738. * @param integer $tableColumnCount The complete count columns of the table
  9739. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9740. * @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)
  9741. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9742. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9743. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9744. * @return void
  9745. */
  9746. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9747. {
  9748. global $langs;
  9749. if ($num === 0) {
  9750. print '<tr class="oddeven">';
  9751. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9752. print '</tr>';
  9753. return;
  9754. }
  9755. if ($nbofloop === 0) {
  9756. // don't show a summary line
  9757. return;
  9758. }
  9759. if ($num === 0) {
  9760. $colspan = $tableColumnCount;
  9761. } elseif ($num > $nbofloop) {
  9762. $colspan = $tableColumnCount;
  9763. } else {
  9764. $colspan = $tableColumnCount - 1;
  9765. }
  9766. if ($extraRightColumn) {
  9767. $colspan--;
  9768. }
  9769. print '<tr class="liste_total">';
  9770. if ($nbofloop > 0 && $num > $nbofloop) {
  9771. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9772. } else {
  9773. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  9774. print '<td class="right" width="100">'.price($total).'</td>';
  9775. }
  9776. if ($extraRightColumn) {
  9777. print '<td></td>';
  9778. }
  9779. print '</tr>';
  9780. }
  9781. /**
  9782. * Return a file on output using a low memory. It can return very large files with no need of memory.
  9783. * WARNING: This close output buffers.
  9784. *
  9785. * @param string $fullpath_original_file_osencoded Full path of file to return.
  9786. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  9787. * @return void
  9788. */
  9789. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  9790. {
  9791. global $conf;
  9792. if ($method == -1) {
  9793. $method = 0;
  9794. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  9795. $method = 1;
  9796. }
  9797. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  9798. $method = 2;
  9799. }
  9800. }
  9801. // Be sure we don't have output buffering enabled to have readfile working correctly
  9802. while (ob_get_level()) {
  9803. ob_end_flush();
  9804. }
  9805. // Solution 0
  9806. if ($method == 0) {
  9807. readfile($fullpath_original_file_osencoded);
  9808. } elseif ($method == 1) {
  9809. // Solution 1
  9810. $handle = fopen($fullpath_original_file_osencoded, "rb");
  9811. while (!feof($handle)) {
  9812. print fread($handle, 8192);
  9813. }
  9814. fclose($handle);
  9815. } elseif ($method == 2) {
  9816. // Solution 2
  9817. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  9818. $handle2 = fopen("php://output", "wb");
  9819. stream_copy_to_stream($handle1, $handle2);
  9820. fclose($handle1);
  9821. fclose($handle2);
  9822. }
  9823. }
  9824. /**
  9825. * Create a button to copy $valuetocopy in the clipboard.
  9826. * Code that handle the click is inside lib_foot.jsp.php.
  9827. *
  9828. * @param string $valuetocopy The value to print
  9829. * @param int $showonlyonhover Show the copy-paste button only on hover
  9830. * @param string $texttoshow Replace the value to show with this text
  9831. * @return string The string to print for the button
  9832. */
  9833. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  9834. {
  9835. /*
  9836. global $conf;
  9837. if (!empty($conf->dol_no_mouse_hover)) {
  9838. $showonlyonhover = 0;
  9839. }*/
  9840. $tag = 'span'; // Using div does not work when using the js copy code.
  9841. if ($texttoshow) {
  9842. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint">'.dol_escape_htmltag($texttoshow, 1, 1).'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  9843. } else {
  9844. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  9845. }
  9846. return $result;
  9847. }
  9848. /**
  9849. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  9850. *
  9851. * @param string $stringtodecode String to decode (json or serialize coded)
  9852. * @return mixed The decoded object.
  9853. */
  9854. function jsonOrUnserialize($stringtodecode)
  9855. {
  9856. $result = json_decode($stringtodecode);
  9857. if ($result === null) {
  9858. $result = unserialize($stringtodecode);
  9859. }
  9860. return $result;
  9861. }
  9862. /**
  9863. * Return if a $sqlfilters parameter is valid and will pass the preg_replace_callback() to replace Generic filter string with SQL filter string
  9864. * Example of usage:
  9865. * if ($sqlfilters) {
  9866. * $errormessage = '';
  9867. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9868. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9869. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9870. * }
  9871. * }
  9872. *
  9873. * @param string $sqlfilters sqlfilter string
  9874. * @param string $error Error message
  9875. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  9876. */
  9877. function dolCheckFilters($sqlfilters, &$error = '')
  9878. {
  9879. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  9880. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  9881. $tmp = $sqlfilters;
  9882. $i = 0; $nb = strlen($tmp);
  9883. $counter = 0;
  9884. while ($i < $nb) {
  9885. if ($tmp[$i] == '(') {
  9886. $counter++;
  9887. }
  9888. if ($tmp[$i] == ')') {
  9889. $counter--;
  9890. }
  9891. if ($counter < 0) {
  9892. $error = "Bad sqlfilters=".$sqlfilters;
  9893. dol_syslog($error, LOG_WARNING);
  9894. return false;
  9895. }
  9896. $i++;
  9897. }
  9898. return true;
  9899. }
  9900. /**
  9901. * Function to forge a SQL criteria from a Generic filter string.
  9902. * Example of usage:
  9903. * if ($sqlfilters) {
  9904. * $errormessage = '';
  9905. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9906. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9907. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9908. * }
  9909. * }
  9910. *
  9911. * @param array $matches Array of found string by regex search.
  9912. * Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL"
  9913. * @return string Forged criteria. Example: "t.field like 'abc%'"
  9914. */
  9915. function dolForgeCriteriaCallback($matches)
  9916. {
  9917. global $db;
  9918. dol_syslog("Convert matches ".$matches[1]);
  9919. if (empty($matches[1])) {
  9920. return '';
  9921. }
  9922. $tmp = explode(':', $matches[1], 3);
  9923. if (count($tmp) < 3) {
  9924. return '';
  9925. }
  9926. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  9927. $operator = strtoupper(preg_replace('/[^a-z<>=]/i', '', trim($tmp[1])));
  9928. if ($operator == 'NOTLIKE') {
  9929. $operator = 'NOT LIKE';
  9930. }
  9931. $tmpescaped = trim($tmp[2]);
  9932. $regbis = array();
  9933. if ($operator == 'IN') {
  9934. $tmpescaped = "(".$db->sanitize($tmpescaped, 1).")";
  9935. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  9936. $tmpescaped = "'".$db->escape($regbis[1])."'";
  9937. } else {
  9938. $tmpescaped = $db->sanitize($db->escape($tmpescaped));
  9939. }
  9940. return $db->escape($operand).' '.$db->escape($operator)." ".$tmpescaped;
  9941. }