functions.lib.php 310 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946
  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-2017 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2017 Alexandre Spangaro <aspangaro@zendsi.com>
  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 Frédéric France <frederic.france@netlogic.fr>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. * or see http://www.gnu.org/
  31. */
  32. /**
  33. * \file htdocs/core/lib/functions.lib.php
  34. * \brief A set of functions for Dolibarr
  35. * This file contains all frequently used functions.
  36. */
  37. include_once DOL_DOCUMENT_ROOT .'/core/lib/json.lib.php';
  38. /**
  39. * Function to return value of a static property when class
  40. * name is dynamically defined (not hard coded).
  41. * This is because $myclass::$myvar works from PHP 5.3.0+ only
  42. *
  43. * @param string $class Class name
  44. * @param string $member Name of property
  45. * @return mixed Return value of static property
  46. * @deprecated Dolibarr now requires 5.3.0+, use $class::$property syntax
  47. * @see https://php.net/manual/language.oop5.static.php
  48. */
  49. function getStaticMember($class, $member)
  50. {
  51. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  52. // This part is deprecated. Uncomment if for php 5.2.*, and comment next isset class::member
  53. /*if (version_compare(phpversion(), '5.3.0', '<'))
  54. {
  55. if (is_object($class)) $class = get_class($class);
  56. $classObj = new ReflectionClass($class);
  57. $result = null;
  58. $found=0;
  59. foreach($classObj->getStaticProperties() as $prop => $value)
  60. {
  61. if ($prop == $member)
  62. {
  63. $result = $value;
  64. $found++;
  65. break;
  66. }
  67. }
  68. if ($found) return $result;
  69. }*/
  70. if (isset($class::$member)) return $class::$member;
  71. dol_print_error('','Try to get a static member "'.$member.'" in class "'.$class.'" that does not exists or is not static.');
  72. return null;
  73. }
  74. /**
  75. * Return a DoliDB instance (database handler).
  76. *
  77. * @param string $type Type of database (mysql, pgsql...)
  78. * @param string $host Address of database server
  79. * @param string $user Nom de l'utilisateur autorise
  80. * @param string $pass Mot de passe
  81. * @param string $name Nom de la database
  82. * @param int $port Port of database server
  83. * @return DoliDB A DoliDB instance
  84. */
  85. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  86. {
  87. require_once DOL_DOCUMENT_ROOT ."/core/db/".$type.'.class.php';
  88. $class='DoliDB'.ucfirst($type);
  89. $dolidb=new $class($type, $host, $user, $pass, $name, $port);
  90. return $dolidb;
  91. }
  92. /**
  93. * Get list of entity id to use.
  94. *
  95. * @param string $element Current element
  96. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  97. * 'product', 'productprice', 'stock',
  98. * 'propal', 'supplier_proposal', 'facture', 'facture_fourn', 'payment_various',
  99. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  100. * 'commande', 'commande_fournisseur', 'expedition', 'intervention', 'survey',
  101. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  102. * 'email_template', 'event', 'donation'
  103. * 'c_paiement', 'c_payment_term', ...
  104. * @param int $shared 0=Return id of current entity only,
  105. * 1=Return id of current entity + shared entities (default)
  106. * @param object $currentobject Current object if needed
  107. * @return mixed Entity id(s) to use
  108. */
  109. function getEntity($element, $shared=1, $currentobject=null)
  110. {
  111. global $conf, $mc;
  112. if (is_object($mc))
  113. {
  114. return $mc->getEntity($element, $shared, $currentobject);
  115. }
  116. else
  117. {
  118. $out='';
  119. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  120. if (in_array($element, $addzero)) $out.= '0,';
  121. $out.= $conf->entity;
  122. return $out;
  123. }
  124. }
  125. /**
  126. * Return information about user browser
  127. *
  128. * Returns array with the following format:
  129. * array(
  130. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  131. * 'browserversion' => Browser version. Empty if unknown
  132. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  133. * 'layout' => (tablet|phone|classic)
  134. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  135. * 'tablet' => true/false
  136. * )
  137. *
  138. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  139. * @return array Check function documentation
  140. */
  141. function getBrowserInfo($user_agent)
  142. {
  143. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  144. $name='unknown';
  145. $version='';
  146. $os='unknown';
  147. $phone = '';
  148. $detectmobile = new Mobile_Detect(null, $user_agent);
  149. $tablet = $detectmobile->isTablet();
  150. if ($detectmobile->isMobile()) {
  151. $phone = 'unknown';
  152. // If phone/smartphone, we set phone os name.
  153. if ($detectmobile->is('AndroidOS')) {
  154. $os = $phone = 'android';
  155. } elseif ($detectmobile->is('BlackBerryOS')) {
  156. $os = $phone = 'blackberry';
  157. } elseif ($detectmobile->is('iOS')) {
  158. $os = 'ios';
  159. $phone = 'iphone';
  160. } elseif ($detectmobile->is('PalmOS')) {
  161. $os = $phone = 'palm';
  162. } elseif ($detectmobile->is('SymbianOS')) {
  163. $os = 'symbian';
  164. } elseif ($detectmobile->is('webOS')) {
  165. $os = 'webos';
  166. } elseif ($detectmobile->is('MaemoOS')) {
  167. $os = 'maemo';
  168. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  169. $os = 'windows';
  170. }
  171. }
  172. // OS
  173. if (preg_match('/linux/i', $user_agent)) { $os='linux'; }
  174. elseif (preg_match('/macintosh/i', $user_agent)) { $os='macintosh'; }
  175. elseif (preg_match('/windows/i', $user_agent)) { $os='windows'; }
  176. // Name
  177. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='firefox'; $version=$reg[2]; }
  178. elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='edge'; $version=$reg[2]; }
  179. elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name='chrome'; $version=$reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string
  180. elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name='chrome'; }
  181. elseif (preg_match('/iceweasel/i', $user_agent)) { $name='iceweasel'; }
  182. elseif (preg_match('/epiphany/i', $user_agent)) { $name='epiphany'; }
  183. elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='safari'; $version=$reg[2]; } // Safari is often present in string for mobile but its not.
  184. elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='opera'; $version=$reg[2]; }
  185. elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name='ie'; $version=end($reg); } // MS products at end
  186. elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name='ie'; $version=end($reg); } // MS products at end
  187. elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name='lynxlinks'; $version=$reg[4]; }
  188. if ($tablet) {
  189. $layout = 'tablet';
  190. } elseif ($phone) {
  191. $layout = 'phone';
  192. } else {
  193. $layout = 'classic';
  194. }
  195. return array(
  196. 'browsername' => $name,
  197. 'browserversion' => $version,
  198. 'browseros' => $os,
  199. 'layout' => $layout,
  200. 'phone' => $phone,
  201. 'tablet' => $tablet
  202. );
  203. }
  204. /**
  205. * Function called at end of web php process
  206. *
  207. * @return void
  208. */
  209. function dol_shutdown()
  210. {
  211. global $conf,$user,$langs,$db;
  212. $disconnectdone=false; $depth=0;
  213. if (is_object($db) && ! empty($db->connected)) { $depth=$db->transaction_opened; $disconnectdone=$db->close(); }
  214. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth)?' (Warn: db disconnection forced, transaction depth was '.$depth.')':''), (($disconnectdone && $depth)?LOG_WARNING:LOG_INFO));
  215. }
  216. /**
  217. * Return true if we are in a context of submitting a parameter
  218. *
  219. * @param string $paramname Name or parameter to test
  220. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  221. */
  222. function GETPOSTISSET($paramname)
  223. {
  224. return (isset($_POST[$paramname]) || isset($_GET[$paramname]));
  225. }
  226. /**
  227. * Return value of a param into GET or POST supervariable.
  228. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  229. * Note: The property $user->default_values is loaded by main.php when loading the user.
  230. *
  231. * @param string $paramname Name of parameter to found
  232. * @param string $check Type of check
  233. * ''=no check (deprecated)
  234. * 'none'=no check (only for param that should have very rich content)
  235. * 'int'=check it's numeric (integer or float)
  236. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  237. * 'alpha'=check it's text and sign
  238. * 'aZ'=check it's a-z only
  239. * 'aZ09'=check it's simple alpha string (recommended for keys)
  240. * 'array'=check it's array
  241. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  242. * 'nohtml', 'alphanohtml'=check there is no html content
  243. * 'custom'= custom filter specify $filter and $options)
  244. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get, 4 = post then get then cookie)
  245. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  246. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  247. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  248. * @return string|string[] Value found (string or array), or '' if check fails
  249. */
  250. function GETPOST($paramname, $check='none', $method=0, $filter=null, $options=null, $noreplace=0)
  251. {
  252. global $mysoc,$user,$conf;
  253. if (empty($paramname)) return 'BadFirstParameterForGETPOST';
  254. if (empty($check))
  255. {
  256. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  257. // Enable this line to know who call the GETPOST with '' $check parameter.
  258. //var_dump(debug_backtrace()[0]);
  259. }
  260. if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
  261. elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
  262. elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
  263. elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
  264. elseif ($method==4) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:(isset($_COOKIE[$paramname])?$_COOKIE[$paramname]:''));
  265. else return 'BadThirdParameterForGETPOST';
  266. if (empty($method) || $method == 3 || $method == 4)
  267. {
  268. $relativepathstring = $_SERVER["PHP_SELF"];
  269. // Clean $relativepathstring
  270. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
  271. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  272. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  273. //var_dump($relativepathstring);
  274. //var_dump($user->default_values);
  275. // Code for search criteria persistence.
  276. // Retrieve values if restore_lastsearch_values
  277. if (! empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  278. {
  279. if (! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  280. {
  281. $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  282. if (is_array($tmp))
  283. {
  284. foreach($tmp as $key => $val)
  285. {
  286. if ($key == $paramname) // We are on the requested parameter
  287. {
  288. $out=$val;
  289. break;
  290. }
  291. }
  292. }
  293. }
  294. // If there is saved contextpage, page or limit
  295. if ($paramname == 'contextpage' && ! empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  296. {
  297. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  298. }
  299. elseif ($paramname == 'page' && ! empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  300. {
  301. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  302. }
  303. elseif ($paramname == 'limit' && ! empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  304. {
  305. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  306. }
  307. }
  308. // Else, retreive default values if we are not doing a sort
  309. elseif (! isset($_GET['sortfield'])) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
  310. {
  311. if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  312. {
  313. // Search default value from $object->field
  314. global $object;
  315. if (is_object($object) && isset($object->fields[$paramname]['default']))
  316. {
  317. $out = $object->fields[$paramname]['default'];
  318. }
  319. }
  320. if (! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
  321. {
  322. if (! empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  323. {
  324. // Now search in setup to overwrite default values
  325. if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  326. {
  327. if (isset($user->default_values[$relativepathstring]['createform']))
  328. {
  329. foreach($user->default_values[$relativepathstring]['createform'] as $defkey => $defval)
  330. {
  331. $qualified = 0;
  332. if ($defkey != '_noquery_')
  333. {
  334. $tmpqueryarraytohave=explode('&', $defkey);
  335. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  336. $foundintru=0;
  337. foreach($tmpqueryarraytohave as $tmpquerytohave)
  338. {
  339. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  340. }
  341. if (! $foundintru) $qualified=1;
  342. //var_dump($defkey.'-'.$qualified);
  343. }
  344. else $qualified = 1;
  345. if ($qualified)
  346. {
  347. //var_dump($user->default_values[$relativepathstring][$defkey]['createform']);
  348. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname]))
  349. {
  350. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  351. break;
  352. }
  353. }
  354. }
  355. }
  356. }
  357. }
  358. // Management of default search_filters and sort order
  359. //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  360. elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  361. {
  362. if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  363. {
  364. //var_dump($user->default_values[$relativepathstring]);
  365. if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ?
  366. {
  367. if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...']
  368. {
  369. foreach($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval)
  370. {
  371. $qualified = 0;
  372. if ($defkey != '_noquery_')
  373. {
  374. $tmpqueryarraytohave=explode('&', $defkey);
  375. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  376. $foundintru=0;
  377. foreach($tmpqueryarraytohave as $tmpquerytohave)
  378. {
  379. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  380. }
  381. if (! $foundintru) $qualified=1;
  382. //var_dump($defkey.'-'.$qualified);
  383. }
  384. else $qualified = 1;
  385. if ($qualified)
  386. {
  387. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  388. foreach($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val)
  389. {
  390. if ($out) $out.=', ';
  391. if ($paramname == 'sortfield')
  392. {
  393. $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  394. }
  395. if ($paramname == 'sortorder')
  396. {
  397. $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  398. }
  399. }
  400. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  401. }
  402. }
  403. }
  404. }
  405. elseif (isset($user->default_values[$relativepathstring]['filters']))
  406. {
  407. foreach($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  408. {
  409. $qualified = 0;
  410. if ($defkey != '_noquery_')
  411. {
  412. $tmpqueryarraytohave=explode('&', $defkey);
  413. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  414. $foundintru=0;
  415. foreach($tmpqueryarraytohave as $tmpquerytohave)
  416. {
  417. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  418. }
  419. if (! $foundintru) $qualified=1;
  420. //var_dump($defkey.'-'.$qualified);
  421. }
  422. else $qualified = 1;
  423. if ($qualified)
  424. {
  425. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all']))
  426. {
  427. // We made a search from quick search menu, do we still use default filter ?
  428. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH))
  429. {
  430. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  431. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  432. }
  433. }
  434. else
  435. {
  436. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  437. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  438. }
  439. break;
  440. }
  441. }
  442. }
  443. }
  444. }
  445. }
  446. }
  447. }
  448. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable paramaters)
  449. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  450. // 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.
  451. if (! is_array($out) && empty($_POST[$paramname]) && empty($noreplace))
  452. {
  453. $maxloop=20; $loopnb=0; // Protection against infinite loop
  454. 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.
  455. {
  456. $loopnb++; $newout = '';
  457. if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; }
  458. elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; }
  459. elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; }
  460. elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; }
  461. elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; }
  462. elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); }
  463. elseif ($reg[1] == 'NEXT_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; }
  464. elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; }
  465. elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); }
  466. elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID')
  467. {
  468. $newout = $mysoc->country_id;
  469. }
  470. elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID')
  471. {
  472. $newout = $user->id;
  473. }
  474. elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID')
  475. {
  476. $newout = $user->fk_user;
  477. }
  478. elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID')
  479. {
  480. $newout = $conf->entity;
  481. }
  482. else $newout = ''; // Key not found, we replace with empty string
  483. //var_dump('__'.$reg[1].'__ -> '.$newout);
  484. $out = preg_replace('/__'.preg_quote($reg[1],'/').'__/', $newout, $out);
  485. }
  486. }
  487. // Check is done after replacement
  488. switch ($check)
  489. {
  490. case 'none':
  491. break;
  492. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  493. if (! is_numeric($out)) { $out=''; }
  494. break;
  495. case 'intcomma':
  496. if (preg_match('/[^0-9,-]+/i',$out)) $out='';
  497. break;
  498. case 'alpha':
  499. if (! is_array($out))
  500. {
  501. $out=trim($out);
  502. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  503. // '../' is dangerous because it allows dir transversals
  504. if (preg_match('/"/',$out)) $out='';
  505. else if (preg_match('/\.\.\//',$out)) $out='';
  506. }
  507. break;
  508. case 'san_alpha':
  509. $out=filter_var($out,FILTER_SANITIZE_STRING);
  510. break;
  511. case 'aZ':
  512. if (! is_array($out))
  513. {
  514. $out=trim($out);
  515. if (preg_match('/[^a-z]+/i',$out)) $out='';
  516. }
  517. break;
  518. case 'aZ09':
  519. if (! is_array($out))
  520. {
  521. $out=trim($out);
  522. if (preg_match('/[^a-z0-9_\-\.]+/i',$out)) $out='';
  523. }
  524. break;
  525. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  526. if (! is_array($out))
  527. {
  528. $out=trim($out);
  529. if (preg_match('/[^a-z0-9_\-\.,]+/i',$out)) $out='';
  530. }
  531. break;
  532. case 'array':
  533. if (! is_array($out) || empty($out)) $out=array();
  534. break;
  535. case 'nohtml': // Recommended for most scalar parameters
  536. $out=dol_string_nohtmltag($out, 0);
  537. break;
  538. case 'alphanohtml': // Recommended for search parameters
  539. if (! is_array($out))
  540. {
  541. $out=trim($out);
  542. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  543. // '../' is dangerous because it allows dir transversals
  544. if (preg_match('/"/',$out)) $out='';
  545. else if (preg_match('/\.\.\//',$out)) $out='';
  546. $out=dol_string_nohtmltag($out);
  547. }
  548. break;
  549. case 'custom':
  550. if (empty($filter)) return 'BadFourthParameterForGETPOST';
  551. $out=filter_var($out, $filter, $options);
  552. break;
  553. }
  554. // Code for search criteria persistence.
  555. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  556. if (empty($method) || $method == 3 || $method == 4)
  557. {
  558. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield')))
  559. {
  560. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  561. // We save search key only if $out not empty that means:
  562. // - posted value not empty, or
  563. // - 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).
  564. if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep
  565. {
  566. $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out;
  567. }
  568. }
  569. }
  570. return $out;
  571. }
  572. if (! function_exists('dol_getprefix'))
  573. {
  574. /**
  575. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  576. * The prefix for session is unique in a web context only and is unique for instance and avoid conflict
  577. * between multi-instances, even when having two instances with same root dir or two instances in same virtual servers.
  578. * The prefix for email is unique if MAIL_PREFIX_FOR_EMAIL_ID is set to a value, otherwise value may be same than other instance.
  579. *
  580. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  581. * @return string A calculated prefix
  582. */
  583. function dol_getprefix($mode='')
  584. {
  585. global $conf;
  586. // If prefix is for email
  587. if ($mode == 'email')
  588. {
  589. if (! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  590. {
  591. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  592. else if (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"];
  593. }
  594. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  595. }
  596. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"]))
  597. {
  598. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  599. // Use this for a "readable" key
  600. //return dol_sanitizeFileName($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  601. }
  602. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  603. }
  604. }
  605. /**
  606. * Make an include_once using default root and alternate root if it fails.
  607. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  608. * To link to a module file from a module file, use include './mymodulefile';
  609. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  610. *
  611. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  612. * @param string $classname Class name (deprecated)
  613. * @return bool True if load is a success, False if it fails
  614. */
  615. function dol_include_once($relpath, $classname='')
  616. {
  617. global $conf,$langs,$user,$mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var']
  618. $fullpath = dol_buildpath($relpath);
  619. if (!file_exists($fullpath)) {
  620. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_ERR);
  621. return false;
  622. }
  623. if (! empty($classname) && ! class_exists($classname)) {
  624. return include $fullpath;
  625. } else {
  626. return include_once $fullpath;
  627. }
  628. }
  629. /**
  630. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  631. *
  632. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  633. * @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)
  634. * @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)
  635. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  636. * 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
  637. * @return string Full filesystem path (if path=0), Full url path (if mode=1)
  638. */
  639. function dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
  640. {
  641. global $conf;
  642. $path=preg_replace('/^\//','',$path);
  643. if (empty($type)) // For a filesystem path
  644. {
  645. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  646. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  647. {
  648. if ($key == 'main')
  649. {
  650. continue;
  651. }
  652. if (file_exists($dirroot.'/'.$path))
  653. {
  654. $res=$dirroot.'/'.$path;
  655. return $res;
  656. }
  657. }
  658. if ($returnemptyifnotfound) // Not found into alternate dir
  659. {
  660. if ($returnemptyifnotfound == 1 || ! file_exists($res)) return '';
  661. }
  662. }
  663. else // For an url path
  664. {
  665. // We try to get local path of file on filesystem from url
  666. // Note that trying to know if a file on disk exist by forging path on disk from url
  667. // works only for some web server and some setup. This is bugged when
  668. // using proxy, rewriting, virtual path, etc...
  669. $res='';
  670. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  671. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  672. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  673. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  674. {
  675. if ($key == 'main')
  676. {
  677. if ($type == 3)
  678. {
  679. global $dolibarr_main_url_root;
  680. // Define $urlwithroot
  681. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  682. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  683. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  684. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  685. }
  686. continue;
  687. }
  688. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  689. if (! empty($regs[1]))
  690. {
  691. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  692. if (file_exists($dirroot.'/'.$regs[1]))
  693. {
  694. if ($type == 1)
  695. {
  696. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  697. }
  698. if ($type == 2)
  699. {
  700. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  701. }
  702. if ($type == 3)
  703. {
  704. global $dolibarr_main_url_root;
  705. // Define $urlwithroot
  706. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  707. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  708. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  709. $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
  710. }
  711. break;
  712. }
  713. }
  714. }
  715. }
  716. return $res;
  717. }
  718. /**
  719. * Create a clone of instance of object (new instance with same value for properties)
  720. * With native = 0: Property that are reference are also new object (true clone). This means $this->db is not valid.
  721. * With native = 1: Use PHP clone. Property that are reference are same pointer. This means $this->db is still valid.
  722. *
  723. * @param object $object Object to clone
  724. * @param int $native Native method or true method
  725. * @return object Object clone
  726. * @see https://php.net/manual/language.oop5.cloning.php
  727. */
  728. function dol_clone($object, $native=0)
  729. {
  730. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  731. if (empty($native))
  732. {
  733. $myclone=unserialize(serialize($object));
  734. }
  735. else
  736. {
  737. $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable)
  738. }
  739. return $myclone;
  740. }
  741. /**
  742. * Optimize a size for some browsers (phone, smarphone, ...)
  743. *
  744. * @param int $size Size we want
  745. * @param string $type Type of optimizing:
  746. * '' = function used to define a size for truncation
  747. * 'width' = function is used to define a width
  748. * @return int New size after optimizing
  749. */
  750. function dol_size($size,$type='')
  751. {
  752. global $conf;
  753. if (empty($conf->dol_optimize_smallscreen)) return $size;
  754. if ($type == 'width' && $size > 250) return 250;
  755. else return 10;
  756. }
  757. /**
  758. * Clean a string to use it as a file name
  759. *
  760. * @param string $str String to clean
  761. * @param string $newstr String to replace bad chars with
  762. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  763. * @return string String cleaned (a-zA-Z_)
  764. *
  765. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizePathName
  766. */
  767. function dol_sanitizeFileName($str,$newstr='_',$unaccent=1)
  768. {
  769. $filesystem_forbidden_chars = array('<','>','/','\\','?','*','|','"','°');
  770. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  771. }
  772. /**
  773. * Clean a string to use it as a path name
  774. *
  775. * @param string $str String to clean
  776. * @param string $newstr String to replace bad chars with
  777. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  778. * @return string String cleaned (a-zA-Z_)
  779. *
  780. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizeFileName
  781. */
  782. function dol_sanitizePathName($str,$newstr='_',$unaccent=1)
  783. {
  784. $filesystem_forbidden_chars = array('<','>','?','*','|','"','°');
  785. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  786. }
  787. /**
  788. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  789. *
  790. * @param string $str String to clean
  791. * @return string Cleaned string
  792. *
  793. * @see dol_sanitizeFilename, dol_string_nospecial
  794. */
  795. function dol_string_unaccent($str)
  796. {
  797. if (utf8_check($str))
  798. {
  799. // See http://www.utf8-chartable.de/
  800. $string = rawurlencode($str);
  801. $replacements = array(
  802. '%C3%80' => 'A','%C3%81' => 'A','%C3%82' => 'A','%C3%83' => 'A','%C3%84' => 'A','%C3%85' => 'A',
  803. '%C3%88' => 'E','%C3%89' => 'E','%C3%8A' => 'E','%C3%8B' => 'E',
  804. '%C3%8C' => 'I','%C3%8D' => 'I','%C3%8E' => 'I','%C3%8F' => 'I',
  805. '%C3%92' => 'O','%C3%93' => 'O','%C3%94' => 'O','%C3%95' => 'O','%C3%96' => 'O',
  806. '%C3%99' => 'U','%C3%9A' => 'U','%C3%9B' => 'U','%C3%9C' => 'U',
  807. '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a','%C3%A3' => 'a','%C3%A4' => 'a','%C3%A5' => 'a',
  808. '%C3%A7' => 'c',
  809. '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
  810. '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i','%C3%AF' => 'i',
  811. '%C3%B1' => 'n',
  812. '%C3%B2' => 'o','%C3%B3' => 'o','%C3%B4' => 'o','%C3%B5' => 'o','%C3%B6' => 'o',
  813. '%C3%B9' => 'u','%C3%BA' => 'u','%C3%BB' => 'u','%C3%BC' => 'u',
  814. '%C3%BF' => 'y'
  815. );
  816. $string=strtr($string, $replacements);
  817. return rawurldecode($string);
  818. }
  819. else
  820. {
  821. // See http://www.ascii-code.com/
  822. $string = strtr(
  823. $str,
  824. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  825. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  826. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  827. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  828. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  829. \xF9\xFA\xFB\xFC\xFD\xFF",
  830. "AAAAAAC
  831. EEEEIIIIDN
  832. OOOOOUUUY
  833. aaaaaaceeee
  834. iiiidnooooo
  835. uuuuyy"
  836. );
  837. $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"));
  838. return $string;
  839. }
  840. }
  841. /**
  842. * Clean a string from all punctuation characters to use it as a ref or login.
  843. * This is a more complete function than dol_sanitizeFileName.
  844. *
  845. * @param string $str String to clean
  846. * @param string $newstr String to replace forbidden chars with
  847. * @param array $badcharstoreplace List of forbidden characters
  848. * @return string Cleaned string
  849. *
  850. * @see dol_sanitizeFilename, dol_string_unaccent
  851. */
  852. function dol_string_nospecial($str,$newstr='_',$badcharstoreplace='')
  853. {
  854. $forbidden_chars_to_replace=array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  855. $forbidden_chars_to_remove=array();
  856. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace=$badcharstoreplace;
  857. //$forbidden_chars_to_remove=array("(",")");
  858. return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
  859. }
  860. /**
  861. * Encode string for xml usage
  862. *
  863. * @param string $string String to encode
  864. * @return string String encoded
  865. */
  866. function dolEscapeXML($string)
  867. {
  868. return strtr($string, array('\''=>'&apos;','"'=>'&quot;','&'=>'&amp;','<'=>'&lt;','>'=>'&gt;'));
  869. }
  870. /**
  871. * Returns text escaped for inclusion into javascript code
  872. *
  873. * @param string $stringtoescape String to escape
  874. * @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 \
  875. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  876. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  877. */
  878. function dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
  879. {
  880. // escape quotes and backslashes, newlines, etc.
  881. $substitjs=array("&#039;"=>"\\'","\r"=>'\\r');
  882. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  883. if (empty($noescapebackslashn)) { $substitjs["\n"]='\\n'; $substitjs['\\']='\\\\'; }
  884. if (empty($mode)) { $substitjs["'"]="\\'"; $substitjs['"']="\\'"; }
  885. else if ($mode == 1) $substitjs["'"]="\\'";
  886. else if ($mode == 2) { $substitjs['"']='\\"'; }
  887. else if ($mode == 3) { $substitjs["'"]="\\'"; $substitjs['"']="\\\""; }
  888. return strtr($stringtoescape, $substitjs);
  889. }
  890. /**
  891. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  892. *
  893. * @param string $stringtoescape String to escape
  894. * @param int $keepb 1=Preserve b tags (otherwise, remove them)
  895. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  896. * @param string $keepmoretags '' or 'common' or list of tags
  897. * @return string Escaped string
  898. * @see dol_string_nohtmltag, dol_string_nospecial, dol_string_unaccent
  899. */
  900. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $keepmoretags = '')
  901. {
  902. if ($keepmoretags == 'common') $keepmoretags = 'html,body,a,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  903. // TODO Implement $keepmoretags
  904. // escape quotes and backslashes, newlines, etc.
  905. $tmp=html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
  906. if (! $keepb) $tmp=strtr($tmp, array("<b>"=>'','</b>'=>''));
  907. if (! $keepn) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n'));
  908. return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html tags
  909. }
  910. /**
  911. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  912. *
  913. * @param string $utf8_string String to encode
  914. * @return string String converted
  915. */
  916. function dol_strtolower($utf8_string)
  917. {
  918. return mb_strtolower($utf8_string, "UTF-8");
  919. }
  920. /**
  921. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  922. *
  923. * @param string $utf8_string String to encode
  924. * @return string String converted
  925. */
  926. function dol_strtoupper($utf8_string)
  927. {
  928. return mb_strtoupper($utf8_string, "UTF-8");
  929. }
  930. /**
  931. * Write log message into outputs. Possible outputs can be:
  932. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  933. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  934. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  935. * this, use logging to files instead of syslog (see setup of module).
  936. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  937. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  938. * This function works only if syslog module is enabled.
  939. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  940. *
  941. * @param string $message Line to log. ''=Show nothing
  942. * @param int $level Log level
  943. * 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
  944. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  945. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  946. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  947. * @param string $restricttologhandler Output log only for this log handler
  948. * @return void
  949. */
  950. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename='', $restricttologhandler='')
  951. {
  952. global $conf, $user;
  953. // If syslog module enabled
  954. if (empty($conf->syslog->enabled)) return;
  955. if ($ident < 0)
  956. {
  957. foreach ($conf->loghandlers as $loghandlerinstance)
  958. {
  959. $loghandlerinstance->setIdent($ident);
  960. }
  961. }
  962. if (! empty($message))
  963. {
  964. // Test log level
  965. $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG);
  966. if (!in_array($level, $logLevels, true))
  967. {
  968. throw new Exception('Incorrect log level');
  969. }
  970. if ($level > $conf->global->SYSLOG_LEVEL) return;
  971. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  972. // If adding log inside HTML page is required
  973. if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility
  974. {
  975. $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
  976. }
  977. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  978. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  979. if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"]))
  980. {
  981. print "\n\n<!-- Log start\n";
  982. print $message."\n";
  983. print "Log end -->\n";
  984. }
  985. $data = array(
  986. 'message' => $message,
  987. 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false),
  988. 'level' => $level,
  989. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  990. 'ip' => false
  991. );
  992. // This is when server run behind a reverse proxy
  993. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']);
  994. // This is when server run normally on a server
  995. else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR'];
  996. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  997. else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  998. // 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).
  999. else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']);
  1000. // 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).
  1001. else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1002. // Loop on each log handler and send output
  1003. foreach ($conf->loghandlers as $loghandlerinstance)
  1004. {
  1005. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  1006. $loghandlerinstance->export($data,$suffixinfilename);
  1007. }
  1008. unset($data);
  1009. }
  1010. if ($ident > 0)
  1011. {
  1012. foreach ($conf->loghandlers as $loghandlerinstance)
  1013. {
  1014. $loghandlerinstance->setIdent($ident);
  1015. }
  1016. }
  1017. }
  1018. /**
  1019. * Show tab header of a card
  1020. *
  1021. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1022. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1023. * @param string $title Title
  1024. * @param int $notab -1 or 0=Add tab header, 1=no tab header. If you set this to 1, using dol_fiche_end() to close tab is not required.
  1025. * @param string $picto Add a picto on tab title
  1026. * @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.
  1027. * @param string $morehtmlright Add more html content on right of tabs title
  1028. * @param string $morecss More Css
  1029. * @return void
  1030. */
  1031. function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='')
  1032. {
  1033. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss);
  1034. }
  1035. /**
  1036. * Show tab header of a card
  1037. *
  1038. * @param array $links Array of tabs
  1039. * @param string $active Active tab name
  1040. * @param string $title Title
  1041. * @param int $notab -1 or 0=Add tab header, 1=no tab header. If you set this to 1, using dol_fiche_end() to close tab is not required.
  1042. * @param string $picto Add a picto on tab title
  1043. * @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.
  1044. * @param string $morehtmlright Add more html content on right of tabs title
  1045. * @param string $morecss More Css
  1046. * @return string
  1047. */
  1048. function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='')
  1049. {
  1050. global $conf, $langs, $hookmanager;
  1051. $out="\n".'<div class="tabs" data-role="controlgroup" data-type="horizontal">'."\n";
  1052. if ($morehtmlright) $out.='<div class="inline-block floatright tabsElem">'.$morehtmlright.'</div>'; // Output right area first so when space is missing, text is in front of tabs and not under.
  1053. // Show title
  1054. $showtitle=1;
  1055. if (! empty($conf->dol_optimize_smallscreen)) $showtitle=0;
  1056. if (! empty($title) && $showtitle)
  1057. {
  1058. $limittitle=30;
  1059. $out.='<a class="tabTitle">';
  1060. if ($picto) $out.=img_picto($title,($pictoisfullpath?'':'object_').$picto,'',$pictoisfullpath).' ';
  1061. $out.='<span class="tabTitleText">'.dol_trunc($title,$limittitle).'</span>';
  1062. $out.='</a>';
  1063. }
  1064. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1065. $maxkey=-1;
  1066. if (is_array($links) && ! empty($links))
  1067. {
  1068. $keys=array_keys($links);
  1069. if (count($keys)) $maxkey=max($keys);
  1070. }
  1071. if (! empty($conf->dol_optimize_smallscreen)) $conf->global->MAIN_MAXTABS_IN_CARD=2;
  1072. // Show tabs
  1073. $bactive=false;
  1074. // if =0 we don't use the feature
  1075. $limittoshow=(empty($conf->global->MAIN_MAXTABS_IN_CARD)?99:$conf->global->MAIN_MAXTABS_IN_CARD);
  1076. $displaytab=0;
  1077. $nbintab=0;
  1078. $popuptab=0; $outmore='';
  1079. for ($i = 0 ; $i <= $maxkey ; $i++)
  1080. {
  1081. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  1082. {
  1083. // If active tab is already present
  1084. if ($i >= $limittoshow) $limittoshow--;
  1085. }
  1086. }
  1087. for ($i = 0 ; $i <= $maxkey ; $i++)
  1088. {
  1089. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  1090. {
  1091. $isactive=true;
  1092. $bactive=true;
  1093. }
  1094. else
  1095. {
  1096. $isactive=false;
  1097. }
  1098. if ($i < $limittoshow || $isactive)
  1099. {
  1100. $out.='<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((! $isactive && ! empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT))?' hideonprint':'').'"><!-- id tab = '.(empty($links[$i][2])?'':$links[$i][2]).' -->';
  1101. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1102. {
  1103. if (!empty($links[$i][0]))
  1104. {
  1105. $out.='<a class="tabimage'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1106. }
  1107. else
  1108. {
  1109. $out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1110. }
  1111. }
  1112. else if (! empty($links[$i][1]))
  1113. {
  1114. //print "x $i $active ".$links[$i][2]." z";
  1115. if ($isactive)
  1116. {
  1117. $out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabactive tab inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1118. $out.=$links[$i][1];
  1119. $out.='</a>'."\n";
  1120. }
  1121. else
  1122. {
  1123. $out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabunactive tab inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1124. $out.=$links[$i][1];
  1125. $out.='</a>'."\n";
  1126. }
  1127. }
  1128. $out.='</div>';
  1129. }
  1130. else
  1131. {
  1132. // The popup with the other tabs
  1133. if (! $popuptab)
  1134. {
  1135. $popuptab=1;
  1136. $outmore.='<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1137. }
  1138. $outmore.='<div class="popuptab wordwrap" style="display:inherit;">';
  1139. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1140. {
  1141. if (!empty($links[$i][0]))
  1142. $outmore.='<a class="tabimage'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1143. else
  1144. $outmore.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1145. }
  1146. else if (! empty($links[$i][1]))
  1147. {
  1148. $outmore.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="wordwrap inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1149. $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.
  1150. $outmore.='</a>'."\n";
  1151. }
  1152. $outmore.='</div>';
  1153. $nbintab++;
  1154. }
  1155. $displaytab=$i;
  1156. }
  1157. if ($popuptab) $outmore.='</div>';
  1158. if ($displaytab > $limittoshow)
  1159. {
  1160. $left=($langs->trans("DIRECTION") == 'rtl'?'right':'left');
  1161. $right=($langs->trans("DIRECTION") == 'rtl'?'left':'right');
  1162. $tabsname=str_replace("@", "", $picto);
  1163. $out.='<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1164. $out.='<a href="#" class="tab moretab inline-block tabunactive reposition">'.$langs->trans("More").'... ('.$nbintab.')</a>';
  1165. $out.='<div id="moretabsList'.$tabsname.'" style="position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px">';
  1166. $out.=$outmore;
  1167. $out.='</div>';
  1168. $out.='<div></div>';
  1169. $out.="</div>\n";
  1170. $out.="<script>";
  1171. $out.="$('#moretabs".$tabsname."').mouseenter( function() { console.log('mouseenter ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','auto');});";
  1172. $out.="$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1173. $out.="</script>";
  1174. }
  1175. $out.="</div>\n";
  1176. if (! $notab || $notab == -1) $out.="\n".'<div class="tabBar'.($notab == -1 ? '' : ' tabBarWithBottom').'">'."\n";
  1177. $parameters=array('tabname' => $active, 'out' => $out);
  1178. $reshook=$hookmanager->executeHooks('printTabsHead',$parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1179. if ($reshook > 0)
  1180. {
  1181. $out = $hookmanager->resPrint;
  1182. }
  1183. return $out;
  1184. }
  1185. /**
  1186. * Show tab footer of a card
  1187. *
  1188. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1189. * @return void
  1190. */
  1191. function dol_fiche_end($notab=0)
  1192. {
  1193. print dol_get_fiche_end($notab);
  1194. }
  1195. /**
  1196. * Return tab footer of a card
  1197. *
  1198. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1199. * @return string
  1200. */
  1201. function dol_get_fiche_end($notab=0)
  1202. {
  1203. if (! $notab || $notab == -1) return "\n</div>\n";
  1204. else return '';
  1205. }
  1206. /**
  1207. * Show tab footer of a card.
  1208. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1209. *
  1210. * @param Object $object Object to show
  1211. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1212. * @param string $morehtml More html content to output just before the nav bar
  1213. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1214. * @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.
  1215. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1216. * @param string $morehtmlref More html to show after ref
  1217. * @param string $moreparam More param to add in nav link url.
  1218. * @param int $nodbprefix Do not include DB prefix to forge table name
  1219. * @param string $morehtmlleft More html code to show before ref
  1220. * @param string $morehtmlstatus More html code to show under navigation arrows
  1221. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1222. * @param string $morehtmlright More html code to show before navigation arrows
  1223. * @return void
  1224. */
  1225. function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
  1226. {
  1227. global $conf, $form, $user, $langs;
  1228. $error = 0;
  1229. $maxvisiblephotos=1;
  1230. $showimage=1;
  1231. $entity=(empty($object->entity)?$conf->entity:$object->entity);
  1232. $showbarcode=empty($conf->barcode->enabled)?0:($object->barcode?1:0);
  1233. if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;
  1234. $modulepart='unknown';
  1235. if ($object->element == 'societe') $modulepart='societe';
  1236. if ($object->element == 'contact') $modulepart='contact';
  1237. if ($object->element == 'member') $modulepart='memberphoto';
  1238. if ($object->element == 'user') $modulepart='userphoto';
  1239. if ($object->element == 'product') $modulepart='product';
  1240. if (class_exists("Imagick"))
  1241. {
  1242. if ($object->element == 'propal') $modulepart='propal';
  1243. if ($object->element == 'commande') $modulepart='commande';
  1244. if ($object->element == 'facture') $modulepart='facture';
  1245. if ($object->element == 'fichinter') $modulepart='ficheinter';
  1246. if ($object->element == 'contrat') $modulepart='contract';
  1247. if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal';
  1248. if ($object->element == 'order_supplier') $modulepart='supplier_order';
  1249. if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice';
  1250. if ($object->element == 'expensereport') $modulepart='expensereport';
  1251. }
  1252. if ($object->element == 'product')
  1253. {
  1254. $width=80; $cssclass='photoref';
  1255. $showimage=$object->is_photo_available($conf->product->multidir_output[$entity]);
  1256. $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5);
  1257. if ($conf->browser->layout == 'phone') $maxvisiblephotos=1;
  1258. if ($showimage) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity],'small',$maxvisiblephotos,0,0,0,$width,0).'</div>';
  1259. else
  1260. {
  1261. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1262. $nophoto='';
  1263. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1264. }
  1265. //elseif ($conf->browser->layout != 'phone') { // Show no photo link
  1266. $nophoto='/public/theme/common/nophoto.png';
  1267. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1268. //}
  1269. }
  1270. }
  1271. elseif ($object->element == 'ticket')
  1272. {
  1273. $width=80; $cssclass='photoref';
  1274. $showimage=$object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->track_id);
  1275. $maxvisiblephotos=(isset($conf->global->TICKETSUP_MAX_VISIBLE_PHOTO)?$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO:2);
  1276. if ($conf->browser->layout == 'phone') $maxvisiblephotos=1;
  1277. if ($showimage) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('ticket', $conf->ticket->multidir_output[$entity],'small',$maxvisiblephotos,0,0,0,$width,0).'</div>';
  1278. else
  1279. {
  1280. if (!empty($conf->global->TICKETSUP_NODISPLAYIFNOPHOTO)) {
  1281. $nophoto='';
  1282. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1283. }
  1284. //elseif ($conf->browser->layout != 'phone') { // Show no photo link
  1285. $nophoto='/public/theme/common/nophoto.png';
  1286. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1287. //}
  1288. }
  1289. }
  1290. else
  1291. {
  1292. if ($showimage)
  1293. {
  1294. if ($modulepart != 'unknown')
  1295. {
  1296. $phototoshow='';
  1297. // Check if a preview file is available
  1298. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick"))
  1299. {
  1300. $objectref = dol_sanitizeFileName($object->ref);
  1301. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity]) . "/";
  1302. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1303. {
  1304. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1305. $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
  1306. }
  1307. else
  1308. {
  1309. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1310. }
  1311. if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1312. $filepath = $dir_output . $subdir . "/";
  1313. $file = $filepath . $objectref . ".pdf";
  1314. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1315. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1316. $fileimage = $file.'_preview.png'; // If PDF has 1 page
  1317. $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page
  1318. $relativepathimage = $relativepath.'_preview.png';
  1319. // Si fichier PDF existe
  1320. if (file_exists($file))
  1321. {
  1322. $encfile = urlencode($file);
  1323. // Conversion du PDF en image png si fichier png non existant
  1324. if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file)))
  1325. && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file)))
  1326. )
  1327. {
  1328. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experienc trouble with pdf thumb generation and imagick, you can disable here.
  1329. {
  1330. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1331. $ret = dol_convert_file($file, 'png', $fileimage);
  1332. if ($ret < 0) $error++;
  1333. }
  1334. }
  1335. $heightforphotref=70;
  1336. if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60;
  1337. // Si fichier png PDF d'1 page trouve
  1338. if (file_exists($fileimage))
  1339. {
  1340. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1341. $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1342. $phototoshow.= '</div></div>';
  1343. }
  1344. // Si fichier png PDF de plus d'1 page trouve
  1345. elseif (file_exists($fileimagebis))
  1346. {
  1347. $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png";
  1348. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1349. $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
  1350. $phototoshow.= '</div></div>';
  1351. }
  1352. }
  1353. }
  1354. else if (! $phototoshow)
  1355. {
  1356. $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos);
  1357. }
  1358. if ($phototoshow)
  1359. {
  1360. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1361. $morehtmlleft.=$phototoshow;
  1362. $morehtmlleft.='</div>';
  1363. }
  1364. }
  1365. if (! $phototoshow) // Show No photo link (picto of pbject)
  1366. {
  1367. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1368. if ($object->element == 'action')
  1369. {
  1370. $width=80;
  1371. $cssclass='photorefcenter';
  1372. $nophoto=img_picto('', 'title_agenda', '', false, 1);
  1373. }
  1374. else
  1375. {
  1376. $width=14; $cssclass='photorefcenter';
  1377. $picto = $object->picto;
  1378. if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub
  1379. $nophoto=img_picto('', 'object_'.$picto, '', false, 1);
  1380. }
  1381. $morehtmlleft.='<!-- No photo to show -->';
  1382. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.$nophoto.'"></div></div>';
  1383. $morehtmlleft.='</div>';
  1384. }
  1385. }
  1386. }
  1387. if ($showbarcode) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1388. if ($object->element == 'societe')
  1389. {
  1390. if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1391. {
  1392. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1393. }
  1394. else {
  1395. $morehtmlstatus.=$object->getLibStatut(6);
  1396. }
  1397. }
  1398. elseif ($object->element == 'product')
  1399. {
  1400. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1401. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1402. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1403. } else {
  1404. $morehtmlstatus.='<span class="statusrefsell">'.$object->getLibStatut(5,0).'</span>';
  1405. }
  1406. $morehtmlstatus.=' &nbsp; ';
  1407. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1408. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1409. $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1410. } else {
  1411. $morehtmlstatus.='<span class="statusrefbuy">'.$object->getLibStatut(5,1).'</span>';
  1412. }
  1413. }
  1414. elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan')))
  1415. {
  1416. $tmptxt=$object->getLibStatut(6, $object->totalpaye);
  1417. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye);
  1418. $morehtmlstatus.=$tmptxt;
  1419. }
  1420. elseif ($object->element == 'contrat' || $object->element == 'contract')
  1421. {
  1422. if ($object->statut == 0) $morehtmlstatus.=$object->getLibStatut(5);
  1423. else $morehtmlstatus.=$object->getLibStatut(4);
  1424. }
  1425. elseif ($object->element == 'facturerec')
  1426. {
  1427. if ($object->frequency == 0) $morehtmlstatus.=$object->getLibStatut(2);
  1428. else $morehtmlstatus.=$object->getLibStatut(5);
  1429. }
  1430. elseif ($object->element == 'project_task')
  1431. {
  1432. $object->fk_statut = 1;
  1433. if ($object->progress > 0) $object->fk_statut = 2;
  1434. if ($object->progress >= 100) $object->fk_statut = 3;
  1435. $tmptxt=$object->getLibStatut(5);
  1436. $morehtmlstatus.=$tmptxt; // No status on task
  1437. }
  1438. else { // Generic case
  1439. $tmptxt=$object->getLibStatut(6);
  1440. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5);
  1441. $morehtmlstatus.=$tmptxt;
  1442. }
  1443. // Add if object was dispatched "into accountancy"
  1444. if (! empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport')))
  1445. {
  1446. if (method_exists($object, 'getVentilExportCompta'))
  1447. {
  1448. $accounted = $object->getVentilExportCompta();
  1449. $langs->load("accountancy");
  1450. $morehtmlstatus.='</div><div class="statusref statusrefbis">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted"));
  1451. }
  1452. }
  1453. // Add alias for thirdparty
  1454. if (! empty($object->name_alias)) $morehtmlref.='<div class="refidno">'.$object->name_alias.'</div>';
  1455. // Add label
  1456. if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task')
  1457. {
  1458. if (! empty($object->label)) $morehtmlref.='<div class="refidno">'.$object->label.'</div>';
  1459. }
  1460. if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files')
  1461. {
  1462. $morehtmlref.='<div class="refidno">';
  1463. $morehtmlref.=$object->getBannerAddress('refaddress',$object);
  1464. $morehtmlref.='</div>';
  1465. }
  1466. if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product')))
  1467. {
  1468. $morehtmlref.='<div style="clear: both;"></div><div class="refidno">';
  1469. $morehtmlref.=$langs->trans("TechnicalID").': '.$object->id;
  1470. $morehtmlref.='</div>';
  1471. }
  1472. print '<div class="'.($onlybanner?'arearefnobottom ':'arearef ').'heightref valignmiddle" width="100%">';
  1473. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1474. print '</div>';
  1475. print '<div class="underrefbanner clearboth"></div>';
  1476. }
  1477. /**
  1478. * Show a string with the label tag dedicated to the HTML edit field.
  1479. *
  1480. * @param string $langkey Translation key
  1481. * @param string $fieldkey Key of the html select field the text refers to
  1482. * @param int $fieldrequired 1=Field is mandatory
  1483. * @return string
  1484. * @deprecated Form::editfieldkey
  1485. */
  1486. function fieldLabel($langkey, $fieldkey, $fieldrequired=0)
  1487. {
  1488. global $conf, $langs;
  1489. $ret='';
  1490. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  1491. if (($conf->dol_use_jmobile != 4)) $ret.='<label for="'.$fieldkey.'">';
  1492. $ret.=$langs->trans($langkey);
  1493. if (($conf->dol_use_jmobile != 4)) $ret.='</label>';
  1494. if ($fieldrequired) $ret.='</span>';
  1495. return $ret;
  1496. }
  1497. /**
  1498. * Return string to add class property on html element with pair/impair.
  1499. *
  1500. * @param string $var 0 or 1
  1501. * @param string $moreclass More class to add
  1502. * @return string String to add class onto HTML element
  1503. */
  1504. function dol_bc($var,$moreclass='')
  1505. {
  1506. global $bc;
  1507. $ret=' '.$bc[$var];
  1508. if ($moreclass) $ret=preg_replace('/class=\"/','class="'.$moreclass.' ',$ret);
  1509. return $ret;
  1510. }
  1511. /**
  1512. * Return a formated address (part address/zip/town/state) according to country rules
  1513. *
  1514. * @param Object $object A company or contact object
  1515. * @param int $withcountry 1=Add country into address string
  1516. * @param string $sep Separator to use to build string
  1517. * @param Translate $outputlangs Object lang that contains language for text translation.
  1518. * @param int $mode 0=Standard output, 1=Remove address
  1519. * @return string Formated string
  1520. * @see dol_print_address
  1521. */
  1522. function dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs='', $mode=0)
  1523. {
  1524. global $conf,$langs;
  1525. $ret='';
  1526. $countriesusingstate=array('AU','CA','US','IN','GB','ES','UK','TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1527. // Address
  1528. if (empty($mode)) {
  1529. $ret .= $object->address;
  1530. }
  1531. // Zip/Town/State
  1532. if (in_array($object->country_code,array('AU', 'CA', 'US')) || ! empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) // US: title firstname name \n address lines \n town, state, zip \n country
  1533. {
  1534. $ret .= ($ret ? $sep : '' ).$object->town;
  1535. if ($object->state)
  1536. {
  1537. $ret.=($ret?", ":'').$object->state;
  1538. }
  1539. if ($object->zip) $ret .= ($ret?", ":'').$object->zip;
  1540. }
  1541. else if (in_array($object->country_code,array('GB','UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country
  1542. {
  1543. $ret .= ($ret ? $sep : '' ).$object->town;
  1544. if ($object->state)
  1545. {
  1546. $ret.=($ret?", ":'').$object->state;
  1547. }
  1548. if ($object->zip) $ret .= ($ret ? $sep : '' ).$object->zip;
  1549. }
  1550. else if (in_array($object->country_code,array('ES','TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country
  1551. {
  1552. $ret .= ($ret ? $sep : '' ).$object->zip;
  1553. $ret .= ($object->town?(($object->zip?' ':'').$object->town):'');
  1554. if ($object->state)
  1555. {
  1556. $ret.="\n".$object->state;
  1557. }
  1558. }
  1559. else if (in_array($object->country_code,array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1560. {
  1561. $ret .= ($ret ? $sep : '' ).$object->zip;
  1562. $ret .= ($object->town?(($object->zip?' ':'').$object->town):'');
  1563. $ret .= ($object->departement_id?(' ('.($object->departement_id).')'):'');
  1564. }
  1565. else // Other: title firstname name \n address lines \n zip town \n country
  1566. {
  1567. $ret .= $object->zip ? (($ret ? $sep : '' ).$object->zip) : '';
  1568. $ret .= ($object->town?(($object->zip?' ':($ret ? $sep : '' )).$object->town):'');
  1569. if ($object->state && in_array($object->country_code,$countriesusingstate))
  1570. {
  1571. $ret.=($ret?", ":'').$object->state;
  1572. }
  1573. }
  1574. if (! is_object($outputlangs)) $outputlangs=$langs;
  1575. if ($withcountry)
  1576. {
  1577. $langs->load("dict");
  1578. $ret.=($object->country_code?($ret?$sep:'').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)):'');
  1579. }
  1580. return $ret;
  1581. }
  1582. /**
  1583. * Format a string.
  1584. *
  1585. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1586. * @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)
  1587. * @param int $is_gmt See comment of timestamp parameter
  1588. * @return string A formatted string
  1589. */
  1590. function dol_strftime($fmt, $ts=false, $is_gmt=false)
  1591. {
  1592. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1593. return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
  1594. }
  1595. else return 'Error date into a not supported range';
  1596. }
  1597. /**
  1598. * Output date in a string format according to outputlangs (or langs if not defined).
  1599. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1600. *
  1601. * @param int $time GM Timestamps date
  1602. * @param string $format Output date format (tag of strftime function)
  1603. * "%d %b %Y",
  1604. * "%d/%m/%Y %H:%M",
  1605. * "%d/%m/%Y %H:%M:%S",
  1606. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1607. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1608. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1609. * false or 'tzserver' => output string is for local PHP server TZ usage
  1610. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  1611. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  1612. * @param Translate $outputlangs Object lang that contains language for text translation.
  1613. * @param boolean $encodetooutput false=no convert into output pagecode
  1614. * @return string Formated date or '' if time is null
  1615. *
  1616. * @see dol_mktime, dol_stringtotime, dol_getdate
  1617. */
  1618. function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
  1619. {
  1620. global $conf,$langs;
  1621. // Clean parameters
  1622. $to_gmt=false;
  1623. $offsettz=$offsetdst=0;
  1624. if ($tzoutput)
  1625. {
  1626. $to_gmt=true; // For backward compatibility
  1627. if (is_string($tzoutput))
  1628. {
  1629. if ($tzoutput == 'tzserver')
  1630. {
  1631. $to_gmt=false;
  1632. $offsettzstring=@date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1633. $offsettz=0;
  1634. $offsetdst=0;
  1635. }
  1636. elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel')
  1637. {
  1638. $to_gmt=true;
  1639. $offsettzstring=(empty($_SESSION['dol_tz_string'])?'UTC':$_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1640. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60; // Will not be used anymore
  1641. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60; // Will not be used anymore
  1642. }
  1643. }
  1644. }
  1645. if (! is_object($outputlangs)) $outputlangs=$langs;
  1646. if (! $format) $format='daytextshort';
  1647. $reduceformat=(! empty($conf->dol_optimize_smallscreen) && in_array($format,array('day','dayhour')))?1:0;
  1648. $formatwithoutreduce = preg_replace('/reduceformat/','',$format);
  1649. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat=1; } // so format 'dayreduceformat' is processed like day
  1650. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1651. // TODO Add format daysmallyear and dayhoursmallyear
  1652. if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
  1653. else if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
  1654. else if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
  1655. else if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
  1656. else if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
  1657. else if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
  1658. else if ($format == 'dayhoursec') $format=($outputlangs->trans("FormatDateHourSecShort")!="FormatDateHourSecShort"?$outputlangs->trans("FormatDateHourSecShort"):$conf->format_date_hour_sec_short);
  1659. else if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
  1660. else if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
  1661. // Format not sensitive to language
  1662. else if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
  1663. else if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
  1664. else if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
  1665. else if ($format == 'dayxcard') $format='%Y%m%d';
  1666. else if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
  1667. else if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1668. else if ($format == 'standard') $format='%Y-%m-%d %H:%M:%S';
  1669. if ($reduceformat)
  1670. {
  1671. $format=str_replace('%Y','%y',$format);
  1672. $format=str_replace('yyyy','yy',$format);
  1673. }
  1674. // If date undefined or "", we return ""
  1675. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1676. // Clean format
  1677. if (preg_match('/%b/i',$format)) // There is some text to translate
  1678. {
  1679. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1680. $format=str_replace('%b','__b__',$format);
  1681. $format=str_replace('%B','__B__',$format);
  1682. }
  1683. if (preg_match('/%a/i',$format)) // There is some text to translate
  1684. {
  1685. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1686. $format=str_replace('%a','__a__',$format);
  1687. $format=str_replace('%A','__A__',$format);
  1688. }
  1689. // Analyze date
  1690. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
  1691. || 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
  1692. {
  1693. // TODO Remove this.
  1694. // This part of code should not be used.
  1695. dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_ERR);
  1696. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
  1697. $syear = (! empty($reg[1]) ? $reg[1] : '');
  1698. $smonth = (! empty($reg[2]) ? $reg[2] : '');
  1699. $sday = (! empty($reg[3]) ? $reg[3] : '');
  1700. $shour = (! empty($reg[4]) ? $reg[4] : '');
  1701. $smin = (! empty($reg[5]) ? $reg[5] : '');
  1702. $ssec = (! empty($reg[6]) ? $reg[6] : '');
  1703. $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
  1704. $ret=adodb_strftime($format, $time+$offsettz+$offsetdst, $to_gmt);
  1705. }
  1706. else
  1707. {
  1708. // Date is a timestamps
  1709. if ($time < 100000000000) // Protection against bad date values
  1710. {
  1711. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1712. $ret=adodb_strftime($format, $timetouse, $to_gmt);
  1713. }
  1714. else $ret='Bad value '.$time.' for date';
  1715. }
  1716. if (preg_match('/__b__/i',$format))
  1717. {
  1718. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1719. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1720. $month=adodb_strftime('%m', $timetouse);
  1721. $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  1722. if ($encodetooutput)
  1723. {
  1724. $monthtext=$outputlangs->transnoentities('Month'.$month);
  1725. $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
  1726. }
  1727. else
  1728. {
  1729. $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
  1730. $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1731. }
  1732. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1733. $ret=str_replace('__b__',$monthtextshort,$ret);
  1734. $ret=str_replace('__B__',$monthtext,$ret);
  1735. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1736. //return $ret;
  1737. }
  1738. if (preg_match('/__a__/i',$format))
  1739. {
  1740. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1741. $w=adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1742. $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
  1743. $ret=str_replace('__A__',$dayweek,$ret);
  1744. $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
  1745. }
  1746. return $ret;
  1747. }
  1748. /**
  1749. * Return an array with locale date info.
  1750. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1751. * WARNING: This function always use PHP server timezone to return locale informations !!!
  1752. * Usage must be avoid.
  1753. * FIXME: Replace this with PHP date function and a parameter $gm
  1754. *
  1755. * @param int $timestamp Timestamp
  1756. * @param boolean $fast Fast mode
  1757. * @return array Array of informations
  1758. * If no fast mode:
  1759. * 'seconds' => $secs,
  1760. * 'minutes' => $min,
  1761. * 'hours' => $hour,
  1762. * 'mday' => $day,
  1763. * 'wday' => $dow, 0=sunday, 6=saturday
  1764. * 'mon' => $month,
  1765. * 'year' => $year,
  1766. * 'yday' => floor($secsInYear/$_day_power),
  1767. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  1768. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  1769. * If fast mode:
  1770. * 'seconds' => $secs,
  1771. * 'minutes' => $min,
  1772. * 'hours' => $hour,
  1773. * 'mday' => $day,
  1774. * 'mon' => $month,
  1775. * 'year' => $year,
  1776. * 'yday' => floor($secsInYear/$_day_power),
  1777. * 'leap' => $leaf,
  1778. * 'ndays' => $ndays
  1779. * @see dol_print_date, dol_stringtotime, dol_mktime
  1780. */
  1781. function dol_getdate($timestamp,$fast=false)
  1782. {
  1783. global $conf;
  1784. $usealternatemethod=false;
  1785. if ($timestamp <= 0) $usealternatemethod=true; // <= 1970
  1786. if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038
  1787. if ($usealternatemethod)
  1788. {
  1789. $arrayinfo=adodb_getdate($timestamp,$fast);
  1790. }
  1791. else
  1792. {
  1793. $arrayinfo=getdate($timestamp);
  1794. }
  1795. return $arrayinfo;
  1796. }
  1797. /**
  1798. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  1799. * Replace function mktime not available under Windows if year < 1970
  1800. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1801. *
  1802. * @param int $hour Hour (can be -1 for undefined)
  1803. * @param int $minute Minute (can be -1 for undefined)
  1804. * @param int $second Second (can be -1 for undefined)
  1805. * @param int $month Month (1 to 12)
  1806. * @param int $day Day (1 to 31)
  1807. * @param int $year Year
  1808. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  1809. * False or 0 or 'server' = local to server TZ
  1810. * 'user' = local to user TZ
  1811. * 'tz,TimeZone' = use specified timezone
  1812. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  1813. * @return int|string Date as a timestamp, '' or false if error
  1814. * @see dol_print_date, dol_stringtotime, dol_getdate
  1815. */
  1816. function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
  1817. {
  1818. global $conf;
  1819. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  1820. // Clean parameters
  1821. if ($hour == -1 || empty($hour)) $hour=0;
  1822. if ($minute == -1 || empty($minute)) $minute=0;
  1823. if ($second == -1 || empty($second)) $second=0;
  1824. // Check parameters
  1825. if ($check)
  1826. {
  1827. if (! $month || ! $day) return '';
  1828. if ($day > 31) return '';
  1829. if ($month > 12) return '';
  1830. if ($hour < 0 || $hour > 24) return '';
  1831. if ($minute< 0 || $minute > 60) return '';
  1832. if ($second< 0 || $second > 60) return '';
  1833. }
  1834. if (method_exists('DateTime','getTimestamp'))
  1835. {
  1836. if (empty($gm) || $gm === 'server')
  1837. {
  1838. $default_timezone=@date_default_timezone_get(); // Example 'Europe/Berlin'
  1839. $localtz = new DateTimeZone($default_timezone);
  1840. }
  1841. else if ($gm === 'user')
  1842. {
  1843. // We use dol_tz_string first because it is more reliable.
  1844. $default_timezone=(empty($_SESSION["dol_tz_string"])?@date_default_timezone_get():$_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  1845. try {
  1846. $localtz = new DateTimeZone($default_timezone);
  1847. }
  1848. catch(Exception $e)
  1849. {
  1850. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  1851. $default_timezone=@date_default_timezone_get();
  1852. }
  1853. }
  1854. else if (strrpos($gm, "tz,") !== false)
  1855. {
  1856. $timezone=str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  1857. try
  1858. {
  1859. $localtz = new DateTimeZone($timezone);
  1860. }
  1861. catch(Exception $e)
  1862. {
  1863. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  1864. }
  1865. }
  1866. if (empty($localtz)) {
  1867. $localtz = new DateTimeZone('UTC');
  1868. }
  1869. //var_dump($localtz);
  1870. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  1871. $dt = new DateTime(null,$localtz);
  1872. $dt->setDate($year,$month,$day);
  1873. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  1874. $date=$dt->getTimestamp(); // should include daylight saving time
  1875. //var_dump($date);
  1876. return $date;
  1877. }
  1878. else
  1879. {
  1880. dol_print_error('','PHP version must be 5.4+');
  1881. return '';
  1882. }
  1883. }
  1884. /**
  1885. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  1886. *
  1887. * @param string $mode 'gmt' => we return GMT timestamp,
  1888. * 'tzserver' => we add the PHP server timezone
  1889. * 'tzref' => we add the company timezone
  1890. * 'tzuser' => we add the user timezone
  1891. * @return int $date Timestamp
  1892. */
  1893. function dol_now($mode='gmt')
  1894. {
  1895. $ret=0;
  1896. // Note that gmmktime and mktime return same value (GMT) when used without parameters
  1897. //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead
  1898. if ($mode == 'gmt') $ret=time(); // Time for now at greenwich.
  1899. else if ($mode == 'tzserver') // Time for now with PHP server timezone added
  1900. {
  1901. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1902. $tzsecond=getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  1903. $ret=(int) (dol_now('gmt')+($tzsecond*3600));
  1904. }
  1905. /*else if ($mode == 'tzref') // Time for now with parent company timezone is added
  1906. {
  1907. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1908. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  1909. $ret=dol_now('gmt')+($tzsecond*3600);
  1910. }*/
  1911. else if ($mode == 'tzuser') // Time for now with user timezone added
  1912. {
  1913. //print 'time: '.time().'-'.mktime().'-'.gmmktime();
  1914. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
  1915. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
  1916. $ret=(int) (dol_now('gmt')+($offsettz+$offsetdst));
  1917. }
  1918. return $ret;
  1919. }
  1920. /**
  1921. * Return string with formated size
  1922. *
  1923. * @param int $size Size to print
  1924. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1925. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  1926. * @return string Link
  1927. */
  1928. function dol_print_size($size,$shortvalue=0,$shortunit=0)
  1929. {
  1930. global $conf,$langs;
  1931. $level=1024;
  1932. if (! empty($conf->dol_optimize_smallscreen)) $shortunit=1;
  1933. // Set value text
  1934. if (empty($shortvalue) || $size < ($level*10))
  1935. {
  1936. $ret=$size;
  1937. $textunitshort=$langs->trans("b");
  1938. $textunitlong=$langs->trans("Bytes");
  1939. }
  1940. else
  1941. {
  1942. $ret=round($size/$level,0);
  1943. $textunitshort=$langs->trans("Kb");
  1944. $textunitlong=$langs->trans("KiloBytes");
  1945. }
  1946. // Use long or short text unit
  1947. if (empty($shortunit)) { $ret.=' '.$textunitlong; }
  1948. else { $ret.=' '.$textunitshort; }
  1949. return $ret;
  1950. }
  1951. /**
  1952. * Show Url link
  1953. *
  1954. * @param string $url Url to show
  1955. * @param string $target Target for link
  1956. * @param int $max Max number of characters to show
  1957. * @param int $withpicto With picto
  1958. * @return string HTML Link
  1959. */
  1960. function dol_print_url($url,$target='_blank',$max=32,$withpicto=0)
  1961. {
  1962. global $langs;
  1963. if (empty($url)) return '';
  1964. $link='<a href="';
  1965. if (! preg_match('/^http/i',$url)) $link.='http://';
  1966. $link.=$url;
  1967. $link.='"';
  1968. if ($target) $link.=' target="'.$target.'"';
  1969. $link.='>';
  1970. if (! preg_match('/^http/i',$url)) $link.='http://';
  1971. $link.=dol_trunc($url,$max);
  1972. $link.='</a>';
  1973. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("Url"), 'object_globe.png').' ':'').$link.'</div>';
  1974. }
  1975. /**
  1976. * Show EMail link
  1977. *
  1978. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  1979. * @param int $cid Id of contact if known
  1980. * @param int $socid Id of third party if known
  1981. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  1982. * @param int $max Max number of characters to show
  1983. * @param int $showinvalid Show warning if syntax email is wrong
  1984. * @param int $withpicto Show picto
  1985. * @return string HTML Link
  1986. */
  1987. function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1,$withpicto=0)
  1988. {
  1989. global $conf,$user,$langs,$hookmanager;
  1990. $newemail=$email;
  1991. if (empty($email)) return '&nbsp;';
  1992. if (! empty($addlink))
  1993. {
  1994. $newemail='<a style="text-overflow: ellipsis;" href="';
  1995. if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
  1996. $newemail.=$email;
  1997. $newemail.='">';
  1998. $newemail.=dol_trunc($email,$max);
  1999. $newemail.='</a>';
  2000. if ($showinvalid && ! isValidEmail($email))
  2001. {
  2002. $langs->load("errors");
  2003. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  2004. }
  2005. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2006. {
  2007. $type='AC_EMAIL'; $link='';
  2008. if (! empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  2009. if ($link) $newemail='<div>'.$newemail.' '.$link.'</div>';
  2010. }
  2011. }
  2012. else
  2013. {
  2014. if ($showinvalid && ! isValidEmail($email))
  2015. {
  2016. $langs->load("errors");
  2017. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  2018. }
  2019. }
  2020. $rep = '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("EMail"), 'object_email.png').' ':'').$newemail.'</div>';
  2021. if ($hookmanager) {
  2022. $parameters = array('cid' => $cid, 'socid' => $socid,'addlink' => $addlink, 'picto' => $withpicto);
  2023. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2024. $rep.=$hookmanager->resPrint;
  2025. }
  2026. return $rep;
  2027. }
  2028. /**
  2029. * Show social network link
  2030. *
  2031. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2032. * @param int $cid Id of contact if known
  2033. * @param int $socid Id of third party if known
  2034. * @param string $type 'skype','facebook',...
  2035. * @return string HTML Link
  2036. */
  2037. function dol_print_socialnetworks($value,$cid,$socid,$type)
  2038. {
  2039. global $conf,$user,$langs;
  2040. $newskype=$value;
  2041. if (empty($value)) return '&nbsp;';
  2042. if (! empty($type))
  2043. {
  2044. $newskype ='<div class="divsocialnetwork inline-block valignmiddle">';
  2045. $newskype.=img_picto($langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright');
  2046. $newskype.=$value;
  2047. if ($type == 'skype')
  2048. {
  2049. $newskype.= '&nbsp;';
  2050. $newskype.='<a href="skype:';
  2051. $newskype.=$value;
  2052. $newskype.='?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2053. $newskype.='<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2054. $newskype.='</a><a href="skype:';
  2055. $newskype.=$value;
  2056. $newskype.='?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2057. $newskype.='<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2058. $newskype.='</a>';
  2059. }
  2060. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type=='skype')
  2061. {
  2062. $addlink='AC_SKYPE'; $link='';
  2063. if (! empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$addlink.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  2064. $newskype.=($link?' '.$link:'');
  2065. }
  2066. $newskype.='</div>';
  2067. }
  2068. else
  2069. {
  2070. $langs->load("errors");
  2071. $newskype.=img_warning($langs->trans("ErrorBadSocialNetworkValue",$value));
  2072. }
  2073. return $newskype;
  2074. }
  2075. /**
  2076. * Format phone numbers according to country
  2077. *
  2078. * @param string $phone Phone number to format
  2079. * @param string $countrycode Country code to use for formatting
  2080. * @param int $cid Id of contact if known
  2081. * @param int $socid Id of third party if known
  2082. * @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)
  2083. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2084. * @param string $withpicto Show picto
  2085. * @param string $titlealt Text to show on alt
  2086. * @param int $adddivfloat Add div float around phone.
  2087. * @return string Formated phone number
  2088. */
  2089. function dol_print_phone($phone,$countrycode='',$cid=0,$socid=0,$addlink='',$separ="&nbsp;",$withpicto='',$titlealt='',$adddivfloat=0)
  2090. {
  2091. global $conf, $user, $langs, $mysoc, $hookmanager;
  2092. // Clean phone parameter
  2093. $phone = preg_replace("/[\s.-]/","",trim($phone));
  2094. if (empty($phone)) { return ''; }
  2095. if (empty($countrycode)) $countrycode=$mysoc->country_code;
  2096. // Short format for small screens
  2097. if ($conf->dol_optimize_smallscreen) $separ='';
  2098. $newphone=$phone;
  2099. if (strtoupper($countrycode) == "FR")
  2100. {
  2101. // France
  2102. if (dol_strlen($phone) == 10) {
  2103. $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);
  2104. }
  2105. elseif (dol_strlen($phone) == 7)
  2106. {
  2107. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
  2108. }
  2109. elseif (dol_strlen($phone) == 9)
  2110. {
  2111. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
  2112. }
  2113. elseif (dol_strlen($phone) == 11)
  2114. {
  2115. $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);
  2116. }
  2117. elseif (dol_strlen($phone) == 12)
  2118. {
  2119. $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);
  2120. }
  2121. }
  2122. elseif (strtoupper($countrycode) == "CA")
  2123. {
  2124. if (dol_strlen($phone) == 10) {
  2125. $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4);
  2126. }
  2127. }
  2128. elseif (strtoupper($countrycode) == "PT" )
  2129. {//Portugal
  2130. if (dol_strlen($phone) == 13)
  2131. {//ex: +351_ABC_DEF_GHI
  2132. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2133. }
  2134. }
  2135. elseif (strtoupper($countrycode) == "SR" )
  2136. {//Suriname
  2137. if (dol_strlen($phone) == 10)
  2138. {//ex: +597_ABC_DEF
  2139. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3);
  2140. }
  2141. elseif (dol_strlen($phone) == 11)
  2142. {//ex: +597_ABC_DEFG
  2143. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,4);
  2144. }
  2145. }
  2146. elseif (strtoupper($countrycode) == "DE" )
  2147. {//Allemagne
  2148. if (dol_strlen($phone) == 14)
  2149. {//ex: +49_ABCD_EFGH_IJK
  2150. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,4).$separ.substr($newphone,11,3);
  2151. }
  2152. elseif (dol_strlen($phone) == 13)
  2153. {//ex: +49_ABC_DEFG_HIJ
  2154. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,4).$separ.substr($newphone,10,3);
  2155. }
  2156. }
  2157. elseif (strtoupper($countrycode) == "ES")
  2158. {//Espagne
  2159. if (dol_strlen($phone) == 12)
  2160. {//ex: +34_ABC_DEF_GHI
  2161. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2162. }
  2163. }
  2164. elseif (strtoupper($countrycode) == "BF")
  2165. {// Burkina Faso
  2166. if (dol_strlen($phone) == 12)
  2167. {//ex : +22 A BC_DE_FG_HI
  2168. $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);
  2169. }
  2170. }
  2171. elseif (strtoupper($countrycode) == "RO")
  2172. {// Roumanie
  2173. if (dol_strlen($phone) == 12)
  2174. {//ex : +40 AB_CDE_FG_HI
  2175. $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);
  2176. }
  2177. }
  2178. elseif (strtoupper($countrycode) == "TR")
  2179. {//Turquie
  2180. if (dol_strlen($phone) == 13)
  2181. {//ex : +90 ABC_DEF_GHIJ
  2182. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,4);
  2183. }
  2184. }
  2185. elseif (strtoupper($countrycode) == "US")
  2186. {//Etat-Unis
  2187. if (dol_strlen($phone) == 12)
  2188. {//ex: +1 ABC_DEF_GHIJ
  2189. $newphone= substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,3).$separ.substr($newphone,8,4);
  2190. }
  2191. }
  2192. elseif (strtoupper($countrycode) == "MX")
  2193. {//Mexique
  2194. if (dol_strlen($phone) == 12)
  2195. {//ex: +52 ABCD_EFG_HI
  2196. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,3).$separ.substr($newphone,10,2);
  2197. }
  2198. elseif (dol_strlen($phone) == 11)
  2199. {//ex: +52 AB_CD_EF_GH
  2200. $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);
  2201. }
  2202. elseif (dol_strlen($phone) == 13)
  2203. {//ex: +52 ABC_DEF_GHIJ
  2204. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,4);
  2205. }
  2206. }
  2207. elseif (strtoupper($countrycode) == "ML")
  2208. {//Mali
  2209. if(dol_strlen($phone) == 12)
  2210. {//ex: +223 AB_CD_EF_GH
  2211. $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);
  2212. }
  2213. }
  2214. elseif (strtoupper($countrycode) == "TH")
  2215. {//Thaïlande
  2216. if(dol_strlen($phone) == 11)
  2217. {//ex: +66_ABC_DE_FGH
  2218. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,2).$separ.substr($newphone,8,3);
  2219. }
  2220. elseif(dol_strlen($phone) == 12)
  2221. {//ex: +66_A_BCD_EF_GHI
  2222. $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);
  2223. }
  2224. }
  2225. elseif (strtoupper($countrycode) == "MU")
  2226. {//Maurice
  2227. if(dol_strlen($phone) == 11)
  2228. {//ex: +230_ABC_DE_FG
  2229. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
  2230. }
  2231. elseif(dol_strlen($phone) == 12)
  2232. {//ex: +230_ABCD_EF_GH
  2233. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,4).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  2234. }
  2235. }
  2236. elseif (strtoupper($countrycode) == "ZA")
  2237. {//Afrique du sud
  2238. if(dol_strlen($phone) == 12)
  2239. {//ex: +27_AB_CDE_FG_HI
  2240. $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);
  2241. }
  2242. }
  2243. elseif (strtoupper($countrycode) == "SY")
  2244. {//Syrie
  2245. if(dol_strlen($phone) == 12)
  2246. {//ex: +963_AB_CD_EF_GH
  2247. $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);
  2248. }
  2249. elseif(dol_strlen($phone) == 13)
  2250. {//ex: +963_AB_CD_EF_GHI
  2251. $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);
  2252. }
  2253. }
  2254. elseif (strtoupper($countrycode) == "AE")
  2255. {//Emirats Arabes Unis
  2256. if(dol_strlen($phone) == 12)
  2257. {//ex: +971_ABC_DEF_GH
  2258. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,2);
  2259. }
  2260. elseif(dol_strlen($phone) == 13)
  2261. {//ex: +971_ABC_DEF_GHI
  2262. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2263. }
  2264. elseif(dol_strlen($phone) == 14)
  2265. {//ex: +971_ABC_DEF_GHIK
  2266. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,4);
  2267. }
  2268. }
  2269. elseif (strtoupper($countrycode) == "DZ")
  2270. {//Algérie
  2271. if(dol_strlen($phone) == 13)
  2272. {//ex: +213_ABC_DEF_GHI
  2273. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2274. }
  2275. }
  2276. elseif (strtoupper($countrycode) == "BE")
  2277. {//Belgique
  2278. if(dol_strlen($phone) == 11)
  2279. {//ex: +32_ABC_DE_FGH
  2280. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,2).$separ.substr($newphone,8,3);
  2281. }
  2282. elseif(dol_strlen($phone) == 12)
  2283. {//ex: +32_ABC_DEF_GHI
  2284. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2285. }
  2286. }
  2287. elseif (strtoupper($countrycode) == "PF")
  2288. {//Polynésie française
  2289. if(dol_strlen($phone) == 12)
  2290. {//ex: +689_AB_CD_EF_GH
  2291. $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);
  2292. }
  2293. }
  2294. elseif (strtoupper($countrycode) == "CO")
  2295. {//Colombie
  2296. if(dol_strlen($phone) == 13)
  2297. {//ex: +57_ABC_DEF_GH_IJ
  2298. $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);
  2299. }
  2300. }
  2301. elseif (strtoupper($countrycode) == "JO")
  2302. {//Jordanie
  2303. if(dol_strlen($phone) == 12)
  2304. {//ex: +962_A_BCD_EF_GH
  2305. $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);
  2306. }
  2307. }
  2308. elseif (strtoupper($countrycode) == "MG")
  2309. {//Madagascar
  2310. if(dol_strlen($phone) == 13)
  2311. {//ex: +261_AB_CD_EF_GHI
  2312. $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);
  2313. }
  2314. }
  2315. elseif (strtoupper($countrycode) == "GB")
  2316. {//Royaume uni
  2317. if(dol_strlen($phone) == 13)
  2318. {//ex: +44_ABCD_EFG_HIJ
  2319. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2320. }
  2321. }
  2322. elseif (strtoupper($countrycode) == "CH")
  2323. {//Suisse
  2324. if(dol_strlen($phone) == 12)
  2325. {//ex: +41_AB_CDE_FG_HI
  2326. $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);
  2327. }
  2328. elseif(dol_strlen($phone) == 15)
  2329. {// +41_AB_CDE_FGH_IJKL
  2330. $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);
  2331. }
  2332. }
  2333. elseif (strtoupper($countrycode) == "TN")
  2334. {//Tunisie
  2335. if(dol_strlen($phone) == 12)
  2336. {//ex: +216_AB_CDE_FGH
  2337. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2338. }
  2339. }
  2340. elseif (strtoupper($countrycode) == "GF")
  2341. {//Guyane francaise
  2342. if(dol_strlen($phone) == 13)
  2343. {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2344. $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);
  2345. }
  2346. }
  2347. elseif (strtoupper($countrycode) == "GP")
  2348. {//Guadeloupe
  2349. if(dol_strlen($phone) == 13)
  2350. {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2351. $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);
  2352. }
  2353. }
  2354. elseif (strtoupper($countrycode) == "MQ")
  2355. {//Martinique
  2356. if(dol_strlen($phone) == 13)
  2357. {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2358. $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);
  2359. }
  2360. }
  2361. elseif (strtoupper($countrycode) == "IT")
  2362. {//Italie
  2363. if(dol_strlen($phone) == 12)
  2364. {//ex: +39_ABC_DEF_GHI
  2365. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2366. }
  2367. elseif(dol_strlen($phone) == 13)
  2368. {//ex: +39_ABC_DEF_GH_IJ
  2369. $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);
  2370. }
  2371. }
  2372. elseif(strtoupper($countrycode) == "AU")
  2373. {//Australie
  2374. if(dol_strlen($phone) == 12)
  2375. {//ex: +61_A_BCDE_FGHI
  2376. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,1).$separ.substr($newphone,4,4).$separ.substr($newphone,8,4);
  2377. }
  2378. }
  2379. if (! empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2380. {
  2381. 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
  2382. {
  2383. $newphone ='<a href="tel:'.$phone.'"';
  2384. $newphone.='>'.$phone.'</a>';
  2385. }
  2386. else if (! empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  2387. {
  2388. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  2389. // Define urlmask
  2390. $urlmask='ErrorClickToDialModuleNotConfigured';
  2391. if (! empty($conf->global->CLICKTODIAL_URL)) $urlmask=$conf->global->CLICKTODIAL_URL;
  2392. if (! empty($user->clicktodial_url)) $urlmask=$user->clicktodial_url;
  2393. $clicktodial_poste=(! empty($user->clicktodial_poste)?urlencode($user->clicktodial_poste):'');
  2394. $clicktodial_login=(! empty($user->clicktodial_login)?urlencode($user->clicktodial_login):'');
  2395. $clicktodial_password=(! empty($user->clicktodial_password)?urlencode($user->clicktodial_password):'');
  2396. // This line is for backward compatibility
  2397. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2398. // Thoose lines are for substitution
  2399. $substitarray=array('__PHONEFROM__'=>$clicktodial_poste,
  2400. '__PHONETO__'=>urlencode($phone),
  2401. '__LOGIN__'=>$clicktodial_login,
  2402. '__PASS__'=>$clicktodial_password);
  2403. $url = make_substitutions($url, $substitarray);
  2404. $newphonesav=$newphone;
  2405. $newphone ='<a href="'.$url.'"';
  2406. if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
  2407. $newphone.='>'.$newphonesav.'</a>';
  2408. }
  2409. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2410. if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2411. {
  2412. $type='AC_TEL'; $link='';
  2413. if ($addlink == 'AC_FAX') $type='AC_FAX';
  2414. if (! empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid?'&amp;contactid='.$cid:'').($socid?'&amp;socid='.$socid:'').'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  2415. if ($link) $newphone='<div>'.$newphone.' '.$link.'</div>';
  2416. }
  2417. }
  2418. if (empty($titlealt))
  2419. {
  2420. $titlealt=($withpicto=='fax'?$langs->trans("Fax"):$langs->trans("Phone"));
  2421. }
  2422. $rep='';
  2423. if ($hookmanager) {
  2424. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid,'titlealt' => $titlealt, 'picto' => $withpicto);
  2425. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2426. $rep.=$hookmanager->resPrint;
  2427. }
  2428. if (empty($reshook))
  2429. {
  2430. $picto = '';
  2431. if($withpicto){
  2432. if($withpicto=='fax'){
  2433. $picto = 'phoning_fax';
  2434. }elseif($withpicto=='phone'){
  2435. $picto = 'phoning';
  2436. }elseif($withpicto=='mobile'){
  2437. $picto = 'phoning_mobile';
  2438. }else{
  2439. $picto = '';
  2440. }
  2441. }
  2442. if ($adddivfloat) $rep.='<div class="nospan float" style="margin-right: 10px">';
  2443. else $rep.='<span style="margin-right: 10px;">';
  2444. $rep.=($withpicto?img_picto($titlealt, 'object_'.$picto.'.png').' ':'').$newphone;
  2445. if ($adddivfloat) $rep.='</div>';
  2446. else $rep.='</span>';
  2447. }
  2448. return $rep;
  2449. }
  2450. /**
  2451. * Return an IP formated to be shown on screen
  2452. *
  2453. * @param string $ip IP
  2454. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2455. * @return string Formated IP, with country if GeoIP module is enabled
  2456. */
  2457. function dol_print_ip($ip,$mode=0)
  2458. {
  2459. global $conf,$langs;
  2460. $ret='';
  2461. if (empty($mode)) $ret.=$ip;
  2462. if ($mode != 2)
  2463. {
  2464. $countrycode=dolGetCountryCodeFromIp($ip);
  2465. if ($countrycode) // If success, countrycode is us, fr, ...
  2466. {
  2467. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  2468. {
  2469. $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
  2470. }
  2471. else $ret.=' ('.$countrycode.')';
  2472. }
  2473. }
  2474. return $ret;
  2475. }
  2476. /**
  2477. * Return the IP of remote user.
  2478. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2479. * Then HTTP_CLIENT_IP if defined (rare)
  2480. * Then REMOTE_ADDR (not way to be modified by user but may be wrong if using proxy)
  2481. *
  2482. * @return string Ip of remote user.
  2483. */
  2484. function getUserRemoteIP()
  2485. {
  2486. $ip = empty($_SERVER['HTTP_X_FORWARDED_FOR'])? (empty($_SERVER['HTTP_CLIENT_IP'])?(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']):$_SERVER['HTTP_CLIENT_IP']) : $_SERVER['HTTP_X_FORWARDED_FOR'];
  2487. return $ip;
  2488. }
  2489. /**
  2490. * Return a country code from IP. Empty string if not found.
  2491. *
  2492. * @param string $ip IP
  2493. * @return string Country code ('us', 'fr', ...)
  2494. */
  2495. function dolGetCountryCodeFromIp($ip)
  2496. {
  2497. global $conf;
  2498. $countrycode='';
  2499. if (! empty($conf->geoipmaxmind->enabled))
  2500. {
  2501. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2502. //$ip='24.24.24.24';
  2503. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  2504. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2505. $geoip=new DolGeoIP('country',$datafile);
  2506. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2507. //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
  2508. $countrycode=$geoip->getCountryCodeFromIP($ip);
  2509. }
  2510. return $countrycode;
  2511. }
  2512. /**
  2513. * Return country code for current user.
  2514. * If software is used inside a local network, detection may fails (we need a public ip)
  2515. *
  2516. * @return string Country code (fr, es, it, us, ...)
  2517. */
  2518. function dol_user_country()
  2519. {
  2520. global $conf,$langs,$user;
  2521. //$ret=$user->xxx;
  2522. $ret='';
  2523. if (! empty($conf->geoipmaxmind->enabled))
  2524. {
  2525. $ip=getUserRemoteIP();
  2526. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2527. //$ip='24.24.24.24';
  2528. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2529. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2530. $geoip=new DolGeoIP('country',$datafile);
  2531. $countrycode=$geoip->getCountryCodeFromIP($ip);
  2532. $ret=$countrycode;
  2533. }
  2534. return $ret;
  2535. }
  2536. /**
  2537. * Format address string
  2538. *
  2539. * @param string $address Address
  2540. * @param int $htmlid Html ID (for example 'gmap')
  2541. * @param int $mode thirdparty|contact|member|other
  2542. * @param int $id Id of object
  2543. * @param int $noprint No output. Result is the function return
  2544. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2545. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2546. * @see dol_format_address
  2547. */
  2548. function dol_print_address($address, $htmlid, $mode, $id, $noprint=0, $charfornl='')
  2549. {
  2550. global $conf, $user, $langs, $hookmanager;
  2551. $out = '';
  2552. if ($address)
  2553. {
  2554. if ($hookmanager) {
  2555. $parameters = array('element' => $mode, 'id' => $id);
  2556. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2557. $out.=$hookmanager->resPrint;
  2558. }
  2559. if (empty($reshook))
  2560. {
  2561. if (empty($charfornl)) $out.=nl2br($address);
  2562. else $out.=preg_replace('/[\r\n]+/', $charfornl, $address);
  2563. $showgmap=$showomap=0;
  2564. // TODO Add a hook here
  2565. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1;
  2566. if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1;
  2567. if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1;
  2568. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1;
  2569. if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1;
  2570. if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1;
  2571. if ($showgmap)
  2572. {
  2573. $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1);
  2574. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2575. }
  2576. if ($showomap)
  2577. {
  2578. $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1);
  2579. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2580. }
  2581. }
  2582. }
  2583. if ($noprint) return $out;
  2584. else print $out;
  2585. }
  2586. /**
  2587. * Return true if email syntax is ok
  2588. *
  2589. * @param string $address email (Ex: "toto@examle.com", "John Do <johndo@example.com>")
  2590. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2591. * @return boolean true if email syntax is OK, false if KO or empty string
  2592. */
  2593. function isValidEmail($address, $acceptsupervisorkey=0)
  2594. {
  2595. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2596. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2597. return false;
  2598. }
  2599. /**
  2600. * Return if the domain name has a valid MX record.
  2601. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  2602. *
  2603. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  2604. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  2605. */
  2606. function isValidMXRecord($domain)
  2607. {
  2608. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr'))
  2609. {
  2610. if (! checkdnsrr(idn_to_ascii($domain), 'MX'))
  2611. {
  2612. return 0;
  2613. }
  2614. if (function_exists('getmxrr'))
  2615. {
  2616. $mxhosts=array();
  2617. $weight=array();
  2618. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  2619. if (count($mxhosts) > 1) return 1;
  2620. if (count($mxhosts) == 1 && ! empty($mxhosts[0])) return 1;
  2621. return 0;
  2622. }
  2623. }
  2624. return -1;
  2625. }
  2626. /**
  2627. * Return true if phone number syntax is ok
  2628. * TODO Decide what to do with this
  2629. *
  2630. * @param string $phone phone (Ex: "0601010101")
  2631. * @return boolean true if phone syntax is OK, false if KO or empty string
  2632. */
  2633. function isValidPhone($phone)
  2634. {
  2635. return true;
  2636. }
  2637. /**
  2638. * Make a strlen call. Works even if mbstring module not enabled
  2639. *
  2640. * @param string $string String to calculate length
  2641. * @param string $stringencoding Encoding of string
  2642. * @return int Length of string
  2643. */
  2644. function dol_strlen($string, $stringencoding='UTF-8')
  2645. {
  2646. if (function_exists('mb_strlen')) return mb_strlen($string,$stringencoding);
  2647. else return strlen($string);
  2648. }
  2649. /**
  2650. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  2651. *
  2652. * @param string $string String to scan
  2653. * @param string $start Start position
  2654. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  2655. * @param string $stringencoding Page code used for input string encoding
  2656. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  2657. * @return string substring
  2658. */
  2659. function dol_substr($string, $start, $length, $stringencoding='', $trunconbytes=0)
  2660. {
  2661. global $langs;
  2662. if (empty($stringencoding)) $stringencoding=$langs->charset_output;
  2663. $ret='';
  2664. if (empty($trunconbytes))
  2665. {
  2666. if (function_exists('mb_substr'))
  2667. {
  2668. $ret=mb_substr($string, $start, $length, $stringencoding);
  2669. }
  2670. else
  2671. {
  2672. $ret=substr($string, $start, $length);
  2673. }
  2674. }
  2675. else
  2676. {
  2677. if (function_exists('mb_strcut'))
  2678. {
  2679. $ret=mb_strcut($string, $start, $length, $stringencoding);
  2680. }
  2681. else
  2682. {
  2683. $ret=substr($string, $start, $length);
  2684. }
  2685. }
  2686. return $ret;
  2687. }
  2688. /**
  2689. * Truncate a string to a particular length adding '...' if string larger than length.
  2690. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2691. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2692. *
  2693. * @param string $string String to truncate
  2694. * @param int $size Max string size visible (excluding ...). 0 for no limit. WARNING: Final string size can have 3 more chars (if we added ..., or if size was max+1 or max+2 or max+3 so it does not worse to replace with ...)
  2695. * @param string $trunc Where to trunc: right, left, middle (size must be a 2 power), wrap
  2696. * @param string $stringencoding Tell what is source string encoding
  2697. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2698. * @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)
  2699. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  2700. */
  2701. function dol_trunc($string,$size=40,$trunc='right',$stringencoding='UTF-8',$nodot=0, $display=0)
  2702. {
  2703. global $conf;
  2704. if ($size==0 || ! empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2705. if (empty($stringencoding)) $stringencoding='UTF-8';
  2706. // reduce for small screen
  2707. if ($conf->dol_optimize_smallscreen==1 && $display==1) $size = round($size/3);
  2708. // We go always here
  2709. if ($trunc == 'right')
  2710. {
  2711. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2712. if (dol_strlen($newstring,$stringencoding) > ($size+($nodot?0:3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
  2713. return dol_substr($newstring,0,$size,$stringencoding).($nodot?'':'...');
  2714. else
  2715. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  2716. return $string;
  2717. }
  2718. elseif ($trunc == 'middle')
  2719. {
  2720. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2721. if (dol_strlen($newstring,$stringencoding) > 2 && dol_strlen($newstring,$stringencoding) > ($size+1))
  2722. {
  2723. $size1=round($size/2);
  2724. $size2=round($size/2);
  2725. return dol_substr($newstring,0,$size1,$stringencoding).'...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size2,$size2,$stringencoding);
  2726. }
  2727. else
  2728. return $string;
  2729. }
  2730. elseif ($trunc == 'left')
  2731. {
  2732. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2733. if (dol_strlen($newstring,$stringencoding) > ($size+($nodot?0:3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
  2734. return '...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size,$size,$stringencoding);
  2735. else
  2736. return $string;
  2737. }
  2738. elseif ($trunc == 'wrap')
  2739. {
  2740. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2741. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  2742. return dol_substr($newstring,0,$size,$stringencoding)."\n".dol_trunc(dol_substr($newstring,$size,dol_strlen($newstring,$stringencoding)-$size,$stringencoding),$size,$trunc);
  2743. else
  2744. return $string;
  2745. }
  2746. else return 'BadParam3CallingDolTrunc';
  2747. }
  2748. /**
  2749. * Show picto whatever it's its name (generic function)
  2750. *
  2751. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  2752. * @param string $picto Name of image file to show ('filenew', ...)
  2753. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2754. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2755. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2756. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2757. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2758. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  2759. * @param int $srconly Return only content of the src attribute of img.
  2760. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2761. * @param string $alt Force alt for bind people
  2762. * @param string $morecss Add more class css on img tag (For example 'myclascss'). Work only if $moreatt is empty.
  2763. * @return string Return img tag
  2764. * @see #img_object, #img_picto_common
  2765. */
  2766. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0, $alt='', $morecss='')
  2767. {
  2768. global $conf, $langs;
  2769. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2770. $url = DOL_URL_ROOT;
  2771. $theme = $conf->theme;
  2772. $path = 'theme/'.$theme;
  2773. // Define fullpathpicto to use into src
  2774. if ($pictoisfullpath) {
  2775. // Clean parameters
  2776. if (! preg_match('/(\.png|\.gif|\.svg)$/i',$picto)) {
  2777. $picto .= '.png';
  2778. }
  2779. $fullpathpicto = $picto;
  2780. }
  2781. else {
  2782. $pictowithoutext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  2783. //if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on')))
  2784. if (empty($srconly) && in_array($pictowithoutext, array(
  2785. 'bank', 'close_title', 'delete', 'edit', 'ellipsis-h', 'filter', 'grip', 'grip_title', 'list', 'listlight', 'off', 'on', 'play', 'playdisabled', 'printer', 'resize',
  2786. 'note', 'split', 'switch_off', 'switch_on', 'unlink', 'uparrow', '1downarrow', '1uparrow',
  2787. 'jabber','skype','twitter','facebook'
  2788. )
  2789. )) {
  2790. $fakey = $pictowithoutext;
  2791. $facolor = ''; $fasize = '';
  2792. $marginleftonlyshort = 2;
  2793. if ($pictowithoutext == 'switch_off') {
  2794. $fakey = 'fa-toggle-off';
  2795. $facolor = '#999';
  2796. $fasize = '2em';
  2797. }
  2798. elseif ($pictowithoutext == 'switch_on') {
  2799. $fakey = 'fa-toggle-on';
  2800. $facolor = '#227722';
  2801. $fasize = '2em';
  2802. }
  2803. elseif ($pictowithoutext == 'off') {
  2804. $fakey = 'fa-square-o';
  2805. $fasize = '1.3em';
  2806. }
  2807. elseif ($pictowithoutext == 'on') {
  2808. $fakey = 'fa-check-square-o';
  2809. $fasize = '1.3em';
  2810. }
  2811. elseif ($pictowithoutext == 'bank') {
  2812. $fakey = 'fa-bank';
  2813. $facolor = '#444';
  2814. }
  2815. elseif ($pictowithoutext == 'close_title') {
  2816. $fakey = 'fa-window-close';
  2817. }
  2818. elseif ($pictowithoutext == 'delete') {
  2819. $fakey = 'fa-trash';
  2820. $facolor = '#444';
  2821. }
  2822. elseif ($pictowithoutext == 'edit') {
  2823. $fakey = 'fa-pencil';
  2824. $facolor = '#444';
  2825. }
  2826. elseif ($pictowithoutext == 'filter') {
  2827. $fakey = 'fa-'.$pictowithoutext;
  2828. }
  2829. elseif ($pictowithoutext == 'grip_title' || $pictowithoutext == 'grip') {
  2830. $fakey = 'fa-arrows';
  2831. }
  2832. elseif ($pictowithoutext == 'listlight') {
  2833. $fakey = 'fa-download';
  2834. $facolor = '#999';
  2835. $marginleftonlyshort=1;
  2836. }
  2837. elseif ($pictowithoutext == 'printer') {
  2838. $fakey = 'fa-print';
  2839. $fasize = '1.2em';
  2840. $facolor = '#444';
  2841. }
  2842. elseif ($pictowithoutext == 'resize') {
  2843. $fakey = 'fa-crop';
  2844. $facolor = '#444';
  2845. }
  2846. elseif ($pictowithoutext == 'note') {
  2847. $fakey = 'fa-sticky-note-o';
  2848. $facolor = '#999';
  2849. $marginleftonlyshort=1;
  2850. }
  2851. elseif ($pictowithoutext == 'uparrow') {
  2852. $fakey = 'fa-mail-forward';
  2853. $facolor = '#555';
  2854. }
  2855. elseif ($pictowithoutext == '1uparrow') {
  2856. $fakey = 'fa-caret-up';
  2857. $marginleftonlyshort = 1;
  2858. }
  2859. elseif ($pictowithoutext == '1downarrow') {
  2860. $fakey = 'fa-caret-down';
  2861. $marginleftonlyshort = 1;
  2862. }
  2863. elseif ($pictowithoutext == 'unlink') {
  2864. $fakey = 'fa-chain-broken';
  2865. $facolor = '#555';
  2866. }
  2867. elseif ($pictowithoutext == 'playdisabled') {
  2868. $fakey = 'fa-play';
  2869. $facolor = '#ccc';
  2870. } elseif ($pictowithoutext == 'play') {
  2871. $fakey = 'fa-play';
  2872. $facolor = '#444';
  2873. }
  2874. elseif ($pictowithoutext == 'jabber') {
  2875. $fakey = 'fa-comment-o';
  2876. }
  2877. elseif ($pictowithoutext == 'split') {
  2878. $fakey = 'fa-code-fork';
  2879. }
  2880. else {
  2881. $fakey = 'fa-'.$pictowithoutext;
  2882. $facolor = '#444';
  2883. $marginleftonlyshort=0;
  2884. }
  2885. $reg=array();
  2886. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2887. $morecss.= ($morecss?' ':'').$reg[1];
  2888. }
  2889. $enabledisablehtml = '<span class="fa '.$fakey.' '.($marginleftonlyshort?($marginleftonlyshort==1?'marginleftonlyshort':'marginleftonly'):'').' valignmiddle'.($morecss?' '.$morecss:'').'" style="'.($fasize?('font-size: '.$fasize.';'):'').($facolor?(' color: '.$facolor.';'):'').'" alt="'.dol_escape_htmltag($titlealt).'"'.(($notitle || empty($titlealt))?'':' title="'.dol_escape_htmltag($titlealt).'"').($moreatt?' '.$moreatt:'').'>';
  2890. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2891. $enabledisablehtml.= $titlealt;
  2892. }
  2893. $enabledisablehtml.= '</span>';
  2894. return $enabledisablehtml;
  2895. }
  2896. if (! empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  2897. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  2898. }
  2899. else if (! empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  2900. $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
  2901. }
  2902. else if (! empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  2903. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  2904. }
  2905. // If we ask an image into $url/$mymodule/img (instead of default path)
  2906. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  2907. $picto = $regs[1];
  2908. $path = $regs[2]; // $path is $mymodule
  2909. }
  2910. // Clean parameters
  2911. if (! preg_match('/(\.png|\.gif|\.svg)$/i',$picto)) {
  2912. $picto .= '.png';
  2913. }
  2914. // If alt path are defined, define url where img file is, according to physical path
  2915. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  2916. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  2917. if ($type == 'main') {
  2918. continue;
  2919. }
  2920. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  2921. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  2922. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  2923. break;
  2924. }
  2925. }
  2926. // $url is '' or '/custom', $path is current theme or
  2927. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  2928. }
  2929. if ($srconly) {
  2930. return $fullpathpicto;
  2931. }
  2932. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for bind people
  2933. return '<img src="'.$fullpathpicto.'" alt="'.dol_escape_htmltag($alt).'"'.(($notitle || empty($titlealt))?'':' title="'.dol_escape_htmltag($titlealt).'"').($moreatt?' '.$moreatt:' class="inline-block'.($morecss?' '.$morecss:'').'"').'>'; // Alt is used for accessibility, title for popup
  2934. }
  2935. /**
  2936. * Show a picto called object_picto (generic function)
  2937. *
  2938. * @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.
  2939. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  2940. * For external modules use imagename@mymodule to search into directory "img" of module.
  2941. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  2942. * @param int $pictoisfullpath If 1, image path is a full path
  2943. * @param int $srconly Return only content of the src attribute of img.
  2944. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2945. * @return string Return img tag
  2946. * @see #img_picto, #img_picto_common
  2947. */
  2948. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0)
  2949. {
  2950. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  2951. }
  2952. /**
  2953. * Show weather picto
  2954. *
  2955. * @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.
  2956. * @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.
  2957. * @param string $moreatt Add more attribute on img tag
  2958. * @param int $pictoisfullpath If 1, image path is a full path
  2959. * @return string Return img tag
  2960. * @see #img_object, #img_picto
  2961. */
  2962. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  2963. {
  2964. global $conf;
  2965. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  2966. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  2967. return img_picto($titlealt, $path, $moreatt, 1);
  2968. }
  2969. /**
  2970. * Show picto (generic function)
  2971. *
  2972. * @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.
  2973. * @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.
  2974. * @param string $moreatt Add more attribute on img tag
  2975. * @param int $pictoisfullpath If 1, image path is a full path
  2976. * @return string Return img tag
  2977. * @see #img_object, #img_picto
  2978. */
  2979. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  2980. {
  2981. global $conf;
  2982. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  2983. if ($pictoisfullpath) $path = $picto;
  2984. else
  2985. {
  2986. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  2987. if (! empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  2988. {
  2989. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  2990. if (file_exists($themepath)) $path = $themepath;
  2991. }
  2992. }
  2993. return img_picto($titlealt, $path, $moreatt, 1);
  2994. }
  2995. /**
  2996. * Show logo action
  2997. *
  2998. * @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.
  2999. * @param string $numaction Action id or code to show
  3000. * @return string Return an img tag
  3001. */
  3002. function img_action($titlealt, $numaction)
  3003. {
  3004. global $conf, $langs;
  3005. if (empty($titlealt) || $titlealt == 'default')
  3006. {
  3007. if ($numaction == '-1' || $numaction == 'ST_NO') { $numaction = -1; $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); }
  3008. elseif ($numaction == '0' || $numaction == 'ST_NEVER') { $numaction = 0; $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); }
  3009. elseif ($numaction == '1' || $numaction == 'ST_TODO') { $numaction = 1; $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); }
  3010. elseif ($numaction == '2' || $numaction == 'ST_PEND') { $numaction = 2; $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); }
  3011. elseif ($numaction == '3' || $numaction == 'ST_DONE') { $numaction = 3; $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); }
  3012. else { $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction); $numaction = 0; }
  3013. }
  3014. if (! is_numeric($numaction)) $numaction=0;
  3015. return img_picto($titlealt, 'stcomm'.$numaction.'.png');
  3016. }
  3017. /**
  3018. * Show pdf logo
  3019. *
  3020. * @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.
  3021. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3022. * @return string Retourne tag img
  3023. */
  3024. function img_pdf($titlealt = 'default', $size = 3)
  3025. {
  3026. global $conf, $langs;
  3027. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  3028. return img_picto($titlealt, 'pdf'.$size.'.png');
  3029. }
  3030. /**
  3031. * Show logo +
  3032. *
  3033. * @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.
  3034. * @param string $other Add more attributes on img
  3035. * @return string Return tag img
  3036. */
  3037. function img_edit_add($titlealt = 'default', $other = '')
  3038. {
  3039. global $conf, $langs;
  3040. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  3041. return img_picto($titlealt, 'edit_add.png', $other);
  3042. }
  3043. /**
  3044. * Show logo -
  3045. *
  3046. * @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.
  3047. * @param string $other Add more attributes on img
  3048. * @return string Return tag img
  3049. */
  3050. function img_edit_remove($titlealt = 'default', $other='')
  3051. {
  3052. global $conf, $langs;
  3053. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  3054. return img_picto($titlealt, 'edit_remove.png', $other);
  3055. }
  3056. /**
  3057. * Show logo editer/modifier fiche
  3058. *
  3059. * @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.
  3060. * @param integer $float Si il faut y mettre le style "float: right"
  3061. * @param string $other Add more attributes on img
  3062. * @return string Return tag img
  3063. */
  3064. function img_edit($titlealt = 'default', $float = 0, $other = 'class="pictoedit"')
  3065. {
  3066. global $conf, $langs;
  3067. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  3068. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl'?'left':'right').'"' : "") . ($other?' '.$other:''));
  3069. }
  3070. /**
  3071. * Show logo view card
  3072. *
  3073. * @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.
  3074. * @param integer $float Si il faut y mettre le style "float: right"
  3075. * @param string $other Add more attributes on img
  3076. * @return string Return tag img
  3077. */
  3078. function img_view($titlealt = 'default', $float = 0, $other = '')
  3079. {
  3080. global $conf, $langs;
  3081. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  3082. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3083. return img_picto($titlealt, 'view.png', $moreatt);
  3084. }
  3085. /**
  3086. * Show delete logo
  3087. *
  3088. * @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.
  3089. * @param string $other Add more attributes on img
  3090. * @return string Retourne tag img
  3091. */
  3092. function img_delete($titlealt = 'default', $other = 'class="pictodelete"')
  3093. {
  3094. global $conf, $langs;
  3095. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  3096. return img_picto($titlealt, 'delete.png', $other);
  3097. //return '<span class="fa fa-trash fa-2x fa-fw" style="font-size: 1.7em;" title="'.$titlealt.'"></span>';
  3098. }
  3099. /**
  3100. * Show printer logo
  3101. *
  3102. * @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.
  3103. * @param string $other Add more attributes on img
  3104. * @return string Retourne tag img
  3105. */
  3106. function img_printer($titlealt = "default", $other='')
  3107. {
  3108. global $conf,$langs;
  3109. if ($titlealt=="default") $titlealt=$langs->trans("Print");
  3110. return img_picto($titlealt,'printer.png',$other);
  3111. }
  3112. /**
  3113. * Show split logo
  3114. *
  3115. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3116. * @param string $other Add more attributes on img
  3117. * @return string Retourne tag img
  3118. */
  3119. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3120. {
  3121. global $conf, $langs;
  3122. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  3123. return img_picto($titlealt, 'split.png', $other);
  3124. }
  3125. /**
  3126. * Show help logo with cursor "?"
  3127. *
  3128. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3129. * @param int|string $usealttitle Text to use as alt title
  3130. * @return string Return tag img
  3131. */
  3132. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3133. {
  3134. global $conf, $langs;
  3135. if ($usealttitle)
  3136. {
  3137. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  3138. else $usealttitle = $langs->trans('Info');
  3139. }
  3140. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help': ($usehelpcursor == 2 ? ' cursor: pointer':'')).'"');
  3141. }
  3142. /**
  3143. * Show info logo
  3144. *
  3145. * @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.
  3146. * @return string Return img tag
  3147. */
  3148. function img_info($titlealt = 'default')
  3149. {
  3150. global $conf, $langs;
  3151. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  3152. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3153. }
  3154. /**
  3155. * Show warning logo
  3156. *
  3157. * @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.
  3158. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3159. * @return string Return img tag
  3160. */
  3161. function img_warning($titlealt = 'default', $moreatt = '')
  3162. {
  3163. global $conf, $langs;
  3164. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  3165. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3166. return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): ''));
  3167. }
  3168. /**
  3169. * Show error logo
  3170. *
  3171. * @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.
  3172. * @return string Return img tag
  3173. */
  3174. function img_error($titlealt = 'default')
  3175. {
  3176. global $conf, $langs;
  3177. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  3178. return img_picto($titlealt, 'error.png', 'class="valigntextbottom"');
  3179. }
  3180. /**
  3181. * Show next logo
  3182. *
  3183. * @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.
  3184. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3185. * @return string Return img tag
  3186. */
  3187. function img_next($titlealt = 'default', $moreatt='')
  3188. {
  3189. global $conf, $langs;
  3190. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  3191. //return img_picto($titlealt, 'next.png', $moreatt);
  3192. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3193. }
  3194. /**
  3195. * Show previous logo
  3196. *
  3197. * @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.
  3198. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3199. * @return string Return img tag
  3200. */
  3201. function img_previous($titlealt = 'default', $moreatt='')
  3202. {
  3203. global $conf, $langs;
  3204. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  3205. //return img_picto($titlealt, 'previous.png', $moreatt);
  3206. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3207. }
  3208. /**
  3209. * Show down arrow logo
  3210. *
  3211. * @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.
  3212. * @param int $selected Selected
  3213. * @param string $moreclass Add more CSS classes
  3214. * @return string Return img tag
  3215. */
  3216. function img_down($titlealt = 'default', $selected = 0, $moreclass='')
  3217. {
  3218. global $conf, $langs;
  3219. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  3220. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass?" ".$moreclass:"").'"');
  3221. }
  3222. /**
  3223. * Show top arrow logo
  3224. *
  3225. * @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.
  3226. * @param int $selected Selected
  3227. * @param string $moreclass Add more CSS classes
  3228. * @return string Return img tag
  3229. */
  3230. function img_up($titlealt = 'default', $selected = 0, $moreclass='')
  3231. {
  3232. global $conf, $langs;
  3233. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  3234. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass?" ".$moreclass:"").'"');
  3235. }
  3236. /**
  3237. * Show left arrow logo
  3238. *
  3239. * @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.
  3240. * @param int $selected Selected
  3241. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3242. * @return string Return img tag
  3243. */
  3244. function img_left($titlealt = 'default', $selected = 0, $moreatt='')
  3245. {
  3246. global $conf, $langs;
  3247. if ($titlealt == 'default') $titlealt = $langs->trans('Left');
  3248. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3249. }
  3250. /**
  3251. * Show right arrow logo
  3252. *
  3253. * @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.
  3254. * @param int $selected Selected
  3255. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3256. * @return string Return img tag
  3257. */
  3258. function img_right($titlealt = 'default', $selected = 0, $moreatt='')
  3259. {
  3260. global $conf, $langs;
  3261. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  3262. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3263. }
  3264. /**
  3265. * Show tick logo if allowed
  3266. *
  3267. * @param string $allow Allow
  3268. * @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.
  3269. * @return string Return img tag
  3270. */
  3271. function img_allow($allow, $titlealt = 'default')
  3272. {
  3273. global $conf, $langs;
  3274. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  3275. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  3276. return '-';
  3277. }
  3278. /**
  3279. * Return image of a credit card according to its brand name
  3280. *
  3281. * @param string $brand Brand name of credit card
  3282. * @return string Return img tag
  3283. */
  3284. function img_credit_card($brand)
  3285. {
  3286. if ($brand == 'Visa') {$brand='cc-visa';}
  3287. elseif ($brand == 'MasterCard') {$brand='cc-mastercard';}
  3288. elseif ($brand == 'American Express') {$brand='cc-amex';}
  3289. elseif ($brand == 'Discover') {$brand='cc-discover';}
  3290. elseif ($brand == 'JCB') {$brand='cc-jcb';}
  3291. elseif ($brand == 'Diners Club') {$brand='cc-diners-club';}
  3292. elseif (! in_array($brand, array('cc-visa','cc-mastercard','cc-amex','cc-discover','cc-jcb','cc-diners-club'))) {$brand='credit-card';}
  3293. return '<span class="fa fa-'.$brand.' fa-2x fa-fw"></span>';
  3294. }
  3295. /**
  3296. * Show MIME img of a file
  3297. *
  3298. * @param string $file Filename
  3299. * @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.
  3300. * @param string $morecss More css
  3301. * @return string Return img tag
  3302. */
  3303. function img_mime($file, $titlealt = '', $morecss='')
  3304. {
  3305. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3306. $mimetype = dol_mimetype($file, '', 1);
  3307. $mimeimg = dol_mimetype($file, '', 2);
  3308. $mimefa = dol_mimetype($file, '', 4);
  3309. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  3310. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3311. return '<i class="fa fa-'.$mimefa.' paddingright"></i>';
  3312. }
  3313. /**
  3314. * Show phone logo.
  3315. * Use img_picto instead.
  3316. *
  3317. * @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.
  3318. * @param int $option Option
  3319. * @return string Return img tag
  3320. * @deprecated
  3321. * @see img_picto
  3322. */
  3323. function img_phone($titlealt = 'default', $option = 0)
  3324. {
  3325. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  3326. global $conf,$langs;
  3327. if ($titlealt == 'default') $titlealt = $langs->trans('Call');
  3328. if ($option == 1) $img = 'call';
  3329. else $img = 'call_out';
  3330. return img_picto($titlealt, $img);
  3331. }
  3332. /**
  3333. * Show search logo
  3334. *
  3335. * @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.
  3336. * @param string $other Add more attributes on img
  3337. * @return string Retourne tag img
  3338. */
  3339. function img_search($titlealt = 'default', $other = '')
  3340. {
  3341. global $conf, $langs;
  3342. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3343. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3344. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3345. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3346. return $input;
  3347. }
  3348. /**
  3349. * Show search logo
  3350. *
  3351. * @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.
  3352. * @param string $other Add more attributes on img
  3353. * @return string Retourne tag img
  3354. */
  3355. function img_searchclear($titlealt = 'default', $other = '')
  3356. {
  3357. global $conf, $langs;
  3358. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3359. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3360. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3361. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3362. return $input;
  3363. }
  3364. /**
  3365. * Show information for admin users or standard users
  3366. *
  3367. * @param string $text Text info
  3368. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3369. * @param int $nodiv No div
  3370. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'xxx'=Other
  3371. * @param string $morecss More CSS
  3372. * @return string String with info text
  3373. */
  3374. function info_admin($text, $infoonimgalt = 0, $nodiv=0, $admin='1', $morecss='')
  3375. {
  3376. global $conf, $langs;
  3377. if ($infoonimgalt)
  3378. {
  3379. return img_picto($text, 'info', 'class="hideonsmartphone'.($morecss?' '.$morecss:'').'"');
  3380. }
  3381. return ($nodiv?'':'<div class="'.(empty($admin)?'':($admin=='1'?'info':$admin)).' hideonsmartphone'.($morecss?' '.$morecss:'').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin?$langs->trans('InfoAdmin'):$langs->trans('Note')).'"></span> '.$text.($nodiv?'':'</div>');
  3382. }
  3383. /**
  3384. * Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
  3385. * On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
  3386. * Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
  3387. * renvoyer leur erreur par l'intermediaire de leur propriete "error".
  3388. *
  3389. * @param DoliDB $db Database handler
  3390. * @param mixed $error String or array of errors strings to show
  3391. * @param array $errors Array of errors
  3392. * @return void
  3393. * @see dol_htmloutput_errors
  3394. */
  3395. function dol_print_error($db='',$error='',$errors=null)
  3396. {
  3397. global $conf,$langs,$argv;
  3398. global $dolibarr_main_prod;
  3399. $out = '';
  3400. $syslog = '';
  3401. // Si erreur intervenue avant chargement langue
  3402. if (! $langs)
  3403. {
  3404. require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
  3405. $langs = new Translate('', $conf);
  3406. $langs->load("main");
  3407. }
  3408. // Load translation files required by the page
  3409. $langs->loadLangs(array('main', 'errors'));
  3410. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3411. {
  3412. $out.=$langs->trans("DolibarrHasDetectedError").".<br>\n";
  3413. if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $out.="You use an experimental or develop level of features, so please do NOT report any bugs, except if problem is confirmed moving option MAIN_FEATURES_LEVEL back to 0.<br>\n";
  3414. $out.=$langs->trans("InformationToHelpDiagnose").":<br>\n";
  3415. $out.="<b>".$langs->trans("Date").":</b> ".dol_print_date(time(),'dayhourlog')."<br>\n";
  3416. $out.="<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";
  3417. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  3418. if (function_exists("phpversion"))
  3419. {
  3420. $out.="<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  3421. }
  3422. $out.="<b>".$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";
  3423. if (function_exists("php_uname"))
  3424. {
  3425. $out.="<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  3426. }
  3427. $out.="<b>".$langs->trans("UserAgent").":</b> ".$_SERVER["HTTP_USER_AGENT"]."<br>\n";
  3428. $out.="<br>\n";
  3429. $out.="<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"],ENT_COMPAT,'UTF-8')."<br>\n";
  3430. $out.="<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"])?dol_htmlentities($_SERVER["HTTP_REFERER"],ENT_COMPAT,'UTF-8'):'')."<br>\n";
  3431. $out.="<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu)?$conf->standard_menu:'')."<br>\n";
  3432. $out.="<br>\n";
  3433. $syslog.="url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  3434. $syslog.=", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  3435. }
  3436. else // Mode CLI
  3437. {
  3438. $out.='> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  3439. $syslog.="pid=".dol_getmypid();
  3440. }
  3441. if (is_object($db))
  3442. {
  3443. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3444. {
  3445. $out.="<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  3446. $out.="<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror()?dol_escape_htmltag($db->lastqueryerror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3447. $out.="<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno()?dol_escape_htmltag($db->lasterrno()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3448. $out.="<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror()?dol_escape_htmltag($db->lasterror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3449. $out.="<br>\n";
  3450. }
  3451. else // Mode CLI
  3452. {
  3453. // No dol_escape_htmltag for output, we are in CLI mode
  3454. $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  3455. $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3456. $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3457. $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3458. }
  3459. $syslog.=", sql=".$db->lastquery();
  3460. $syslog.=", db_error=".$db->lasterror();
  3461. }
  3462. if ($error || $errors)
  3463. {
  3464. $langs->load("errors");
  3465. // Merge all into $errors array
  3466. if (is_array($error) && is_array($errors)) $errors=array_merge($error,$errors);
  3467. elseif (is_array($error)) $errors=$error;
  3468. elseif (is_array($errors)) $errors=array_merge(array($error),$errors);
  3469. else $errors=array_merge(array($error));
  3470. foreach($errors as $msg)
  3471. {
  3472. if (empty($msg)) continue;
  3473. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3474. {
  3475. $out.="<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n" ;
  3476. }
  3477. else // Mode CLI
  3478. {
  3479. $out.='> '.$langs->transnoentities("Message").":\n".$msg."\n" ;
  3480. }
  3481. $syslog.=", msg=".$msg;
  3482. }
  3483. }
  3484. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  3485. {
  3486. xdebug_print_function_stack();
  3487. $out.='<b>XDebug informations:</b>'."<br>\n";
  3488. $out.='File: '.xdebug_call_file()."<br>\n";
  3489. $out.='Line: '.xdebug_call_line()."<br>\n";
  3490. $out.='Function: '.xdebug_call_function()."<br>\n";
  3491. $out.="<br>\n";
  3492. }
  3493. if (empty($dolibarr_main_prod)) print $out;
  3494. else
  3495. {
  3496. print $langs->trans("DolibarrHasDetectedError").'. ';
  3497. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  3498. define("MAIN_CORE_ERROR", 1);
  3499. }
  3500. //else print 'Sorry, an error occured but the parameter $dolibarr_main_prod is defined in conf file so no message is reported to your browser. Please read the log file for error message.';
  3501. dol_syslog("Error ".$syslog, LOG_ERR);
  3502. }
  3503. /**
  3504. * Show a public email and error code to contact if technical error
  3505. *
  3506. * @param string $prefixcode Prefix of public error code
  3507. * @param string $errormessage Complete error message
  3508. * @param array $errormessages Array of error messages
  3509. * @param string $morecss More css
  3510. * @param string $email Email
  3511. * @return void
  3512. */
  3513. function dol_print_error_email($prefixcode, $errormessage='', $errormessages=array(), $morecss='error', $email='')
  3514. {
  3515. global $langs,$conf;
  3516. if (empty($email)) $email=$conf->global->MAIN_INFO_SOCIETE_MAIL;
  3517. $langs->load("errors");
  3518. $now=dol_now();
  3519. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  3520. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now,'%Y%m%d'));
  3521. if ($errormessage) print '<br><br>'.$errormessage;
  3522. if (is_array($errormessages) && count($errormessages))
  3523. {
  3524. foreach($errormessages as $mesgtoshow)
  3525. {
  3526. print '<br><br>'.$mesgtoshow;
  3527. }
  3528. }
  3529. print '</div></div>';
  3530. }
  3531. /**
  3532. * Show title line of an array
  3533. *
  3534. * @param string $name Label of field
  3535. * @param string $file Url used when we click on sort picto
  3536. * @param string $field Field to use for new sorting
  3537. * @param string $begin ("" by defaut)
  3538. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3539. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  3540. * @param string $sortfield Current field used to sort
  3541. * @param string $sortorder Current sort order
  3542. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  3543. * @param string $tooltip Tooltip
  3544. * @return void
  3545. */
  3546. function print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="")
  3547. {
  3548. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip);
  3549. }
  3550. /**
  3551. * Get title line of an array
  3552. *
  3553. * @param string $name Translation key of field
  3554. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  3555. * @param string $file Url used when we click on sort picto
  3556. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  3557. * @param string $begin ("" by defaut)
  3558. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3559. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  3560. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  3561. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  3562. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  3563. * @param string $disablesortlink 1=Disable sort link
  3564. * @param string $tooltip Tooltip
  3565. * @return string
  3566. */
  3567. function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $disablesortlink=0, $tooltip='')
  3568. {
  3569. global $conf, $langs, $form;
  3570. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  3571. $sortorder=strtoupper($sortorder);
  3572. $out='';
  3573. $sortimg='';
  3574. $tag='th';
  3575. if ($thead==2) $tag='div';
  3576. $tmpsortfield=explode(',',$sortfield);
  3577. $sortfield1=trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  3578. $tmpfield=explode(',',$field);
  3579. $field1=trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  3580. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  3581. // If field is used as sort criteria we use a specific css class liste_titre_sel
  3582. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  3583. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./","",$field1))) $out.= '<'.$tag.' class="'.$prefix.'liste_titre_sel" '. $moreattrib.'>';
  3584. else $out.= '<'.$tag.' class="'.$prefix.'liste_titre" '. $moreattrib.'>';
  3585. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3586. {
  3587. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  3588. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  3589. $options=preg_replace('/&+/i','&',$options);
  3590. if (! preg_match('/^&/',$options)) $options='&'.$options;
  3591. $sortordertouseinlink='';
  3592. if ($field1 != $sortfield1) // We are on another field than current sorted field
  3593. {
  3594. if (preg_match('/^DESC/i', $sortorder))
  3595. {
  3596. $sortordertouseinlink.=str_repeat('desc,', count(explode(',',$field)));
  3597. }
  3598. else // We reverse the var $sortordertouseinlink
  3599. {
  3600. $sortordertouseinlink.=str_repeat('asc,', count(explode(',',$field)));
  3601. }
  3602. }
  3603. else // We are on field that is the first current sorting criteria
  3604. {
  3605. if (preg_match('/^ASC/i', $sortorder)) // We reverse the var $sortordertouseinlink
  3606. {
  3607. $sortordertouseinlink.=str_repeat('desc,', count(explode(',',$field)));
  3608. }
  3609. else
  3610. {
  3611. $sortordertouseinlink.=str_repeat('asc,', count(explode(',',$field)));
  3612. }
  3613. }
  3614. $sortordertouseinlink=preg_replace('/,$/', '', $sortordertouseinlink);
  3615. $out.= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'">';
  3616. }
  3617. if ($tooltip) $out.=$form->textwithpicto($langs->trans($name), $langs->trans($tooltip));
  3618. else $out.=$langs->trans($name);
  3619. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3620. {
  3621. $out.='</a>';
  3622. }
  3623. if (empty($thead) && $field) // If this is a sort field
  3624. {
  3625. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  3626. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  3627. $options=preg_replace('/&+/i','&',$options);
  3628. if (! preg_match('/^&/',$options)) $options='&'.$options;
  3629. if (! $sortorder || $field1 != $sortfield1)
  3630. {
  3631. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3632. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3633. }
  3634. else
  3635. {
  3636. if (preg_match('/^DESC/', $sortorder)) {
  3637. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3638. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3639. $sortimg.= '<span class="nowrap">'.img_up("Z-A",0).'</span>';
  3640. }
  3641. if (preg_match('/^ASC/', $sortorder)) {
  3642. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3643. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3644. $sortimg.= '<span class="nowrap">'.img_down("A-Z",0).'</span>';
  3645. }
  3646. }
  3647. }
  3648. $out.=$sortimg;
  3649. $out.='</'.$tag.'>';
  3650. return $out;
  3651. }
  3652. /**
  3653. * Show a title.
  3654. *
  3655. * @param string $title Title to show
  3656. * @return string Title to show
  3657. * @deprecated Use load_fiche_titre instead
  3658. * @see load_fiche_titre
  3659. */
  3660. function print_titre($title)
  3661. {
  3662. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  3663. print '<div class="titre">'.$title.'</div>';
  3664. }
  3665. /**
  3666. * Show a title with picto
  3667. *
  3668. * @param string $title Title to show
  3669. * @param string $mesg Added message to show on right
  3670. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3671. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3672. * @param int $id To force an id on html objects
  3673. * @return void
  3674. * @deprecated Use print load_fiche_titre instead
  3675. */
  3676. function print_fiche_titre($title, $mesg='', $picto='title_generic.png', $pictoisfullpath=0, $id='')
  3677. {
  3678. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3679. }
  3680. /**
  3681. * Load a title with picto
  3682. *
  3683. * @param string $titre Title to show
  3684. * @param string $morehtmlright Added message to show on right
  3685. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3686. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3687. * @param string $id To force an id on html objects
  3688. * @param string $morecssontable More css on table
  3689. * @param string $morehtmlcenter Added message to show on center
  3690. * @return string
  3691. * @see print_barre_liste
  3692. */
  3693. function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
  3694. {
  3695. global $conf;
  3696. $return='';
  3697. if ($picto == 'setup') $picto='title_generic.png';
  3698. $return.= "\n";
  3699. $return.= '<table '.($id?'id="'.$id.'" ':'').'summary="" class="centpercent notopnoleftnoright'.($morecssontable?' '.$morecssontable:'').'" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into print_barre_list
  3700. if ($picto) $return.= '<td class="nobordernopadding widthpictotitle opacityhigh" valign="middle">'.img_picto('',$picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  3701. $return.= '<td class="nobordernopadding valignmiddle">';
  3702. $return.= '<div class="titre inline-block">'.$titre.'</div>';
  3703. $return.= '</td>';
  3704. if (dol_strlen($morehtmlcenter))
  3705. {
  3706. $return.= '<td class="nobordernopadding" align="center" valign="middle">'.$morehtmlcenter.'</td>';
  3707. }
  3708. if (dol_strlen($morehtmlright))
  3709. {
  3710. $return.= '<td class="nobordernopadding titre_right wordbreak" align="right" valign="middle">'.$morehtmlright.'</td>';
  3711. }
  3712. $return.= '</tr></table>'."\n";
  3713. return $return;
  3714. }
  3715. /**
  3716. * Print a title with navigation controls for pagination
  3717. *
  3718. * @param string $titre Title to show (required)
  3719. * @param int $page Numero of page to show in navigation links (required)
  3720. * @param string $file Url of page (required)
  3721. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  3722. * @param string $sortfield Field to sort on ('' by default)
  3723. * @param string $sortorder Order to sort ('' by default)
  3724. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  3725. * @param int $num Number of records found by select with limit+1
  3726. * @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.
  3727. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3728. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3729. * @param string $morehtmlright More html to show
  3730. * @param string $morecss More css to the table
  3731. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  3732. * @param int $hideselectlimit Force to hide select limit
  3733. * @param int $hidenavigation Force to hide all navigation tools
  3734. * @return void
  3735. */
  3736. function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='title_generic.png', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $hideselectlimit=0, $hidenavigation=0)
  3737. {
  3738. global $conf,$langs;
  3739. $savlimit = $limit;
  3740. $savtotalnboflines = $totalnboflines;
  3741. $totalnboflines=abs($totalnboflines);
  3742. if ($picto == 'setup') $picto='title_setup.png';
  3743. if (($conf->browser->name == 'ie') && $picto=='title_generic.png') $picto='title.gif';
  3744. if ($limit < 0) $limit = $conf->liste_limit;
  3745. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  3746. {
  3747. $nextpage = 1;
  3748. }
  3749. else
  3750. {
  3751. $nextpage = 0;
  3752. }
  3753. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  3754. print "\n";
  3755. print "<!-- Begin title '".$titre."' -->\n";
  3756. print '<table border="0" class="centpercent notopnoleftnoright'.($morecss?' '.$morecss:'').'" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into load_fiche_tire
  3757. // Left
  3758. //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
  3759. print '<td class="nobordernopadding valignmiddle">';
  3760. if ($picto && $titre) print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
  3761. print '<div class="titre inline-block">'.$titre;
  3762. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print ' ('.$totalnboflines.')';
  3763. print '</div></td>';
  3764. // Center
  3765. if ($morehtmlcenter)
  3766. {
  3767. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3768. }
  3769. // Right
  3770. print '<td class="nobordernopadding valignmiddle" align="right">';
  3771. if ($sortfield) $options .= "&sortfield=".urlencode($sortfield);
  3772. if ($sortorder) $options .= "&sortorder=".urlencode($sortorder);
  3773. // Show navigation bar
  3774. $pagelist = '';
  3775. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  3776. {
  3777. if ($totalnboflines) // If we know total nb of lines
  3778. {
  3779. // Define nb of extra page links before and after selected page + ... + first or last
  3780. $maxnbofpage=(empty($conf->dol_optimize_smallscreen) ? 4 : 1);
  3781. if ($limit > 0) $nbpages=ceil($totalnboflines/$limit);
  3782. else $nbpages=1;
  3783. $cpt=($page-$maxnbofpage);
  3784. if ($cpt < 0) { $cpt=0; }
  3785. if ($cpt>=1)
  3786. {
  3787. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  3788. if ($cpt > 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3789. else if ($cpt == 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  3790. }
  3791. do
  3792. {
  3793. if ($cpt==$page)
  3794. {
  3795. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1).'</span></li>';
  3796. }
  3797. else
  3798. {
  3799. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt+1).'</a></li>';
  3800. }
  3801. $cpt++;
  3802. }
  3803. while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage);
  3804. if ($cpt<$nbpages)
  3805. {
  3806. if ($cpt<$nbpages-2) $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3807. else if ($cpt == $nbpages-2) $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.($nbpages-2).$options.'">'.($nbpages - 1).'</a></li>';
  3808. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.($nbpages-1).$options.'">'.$nbpages.'</a></li>';
  3809. }
  3810. }
  3811. else
  3812. {
  3813. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1)."</li>";
  3814. }
  3815. }
  3816. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist
  3817. print '</td>';
  3818. print '</tr></table>'."\n";
  3819. print "<!-- End title -->\n\n";
  3820. }
  3821. /**
  3822. * Function to show navigation arrows into lists
  3823. *
  3824. * @param int $page Number of page
  3825. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  3826. * @param string $options Other url paramaters to propagate ("" by default, may include sortfield and sortorder)
  3827. * @param integer $nextpage Do we show a next page button
  3828. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  3829. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  3830. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  3831. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  3832. * @param int $hideselectlimit Force to hide select limit
  3833. * @return void
  3834. */
  3835. function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0)
  3836. {
  3837. global $conf, $langs;
  3838. print '<div class="pagination"><ul>';
  3839. if ((int) $limit >= 0 && empty($hideselectlimit))
  3840. {
  3841. $pagesizechoices='10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  3842. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  3843. //$pagesizechoices.=',2:2';
  3844. if (! empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices=$conf->global->MAIN_PAGESIZE_CHOICES;
  3845. print '<li class="pagination">';
  3846. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  3847. $tmpchoice=explode(',',$pagesizechoices);
  3848. $tmpkey=$limit.':'.$limit;
  3849. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3850. $tmpkey=$conf->liste_limit.':'.$conf->liste_limit;
  3851. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3852. asort($tmpchoice, SORT_NUMERIC);
  3853. $found=false;
  3854. foreach($tmpchoice as $val)
  3855. {
  3856. $selected='';
  3857. $tmp=explode(':',$val);
  3858. $key=$tmp[0];
  3859. $val=$tmp[1];
  3860. if ($key != '' && $val != '')
  3861. {
  3862. if ((int) $key == (int) $limit)
  3863. {
  3864. $selected = ' selected="selected"';
  3865. $found = true;
  3866. }
  3867. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  3868. }
  3869. }
  3870. print '</select>';
  3871. if ($conf->use_javascript_ajax)
  3872. {
  3873. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  3874. <script type="text/javascript">
  3875. jQuery(document).ready(function () {
  3876. jQuery(".selectlimit").change(function() {
  3877. console.log("Change limit. Send submit");
  3878. $(this).parents(\'form:first\').submit();
  3879. });
  3880. });
  3881. </script>
  3882. ';
  3883. }
  3884. print '</li>';
  3885. }
  3886. if ($page > 0)
  3887. {
  3888. print '<li class="pagination"><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>';
  3889. }
  3890. if ($betweenarrows)
  3891. {
  3892. print $betweenarrows;
  3893. }
  3894. if ($nextpage > 0)
  3895. {
  3896. print '<li class="pagination"><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>';
  3897. }
  3898. if ($afterarrows)
  3899. {
  3900. print '<li class="paginationafterarrows">';
  3901. print $afterarrows;
  3902. print '</li>';
  3903. }
  3904. print '</ul></div>'."\n";
  3905. }
  3906. /**
  3907. * Return a string with VAT rate label formated for view output
  3908. * Used into pdf and HTML pages
  3909. *
  3910. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  3911. * @param boolean $addpercent Add a percent % sign in output
  3912. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  3913. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  3914. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  3915. */
  3916. function vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
  3917. {
  3918. $morelabel='';
  3919. if (preg_match('/%/',$rate))
  3920. {
  3921. $rate=str_replace('%','',$rate);
  3922. $addpercent=true;
  3923. }
  3924. if (preg_match('/\((.*)\)/',$rate,$reg))
  3925. {
  3926. $morelabel=' ('.$reg[1].')';
  3927. $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate);
  3928. }
  3929. if (preg_match('/\*/',$rate))
  3930. {
  3931. $rate=str_replace('*','',$rate);
  3932. $info_bits |= 1;
  3933. }
  3934. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  3935. if (! preg_match('/\//', $rate)) $ret=price($rate,0,'',0,0).($addpercent?'%':'');
  3936. else
  3937. {
  3938. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  3939. $ret=$rate.($addpercent?'%':'');
  3940. }
  3941. if (($info_bits & 1) && $usestarfornpr >= 0) $ret.=' *';
  3942. $ret.=$morelabel;
  3943. return $ret;
  3944. }
  3945. /**
  3946. * Function to format a value into an amount for visual output
  3947. * Function used into PDF and HTML pages
  3948. *
  3949. * @param float $amount Amount to format
  3950. * @param integer $form Type of format, HTML or not (not by default)
  3951. * @param Translate $outlangs Object langs for output
  3952. * @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.
  3953. * @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)
  3954. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  3955. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  3956. * @return string Chaine avec montant formate
  3957. *
  3958. * @see price2num() Revert function of price
  3959. */
  3960. function price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
  3961. {
  3962. global $langs,$conf;
  3963. // Clean parameters
  3964. if (empty($amount)) $amount=0; // To have a numeric value if amount not defined or = ''
  3965. $amount = (is_numeric($amount)?$amount:0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  3966. if ($rounding < 0) $rounding=min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
  3967. $nbdecimal=$rounding;
  3968. // Output separators by default (french)
  3969. $dec=','; $thousand=' ';
  3970. // If $outlangs not forced, we use use language
  3971. if (! is_object($outlangs)) $outlangs=$langs;
  3972. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$outlangs->transnoentitiesnoconv("SeparatorDecimal");
  3973. if ($outlangs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$outlangs->transnoentitiesnoconv("SeparatorThousand");
  3974. if ($thousand == 'None') $thousand='';
  3975. else if ($thousand == 'Space') $thousand=' ';
  3976. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  3977. //print "amount=".$amount."-";
  3978. $amount = str_replace(',','.',$amount); // should be useless
  3979. //print $amount."-";
  3980. $datas = explode('.',$amount);
  3981. $decpart = isset($datas[1])?$datas[1]:'';
  3982. $decpart = preg_replace('/0+$/i','',$decpart); // Supprime les 0 de fin de partie decimale
  3983. //print "decpart=".$decpart."<br>";
  3984. $end='';
  3985. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  3986. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal=dol_strlen($decpart);
  3987. // Si on depasse max
  3988. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  3989. {
  3990. $nbdecimal=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
  3991. if (preg_match('/\.\.\./i',$conf->global->MAIN_MAX_DECIMALS_SHOWN))
  3992. {
  3993. // Si un affichage est tronque, on montre des ...
  3994. $end='...';
  3995. }
  3996. }
  3997. // If force rounding
  3998. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  3999. // Format number
  4000. $output=number_format($amount, $nbdecimal, $dec, $thousand);
  4001. if ($form)
  4002. {
  4003. $output=preg_replace('/\s/','&nbsp;',$output);
  4004. $output=preg_replace('/\'/','&#039;',$output);
  4005. }
  4006. // Add symbol of currency if requested
  4007. $cursymbolbefore=$cursymbolafter='';
  4008. if ($currency_code)
  4009. {
  4010. if ($currency_code == 'auto') $currency_code=$conf->currency;
  4011. $listofcurrenciesbefore=array('USD','GBP','AUD','MXN','PEN','CNY');
  4012. $listoflanguagesbefore=array('nl_NL');
  4013. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore))
  4014. {
  4015. $cursymbolbefore.=$outlangs->getCurrencySymbol($currency_code);
  4016. }
  4017. else
  4018. {
  4019. $tmpcur=$outlangs->getCurrencySymbol($currency_code);
  4020. $cursymbolafter.=($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4021. }
  4022. }
  4023. $output=$cursymbolbefore.$output.$end.($cursymbolafter?' ':'').$cursymbolafter;
  4024. return $output;
  4025. }
  4026. /**
  4027. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4028. * Function to use on each input amount before any numeric test or database insert
  4029. *
  4030. * @param float $amount Amount to convert/clean
  4031. * @param string $rounding ''=No rounding
  4032. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4033. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4034. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4035. * Numeric = Nb of digits for rounding
  4036. * @param int $alreadysqlnb Put 1 if you know that content is already universal format number
  4037. * @return string Amount with universal numeric format (Example: '99.99999') or unchanged text if conversion fails. If amount is null or '', it returns ''.
  4038. *
  4039. * @see price Opposite function of price2num
  4040. */
  4041. function price2num($amount,$rounding='',$alreadysqlnb=0)
  4042. {
  4043. global $langs,$conf;
  4044. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4045. // Numbers must be '1234.56'
  4046. // Decimal delimiter for PHP and database SQL requests must be '.'
  4047. $dec=','; $thousand=' ';
  4048. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$langs->transnoentitiesnoconv("SeparatorDecimal");
  4049. if ($langs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$langs->transnoentitiesnoconv("SeparatorThousand");
  4050. if ($thousand == 'None') $thousand='';
  4051. elseif ($thousand == 'Space') $thousand=' ';
  4052. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4053. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4054. if ($alreadysqlnb != 1) // If not a PHP number or unknown, we change format
  4055. {
  4056. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4057. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4058. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4059. if (is_numeric($amount))
  4060. {
  4061. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4062. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4063. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  4064. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  4065. $amount=number_format($amount,$nbofdec,$dec,$thousand);
  4066. }
  4067. //print "QQ".$amount.'<br>';
  4068. // Now make replace (the main goal of function)
  4069. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  4070. $amount=str_replace(' ','',$amount); // To avoid spaces
  4071. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4072. $amount=str_replace($dec,'.',$amount);
  4073. }
  4074. // Now, make a rounding if required
  4075. if ($rounding)
  4076. {
  4077. $nbofdectoround='';
  4078. if ($rounding == 'MU') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_UNIT;
  4079. elseif ($rounding == 'MT') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_TOT;
  4080. elseif ($rounding == 'MS') $nbofdectoround=empty($conf->global->MAIN_MAX_DECIMALS_STOCK)?5:$conf->global->MAIN_MAX_DECIMALS_STOCK;
  4081. elseif (is_numeric($rounding)) $nbofdectoround=$rounding;
  4082. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  4083. if (dol_strlen($nbofdectoround)) $amount = round($amount,$nbofdectoround); // $nbofdectoround can be 0.
  4084. else return 'ErrorBadParameterProvidedToFunction';
  4085. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4086. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4087. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4088. if (is_numeric($amount))
  4089. {
  4090. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4091. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4092. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  4093. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  4094. $amount=number_format($amount,min($nbofdec,$nbofdectoround),$dec,$thousand); // Convert amount to format with dolibarr dec and thousand
  4095. }
  4096. //print "TT".$amount.'<br>';
  4097. // Always make replace because each math function (like round) replace
  4098. // with local values and we want a number that has a SQL string format x.y
  4099. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  4100. $amount=str_replace(' ','',$amount); // To avoid spaces
  4101. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4102. $amount=str_replace($dec,'.',$amount);
  4103. }
  4104. return $amount;
  4105. }
  4106. /**
  4107. * Output a dimension with best unit
  4108. *
  4109. * @param float $dimension Dimension
  4110. * @param int $unit Unit of dimension (Example: 0=kg, -3=g, 98=ounce, 99=pound, ...)
  4111. * @param string $type 'weight', 'volume', ...
  4112. * @param Translate $outputlangs Translate language object
  4113. * @param int $round -1 = non rounding, x = number of decimal
  4114. * @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)
  4115. * @return string String to show dimensions
  4116. */
  4117. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no')
  4118. {
  4119. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4120. if (($forceunitoutput == 'no' && $dimension < 1/10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  4121. {
  4122. $dimension = $dimension * 1000000;
  4123. $unit = $unit - 6;
  4124. }
  4125. elseif (($forceunitoutput == 'no' && $dimension < 1/10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  4126. {
  4127. $dimension = $dimension * 1000;
  4128. $unit = $unit - 3;
  4129. }
  4130. elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  4131. {
  4132. $dimension = $dimension / 1000000;
  4133. $unit = $unit + 6;
  4134. }
  4135. elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  4136. {
  4137. $dimension = $dimension / 1000;
  4138. $unit = $unit + 3;
  4139. }
  4140. // Special case when we want output unit into pound or ounce
  4141. /* TODO
  4142. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4143. {
  4144. $dimension = // convert dimension from standard unit into ounce or pound
  4145. $unit = $forceunitoutput;
  4146. }
  4147. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4148. {
  4149. $dimension = // convert dimension from standard unit into ounce or pound
  4150. $unit = $forceunitoutput;
  4151. }*/
  4152. $ret=price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type);
  4153. return $ret;
  4154. }
  4155. /**
  4156. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4157. * Note: This function applies same rules than get_default_tva
  4158. *
  4159. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4160. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4161. * @param Societe $thirdparty_buyer Object of buying third party
  4162. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4163. * @param int $vatnpr If vat rate is NPR or not
  4164. * @return mixed 0 if not found, localtax rate if found
  4165. * @see get_default_tva
  4166. */
  4167. function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
  4168. {
  4169. global $db, $conf, $mysoc;
  4170. if (empty($thirdparty_seller) || ! is_object($thirdparty_seller)) $thirdparty_seller=$mysoc;
  4171. 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);
  4172. $vatratecleaned = $vatrate;
  4173. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4174. {
  4175. $vatratecleaned = trim($reg[1]);
  4176. $vatratecode = $reg[2];
  4177. }
  4178. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4179. {
  4180. return 0;
  4181. }*/
  4182. // Some test to guess with no need to make database access
  4183. if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4184. {
  4185. if ($local == 1)
  4186. {
  4187. if (! $mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  4188. if ($thirdparty_seller->id == $mysoc->id)
  4189. {
  4190. if (! $thirdparty_buyer->localtax1_assuj) return 0;
  4191. }
  4192. else
  4193. {
  4194. if (! $thirdparty_seller->localtax1_assuj) return 0;
  4195. }
  4196. }
  4197. if ($local == 2)
  4198. {
  4199. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4200. if (! $mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0.
  4201. if ($thirdparty_seller->id == $mysoc->id)
  4202. {
  4203. if (! $thirdparty_buyer->localtax2_assuj) return 0;
  4204. }
  4205. else
  4206. {
  4207. if (! $thirdparty_seller->localtax2_assuj) return 0;
  4208. }
  4209. }
  4210. }
  4211. else
  4212. {
  4213. if ($local == 1 && ! $thirdparty_seller->localtax1_assuj) return 0;
  4214. if ($local == 2 && ! $thirdparty_seller->localtax2_assuj) return 0;
  4215. }
  4216. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4217. if (in_array($mysoc->country_code, array('ES')))
  4218. {
  4219. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4220. }
  4221. // Search local taxes
  4222. if (! empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  4223. {
  4224. if ($local==1)
  4225. {
  4226. if ($thirdparty_seller != $mysoc)
  4227. {
  4228. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4229. {
  4230. return $thirdparty_seller->localtax1_value;
  4231. }
  4232. }
  4233. else // i am the seller
  4234. {
  4235. if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4236. {
  4237. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4238. }
  4239. }
  4240. }
  4241. if ($local==2)
  4242. {
  4243. if ($thirdparty_seller != $mysoc)
  4244. {
  4245. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4246. // TODO We should also return value defined on thirdparty only if defined
  4247. {
  4248. return $thirdparty_seller->localtax2_value;
  4249. }
  4250. }
  4251. else // i am the seller
  4252. {
  4253. if (in_array($mysoc->country_code, array('ES')))
  4254. {
  4255. return $thirdparty_buyer->localtax2_value;
  4256. }
  4257. else
  4258. {
  4259. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4260. }
  4261. }
  4262. }
  4263. }
  4264. // By default, search value of local tax on line of common tax
  4265. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4266. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4267. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$thirdparty_seller->country_code."'";
  4268. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4269. if ($vatratecode) $sql.= " AND t.code ='".$vatratecode."'"; // If we have the code, we use it in priority
  4270. else $sql.= " AND t.recuperableonly ='".$vatnpr."'";
  4271. dol_syslog("get_localtax", LOG_DEBUG);
  4272. $resql=$db->query($sql);
  4273. if ($resql)
  4274. {
  4275. $obj = $db->fetch_object($resql);
  4276. if ($local==1) return $obj->localtax1;
  4277. elseif ($local==2) return $obj->localtax2;
  4278. }
  4279. return 0;
  4280. }
  4281. /**
  4282. * Return true if LocalTax (1 or 2) is unique.
  4283. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  4284. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  4285. *
  4286. * @param int $local Local tax to test (1 or 2)
  4287. * @return boolean True if LocalTax have multiple values, False if not
  4288. */
  4289. function isOnlyOneLocalTax($local)
  4290. {
  4291. $tax=get_localtax_by_third($local);
  4292. $valors=explode(":", $tax);
  4293. if (count($valors)>1)
  4294. {
  4295. return false;
  4296. }
  4297. else
  4298. {
  4299. return true;
  4300. }
  4301. }
  4302. /**
  4303. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  4304. *
  4305. * @param int $local LocalTax to get
  4306. * @return number Values of localtax
  4307. */
  4308. function get_localtax_by_third($local)
  4309. {
  4310. global $db, $mysoc;
  4311. $sql ="SELECT t.localtax1, t.localtax2 ";
  4312. $sql.=" FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  4313. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND t.active = 1 AND t.taux=(";
  4314. $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";
  4315. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND tt.active = 1";
  4316. $sql.=" )";
  4317. $resql=$db->query($sql);
  4318. if ($resql)
  4319. {
  4320. $obj = $db->fetch_object($resql);
  4321. if ($local==1) return $obj->localtax1;
  4322. elseif ($local==2) return $obj->localtax2;
  4323. }
  4324. return 0;
  4325. }
  4326. /**
  4327. * Get vat main information from Id.
  4328. * You can call getLocalTaxesFromRate after to get other fields.
  4329. *
  4330. * @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.
  4331. * @param Societe $buyer Company object
  4332. * @param Societe $seller Company object
  4333. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  4334. * @return array array('rowid'=> , 'code'=> ...)
  4335. * @see getLocalTaxesFromRate
  4336. */
  4337. function getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
  4338. {
  4339. global $db, $mysoc;
  4340. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  4341. // Search local taxes
  4342. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
  4343. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4344. if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate;
  4345. else
  4346. {
  4347. $vatratecleaned = $vatrate;
  4348. $vatratecode = '';
  4349. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4350. {
  4351. $vatratecleaned = $reg[1];
  4352. $vatratecode = $reg[2];
  4353. }
  4354. $sql.=", ".MAIN_DB_PREFIX."c_country as c";
  4355. /*if ($mysoc->country_code == 'ES') $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // vat in spain use the buyer country ??
  4356. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";*/
  4357. $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
  4358. $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4359. if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'";
  4360. }
  4361. $resql=$db->query($sql);
  4362. if ($resql)
  4363. {
  4364. $obj = $db->fetch_object($resql);
  4365. if ($obj) return array('rowid'=>$obj->rowid, 'code'=>$obj->code, 'rate'=>$obj->rate, 'npr'=>$obj->npr, 'accountancy_code_sell'=>$obj->accountancy_code_sell, 'accountancy_code_buy'=>$obj->accountancy_code_buy);
  4366. else return array();
  4367. }
  4368. else dol_print_error($db);
  4369. return array();
  4370. }
  4371. /**
  4372. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  4373. * This does not take into account the seller setup if subject to vat or not, only country.
  4374. * TODO
  4375. * This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  4376. * Instead this function must be called when adding a line to get the array of localtax and type, and then
  4377. * provide it to the function calcul_price_total.
  4378. *
  4379. * @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.
  4380. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  4381. * @param Societe $buyer Company object
  4382. * @param Societe $seller Company object
  4383. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  4384. * @return array array(localtax_type1(1-6/0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  4385. * @see getTaxesFromId
  4386. */
  4387. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
  4388. {
  4389. global $db, $mysoc;
  4390. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  4391. // Search local taxes
  4392. $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
  4393. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4394. if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate;
  4395. else
  4396. {
  4397. $vatratecleaned = $vatrate;
  4398. $vatratecode = '';
  4399. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "x.x (yy)"
  4400. {
  4401. $vatratecleaned = $reg[1];
  4402. $vatratecode = $reg[2];
  4403. }
  4404. $sql.=", ".MAIN_DB_PREFIX."c_country as c";
  4405. if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ??
  4406. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
  4407. $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4408. if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'";
  4409. }
  4410. $resql=$db->query($sql);
  4411. if ($resql)
  4412. {
  4413. $obj = $db->fetch_object($resql);
  4414. if ($local == 1)
  4415. {
  4416. return array($obj->localtax1_type, get_localtax($vatrate, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4417. }
  4418. elseif ($local == 2)
  4419. {
  4420. return array($obj->localtax2_type, get_localtax($vatrate, $local, $buyer, $seller),$obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4421. }
  4422. else
  4423. {
  4424. return array($obj->localtax1_type, get_localtax($vatrate, 1, $buyer, $seller), $obj->localtax2_type, get_localtax($vatrate, 2, $buyer, $seller), $obj->accountancy_code_sell,$obj->accountancy_code_buy);
  4425. }
  4426. }
  4427. return 0;
  4428. }
  4429. /**
  4430. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  4431. * Function called by get_default_tva
  4432. *
  4433. * @param int $idprod Id of product or 0 if not a predefined product
  4434. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4435. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  4436. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  4437. * @see get_product_localtax_for_country
  4438. */
  4439. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice=0)
  4440. {
  4441. global $db,$conf,$mysoc;
  4442. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4443. $ret=0;
  4444. $found=0;
  4445. if ($idprod > 0)
  4446. {
  4447. // Load product
  4448. $product=new Product($db);
  4449. $result=$product->fetch($idprod);
  4450. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4451. {
  4452. if ($idprodfournprice > 0) // We want vat for product for a "supplier" object
  4453. {
  4454. $product->get_buyprice($idprodfournprice,0,0,0);
  4455. $ret=$product->vatrate_supplier;
  4456. if ($product->default_vat_code) $ret.=' ('.$product->default_vat_code.')';
  4457. }
  4458. else
  4459. {
  4460. $ret=$product->tva_tx; // Default vat of product we defined
  4461. if ($product->default_vat_code) $ret.=' ('.$product->default_vat_code.')';
  4462. }
  4463. $found=1;
  4464. }
  4465. else
  4466. {
  4467. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  4468. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  4469. }
  4470. }
  4471. if (! $found)
  4472. {
  4473. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  4474. {
  4475. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  4476. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  4477. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4478. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  4479. $sql.= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  4480. $sql.= $db->plimit(1);
  4481. $resql=$db->query($sql);
  4482. if ($resql)
  4483. {
  4484. $obj=$db->fetch_object($resql);
  4485. if ($obj)
  4486. {
  4487. $ret=$obj->vat_rate;
  4488. if ($obj->default_vat_code) $ret.=' ('.$obj->default_vat_code.')';
  4489. }
  4490. $db->free($sql);
  4491. }
  4492. else dol_print_error($db);
  4493. }
  4494. else $ret=$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  4495. }
  4496. dol_syslog("get_product_vat_for_country: ret=".$ret);
  4497. return $ret;
  4498. }
  4499. /**
  4500. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  4501. *
  4502. * @param int $idprod Id of product
  4503. * @param int $local 1 for localtax1, 2 for localtax 2
  4504. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4505. * @return int <0 if KO, Vat rate if OK
  4506. * @see get_product_vat_for_country
  4507. */
  4508. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  4509. {
  4510. global $db,$mysoc;
  4511. if (! class_exists('Product')) {
  4512. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4513. }
  4514. $ret=0;
  4515. $found=0;
  4516. if ($idprod > 0)
  4517. {
  4518. // Load product
  4519. $product=new Product($db);
  4520. $result=$product->fetch($idprod);
  4521. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4522. {
  4523. /* Not defined yet, so we don't use this
  4524. if ($local==1) $ret=$product->localtax1_tx;
  4525. elseif ($local==2) $ret=$product->localtax2_tx;
  4526. $found=1;
  4527. */
  4528. }
  4529. else
  4530. {
  4531. // TODO Read default product vat according to countrycode and product
  4532. }
  4533. }
  4534. if (! $found)
  4535. {
  4536. // If vat of product for the country not found or not defined, we return higher vat of country.
  4537. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  4538. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4539. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  4540. $sql.= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  4541. $sql.= $db->plimit(1);
  4542. $resql=$db->query($sql);
  4543. if ($resql)
  4544. {
  4545. $obj=$db->fetch_object($resql);
  4546. if ($obj)
  4547. {
  4548. if ($local==1) $ret=$obj->localtax1;
  4549. elseif ($local==2) $ret=$obj->localtax2;
  4550. }
  4551. }
  4552. else dol_print_error($db);
  4553. }
  4554. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  4555. return $ret;
  4556. }
  4557. /**
  4558. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  4559. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4560. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4561. * 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.
  4562. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4563. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  4564. * Sinon TVA proposee par defaut=0. Fin de regle.
  4565. *
  4566. * @param Societe $thirdparty_seller Objet societe vendeuse
  4567. * @param Societe $thirdparty_buyer Objet societe acheteuse
  4568. * @param int $idprod Id product
  4569. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  4570. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  4571. * @see get_default_npr, get_default_localtax
  4572. */
  4573. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  4574. {
  4575. global $conf;
  4576. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4577. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  4578. $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;
  4579. $seller_country_code = $thirdparty_seller->country_code;
  4580. $seller_in_cee = isInEEC($thirdparty_seller);
  4581. $buyer_country_code = $thirdparty_buyer->country_code;
  4582. $buyer_in_cee = isInEEC($thirdparty_buyer);
  4583. 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:''));
  4584. // 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)
  4585. // we use the buyer VAT.
  4586. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  4587. {
  4588. if ($seller_in_cee && $buyer_in_cee && ! $thirdparty_buyer->isACompany())
  4589. {
  4590. //print 'VATRULE 0';
  4591. return get_product_vat_for_country($idprod,$thirdparty_buyer,$idprodfournprice);
  4592. }
  4593. }
  4594. // If seller does not use VAT
  4595. if (! $seller_use_vat)
  4596. {
  4597. //print 'VATRULE 1';
  4598. return 0;
  4599. }
  4600. // 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.
  4601. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4602. if (($seller_country_code == $buyer_country_code)
  4603. || (in_array($seller_country_code,array('FR,MC')) && in_array($buyer_country_code,array('FR','MC')))) // Warning ->country_code not always defined
  4604. {
  4605. //print 'VATRULE 2';
  4606. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4607. }
  4608. // 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.
  4609. // Not supported
  4610. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  4611. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4612. if (($seller_in_cee && $buyer_in_cee))
  4613. {
  4614. $isacompany=$thirdparty_buyer->isACompany();
  4615. if ($isacompany)
  4616. {
  4617. //print 'VATRULE 3';
  4618. return 0;
  4619. }
  4620. else
  4621. {
  4622. //print 'VATRULE 4';
  4623. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4624. }
  4625. }
  4626. // Si (vendeur en France et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4627. if (! empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee) && !$thirdparty_buyer->isACompany()) {
  4628. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4629. }
  4630. // Sinon la TVA proposee par defaut=0. Fin de regle.
  4631. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  4632. //print 'VATRULE 5';
  4633. return 0;
  4634. }
  4635. /**
  4636. * Fonction qui renvoie si tva doit etre tva percue recuperable
  4637. *
  4638. * @param Societe $thirdparty_seller Thirdparty seller
  4639. * @param Societe $thirdparty_buyer Thirdparty buyer
  4640. * @param int $idprod Id product
  4641. * @param int $idprodfournprice Id supplier price for product
  4642. * @return float 0 or 1
  4643. * @see get_default_tva, get_default_localtax
  4644. */
  4645. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  4646. {
  4647. global $db;
  4648. if ($idprodfournprice > 0)
  4649. {
  4650. if (! class_exists('ProductFournisseur'))
  4651. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  4652. $prodprice = new ProductFournisseur($db);
  4653. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  4654. return $prodprice->fourn_tva_npr;
  4655. }
  4656. elseif ($idprod > 0)
  4657. {
  4658. if (! class_exists('Product'))
  4659. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4660. $prod = new Product($db);
  4661. $prod->fetch($idprod);
  4662. return $prod->tva_npr;
  4663. }
  4664. return 0;
  4665. }
  4666. /**
  4667. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4668. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4669. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4670. * Sinon TVA proposee par defaut=0. Fin de regle.
  4671. *
  4672. * @param Societe $thirdparty_seller Thirdparty seller
  4673. * @param Societe $thirdparty_buyer Thirdparty buyer
  4674. * @param int $local Localtax to process (1 or 2)
  4675. * @param int $idprod Id product
  4676. * @return integer localtax, -1 si ne peut etre determine
  4677. * @see get_default_tva, get_default_npr
  4678. */
  4679. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod=0)
  4680. {
  4681. global $mysoc;
  4682. if (!is_object($thirdparty_seller)) return -1;
  4683. if (!is_object($thirdparty_buyer)) return -1;
  4684. if ($local==1) // Localtax 1
  4685. {
  4686. if ($mysoc->country_code == 'ES')
  4687. {
  4688. if (is_numeric($thirdparty_buyer->localtax1_assuj) && ! $thirdparty_buyer->localtax1_assuj) return 0;
  4689. }
  4690. else
  4691. {
  4692. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  4693. if (is_numeric($thirdparty_seller->localtax1_assuj) && ! $thirdparty_seller->localtax1_assuj) return 0;
  4694. if (! is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj=='localtax1off') return 0;
  4695. }
  4696. }
  4697. elseif ($local==2) //I Localtax 2
  4698. {
  4699. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  4700. if (is_numeric($thirdparty_seller->localtax2_assuj) && ! $thirdparty_seller->localtax2_assuj) return 0;
  4701. if (! is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj=='localtax2off') return 0;
  4702. }
  4703. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  4704. {
  4705. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  4706. }
  4707. return 0;
  4708. }
  4709. /**
  4710. * Return yes or no in current language
  4711. *
  4712. * @param string $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  4713. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  4714. * @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.
  4715. * @return string HTML string
  4716. */
  4717. function yn($yesno, $case=1, $color=0)
  4718. {
  4719. global $langs;
  4720. $result='unknown'; $classname='';
  4721. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  4722. {
  4723. $result=$langs->trans('yes');
  4724. if ($case == 1 || $case == 3) $result=$langs->trans("Yes");
  4725. if ($case == 2) $result='<input type="checkbox" value="1" checked disabled>';
  4726. if ($case == 3) $result='<input type="checkbox" value="1" checked disabled> '.$result;
  4727. $classname='ok';
  4728. }
  4729. elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  4730. {
  4731. $result=$langs->trans("no");
  4732. if ($case == 1 || $case == 3) $result=$langs->trans("No");
  4733. if ($case == 2) $result='<input type="checkbox" value="0" disabled>';
  4734. if ($case == 3) $result='<input type="checkbox" value="0" disabled> '.$result;
  4735. if ($color == 2) $classname='ok';
  4736. else $classname='error';
  4737. }
  4738. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  4739. return $result;
  4740. }
  4741. /**
  4742. * Return a path to have a the directory according to object where files are stored.
  4743. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart)
  4744. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, $modulepart) if multidir_output not defined.
  4745. * Example our with new usage: $object is invoice -> 'INYYMM-ABCD'
  4746. * Example our with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  4747. *
  4748. * @param string $num Id of object (deprecated, $object will be used in future)
  4749. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  4750. * @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)
  4751. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  4752. * @param Object $object Object
  4753. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...')
  4754. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  4755. */
  4756. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
  4757. {
  4758. global $conf;
  4759. $path = '';
  4760. $arrayforoldpath=array('cheque','user','category','holiday','supplier_invoice','invoice_supplier','mailing','supplier_payment');
  4761. if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[]='product';
  4762. if (! empty($level) && in_array($modulepart, $arrayforoldpath))
  4763. {
  4764. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  4765. if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
  4766. else $num = preg_replace('/^.*\-/i','',$num);
  4767. $num = substr("000".$num, -$level);
  4768. if ($level == 1) $path = substr($num,0,1);
  4769. if ($level == 2) $path = substr($num,1,1).'/'.substr($num,0,1);
  4770. if ($level == 3) $path = substr($num,2,1).'/'.substr($num,1,1).'/'.substr($num,0,1);
  4771. }
  4772. else
  4773. {
  4774. // TODO
  4775. // We will enhance here a common way of forging path for document storage
  4776. // Here, object->id, object->ref and modulepart are required.
  4777. //var_dump($modulepart);
  4778. if (in_array($modulepart, array('thirdparty','contact','member','propal','proposal','commande','order','facture','invoice',
  4779. 'supplier_order','supplier_proposal','shipment','contract','expensereport')))
  4780. {
  4781. $path=($object->ref?$object->ref:$object->id);
  4782. }
  4783. }
  4784. if (empty($withoutslash) && ! empty($path)) $path.='/';
  4785. return $path;
  4786. }
  4787. /**
  4788. * Creation of a directory (this can create recursive subdir)
  4789. *
  4790. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  4791. * @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)
  4792. * @param int $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  4793. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  4794. */
  4795. function dol_mkdir($dir, $dataroot='', $newmask=null)
  4796. {
  4797. global $conf;
  4798. dol_syslog("functions.lib::dol_mkdir: dir=".$dir,LOG_INFO);
  4799. $dir_osencoded=dol_osencode($dir);
  4800. if (@is_dir($dir_osencoded)) return 0;
  4801. $nberr=0;
  4802. $nbcreated=0;
  4803. $ccdir='';
  4804. if (! empty($dataroot)) {
  4805. // Remove data root from loop
  4806. $dir = str_replace($dataroot.'/', '', $dir);
  4807. $ccdir = $dataroot.'/';
  4808. }
  4809. $cdir = explode("/", $dir);
  4810. $num=count($cdir);
  4811. for ($i = 0; $i < $num; $i++)
  4812. {
  4813. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  4814. else $ccdir .= $cdir[$i];
  4815. if (preg_match("/^.:$/",$ccdir,$regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  4816. // Attention, le is_dir() peut echouer bien que le rep existe.
  4817. // (ex selon config de open_basedir)
  4818. if ($ccdir)
  4819. {
  4820. $ccdir_osencoded=dol_osencode($ccdir);
  4821. if (! @is_dir($ccdir_osencoded))
  4822. {
  4823. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.",LOG_DEBUG);
  4824. umask(0);
  4825. $dirmaskdec=octdec($newmask);
  4826. if (empty($newmask)) {
  4827. $dirmaskdec = empty( $conf->global->MAIN_UMASK ) ? octdec( '0755' ) : octdec( $conf->global->MAIN_UMASK );
  4828. }
  4829. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  4830. if (! @mkdir($ccdir_osencoded, $dirmaskdec))
  4831. {
  4832. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  4833. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING);
  4834. $nberr++;
  4835. }
  4836. else
  4837. {
  4838. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created",LOG_DEBUG);
  4839. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  4840. $nbcreated++;
  4841. }
  4842. }
  4843. else
  4844. {
  4845. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  4846. }
  4847. }
  4848. }
  4849. return ($nberr ? -$nberr : $nbcreated);
  4850. }
  4851. /**
  4852. * Return picto saying a field is required
  4853. *
  4854. * @return string Chaine avec picto obligatoire
  4855. */
  4856. function picto_required()
  4857. {
  4858. return '<span class="fieldrequired">*</span>';
  4859. }
  4860. /**
  4861. * Clean a string from all HTML tags and entities.
  4862. * This function differs from strip_tags because:
  4863. * - <br> are replaced with \n if removelinefeed=0 or 1
  4864. * - if entities are found, they are decoded BEFORE the strip
  4865. * - you can decide to convert line feed into a space
  4866. *
  4867. * @param string $stringtoclean String to clean
  4868. * @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..."
  4869. * @param string $pagecodeto Encoding of input/output string
  4870. * @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)
  4871. * @return string String cleaned
  4872. *
  4873. * @see dol_escape_htmltag strip_tags dol_string_onlythesehtmltags dol_string_neverthesehtmltags
  4874. */
  4875. function dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0)
  4876. {
  4877. if ($removelinefeed == 2) $stringtoclean = preg_replace('/<br[^>]*>\n+/ims', '<br>', $stringtoclean);
  4878. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  4879. if ($strip_tags) {
  4880. $temp = strip_tags($temp);
  4881. } else {
  4882. $pattern = "/<[^<>]+>/";
  4883. // Exemple of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  4884. $temp = preg_replace($pattern,"",$temp); // pass 1
  4885. // $temp after pass 1: <a href="/myurl" title="A title">0000-021
  4886. $temp = preg_replace($pattern,"",$temp); // pass 2
  4887. // $temp after pass 2: 0000-021
  4888. }
  4889. $temp = dol_html_entity_decode($temp,ENT_COMPAT,$pagecodeto);
  4890. // Supprime aussi les retours
  4891. if ($removelinefeed == 1) $temp=str_replace(array("\r\n","\r","\n")," ",$temp);
  4892. // et les espaces doubles
  4893. while (strpos($temp," "))
  4894. {
  4895. $temp = str_replace(" "," ",$temp);
  4896. }
  4897. return trim($temp);
  4898. }
  4899. /**
  4900. * Clean a string to keep only desirable HTML tags.
  4901. *
  4902. * @param string $stringtoclean String to clean
  4903. * @return string String cleaned
  4904. *
  4905. * @see dol_escape_htmltag strip_tags dol_string_nohtmltag dol_string_neverthesehtmltags
  4906. */
  4907. function dol_string_onlythesehtmltags($stringtoclean)
  4908. {
  4909. $allowed_tags = array(
  4910. "html", "head", "meta", "body", "article", "a", "b", "br", "div", "em", "font", "img", "ins", "hr", "i", "li", "link",
  4911. "ol", "p", "s", "section", "span", "strong", "title",
  4912. "table", "tr", "th", "td", "u", "ul"
  4913. );
  4914. $allowed_tags_string = join("><", $allowed_tags);
  4915. $allowed_tags_string = preg_replace('/^>/','',$allowed_tags_string);
  4916. $allowed_tags_string = preg_replace('/<$/','',$allowed_tags_string);
  4917. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  4918. return $temp;
  4919. }
  4920. /**
  4921. * Clean a string from some undesirable HTML tags.
  4922. *
  4923. * @param string $stringtoclean String to clean
  4924. * @param array $disallowed_tags Array of tags not allowed
  4925. * @return string String cleaned
  4926. *
  4927. * @see dol_escape_htmltag strip_tags dol_string_nohtmltag dol_string_onlythesehtmltags
  4928. */
  4929. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags=array('textarea'))
  4930. {
  4931. $temp = $stringtoclean;
  4932. foreach($disallowed_tags as $tagtoremove)
  4933. {
  4934. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  4935. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  4936. }
  4937. return $temp;
  4938. }
  4939. /**
  4940. * Return first line of text. Cut will depends if content is HTML or not.
  4941. *
  4942. * @param string $text Input text
  4943. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  4944. * @return string Output text
  4945. * @see dol_nboflines_bis, dol_string_nohtmltag, dol_escape_htmltag
  4946. */
  4947. function dolGetFirstLineOfText($text, $nboflines=1)
  4948. {
  4949. if ($nboflines == 1)
  4950. {
  4951. if (dol_textishtml($text))
  4952. {
  4953. $firstline=preg_replace('/<br[^>]*>.*$/s','',$text); // The s pattern modifier means the . can match newline characters
  4954. $firstline=preg_replace('/<div[^>]*>.*$/s','',$firstline); // The s pattern modifier means the . can match newline characters
  4955. }
  4956. else
  4957. {
  4958. $firstline=preg_replace('/[\n\r].*/','',$text);
  4959. }
  4960. return $firstline.((strlen($firstline) != strlen($text))?'...':'');
  4961. }
  4962. else
  4963. {
  4964. $ishtml=0;
  4965. if (dol_textishtml($text))
  4966. {
  4967. $text=preg_replace('/\n/','',$text);
  4968. $ishtml=1;
  4969. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  4970. }
  4971. else
  4972. {
  4973. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  4974. }
  4975. $text = strtr($text, $repTable);
  4976. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  4977. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  4978. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  4979. $firstline='';
  4980. $i=0;
  4981. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  4982. while (($i < $nba) && ($i < ($nboflines * 2)))
  4983. {
  4984. if ($i % 2 == 0) $firstline .= $a[$i];
  4985. elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) $firstline .= ($ishtml?"<br>\n":"\n");
  4986. $i++;
  4987. }
  4988. unset($a);
  4989. return $firstline.(($i < $nba)?'...':'');
  4990. }
  4991. }
  4992. /**
  4993. * Replace CRLF in string with a HTML BR tag
  4994. *
  4995. * @param string $stringtoencode String to encode
  4996. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  4997. * @param bool $forxml false=Use <br>, true=Use <br />
  4998. * @return string String encoded
  4999. * @see dol_nboflines, dolGetFirstLineOfText
  5000. */
  5001. function dol_nl2br($stringtoencode,$nl2brmode=0,$forxml=false)
  5002. {
  5003. if (!$nl2brmode) {
  5004. return nl2br($stringtoencode, $forxml);
  5005. } else {
  5006. $ret=preg_replace('/(\r\n|\r|\n)/i', ($forxml?'<br />':'<br>'), $stringtoencode);
  5007. return $ret;
  5008. }
  5009. }
  5010. /**
  5011. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5012. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5013. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5014. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5015. * For PDF usage, you can show text by 2 ways:
  5016. * - writeHTMLCell -> param must be encoded into HTML.
  5017. * - MultiCell -> param must not be encoded into HTML.
  5018. * Because writeHTMLCell convert also \n into <br>, if function
  5019. * is used to build PDF, nl2brmode must be 1.
  5020. *
  5021. * @param string $stringtoencode String to encode
  5022. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5023. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5024. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5025. * @return string String encoded
  5026. */
  5027. function dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
  5028. {
  5029. $newstring=$stringtoencode;
  5030. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  5031. {
  5032. $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.
  5033. if ($removelasteolbr) $newstring=preg_replace('/<br>$/i','',$newstring); // Remove last <br> (remove only last one)
  5034. $newstring=strtr($newstring,array('&'=>'__and__','<'=>'__lt__','>'=>'__gt__','"'=>'__dquot__'));
  5035. $newstring=dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom); // Make entity encoding
  5036. $newstring=strtr($newstring,array('__and__'=>'&','__lt__'=>'<','__gt__'=>'>','__dquot__'=>'"'));
  5037. }
  5038. else
  5039. {
  5040. if ($removelasteolbr) $newstring=preg_replace('/(\r\n|\r|\n)$/i','',$newstring); // Remove last \n (may remove several)
  5041. $newstring=dol_nl2br(dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom),$nl2brmode);
  5042. }
  5043. // Other substitutions that htmlentities does not do
  5044. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5045. return $newstring;
  5046. }
  5047. /**
  5048. * This function is called to decode a HTML string (it decodes entities and br tags)
  5049. *
  5050. * @param string $stringtodecode String to decode
  5051. * @param string $pagecodeto Page code for result
  5052. * @return string String decoded
  5053. */
  5054. function dol_htmlentitiesbr_decode($stringtodecode,$pagecodeto='UTF-8')
  5055. {
  5056. $ret=dol_html_entity_decode($stringtodecode,ENT_COMPAT,$pagecodeto);
  5057. $ret=preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i',"<br>",$ret);
  5058. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i',"\r\n",$ret);
  5059. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i',"\n",$ret);
  5060. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i',"\n",$ret);
  5061. return $ret;
  5062. }
  5063. /**
  5064. * This function remove all ending \n and br at end
  5065. *
  5066. * @param string $stringtodecode String to decode
  5067. * @return string String decoded
  5068. */
  5069. function dol_htmlcleanlastbr($stringtodecode)
  5070. {
  5071. $ret=preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i',"",$stringtodecode);
  5072. return $ret;
  5073. }
  5074. /**
  5075. * Replace html_entity_decode functions to manage errors
  5076. *
  5077. * @param string $a Operand a
  5078. * @param string $b Operand b (ENT_QUOTES=convert simple and double quotes)
  5079. * @param string $c Operand c
  5080. * @return string String decoded
  5081. */
  5082. function dol_html_entity_decode($a,$b,$c='UTF-8')
  5083. {
  5084. return html_entity_decode($a,$b,$c);
  5085. }
  5086. /**
  5087. * Replace htmlentities functions.
  5088. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5089. *
  5090. * @param string $string The input string to encode
  5091. * @param int $flags Flags (see PHP doc above)
  5092. * @param string $encoding Encoding page code
  5093. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5094. * @return string $ret Encoded string
  5095. */
  5096. function dol_htmlentities($string, $flags=null, $encoding='UTF-8', $double_encode=false)
  5097. {
  5098. return htmlentities($string, $flags, $encoding, $double_encode);
  5099. }
  5100. /**
  5101. * Check if a string is a correct iso string
  5102. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5103. * Example, if string contains euro symbol that has ascii code 128
  5104. *
  5105. * @param string $s String to check
  5106. * @return int 0 if bad iso, 1 if good iso
  5107. */
  5108. function dol_string_is_good_iso($s)
  5109. {
  5110. $len=dol_strlen($s);
  5111. $ok=1;
  5112. for($scursor=0;$scursor<$len;$scursor++)
  5113. {
  5114. $ordchar=ord($s{$scursor});
  5115. //print $scursor.'-'.$ordchar.'<br>';
  5116. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok=0; break; }
  5117. if ($ordchar > 126 && $ordchar < 160) { $ok=0; break; }
  5118. }
  5119. return $ok;
  5120. }
  5121. /**
  5122. * Return nb of lines of a clear text
  5123. *
  5124. * @param string $s String to check
  5125. * @param int $maxchar Not yet used
  5126. * @return int Number of lines
  5127. * @see dol_nboflines_bis, dolGetFirstLineOfText
  5128. */
  5129. function dol_nboflines($s,$maxchar=0)
  5130. {
  5131. if ($s == '') return 0;
  5132. $arraystring=explode("\n",$s);
  5133. $nb=count($arraystring);
  5134. return $nb;
  5135. }
  5136. /**
  5137. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  5138. *
  5139. * @param string $text Text
  5140. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  5141. * @param string $charset Give the charset used to encode the $text variable in memory.
  5142. * @return int Number of lines
  5143. * @see dol_nboflines, dolGetFirstLineOfText
  5144. */
  5145. function dol_nboflines_bis($text,$maxlinesize=0,$charset='UTF-8')
  5146. {
  5147. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5148. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5149. $text = strtr($text, $repTable);
  5150. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5151. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5152. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5153. $nblines = (int) floor((count($a)+1)/2);
  5154. // count possible auto line breaks
  5155. if($maxlinesize)
  5156. {
  5157. foreach ($a as $line)
  5158. {
  5159. if (dol_strlen($line)>$maxlinesize)
  5160. {
  5161. //$line_dec = html_entity_decode(strip_tags($line));
  5162. $line_dec = html_entity_decode($line);
  5163. if(dol_strlen($line_dec)>$maxlinesize)
  5164. {
  5165. $line_dec=wordwrap($line_dec,$maxlinesize,'\n',true);
  5166. $nblines+=substr_count($line_dec,'\n');
  5167. }
  5168. }
  5169. }
  5170. }
  5171. unset($a);
  5172. return $nblines;
  5173. }
  5174. /**
  5175. * Same function than microtime in PHP 5 but compatible with PHP4
  5176. *
  5177. * @return float Time (millisecondes) with microsecondes in decimal part
  5178. * @deprecated Dolibarr does not support PHP4, you should use native function
  5179. * @see microtime()
  5180. */
  5181. function dol_microtime_float()
  5182. {
  5183. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  5184. return microtime(true);
  5185. }
  5186. /**
  5187. * Return if a text is a html content
  5188. *
  5189. * @param string $msg Content to check
  5190. * @param int $option 0=Full detection, 1=Fast check
  5191. * @return boolean true/false
  5192. * @see dol_concatdesc
  5193. */
  5194. function dol_textishtml($msg,$option=0)
  5195. {
  5196. if ($option == 1)
  5197. {
  5198. if (preg_match('/<html/i',$msg)) return true;
  5199. elseif (preg_match('/<body/i',$msg)) return true;
  5200. elseif (preg_match('/<br/i',$msg)) return true;
  5201. return false;
  5202. }
  5203. else
  5204. {
  5205. if (preg_match('/<html/i',$msg)) return true;
  5206. elseif (preg_match('/<body/i',$msg)) return true;
  5207. elseif (preg_match('/<(b|em|i|u)>/i',$msg)) return true;
  5208. elseif (preg_match('/<br\/>/i',$msg)) return true;
  5209. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i',$msg)) return true;
  5210. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i',$msg)) return true;
  5211. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i',$msg)) return true;
  5212. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i',$msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  5213. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i',$msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  5214. elseif (preg_match('/<h[0-9]>/i',$msg)) return true;
  5215. elseif (preg_match('/&[A-Z0-9]{1,6};/i',$msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  5216. elseif (preg_match('/&#[0-9]{2,3};/i',$msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  5217. return false;
  5218. }
  5219. }
  5220. /**
  5221. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  5222. * text1 html + text2 html => text1 + '<br>' + text2
  5223. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  5224. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  5225. * text1 txt + text2 txt => text1 + '\n' + text2
  5226. *
  5227. * @param string $text1 Text 1
  5228. * @param string $text2 Text 2
  5229. * @param bool $forxml false=Use <br> instead of \n if html content detected, true=Use <br /> instead of \n if html content detected
  5230. * @return string Text 1 + new line + Text2
  5231. * @see dol_textishtml
  5232. */
  5233. function dol_concatdesc($text1,$text2,$forxml=false)
  5234. {
  5235. $ret='';
  5236. $ret.= (! dol_textishtml($text1) && dol_textishtml($text2))?dol_nl2br($text1, 0, $forxml):$text1;
  5237. $ret.= (! empty($text1) && ! empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2))?($forxml?"<br \>\n":"<br>\n") : "\n") : "";
  5238. $ret.= (dol_textishtml($text1) && ! dol_textishtml($text2))?dol_nl2br($text2, 0, $forxml):$text2;
  5239. return $ret;
  5240. }
  5241. /**
  5242. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  5243. *
  5244. * @param Translate $outputlangs Output language
  5245. * @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)
  5246. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  5247. * @param Object $object Object for keys on object
  5248. * @return array Array of substitutions
  5249. * @see setSubstitFromObject
  5250. */
  5251. function getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
  5252. {
  5253. global $db, $conf, $mysoc, $user, $extrafields;
  5254. $substitutionarray=array();
  5255. if (empty($exclude) || ! in_array('user', $exclude))
  5256. {
  5257. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  5258. // this will include signature content first and then replace var found into content of signature
  5259. $signature = $user->signature;
  5260. $substitutionarray=array_merge($substitutionarray, array(
  5261. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  5262. )
  5263. );
  5264. // For backward compatibility
  5265. if ($onlykey != 2)
  5266. {
  5267. $substitutionarray['__SIGNATURE__'] = (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '');
  5268. }
  5269. $substitutionarray=array_merge($substitutionarray, array(
  5270. '__USER_ID__' => (string) $user->id,
  5271. '__USER_LOGIN__' => (string) $user->login,
  5272. '__USER_LASTNAME__' => (string) $user->lastname,
  5273. '__USER_FIRSTNAME__' => (string) $user->firstname,
  5274. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  5275. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  5276. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  5277. )
  5278. );
  5279. }
  5280. if ((empty($exclude) || ! in_array('mycompany', $exclude)) && is_object($mysoc))
  5281. {
  5282. $substitutionarray=array_merge($substitutionarray, array(
  5283. '__MYCOMPANY_NAME__' => $mysoc->name,
  5284. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  5285. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  5286. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  5287. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  5288. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  5289. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  5290. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  5291. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  5292. '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '),
  5293. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  5294. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  5295. '__MYCOMPANY_TOWN__' => $mysoc->town,
  5296. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  5297. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  5298. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  5299. ));
  5300. }
  5301. if (($onlykey || is_object($object)) && (empty($exclude) || ! in_array('object', $exclude)))
  5302. {
  5303. if ($onlykey)
  5304. {
  5305. $substitutionarray['__ID__'] = '__ID__';
  5306. $substitutionarray['__REF__'] = '__REF__';
  5307. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  5308. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  5309. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  5310. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  5311. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  5312. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  5313. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  5314. if (! empty($conf->adherent->enabled))
  5315. {
  5316. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  5317. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  5318. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  5319. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  5320. }
  5321. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  5322. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  5323. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  5324. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  5325. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  5326. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  5327. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  5328. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  5329. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  5330. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  5331. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  5332. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  5333. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  5334. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  5335. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  5336. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  5337. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  5338. if (! empty($conf->expedition->enabled))
  5339. {
  5340. $substitutionarray['__SHIPPINGTRACKNUM__']='Shipping tacking number';
  5341. $substitutionarray['__SHIPPINGTRACKNUMURL__']='Shipping tracking url';
  5342. }
  5343. }
  5344. else
  5345. {
  5346. $substitutionarray['__ID__'] = $object->id;
  5347. $substitutionarray['__REF__'] = $object->ref;
  5348. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5349. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5350. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs): '');
  5351. // For backward compatibility
  5352. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5353. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5354. // TODO Remove this
  5355. $msgishtml = 0;
  5356. $birthday = dol_print_date($object->birth,'day');
  5357. if ($object->id > 0)
  5358. {
  5359. $substitutionarray['__MEMBER_ID__']=$object->id;
  5360. if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  5361. $substitutionarray['__MEMBER_FIRSTNAME__']=$msgishtml?dol_htmlentitiesbr($object->firstname):$object->firstname;
  5362. $substitutionarray['__MEMBER_LASTNAME__']=$msgishtml?dol_htmlentitiesbr($object->lastname):$object->lastname;
  5363. if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__']=$msgishtml?dol_htmlentitiesbr($object->getFullName($outputlangs)):$object->getFullName($outputlangs);
  5364. $substitutionarray['__MEMBER_COMPANY__']=$msgishtml?dol_htmlentitiesbr($object->societe):$object->societe;
  5365. $substitutionarray['__MEMBER_ADDRESS__']=$msgishtml?dol_htmlentitiesbr($object->address):$object->address;
  5366. $substitutionarray['__MEMBER_ZIP__']=$msgishtml?dol_htmlentitiesbr($object->zip):$object->zip;
  5367. $substitutionarray['__MEMBER_TOWN__']=$msgishtml?dol_htmlentitiesbr($object->town):$object->town;
  5368. $substitutionarray['__MEMBER_COUNTRY__']=$msgishtml?dol_htmlentitiesbr($object->country):$object->country;
  5369. $substitutionarray['__MEMBER_EMAIL__']=$msgishtml?dol_htmlentitiesbr($object->email):$object->email;
  5370. $substitutionarray['__MEMBER_BIRTH__']=$msgishtml?dol_htmlentitiesbr($birthday):$birthday;
  5371. $substitutionarray['__MEMBER_PHOTO__']=$msgishtml?dol_htmlentitiesbr($object->photo):$object->photo;
  5372. $substitutionarray['__MEMBER_LOGIN__']=$msgishtml?dol_htmlentitiesbr($object->login):$object->login;
  5373. $substitutionarray['__MEMBER_PASSWORD__']=$msgishtml?dol_htmlentitiesbr($object->pass):$object->pass;
  5374. $substitutionarray['__MEMBER_PHONE__']=$msgishtml?dol_htmlentitiesbr($object->phone):$object->phone;
  5375. $substitutionarray['__MEMBER_PHONEPRO__']=$msgishtml?dol_htmlentitiesbr($object->phone_perso):$object->phone_perso;
  5376. $substitutionarray['__MEMBER_PHONEMOBILE__']=$msgishtml?dol_htmlentitiesbr($object->phone_mobile):$object->phone_mobile;
  5377. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  5378. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  5379. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  5380. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  5381. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  5382. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  5383. }
  5384. if (is_object($object) && $object->element == 'societe')
  5385. {
  5386. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object)?$object->id:'');
  5387. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object)?$object->name:'');
  5388. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object)?$object->name_alias:'');
  5389. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object)?$object->email:'');
  5390. }
  5391. elseif (is_object($object->thirdparty) && $object->thirdparty->id > 0)
  5392. {
  5393. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty)?$object->thirdparty->id:'');
  5394. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty)?$object->thirdparty->name:'');
  5395. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty)?$object->thirdparty->name_alias:'');
  5396. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty)?$object->thirdparty->email:'');
  5397. }
  5398. if (is_object($object->projet) && $object->projet->id > 0)
  5399. {
  5400. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet)?$object->projet->id:'');
  5401. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:'');
  5402. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet)?$object->projet->title:'');
  5403. }
  5404. if (is_object($object) && $object->element == 'shipping')
  5405. {
  5406. $substitutionarray['__SHIPPINGTRACKNUM__']=$object->tracking_number;
  5407. $substitutionarray['__SHIPPINGTRACKNUMURL__']=$object->tracking_url;
  5408. }
  5409. if (is_object($object) && $object->element == 'contrat' && is_array($object->lines))
  5410. {
  5411. if ($object->id > 0)
  5412. {
  5413. $dateplannedstart='';
  5414. $datenextexpiration='';
  5415. foreach($object->lines as $line)
  5416. {
  5417. if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue;
  5418. if ($line->statut == 4 && $line->date_fin_prevue && (! $datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue;
  5419. }
  5420. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  5421. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  5422. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  5423. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  5424. }
  5425. }
  5426. // Create dynamic tags for __EXTRAFIELD_FIELD__
  5427. if ($object->table_element && $object->id > 0)
  5428. {
  5429. if (! is_object($extrafields)) $extrafields = new ExtraFields($db);
  5430. $extrafields->fetch_name_optionals_label($object->table_element, true);
  5431. if ($object->fetch_optionals() > 0)
  5432. {
  5433. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
  5434. {
  5435. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  5436. $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
  5437. }
  5438. }
  5439. }
  5440. }
  5441. // Complete substitution array with the url to make online payment
  5442. $paymenturl='';
  5443. if (empty($substitutionarray['__REF__']))
  5444. {
  5445. $paymenturl='';
  5446. }
  5447. else
  5448. {
  5449. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  5450. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  5451. $outputlangs->loadLangs(array('paypal','other'));
  5452. $typeforonlinepayment='free';
  5453. if (is_object($object) && $object->element == 'commande') $typeforonlinepayment='order';
  5454. if (is_object($object) && $object->element == 'facture') $typeforonlinepayment='invoice';
  5455. if (is_object($object) && $object->element == 'member') $typeforonlinepayment='member';
  5456. $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  5457. $paymenturl=$url;
  5458. }
  5459. if ($object->id > 0)
  5460. {
  5461. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__']=($paymenturl?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)):'');
  5462. $substitutionarray['__ONLINE_PAYMENT_URL__']=$paymenturl;
  5463. if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal')
  5464. {
  5465. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  5466. }
  5467. else $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  5468. if (! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande')
  5469. {
  5470. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  5471. }
  5472. else $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  5473. if (! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture')
  5474. {
  5475. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  5476. }
  5477. else $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  5478. }
  5479. }
  5480. }
  5481. if (empty($exclude) || ! in_array('objectamount', $exclude))
  5482. {
  5483. $substitutionarray['__DATE_YMD__'] = is_object($object)?(isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  5484. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object)?(isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  5485. $substitutionarray['__AMOUNT__'] = is_object($object)?$object->total_ttc:'';
  5486. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object)?$object->total_ht:'';
  5487. $substitutionarray['__AMOUNT_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):'';
  5488. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2__'] = is_object($object)?$object->total_localtax1:'';
  5489. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3__'] = is_object($object)?$object->total_localtax2:'';
  5490. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object)?($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5491. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object)?($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5492. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object)?($object->total_vat ? price($object->total_vat, 0, $outputlangs, 0, 0, -1, $conf->currency): ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, 0, -1, $conf->currency) : null)):'';
  5493. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object)? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5494. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object)? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5495. // TODO Add keys for foreign multicurrency
  5496. // For backward compatibility
  5497. if ($onlykey != 2)
  5498. {
  5499. $substitutionarray['__TOTAL_TTC__'] = is_object($object)?$object->total_ttc:'';
  5500. $substitutionarray['__TOTAL_HT__'] = is_object($object)?$object->total_ht:'';
  5501. $substitutionarray['__TOTAL_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):'';
  5502. }
  5503. }
  5504. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  5505. if (empty($exclude) || ! in_array('date', $exclude))
  5506. {
  5507. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5508. $tmp=dol_getdate(dol_now(), true);
  5509. $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5510. $tmp3=dol_get_prev_month($tmp['mon'], $tmp['year']);
  5511. $tmp4=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5512. $tmp5=dol_get_next_month($tmp['mon'], $tmp['year']);
  5513. $substitutionarray=array_merge($substitutionarray, array(
  5514. '__DAY__' => (string) $tmp['mday'],
  5515. '__DAY_TEXT__' => $outputlangs->trans('Day'.$tmp['wday']), // Monday
  5516. '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'].'Min'), // Mon
  5517. '__DAY_TEXT_MIN__' => $outputlangs->trans('Short'.$tmp['weekday']), // M
  5518. '__MONTH__' => (string) $tmp['mon'],
  5519. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  5520. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  5521. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  5522. '__YEAR__' => (string) $tmp['year'],
  5523. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  5524. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  5525. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  5526. '__NEXT_DAY__' => (string) $tmp4['day'],
  5527. '__NEXT_MONTH__' => (string) $tmp5['month'],
  5528. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  5529. ));
  5530. }
  5531. if (! empty($conf->multicompany->enabled))
  5532. {
  5533. $substitutionarray=array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  5534. }
  5535. if (empty($exclude) || ! in_array('system', $exclude))
  5536. {
  5537. $substitutionarray['__DOL_MAIN_URL_ROOT__']=DOL_MAIN_URL_ROOT;
  5538. $substitutionarray['__(AnyTranslationKey)__']=$outputlangs->trans('TranslationOfKey');
  5539. $substitutionarray['__[AnyConstantKey]__']=$outputlangs->trans('ValueOfConstantKey');
  5540. }
  5541. return $substitutionarray;
  5542. }
  5543. /**
  5544. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  5545. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  5546. * Example of usage:
  5547. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  5548. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  5549. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  5550. *
  5551. * @param string $text Source string in which we must do substitution
  5552. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  5553. * @param Translate $outputlangs Output language
  5554. * @return string Output string after substitutions
  5555. * @see complete_substitutions_array, getCommonSubstitutionArray
  5556. */
  5557. function make_substitutions($text, $substitutionarray, $outputlangs=null)
  5558. {
  5559. global $conf, $langs;
  5560. if (! is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  5561. if (empty($outputlangs)) $outputlangs=$langs;
  5562. // Make substitution for language keys
  5563. if (is_object($outputlangs))
  5564. {
  5565. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg))
  5566. {
  5567. $msgishtml = 0;
  5568. if (dol_textishtml($text,1)) $msgishtml = 1;
  5569. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  5570. $tmp=explode('|',$reg[1]);
  5571. if (! empty($tmp[1])) $outputlangs->load($tmp[1]);
  5572. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])):$outputlangs->transnoentitiesnoconv($reg[1]), $text);
  5573. }
  5574. }
  5575. // Make substitution for constant keys. Must be after the substitution of translation, so if text of translation contains a constant,
  5576. // it is also converted.
  5577. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg))
  5578. {
  5579. $msgishtml = 0;
  5580. if (dol_textishtml($text,1)) $msgishtml = 1;
  5581. $keyfound = $reg[1];
  5582. if (preg_match('/(_pass|password|secret|_key|key$)/i', $keyfound)) $newval = '*****forbidden*****';
  5583. else $newval=empty($conf->global->$keyfound)?'':$conf->global->$keyfound;
  5584. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml?dol_htmlentitiesbr($newval):$newval, $text);
  5585. }
  5586. // Make substitition for array $substitutionarray
  5587. foreach ($substitutionarray as $key => $value)
  5588. {
  5589. if (! isset($value)) continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  5590. if ($key == '__SIGNATURE__' && (! empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value=''; // Protection
  5591. if ($key == '__USER_SIGNATURE__' && (! empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value=''; // Protection
  5592. $text=str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  5593. }
  5594. return $text;
  5595. }
  5596. /**
  5597. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  5598. * In this case, method completesubstitutionarray provided by module is called.
  5599. *
  5600. * @param array $substitutionarray Array substitution old value => new value value
  5601. * @param Translate $outputlangs Output language
  5602. * @param Object $object Source object
  5603. * @param mixed $parameters Add more parameters (useful to pass product lines)
  5604. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  5605. * @return void
  5606. * @see make_substitutions
  5607. */
  5608. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
  5609. {
  5610. global $conf,$user;
  5611. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5612. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  5613. // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
  5614. /*if (is_object($object) && is_array($object->array_options))
  5615. {
  5616. foreach($object->array_options as $key => $val)
  5617. {
  5618. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  5619. $substitutionarray['__EXTRAFIELD_'.$keyshort.'__']=$val;
  5620. // For backward compatibiliy
  5621. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  5622. }
  5623. }*/
  5624. // Check if there is external substitution to do, requested by plugins
  5625. $dirsubstitutions=array_merge(array(),(array) $conf->modules_parts['substitutions']);
  5626. foreach($dirsubstitutions as $reldir)
  5627. {
  5628. $dir=dol_buildpath($reldir,0);
  5629. // Check if directory exists
  5630. if (! dol_is_dir($dir)) continue;
  5631. $substitfiles=dol_dir_list($dir,'files',0,'functions_');
  5632. foreach($substitfiles as $substitfile)
  5633. {
  5634. if (preg_match('/functions_(.*)\.lib\.php/i',$substitfile['name'],$reg))
  5635. {
  5636. $module=$reg[1];
  5637. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  5638. // Include the user's functions file
  5639. require_once $dir.$substitfile['name'];
  5640. // Call the user's function, and only if it is defined
  5641. $function_name=$module."_".$callfunc;
  5642. if (function_exists($function_name)) $function_name($substitutionarray,$outputlangs,$object,$parameters);
  5643. }
  5644. }
  5645. }
  5646. }
  5647. /**
  5648. * Format output for start and end date
  5649. *
  5650. * @param int $date_start Start date
  5651. * @param int $date_end End date
  5652. * @param string $format Output format
  5653. * @param Translate $outputlangs Output language
  5654. * @return void
  5655. */
  5656. function print_date_range($date_start,$date_end,$format = '',$outputlangs='')
  5657. {
  5658. print get_date_range($date_start,$date_end,$format,$outputlangs);
  5659. }
  5660. /**
  5661. * Format output for start and end date
  5662. *
  5663. * @param int $date_start Start date
  5664. * @param int $date_end End date
  5665. * @param string $format Output format
  5666. * @param Translate $outputlangs Output language
  5667. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  5668. * @return string String
  5669. */
  5670. function get_date_range($date_start,$date_end,$format = '',$outputlangs='', $withparenthesis=1)
  5671. {
  5672. global $langs;
  5673. $out='';
  5674. if (! is_object($outputlangs)) $outputlangs=$langs;
  5675. if ($date_start && $date_end)
  5676. {
  5677. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFromTo',dol_print_date($date_start, $format, false, $outputlangs),dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  5678. }
  5679. if ($date_start && ! $date_end)
  5680. {
  5681. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFrom',dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis?')':'');
  5682. }
  5683. if (! $date_start && $date_end)
  5684. {
  5685. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateUntil',dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  5686. }
  5687. return $out;
  5688. }
  5689. /**
  5690. * Return firstname and lastname in correct order
  5691. *
  5692. * @param string $firstname Firstname
  5693. * @param string $lastname Lastname
  5694. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
  5695. * @return string Firstname + lastname or Lastname + firstname
  5696. */
  5697. function dolGetFirstLastname($firstname,$lastname,$nameorder=-1)
  5698. {
  5699. global $conf;
  5700. $ret='';
  5701. // If order not defined, we use the setup
  5702. if ($nameorder < 0) $nameorder=(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?1:0);
  5703. if ($nameorder && ((string) $nameorder != '2'))
  5704. {
  5705. $ret.=$firstname;
  5706. if ($firstname && $lastname) $ret.=' ';
  5707. $ret.=$lastname;
  5708. }
  5709. else if ($nameorder == 2)
  5710. {
  5711. $ret.=$firstname;
  5712. }
  5713. else
  5714. {
  5715. $ret.=$lastname;
  5716. if ($firstname && $lastname) $ret.=' ';
  5717. $ret.=$firstname;
  5718. }
  5719. return $ret;
  5720. }
  5721. /**
  5722. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  5723. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5724. * Note: Prefer to use setEventMessages instead.
  5725. *
  5726. * @param mixed $mesgs Message string or array
  5727. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5728. * @return void
  5729. * @see dol_htmloutput_events
  5730. */
  5731. function setEventMessage($mesgs, $style='mesgs')
  5732. {
  5733. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  5734. if (! is_array($mesgs)) // If mesgs is a string
  5735. {
  5736. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  5737. }
  5738. else // If mesgs is an array
  5739. {
  5740. foreach($mesgs as $mesg)
  5741. {
  5742. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  5743. }
  5744. }
  5745. }
  5746. /**
  5747. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  5748. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5749. *
  5750. * @param string $mesg Message string
  5751. * @param array $mesgs Message array
  5752. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5753. * @return void
  5754. * @see dol_htmloutput_events
  5755. */
  5756. function setEventMessages($mesg, $mesgs, $style='mesgs')
  5757. {
  5758. if (empty($mesg) && empty($mesgs))
  5759. {
  5760. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  5761. }
  5762. else
  5763. {
  5764. if (! in_array((string) $style, array('mesgs','warnings','errors'))) dol_print_error('','Bad parameter style='.$style.' for setEventMessages');
  5765. if (empty($mesgs)) setEventMessage($mesg, $style);
  5766. else
  5767. {
  5768. if (! empty($mesg) && ! in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  5769. setEventMessage($mesgs, $style);
  5770. }
  5771. }
  5772. }
  5773. /**
  5774. * Print formated messages to output (Used to show messages on html output).
  5775. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  5776. * no need to call it explicitely.
  5777. *
  5778. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  5779. * @return void
  5780. * @see dol_htmloutput_mesg
  5781. */
  5782. function dol_htmloutput_events($disabledoutputofmessages=0)
  5783. {
  5784. // Show mesgs
  5785. if (isset($_SESSION['dol_events']['mesgs'])) {
  5786. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  5787. unset($_SESSION['dol_events']['mesgs']);
  5788. }
  5789. // Show errors
  5790. if (isset($_SESSION['dol_events']['errors'])) {
  5791. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  5792. unset($_SESSION['dol_events']['errors']);
  5793. }
  5794. // Show warnings
  5795. if (isset($_SESSION['dol_events']['warnings'])) {
  5796. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  5797. unset($_SESSION['dol_events']['warnings']);
  5798. }
  5799. }
  5800. /**
  5801. * Get formated messages to output (Used to show messages on html output).
  5802. * This include also the translation of the message key.
  5803. *
  5804. * @param string $mesgstring Message string or message key
  5805. * @param string[] $mesgarray Array of message strings or message keys
  5806. * @param string $style Style of message output ('ok' or 'error')
  5807. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5808. * @return string Return html output
  5809. *
  5810. * @see dol_print_error
  5811. * @see dol_htmloutput_errors
  5812. * @see setEventMessages
  5813. */
  5814. function get_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
  5815. {
  5816. global $conf, $langs;
  5817. $ret=0; $return='';
  5818. $out='';
  5819. $divstart=$divend='';
  5820. // If inline message with no format, we add it.
  5821. if ((empty($conf->use_javascript_ajax) || ! empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && ! preg_match('/<div class=".*">/i',$out))
  5822. {
  5823. $divstart='<div class="'.$style.' clearboth">';
  5824. $divend='</div>';
  5825. }
  5826. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  5827. {
  5828. $langs->load("errors");
  5829. $out.=$divstart;
  5830. if (is_array($mesgarray) && count($mesgarray))
  5831. {
  5832. foreach($mesgarray as $message)
  5833. {
  5834. $ret++;
  5835. $out.= $langs->trans($message);
  5836. if ($ret < count($mesgarray)) $out.= "<br>\n";
  5837. }
  5838. }
  5839. if ($mesgstring)
  5840. {
  5841. $langs->load("errors");
  5842. $ret++;
  5843. $out.= $langs->trans($mesgstring);
  5844. }
  5845. $out.=$divend;
  5846. }
  5847. if ($out)
  5848. {
  5849. if (! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  5850. {
  5851. $return = '<script type="text/javascript">
  5852. $(document).ready(function() {
  5853. var block = '.(! empty($conf->global->MAIN_USE_JQUERY_BLOCKUI)?"true":"false").'
  5854. if (block) {
  5855. $.dolEventValid("","'.dol_escape_js($out).'");
  5856. } else {
  5857. /* jnotify(message, preset of message type, keepmessage) */
  5858. $.jnotify("'.dol_escape_js($out).'",
  5859. "'.($style=="ok" ? 3000 : $style).'",
  5860. '.($style=="ok" ? "false" : "true").',
  5861. { remove: function (){} } );
  5862. }
  5863. });
  5864. </script>';
  5865. }
  5866. else
  5867. {
  5868. $return = $out;
  5869. }
  5870. }
  5871. return $return;
  5872. }
  5873. /**
  5874. * Get formated error messages to output (Used to show messages on html output).
  5875. *
  5876. * @param string $mesgstring Error message
  5877. * @param array $mesgarray Error messages array
  5878. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5879. * @return string Return html output
  5880. *
  5881. * @see dol_print_error
  5882. * @see dol_htmloutput_mesg
  5883. */
  5884. function get_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
  5885. {
  5886. return get_htmloutput_mesg($mesgstring, $mesgarray,'error',$keepembedded);
  5887. }
  5888. /**
  5889. * Print formated messages to output (Used to show messages on html output).
  5890. *
  5891. * @param string $mesgstring Message string or message key
  5892. * @param string[] $mesgarray Array of message strings or message keys
  5893. * @param string $style Which style to use ('ok', 'warning', 'error')
  5894. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  5895. * @return void
  5896. *
  5897. * @see dol_print_error
  5898. * @see dol_htmloutput_errors
  5899. * @see setEventMessages
  5900. */
  5901. function dol_htmloutput_mesg($mesgstring = '',$mesgarray = array(), $style = 'ok', $keepembedded=0)
  5902. {
  5903. if (empty($mesgstring) && (! is_array($mesgarray) || count($mesgarray) == 0)) return;
  5904. $iserror=0;
  5905. $iswarning=0;
  5906. if (is_array($mesgarray))
  5907. {
  5908. foreach($mesgarray as $val)
  5909. {
  5910. if ($val && preg_match('/class="error"/i',$val)) { $iserror++; break; }
  5911. if ($val && preg_match('/class="warning"/i',$val)) { $iswarning++; break; }
  5912. }
  5913. }
  5914. else if ($mesgstring && preg_match('/class="error"/i',$mesgstring)) $iserror++;
  5915. else if ($mesgstring && preg_match('/class="warning"/i',$mesgstring)) $iswarning++;
  5916. if ($style=='error') $iserror++;
  5917. if ($style=='warning') $iswarning++;
  5918. if ($iserror || $iswarning)
  5919. {
  5920. // Remove div from texts
  5921. $mesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$mesgstring);
  5922. $mesgstring=preg_replace('/<div class="(error|warning)">/','',$mesgstring);
  5923. $mesgstring=preg_replace('/<\/div>/','',$mesgstring);
  5924. // Remove div from texts array
  5925. if (is_array($mesgarray))
  5926. {
  5927. $newmesgarray=array();
  5928. foreach($mesgarray as $val)
  5929. {
  5930. $tmpmesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$val);
  5931. $tmpmesgstring=preg_replace('/<div class="(error|warning)">/','',$tmpmesgstring);
  5932. $tmpmesgstring=preg_replace('/<\/div>/','',$tmpmesgstring);
  5933. $newmesgarray[]=$tmpmesgstring;
  5934. }
  5935. $mesgarray=$newmesgarray;
  5936. }
  5937. print get_htmloutput_mesg($mesgstring,$mesgarray,($iserror?'error':'warning'),$keepembedded);
  5938. }
  5939. else print get_htmloutput_mesg($mesgstring,$mesgarray,'ok',$keepembedded);
  5940. }
  5941. /**
  5942. * Print formated error messages to output (Used to show messages on html output).
  5943. *
  5944. * @param string $mesgstring Error message
  5945. * @param array $mesgarray Error messages array
  5946. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5947. * @return void
  5948. *
  5949. * @see dol_print_error
  5950. * @see dol_htmloutput_mesg
  5951. */
  5952. function dol_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
  5953. {
  5954. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  5955. }
  5956. /**
  5957. * Advanced sort array by second index function, which produces ascending (default)
  5958. * or descending output and uses optionally natural case insensitive sorting (which
  5959. * can be optionally case sensitive as well).
  5960. *
  5961. * @param array $array Array to sort (array of array('key','otherkey1','otherkey2'...))
  5962. * @param string $index Key in array to use for sorting criteria
  5963. * @param int $order Sort order ('asc' or 'desc')
  5964. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  5965. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  5966. * @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.
  5967. * @return array Sorted array
  5968. */
  5969. function dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
  5970. {
  5971. // Clean parameters
  5972. $order=strtolower($order);
  5973. if (is_array($array))
  5974. {
  5975. $sizearray=count($array);
  5976. if ($sizearray>0)
  5977. {
  5978. $temp = array();
  5979. foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
  5980. if (!$natsort) ($order=='asc') ? asort($temp) : arsort($temp);
  5981. else
  5982. {
  5983. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  5984. if($order!='asc') $temp=array_reverse($temp, true);
  5985. }
  5986. $sorted = array();
  5987. foreach(array_keys($temp) as $key)
  5988. {
  5989. (is_numeric($key) && empty($keepindex)) ? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
  5990. }
  5991. return $sorted;
  5992. }
  5993. }
  5994. return $array;
  5995. }
  5996. /**
  5997. * Check if a string is in UTF8
  5998. *
  5999. * @param string $str String to check
  6000. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  6001. */
  6002. function utf8_check($str)
  6003. {
  6004. // We must use here a binary strlen function (so not dol_strlen)
  6005. $strLength = dol_strlen($str);
  6006. for ($i=0; $i<$strLength; $i++)
  6007. {
  6008. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  6009. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n=1; // 110bbbbb
  6010. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n=2; // 1110bbbb
  6011. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n=3; // 11110bbb
  6012. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n=4; // 111110bb
  6013. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n=5; // 1111110b
  6014. else return false; // Does not match any model
  6015. for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
  6016. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  6017. return false;
  6018. }
  6019. }
  6020. return true;
  6021. }
  6022. /**
  6023. * Return a string encoded into OS filesystem encoding. This function is used to define
  6024. * value to pass to filesystem PHP functions.
  6025. *
  6026. * @param string $str String to encode (UTF-8)
  6027. * @return string Encoded string (UTF-8, ISO-8859-1)
  6028. */
  6029. function dol_osencode($str)
  6030. {
  6031. global $conf;
  6032. $tmp=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  6033. if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1'; // By default for windows
  6034. if (empty($tmp)) $tmp='utf-8'; // By default for other
  6035. if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING;
  6036. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  6037. return $str;
  6038. }
  6039. /**
  6040. * Return an id or code from a code or id.
  6041. * Store also Code-Id into a cache to speed up next request on same key.
  6042. *
  6043. * @param DoliDB $db Database handler
  6044. * @param string $key Code or Id to get Id or Code
  6045. * @param string $tablename Table name without prefix
  6046. * @param string $fieldkey Field to search the key into
  6047. * @param string $fieldid Field to get
  6048. * @param int $entityfilter Filter by entity
  6049. * @return int <0 if KO, Id of code if OK
  6050. * @see $langs->getLabelFromKey
  6051. */
  6052. function dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0)
  6053. {
  6054. global $cache_codes;
  6055. // If key empty
  6056. if ($key == '') return '';
  6057. // Check in cache
  6058. if (isset($cache_codes[$tablename][$key][$fieldid])) // Can be defined to 0 or ''
  6059. {
  6060. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  6061. }
  6062. dol_syslog('dol_getIdFromCode (value not found into cache)', LOG_DEBUG);
  6063. $sql = "SELECT ".$fieldid." as valuetoget";
  6064. $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
  6065. $sql.= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  6066. if (! empty($entityfilter))
  6067. $sql.= " AND entity IN (" . getEntity($tablename) . ")";
  6068. $resql = $db->query($sql);
  6069. if ($resql)
  6070. {
  6071. $obj = $db->fetch_object($resql);
  6072. if ($obj) $cache_codes[$tablename][$key][$fieldid]=$obj->valuetoget;
  6073. else $cache_codes[$tablename][$key][$fieldid]='';
  6074. $db->free($resql);
  6075. return $cache_codes[$tablename][$key][$fieldid];
  6076. }
  6077. else
  6078. {
  6079. return -1;
  6080. }
  6081. }
  6082. /**
  6083. * Verify if condition in string is ok or not
  6084. *
  6085. * @param string $strRights String with condition to check
  6086. * @return boolean True or False. Return True if strRights is ''
  6087. */
  6088. function verifCond($strRights)
  6089. {
  6090. global $user,$conf,$langs;
  6091. global $leftmenu;
  6092. global $rights; // To export to dol_eval function
  6093. //print $strRights."<br>\n";
  6094. $rights = true;
  6095. if ($strRights != '')
  6096. {
  6097. $str = 'if(!(' . $strRights . ')) { $rights = false; }';
  6098. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  6099. }
  6100. return $rights;
  6101. }
  6102. /**
  6103. * Replace eval function to add more security.
  6104. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  6105. *
  6106. * @param string $s String to evaluate
  6107. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  6108. * @param int $hideerrors 1=Hide errors
  6109. * @return mixed Nothing or return of eval
  6110. */
  6111. function dol_eval($s, $returnvalue=0, $hideerrors=1)
  6112. {
  6113. // Only global variables can be changed by eval function and returned to caller
  6114. global $db, $langs, $user, $conf, $website, $websitepage;
  6115. global $action, $mainmenu, $leftmenu;
  6116. global $rights;
  6117. global $object;
  6118. global $mysoc;
  6119. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  6120. global $soc; // For backward compatibility
  6121. //print $s."<br>\n";
  6122. if ($returnvalue)
  6123. {
  6124. if ($hideerrors) return @eval('return '.$s.';');
  6125. else return eval('return '.$s.';');
  6126. }
  6127. else
  6128. {
  6129. if ($hideerrors) @eval($s);
  6130. else eval($s);
  6131. }
  6132. }
  6133. /**
  6134. * Return if var element is ok
  6135. *
  6136. * @param string $element Variable to check
  6137. * @return boolean Return true of variable is not empty
  6138. */
  6139. function dol_validElement($element)
  6140. {
  6141. return (trim($element) != '');
  6142. }
  6143. /**
  6144. * Return img flag of country for a language code or country code
  6145. *
  6146. * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR)
  6147. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  6148. * @return string HTML img string with flag.
  6149. */
  6150. function picto_from_langcode($codelang, $moreatt = '')
  6151. {
  6152. global $langs;
  6153. if (empty($codelang)) return '';
  6154. if ($codelang == 'auto')
  6155. {
  6156. return '<span class="fa fa-globe"></span>';
  6157. }
  6158. $langtocountryflag = array(
  6159. 'ar_AR' => '',
  6160. 'ca_ES' => 'catalonia',
  6161. 'da_DA' => 'dk',
  6162. 'fr_CA' => 'mq',
  6163. 'sv_SV' => 'se'
  6164. );
  6165. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  6166. else
  6167. {
  6168. $tmparray = explode('_', $codelang);
  6169. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  6170. }
  6171. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  6172. }
  6173. /**
  6174. * Return default language from country code.
  6175. * Return null if not found.
  6176. *
  6177. * @param string $countrycode Country code like 'US', 'FR', 'CA', ...
  6178. * @return string Value of locale like 'en_US', 'fr_FR', ...
  6179. */
  6180. function getLanguageCodeFromCountryCode($countrycode)
  6181. {
  6182. global $mysoc;
  6183. if (empty($countrycode)) return null;
  6184. if (strtoupper($countrycode) == 'MQ') return 'fr_CA';
  6185. if (strtoupper($countrycode) == 'SE') return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  6186. if (strtoupper($countrycode) == 'CH')
  6187. {
  6188. if ($mysoc->country_code == 'FR') return 'fr_CH';
  6189. if ($mysoc->country_code == 'DE') return 'de_CH';
  6190. }
  6191. // Locale list taken from:
  6192. // http://stackoverflow.com/questions/3191664/
  6193. // list-of-all-locales-and-their-short-codes
  6194. $locales = array(
  6195. 'af-ZA',
  6196. 'am-ET',
  6197. 'ar-AE',
  6198. 'ar-BH',
  6199. 'ar-DZ',
  6200. 'ar-EG',
  6201. 'ar-IQ',
  6202. 'ar-JO',
  6203. 'ar-KW',
  6204. 'ar-LB',
  6205. 'ar-LY',
  6206. 'ar-MA',
  6207. 'ar-OM',
  6208. 'ar-QA',
  6209. 'ar-SA',
  6210. 'ar-SY',
  6211. 'ar-TN',
  6212. 'ar-YE',
  6213. 'as-IN',
  6214. 'ba-RU',
  6215. 'be-BY',
  6216. 'bg-BG',
  6217. 'bn-BD',
  6218. 'bn-IN',
  6219. 'bo-CN',
  6220. 'br-FR',
  6221. 'ca-ES',
  6222. 'co-FR',
  6223. 'cs-CZ',
  6224. 'cy-GB',
  6225. 'da-DK',
  6226. 'de-AT',
  6227. 'de-CH',
  6228. 'de-DE',
  6229. 'de-LI',
  6230. 'de-LU',
  6231. 'dv-MV',
  6232. 'el-GR',
  6233. 'en-AU',
  6234. 'en-BZ',
  6235. 'en-CA',
  6236. 'en-GB',
  6237. 'en-IE',
  6238. 'en-IN',
  6239. 'en-JM',
  6240. 'en-MY',
  6241. 'en-NZ',
  6242. 'en-PH',
  6243. 'en-SG',
  6244. 'en-TT',
  6245. 'en-US',
  6246. 'en-ZA',
  6247. 'en-ZW',
  6248. 'es-AR',
  6249. 'es-BO',
  6250. 'es-CL',
  6251. 'es-CO',
  6252. 'es-CR',
  6253. 'es-DO',
  6254. 'es-EC',
  6255. 'es-ES',
  6256. 'es-GT',
  6257. 'es-HN',
  6258. 'es-MX',
  6259. 'es-NI',
  6260. 'es-PA',
  6261. 'es-PE',
  6262. 'es-PR',
  6263. 'es-PY',
  6264. 'es-SV',
  6265. 'es-US',
  6266. 'es-UY',
  6267. 'es-VE',
  6268. 'et-EE',
  6269. 'eu-ES',
  6270. 'fa-IR',
  6271. 'fi-FI',
  6272. 'fo-FO',
  6273. 'fr-BE',
  6274. 'fr-CA',
  6275. 'fr-CH',
  6276. 'fr-FR',
  6277. 'fr-LU',
  6278. 'fr-MC',
  6279. 'fy-NL',
  6280. 'ga-IE',
  6281. 'gd-GB',
  6282. 'gl-ES',
  6283. 'gu-IN',
  6284. 'he-IL',
  6285. 'hi-IN',
  6286. 'hr-BA',
  6287. 'hr-HR',
  6288. 'hu-HU',
  6289. 'hy-AM',
  6290. 'id-ID',
  6291. 'ig-NG',
  6292. 'ii-CN',
  6293. 'is-IS',
  6294. 'it-CH',
  6295. 'it-IT',
  6296. 'ja-JP',
  6297. 'ka-GE',
  6298. 'kk-KZ',
  6299. 'kl-GL',
  6300. 'km-KH',
  6301. 'kn-IN',
  6302. 'ko-KR',
  6303. 'ky-KG',
  6304. 'lb-LU',
  6305. 'lo-LA',
  6306. 'lt-LT',
  6307. 'lv-LV',
  6308. 'mi-NZ',
  6309. 'mk-MK',
  6310. 'ml-IN',
  6311. 'mn-MN',
  6312. 'mr-IN',
  6313. 'ms-BN',
  6314. 'ms-MY',
  6315. 'mt-MT',
  6316. 'nb-NO',
  6317. 'ne-NP',
  6318. 'nl-BE',
  6319. 'nl-NL',
  6320. 'nn-NO',
  6321. 'oc-FR',
  6322. 'or-IN',
  6323. 'pa-IN',
  6324. 'pl-PL',
  6325. 'ps-AF',
  6326. 'pt-BR',
  6327. 'pt-PT',
  6328. 'rm-CH',
  6329. 'ro-RO',
  6330. 'ru-RU',
  6331. 'rw-RW',
  6332. 'sa-IN',
  6333. 'se-FI',
  6334. 'se-NO',
  6335. 'se-SE',
  6336. 'si-LK',
  6337. 'sk-SK',
  6338. 'sl-SI',
  6339. 'sq-AL',
  6340. 'sv-FI',
  6341. 'sv-SE',
  6342. 'sw-KE',
  6343. 'ta-IN',
  6344. 'te-IN',
  6345. 'th-TH',
  6346. 'tk-TM',
  6347. 'tn-ZA',
  6348. 'tr-TR',
  6349. 'tt-RU',
  6350. 'ug-CN',
  6351. 'uk-UA',
  6352. 'ur-PK',
  6353. 'vi-VN',
  6354. 'wo-SN',
  6355. 'xh-ZA',
  6356. 'yo-NG',
  6357. 'zh-CN',
  6358. 'zh-HK',
  6359. 'zh-MO',
  6360. 'zh-SG',
  6361. 'zh-TW',
  6362. 'zu-ZA',
  6363. );
  6364. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  6365. if (in_array($buildprimarykeytotest, $locales)) return strtolower($countrycode).'_'.strtoupper($countrycode);
  6366. if (function_exists('locale_get_primary_language')) // Need extension php-intl
  6367. {
  6368. foreach ($locales as $locale)
  6369. {
  6370. $locale_language = locale_get_primary_language($locale);
  6371. $locale_region = locale_get_region($locale);
  6372. if (strtoupper($countrycode) == $locale_region)
  6373. {
  6374. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  6375. return strtolower($locale_language).'_'.strtoupper($locale_region);
  6376. }
  6377. }
  6378. }
  6379. else
  6380. {
  6381. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  6382. }
  6383. return null;
  6384. }
  6385. /**
  6386. * Complete or removed entries into a head array (used to build tabs).
  6387. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  6388. * Or by change using hook completeTabsHead
  6389. *
  6390. * @param Conf $conf Object conf
  6391. * @param Translate $langs Object langs
  6392. * @param object|null $object Object object
  6393. * @param array $head Object head
  6394. * @param int $h New position to fill
  6395. * @param string $type Value for object where objectvalue can be
  6396. * 'thirdparty' to add a tab in third party view
  6397. * 'intervention' to add a tab in intervention view
  6398. * 'supplier_order' to add a tab in supplier order view
  6399. * 'supplier_invoice' to add a tab in supplier invoice view
  6400. * 'invoice' to add a tab in customer invoice view
  6401. * 'order' to add a tab in customer order view
  6402. * 'contract' to add a tabl in contract view
  6403. * 'product' to add a tab in product view
  6404. * 'propal' to add a tab in propal view
  6405. * 'user' to add a tab in user view
  6406. * 'group' to add a tab in group view
  6407. * 'member' to add a tab in fundation member view
  6408. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  6409. * 'ecm' to add a tab for another ecm view
  6410. * 'stock' to add a tab for warehouse view
  6411. * @param string $mode 'add' to complete head, 'remove' to remove entries
  6412. * @return void
  6413. */
  6414. function complete_head_from_modules($conf,$langs,$object,&$head,&$h,$type,$mode='add')
  6415. {
  6416. global $hookmanager;
  6417. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  6418. {
  6419. foreach ($conf->modules_parts['tabs'][$type] as $value)
  6420. {
  6421. $values=explode(':',$value);
  6422. if ($mode == 'add' && ! preg_match('/^\-/',$values[1]))
  6423. {
  6424. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  6425. {
  6426. if ($values[0] != $type) continue;
  6427. if (verifCond($values[4]))
  6428. {
  6429. if ($values[3]) $langs->load($values[3]);
  6430. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  6431. {
  6432. $substitutionarray=array();
  6433. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  6434. $label=make_substitutions($reg[1], $substitutionarray);
  6435. }
  6436. else $label=$langs->trans($values[2]);
  6437. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[5]), 1);
  6438. $head[$h][1] = $label;
  6439. $head[$h][2] = str_replace('+','',$values[1]);
  6440. $h++;
  6441. }
  6442. }
  6443. else if (count($values) == 5) // deprecated
  6444. {
  6445. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  6446. if ($values[0] != $type) continue;
  6447. if ($values[3]) $langs->load($values[3]);
  6448. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  6449. {
  6450. $substitutionarray=array();
  6451. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  6452. $label=make_substitutions($reg[1], $substitutionarray);
  6453. }
  6454. else $label=$langs->trans($values[2]);
  6455. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[4]), 1);
  6456. $head[$h][1] = $label;
  6457. $head[$h][2] = str_replace('+','',$values[1]);
  6458. $h++;
  6459. }
  6460. }
  6461. else if ($mode == 'remove' && preg_match('/^\-/',$values[1]))
  6462. {
  6463. if ($values[0] != $type) continue;
  6464. $tabname=str_replace('-','',$values[1]);
  6465. foreach($head as $key => $val)
  6466. {
  6467. $condition = (! empty($values[3]) ? verifCond($values[3]) : 1);
  6468. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  6469. if ($head[$key][2]==$tabname && $condition)
  6470. {
  6471. unset($head[$key]);
  6472. break;
  6473. }
  6474. }
  6475. }
  6476. }
  6477. }
  6478. // No need to make a return $head. Var is modified as a reference
  6479. if (! empty($hookmanager))
  6480. {
  6481. $parameters=array('object' => $object, 'mode' => $mode, 'head' => $head);
  6482. $reshook=$hookmanager->executeHooks('completeTabsHead', $parameters);
  6483. if ($reshook > 0)
  6484. {
  6485. $head = $hookmanager->resArray;
  6486. $h = count($head);
  6487. }
  6488. }
  6489. }
  6490. /**
  6491. * Print common footer :
  6492. * conf->global->MAIN_HTML_FOOTER
  6493. * js for switch of menu hider
  6494. * js for conf->global->MAIN_GOOGLE_AN_ID
  6495. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  6496. * js for conf->logbuffer
  6497. *
  6498. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  6499. * @return void
  6500. */
  6501. function printCommonFooter($zone='private')
  6502. {
  6503. global $conf, $hookmanager, $user;
  6504. global $action;
  6505. global $micro_start_time;
  6506. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  6507. else print "\n".'<!-- Common footer for public page -->'."\n";
  6508. // A div to store page_y POST parameter so we can read it using javascript
  6509. print "\n<!-- A div to store page_y POST paramater -->\n";
  6510. print '<div id="page_y" style="display: none;">'.$_POST['page_y'].'</div>'."\n";
  6511. $parameters=array();
  6512. $reshook=$hookmanager->executeHooks('printCommonFooter',$parameters); // Note that $action and $object may have been modified by some hooks
  6513. if (empty($reshook))
  6514. {
  6515. if (! empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  6516. print "\n";
  6517. if (! empty($conf->use_javascript_ajax))
  6518. {
  6519. print '<script type="text/javascript" language="javascript">'."\n";
  6520. print 'jQuery(document).ready(function() {'."\n";
  6521. if ($zone == 'private' && empty($conf->dol_use_jmobile))
  6522. {
  6523. print "\n";
  6524. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  6525. print 'jQuery(".menuhider").click(function() {';
  6526. print ' console.log("We click on .menuhider");'."\n";
  6527. //print " $('.side-nav').animate({width:'toggle'},200);\n"; // OK with eldy theme but not with md
  6528. print " $('.side-nav').toggle()\n";
  6529. print " $('.login_block').toggle()\n";
  6530. print '});'."\n";
  6531. }
  6532. // Management of focus and mandatory for fields
  6533. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))))
  6534. {
  6535. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  6536. $relativepathstring = $_SERVER["PHP_SELF"];
  6537. // Clean $relativepathstring
  6538. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
  6539. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  6540. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  6541. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  6542. if (!empty($user->default_values[$relativepathstring]['focus']))
  6543. {
  6544. foreach($user->default_values[$relativepathstring]['focus'] as $defkey => $defval)
  6545. {
  6546. $qualified = 0;
  6547. if ($defkey != '_noquery_')
  6548. {
  6549. $tmpqueryarraytohave=explode('&', $defkey);
  6550. $foundintru=0;
  6551. foreach($tmpqueryarraytohave as $tmpquerytohave)
  6552. {
  6553. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  6554. }
  6555. if (! $foundintru) $qualified=1;
  6556. //var_dump($defkey.'-'.$qualified);
  6557. }
  6558. else $qualified = 1;
  6559. if ($qualified)
  6560. {
  6561. foreach($defval as $paramkey => $paramval)
  6562. {
  6563. // Set focus on field
  6564. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  6565. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  6566. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  6567. }
  6568. }
  6569. }
  6570. }
  6571. if (!empty($user->default_values[$relativepathstring]['mandatory']))
  6572. {
  6573. foreach($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval)
  6574. {
  6575. $qualified = 0;
  6576. if ($defkey != '_noquery_')
  6577. {
  6578. $tmpqueryarraytohave=explode('&', $defkey);
  6579. $foundintru=0;
  6580. foreach($tmpqueryarraytohave as $tmpquerytohave)
  6581. {
  6582. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  6583. }
  6584. if (! $foundintru) $qualified=1;
  6585. //var_dump($defkey.'-'.$qualified);
  6586. }
  6587. else $qualified = 1;
  6588. if ($qualified)
  6589. {
  6590. foreach($defval as $paramkey => $paramval)
  6591. {
  6592. // Add property 'required' on input
  6593. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6594. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6595. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
  6596. }
  6597. }
  6598. }
  6599. }
  6600. }
  6601. print '});'."\n";
  6602. // Google Analytics
  6603. // TODO Add a hook here
  6604. if (! empty($conf->google->enabled) && ! empty($conf->global->MAIN_GOOGLE_AN_ID))
  6605. {
  6606. if (($conf->dol_use_jmobile != 4))
  6607. {
  6608. print "\n";
  6609. print "/* JS CODE TO ENABLE for google analtics tag */\n";
  6610. print ' var _gaq = _gaq || [];'."\n";
  6611. print ' _gaq.push([\'_setAccount\', \''.$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
  6612. print ' _gaq.push([\'_trackPageview\']);'."\n";
  6613. print ''."\n";
  6614. print ' (function() {'."\n";
  6615. print ' var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
  6616. print ' ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
  6617. print ' var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
  6618. print ' })();'."\n";
  6619. }
  6620. }
  6621. // End of tuning
  6622. if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || ! empty($conf->global->MAIN_SHOW_TUNING_INFO))
  6623. {
  6624. print "\n";
  6625. print "/* JS CODE TO ENABLE to add memory info */\n";
  6626. print 'window.console && console.log("';
  6627. if (! empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  6628. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED)?$conf->global->MAIN_OPTIMIZE_SPEED:'off');
  6629. if (! empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  6630. {
  6631. $micro_end_time = microtime(true);
  6632. print ' - Build time: '.ceil(1000*($micro_end_time-$micro_start_time)).' ms';
  6633. }
  6634. if (function_exists("memory_get_usage"))
  6635. {
  6636. print ' - Mem: '.memory_get_usage();
  6637. }
  6638. if (function_exists("xdebug_memory_usage"))
  6639. {
  6640. print ' - XDebug time: '.ceil(1000*xdebug_time_index()).' ms';
  6641. print ' - XDebug mem: '.xdebug_memory_usage();
  6642. print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
  6643. }
  6644. if (function_exists("zend_loader_file_encoded"))
  6645. {
  6646. print ' - Zend encoded file: '.(zend_loader_file_encoded()?'yes':'no');
  6647. }
  6648. print '");'."\n";
  6649. }
  6650. print "\n".'</script>'."\n";
  6651. }
  6652. // Add Xdebug coverage of code
  6653. if (defined('XDEBUGCOVERAGE'))
  6654. {
  6655. print_r(xdebug_get_code_coverage());
  6656. }
  6657. // If there is some logs in buffer to show
  6658. if (count($conf->logbuffer))
  6659. {
  6660. print "\n";
  6661. print "<!-- Start of log output\n";
  6662. //print '<div class="hidden">'."\n";
  6663. foreach($conf->logbuffer as $logline)
  6664. {
  6665. print $logline."<br>\n";
  6666. }
  6667. //print '</div>'."\n";
  6668. print "End of log output -->\n";
  6669. }
  6670. }
  6671. }
  6672. /**
  6673. * Split a string with 2 keys into key array.
  6674. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  6675. *
  6676. * @param string $string String to explode
  6677. * @param string $delimiter Delimiter between each couple of data
  6678. * @param string $kv Delimiter between key and value
  6679. * @return array Array of data exploded
  6680. */
  6681. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  6682. {
  6683. if ($a = explode($delimiter, $string))
  6684. {
  6685. $ka = array();
  6686. foreach ($a as $s) { // each part
  6687. if ($s) {
  6688. if ($pos = strpos($s, $kv)) { // key/value delimiter
  6689. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  6690. } else { // key delimiter not found
  6691. $ka[] = trim($s);
  6692. }
  6693. }
  6694. }
  6695. return $ka;
  6696. }
  6697. return array();
  6698. }
  6699. /**
  6700. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  6701. *
  6702. * @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.
  6703. * @return string HTML code to set focus
  6704. */
  6705. function dol_set_focus($selector)
  6706. {
  6707. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  6708. print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  6709. }
  6710. /**
  6711. * Return getmypid() or random PID when function is disabled
  6712. * Some web hosts disable this php function for security reasons
  6713. * and sometimes we can't redeclare function
  6714. *
  6715. * @return int
  6716. */
  6717. function dol_getmypid()
  6718. {
  6719. if (! function_exists('getmypid')) {
  6720. return mt_rand(1,32768);
  6721. } else {
  6722. return getmypid();
  6723. }
  6724. }
  6725. /**
  6726. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  6727. *
  6728. * @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")
  6729. * @param string $value The value to look for.
  6730. * If param $mode is 0, can contains several keywords separated with a space or |
  6731. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  6732. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  6733. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  6734. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  6735. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  6736. * @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')
  6737. * 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 '1,3,4') for search into a multiselect string ('1,2')
  6738. * @param integer $nofirstand 1=Do not output the first 'AND'
  6739. * @return string $res The statement to append to the SQL query
  6740. */
  6741. function natural_search($fields, $value, $mode=0, $nofirstand=0)
  6742. {
  6743. global $db,$langs;
  6744. $value=trim($value);
  6745. if ($mode == 0)
  6746. {
  6747. $value=preg_replace('/\*/','%',$value); // Replace * with %
  6748. }
  6749. if ($mode == 1)
  6750. {
  6751. $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
  6752. }
  6753. $value = preg_replace('/\s*\|\s*/','|', $value);
  6754. $crits = explode(' ', $value);
  6755. $res = '';
  6756. if (! is_array($fields)) $fields = array($fields);
  6757. $nboffields = count($fields);
  6758. $end2 = count($crits);
  6759. $j = 0;
  6760. foreach ($crits as $crit)
  6761. {
  6762. $i = 0; $i2 = 0;
  6763. $newres = '';
  6764. foreach ($fields as $field)
  6765. {
  6766. if ($mode == 1)
  6767. {
  6768. $operator='=';
  6769. $newcrit = preg_replace('/([<>=]+)/','',trim($crit));
  6770. preg_match('/([<>=]+)/',trim($crit), $reg);
  6771. if ($reg[1])
  6772. {
  6773. $operator = $reg[1];
  6774. }
  6775. if ($newcrit != '')
  6776. {
  6777. $numnewcrit = price2num($newcrit);
  6778. if (is_numeric($numnewcrit))
  6779. {
  6780. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' '.$operator.' '.$numnewcrit;
  6781. }
  6782. else
  6783. {
  6784. $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false
  6785. }
  6786. $i2++; // a criteria was added to string
  6787. }
  6788. }
  6789. else if ($mode == 2)
  6790. {
  6791. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $db->escape(trim($crit)) . ")";
  6792. $i2++; // a criteria was added to string
  6793. }
  6794. else if ($mode == 3)
  6795. {
  6796. $tmparray=explode(',',trim($crit));
  6797. if (count($tmparray))
  6798. {
  6799. $listofcodes='';
  6800. foreach($tmparray as $val)
  6801. {
  6802. if ($val)
  6803. {
  6804. $listofcodes.=($listofcodes?',':'');
  6805. $listofcodes.="'".$db->escape(trim($val))."'";
  6806. }
  6807. }
  6808. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $listofcodes . ")";
  6809. $i2++; // a criteria was added to string
  6810. }
  6811. }
  6812. else if ($mode == 4)
  6813. {
  6814. $tmparray=explode(',',trim($crit));
  6815. if (count($tmparray))
  6816. {
  6817. $listofcodes='';
  6818. foreach($tmparray as $val)
  6819. {
  6820. if ($val)
  6821. {
  6822. $newres .= ($i2 > 0 ? ' OR (' : '(') . $field . ' LIKE \'' . $db->escape(trim($val)) . ',%\'';
  6823. $newres .= ' OR '. $field . ' = \'' . $db->escape(trim($val)) . '\'';
  6824. $newres .= ' OR '. $field . ' LIKE \'%,' . $db->escape(trim($val)) . '\'';
  6825. $newres .= ' OR '. $field . ' LIKE \'%,' . $db->escape(trim($val)) . ',%\'';
  6826. $newres .= ')';
  6827. $i2++;
  6828. }
  6829. }
  6830. }
  6831. }
  6832. else // $mode=0
  6833. {
  6834. $textcrit = '';
  6835. $tmpcrits = explode('|',$crit);
  6836. $i3 = 0;
  6837. foreach($tmpcrits as $tmpcrit)
  6838. {
  6839. if(empty($tmpcrit)) continue;
  6840. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  6841. if (preg_match('/\.(id|rowid)$/', $field)) // Special case for rowid that is sometimes a ref so used as a search field
  6842. {
  6843. $newres .= $field . " = " . (is_numeric(trim($tmpcrit))?trim($tmpcrit):'0');
  6844. }
  6845. else
  6846. {
  6847. $newres .= $field . " LIKE '";
  6848. $tmpcrit=trim($tmpcrit);
  6849. $tmpcrit2=$tmpcrit;
  6850. $tmpbefore='%'; $tmpafter='%';
  6851. if (preg_match('/^[\^\$]/', $tmpcrit))
  6852. {
  6853. $tmpbefore='';
  6854. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  6855. }
  6856. if (preg_match('/[\^\$]$/', $tmpcrit))
  6857. {
  6858. $tmpafter='';
  6859. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  6860. }
  6861. $newres .= $tmpbefore;
  6862. $newres .= $db->escape($tmpcrit2);
  6863. $newres .= $tmpafter;
  6864. $newres .= "'";
  6865. if ($tmpcrit2 == '')
  6866. {
  6867. $newres .= ' OR ' . $field . " IS NULL";
  6868. }
  6869. }
  6870. $i3++;
  6871. }
  6872. $i2++; // a criteria was added to string
  6873. }
  6874. $i++;
  6875. }
  6876. if ($newres) $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') .$newres . ($i2 > 1 ? ')' : '');
  6877. $j++;
  6878. }
  6879. $res = ($nofirstand?"":" AND ")."(" . $res . ")";
  6880. //print 'xx'.$res.'yy';
  6881. return $res;
  6882. }
  6883. /**
  6884. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  6885. *
  6886. * @param Object $object Object
  6887. * @return string Url string
  6888. */
  6889. function showDirectDownloadLink($object)
  6890. {
  6891. global $conf, $langs;
  6892. $out='';
  6893. $url = $object->getLastMainDocLink($object->element);
  6894. if ($url)
  6895. {
  6896. $out.= img_picto('','object_globe.png').' '.$langs->trans("DirectDownloadLink").'<br>';
  6897. $out.= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
  6898. $out.= ajax_autoselect("directdownloadlink", 0);
  6899. }
  6900. return $out;
  6901. }
  6902. /**
  6903. * Return the filename of file to get the thumbs
  6904. *
  6905. * @param string $file Original filename (full or relative path)
  6906. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  6907. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  6908. * @return string New file name (full or relative path, including the thumbs/)
  6909. */
  6910. function getImageFileNameForSize($file, $extName, $extImgTarget='')
  6911. {
  6912. $dirName = dirname($file);
  6913. if ($dirName == '.') $dirName='';
  6914. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i','',$file); // We remove extension, whatever is its case
  6915. $fileName = basename($fileName);
  6916. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i',$file)?'.jpg':'');
  6917. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i',$file)?'.jpeg':'');
  6918. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i',$file)?'.gif':'');
  6919. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i',$file)?'.png':'');
  6920. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i',$file)?'.bmp':'');
  6921. if (! $extImgTarget) return $file;
  6922. $subdir='';
  6923. if ($extName) $subdir = 'thumbs/';
  6924. return ($dirName?$dirName.'/':'').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  6925. }
  6926. /**
  6927. * Return URL we can use for advanced preview links
  6928. *
  6929. * @param string $modulepart propal, facture, facture_fourn, ...
  6930. * @param string $relativepath Relative path of docs.
  6931. * @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)
  6932. * @param string $param More param on http links
  6933. * @return string|array Output string with href link or array with all components of link
  6934. */
  6935. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
  6936. {
  6937. global $conf, $langs;
  6938. if (empty($conf->use_javascript_ajax)) return '';
  6939. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'svg+xml');
  6940. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  6941. //$mime_preview[]='archive';
  6942. $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview);
  6943. if ($alldata == 1)
  6944. {
  6945. if ($num_mime !== false) 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), );
  6946. else return array();
  6947. }
  6948. // old behavior
  6949. if ($num_mime !== false) 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')).'\')';
  6950. else return '';
  6951. }
  6952. /**
  6953. * Make content of an input box selected when we click into input field.
  6954. *
  6955. * @param string $htmlname Id of html object
  6956. * @param string $addlink Add a 'link to' after
  6957. * @return string
  6958. */
  6959. function ajax_autoselect($htmlname, $addlink='')
  6960. {
  6961. global $langs;
  6962. $out = '<script type="text/javascript">
  6963. jQuery(document).ready(function () {
  6964. jQuery("#'.$htmlname.'").click(function() { jQuery(this).select(); } );
  6965. });
  6966. </script>';
  6967. if ($addlink) $out.=' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  6968. return $out;
  6969. }
  6970. /**
  6971. * Return mime type of a file
  6972. *
  6973. * @param string $file Filename we looking for MIME type
  6974. * @param string $default Default mime type if extension not found in known list
  6975. * @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
  6976. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  6977. * @see image_format_supported (images.lib.php)
  6978. */
  6979. function dol_mimetype($file, $default='application/octet-stream', $mode=0)
  6980. {
  6981. $mime=$default;
  6982. $imgmime='other.png';
  6983. $famime='file-o';
  6984. $srclang='';
  6985. $tmpfile=preg_replace('/\.noexe$/','',$file);
  6986. // Text files
  6987. if (preg_match('/\.txt$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6988. if (preg_match('/\.rtx$/i',$tmpfile)) { $mime='text/richtext'; $imgmime='text.png'; $famime='file-text-o'; }
  6989. if (preg_match('/\.csv$/i',$tmpfile)) { $mime='text/csv'; $imgmime='text.png'; $famime='file-text-o'; }
  6990. if (preg_match('/\.tsv$/i',$tmpfile)) { $mime='text/tab-separated-values'; $imgmime='text.png'; $famime='file-text-o'; }
  6991. if (preg_match('/\.(cf|conf|log)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6992. if (preg_match('/\.ini$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='ini'; $famime='file-text-o'; }
  6993. if (preg_match('/\.css$/i',$tmpfile)) { $mime='text/css'; $imgmime='css.png'; $srclang='css'; $famime='file-text-o'; }
  6994. // Certificate files
  6995. if (preg_match('/\.(crt|cer|key|pub)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6996. // HTML/XML
  6997. if (preg_match('/\.(html|htm|shtml)$/i',$tmpfile)) { $mime='text/html'; $imgmime='html.png'; $srclang='html'; $famime='file-text-o'; }
  6998. if (preg_match('/\.(xml|xhtml)$/i',$tmpfile)) { $mime='text/xml'; $imgmime='other.png'; $srclang='xml'; $famime='file-text-o'; }
  6999. // Languages
  7000. if (preg_match('/\.bas$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='bas'; $famime='file-code-o'; }
  7001. if (preg_match('/\.(c)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='c'; $famime='file-code-o'; }
  7002. if (preg_match('/\.(cpp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='cpp'; $famime='file-code-o'; }
  7003. if (preg_match('/\.(h)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='h'; $famime='file-code-o'; }
  7004. if (preg_match('/\.(java|jsp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='java'; $famime='file-code-o'; }
  7005. if (preg_match('/\.php([0-9]{1})?$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; $famime='file-code-o'; }
  7006. if (preg_match('/\.phtml$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; $famime='file-code-o'; }
  7007. if (preg_match('/\.(pl|pm)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='pl.png'; $srclang='perl'; $famime='file-code-o'; }
  7008. if (preg_match('/\.sql$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='sql'; $famime='file-code-o'; }
  7009. if (preg_match('/\.js$/i',$tmpfile)) { $mime='text/x-javascript'; $imgmime='jscript.png'; $srclang='js'; $famime='file-code-o'; }
  7010. // Open office
  7011. if (preg_match('/\.odp$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.presentation'; $imgmime='ooffice.png'; $famime='file-powerpoint-o'; }
  7012. if (preg_match('/\.ods$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.spreadsheet'; $imgmime='ooffice.png'; $famime='file-excel-o'; }
  7013. if (preg_match('/\.odt$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.text'; $imgmime='ooffice.png'; $famime='file-word-o'; }
  7014. // MS Office
  7015. if (preg_match('/\.mdb$/i',$tmpfile)) { $mime='application/msaccess'; $imgmime='mdb.png'; $famime='file-o'; }
  7016. if (preg_match('/\.doc(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; $famime='file-word-o'; }
  7017. if (preg_match('/\.dot(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; $famime='file-word-o'; }
  7018. if (preg_match('/\.xlt(x)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7019. if (preg_match('/\.xla(m)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7020. if (preg_match('/\.xls$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7021. if (preg_match('/\.xls(b|m|x)$/i',$tmpfile)) { $mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7022. if (preg_match('/\.pps(m|x)?$/i',$tmpfile)) { $mime='application/vnd.ms-powerpoint'; $imgmime='ppt.png'; $famime='file-powerpoint-o'; }
  7023. if (preg_match('/\.ppt(m|x)?$/i',$tmpfile)) { $mime='application/x-mspowerpoint'; $imgmime='ppt.png'; $famime='file-powerpoint-o'; }
  7024. // Other
  7025. if (preg_match('/\.pdf$/i',$tmpfile)) { $mime='application/pdf'; $imgmime='pdf.png'; $famime='file-pdf-o'; }
  7026. // Scripts
  7027. if (preg_match('/\.bat$/i',$tmpfile)) { $mime='text/x-bat'; $imgmime='script.png'; $srclang='dos'; $famime='file-code-o'; }
  7028. if (preg_match('/\.sh$/i',$tmpfile)) { $mime='text/x-sh'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7029. if (preg_match('/\.ksh$/i',$tmpfile)) { $mime='text/x-ksh'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7030. if (preg_match('/\.bash$/i',$tmpfile)) { $mime='text/x-bash'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7031. // Images
  7032. if (preg_match('/\.ico$/i',$tmpfile)) { $mime='image/x-icon'; $imgmime='image.png'; $famime='file-image-o'; }
  7033. if (preg_match('/\.(jpg|jpeg)$/i',$tmpfile)) { $mime='image/jpeg'; $imgmime='image.png'; $famime='file-image-o'; }
  7034. if (preg_match('/\.png$/i',$tmpfile)) { $mime='image/png'; $imgmime='image.png'; $famime='file-image-o'; }
  7035. if (preg_match('/\.gif$/i',$tmpfile)) { $mime='image/gif'; $imgmime='image.png'; $famime='file-image-o'; }
  7036. if (preg_match('/\.bmp$/i',$tmpfile)) { $mime='image/bmp'; $imgmime='image.png'; $famime='file-image-o'; }
  7037. if (preg_match('/\.(tif|tiff)$/i',$tmpfile)) { $mime='image/tiff'; $imgmime='image.png'; $famime='file-image-o'; }
  7038. if (preg_match('/\.svg$/i',$tmpfile)) { $mime='image/svg+xml';$imgmime='image.png'; $famime='file-image-o'; }
  7039. // Calendar
  7040. if (preg_match('/\.vcs$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; $famime='file-text-o'; }
  7041. if (preg_match('/\.ics$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; $famime='file-text-o'; }
  7042. // Other
  7043. if (preg_match('/\.torrent$/i',$tmpfile)) { $mime='application/x-bittorrent'; $imgmime='other.png'; $famime='file-o'; }
  7044. // Audio
  7045. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i',$tmpfile)) { $mime='audio'; $imgmime='audio.png'; $famime='file-audio-o'; }
  7046. // Video
  7047. if (preg_match('/\.ogv$/i',$tmpfile)) { $mime='video/ogg'; $imgmime='video.png'; $famime='file-video-o'; }
  7048. if (preg_match('/\.webm$/i',$tmpfile)) { $mime='video/webm'; $imgmime='video.png'; $famime='file-video-o'; }
  7049. if (preg_match('/\.avi$/i',$tmpfile)) { $mime='video/x-msvideo'; $imgmime='video.png'; $famime='file-video-o'; }
  7050. if (preg_match('/\.divx$/i',$tmpfile)) { $mime='video/divx'; $imgmime='video.png'; $famime='file-video-o'; }
  7051. if (preg_match('/\.xvid$/i',$tmpfile)) { $mime='video/xvid'; $imgmime='video.png'; $famime='file-video-o'; }
  7052. if (preg_match('/\.(wmv|mpg|mpeg)$/i',$tmpfile)) { $mime='video'; $imgmime='video.png'; $famime='file-video-o'; }
  7053. // Archive
  7054. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i',$tmpfile)) { $mime='archive'; $imgmime='archive.png'; $famime='file-archive-o'; } // application/xxx where zzz is zip, ...
  7055. // Exe
  7056. if (preg_match('/\.(exe|com)$/i',$tmpfile)) { $mime='application/octet-stream'; $imgmime='other.png'; $famime='file-o'; }
  7057. // Lib
  7058. if (preg_match('/\.(dll|lib|o|so|a)$/i',$tmpfile)) { $mime='library'; $imgmime='library.png'; $famime='file-o'; }
  7059. // Err
  7060. if (preg_match('/\.err$/i',$tmpfile)) { $mime='error'; $imgmime='error.png'; $famime='file-text-o'; }
  7061. // Return string
  7062. if ($mode == 1)
  7063. {
  7064. $tmp=explode('/',$mime);
  7065. return (! empty($tmp[1])?$tmp[1]:$tmp[0]);
  7066. }
  7067. if ($mode == 2)
  7068. {
  7069. return $imgmime;
  7070. }
  7071. if ($mode == 3)
  7072. {
  7073. return $srclang;
  7074. }
  7075. if ($mode == 4)
  7076. {
  7077. return $famime;
  7078. }
  7079. return $mime;
  7080. }
  7081. /**
  7082. * Return value from dictionary
  7083. *
  7084. * @param string $tablename name of dictionary
  7085. * @param string $field the value to return
  7086. * @param int $id id of line
  7087. * @param bool $checkentity add filter on entity
  7088. * @param string $rowidfield name of the column rowid
  7089. * @return string
  7090. */
  7091. function getDictvalue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
  7092. {
  7093. global $dictvalues,$db,$langs;
  7094. if (!isset($dictvalues[$tablename]))
  7095. {
  7096. $dictvalues[$tablename] = array();
  7097. $sql = 'SELECT * FROM '.$tablename.' WHERE 1';
  7098. if ($checkentity) $sql.= ' AND entity IN (0,'.getEntity($tablename).')';
  7099. $resql = $db->query($sql);
  7100. if ($resql)
  7101. {
  7102. while ($obj = $db->fetch_object($resql))
  7103. {
  7104. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  7105. }
  7106. }
  7107. else
  7108. {
  7109. dol_print_error($db);
  7110. }
  7111. }
  7112. if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
  7113. else // Not found
  7114. {
  7115. if ($id > 0) return $id;
  7116. return '';
  7117. }
  7118. }
  7119. /**
  7120. * Return true if the color is light
  7121. *
  7122. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  7123. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  7124. */
  7125. function colorIsLight($stringcolor)
  7126. {
  7127. $res = -1;
  7128. if (!empty($stringcolor))
  7129. {
  7130. $res = 0;
  7131. $tmp=explode(',', $stringcolor);
  7132. if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
  7133. {
  7134. $r = $tmp[0];
  7135. $g = $tmp[1];
  7136. $b = $tmp[2];
  7137. }
  7138. else
  7139. {
  7140. $hexr=$stringcolor[0].$stringcolor[1];
  7141. $hexg=$stringcolor[2].$stringcolor[3];
  7142. $hexb=$stringcolor[4].$stringcolor[5];
  7143. $r = hexdec($hexr);
  7144. $g = hexdec($hexg);
  7145. $b = hexdec($hexb);
  7146. }
  7147. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  7148. if ($bright > 0.6) $res = 1;
  7149. }
  7150. return $res;
  7151. }
  7152. /**
  7153. * Function to test if an entry is enabled or not
  7154. *
  7155. * @param string $type_user 0=We test for internal user, 1=We test for external user
  7156. * @param array $menuentry Array for feature entry to test
  7157. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  7158. * @return int 0=Hide, 1=Show, 2=Show gray
  7159. */
  7160. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  7161. {
  7162. global $conf;
  7163. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  7164. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  7165. if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
  7166. if ($type_user && $menuentry['module'])
  7167. {
  7168. $tmploops=explode('|',$menuentry['module']);
  7169. $found=0;
  7170. foreach($tmploops as $tmploop)
  7171. {
  7172. if (in_array($tmploop, $listofmodulesforexternal)) {
  7173. $found++; break;
  7174. }
  7175. }
  7176. if (! $found) return 0; // Entry is for menus all excluded to external users
  7177. }
  7178. if (! $menuentry['perms'] && $type_user) return 0; // No permissions and user is external
  7179. if (! $menuentry['perms'] && ! empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  7180. if (! $menuentry['perms']) return 2; // No permissions and user is external
  7181. return 1;
  7182. }
  7183. /**
  7184. * Round to next multiple.
  7185. *
  7186. * @param double $n Number to round up
  7187. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  7188. * @return integer Value rounded.
  7189. */
  7190. function roundUpToNextMultiple($n, $x=5)
  7191. {
  7192. return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
  7193. }
  7194. /**
  7195. * Return if a file can contains executable content
  7196. *
  7197. * @param string $filename File NamedRange
  7198. * @return boolean True if yes, False if no
  7199. */
  7200. function isAFileWithExecutableContent($filename)
  7201. {
  7202. if (preg_match('/\.(htm|html|js|php|phtml|pl|py|cgi|ksh|sh|bash)$/i', $filename))
  7203. {
  7204. return true;
  7205. }
  7206. return false;
  7207. }