functions.lib.php 305 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937
  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@capnetworks.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 int $forceentity Entity id
  107. * @return mixed Entity id(s) to use
  108. */
  109. function getEntity($element, $shared=1, $forceentity=null)
  110. {
  111. global $conf, $mc;
  112. if (is_object($mc))
  113. {
  114. return $mc->getEntity($element, $shared, $forceentity);
  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']) && $_GET['action'] == 'create' && ! 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)
  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", 'smonth', 'syear', 'month', 'year')))
  559. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield')))
  560. {
  561. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  562. // We save search key only if $out not empty that means:
  563. // - posted value not empty, or
  564. // - 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).
  565. //if (! empty($out) || ! empty($user->default_values[$relativepathstring]['filters'][$paramname]))
  566. if ($out != '') // $out = '0' like 'abc' is a search criteria to keep
  567. {
  568. $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out;
  569. }
  570. }
  571. }
  572. return $out;
  573. }
  574. /**
  575. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  576. * This prefix is valid in a web context only and is unique for instance and avoid conflict
  577. * between multi-instances, even when having two instances with one root dir or two instances
  578. * in virtual servers.
  579. *
  580. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  581. * @return string A calculated prefix
  582. */
  583. if (! function_exists('dol_getprefix'))
  584. {
  585. function dol_getprefix($mode='')
  586. {
  587. global $conf;
  588. // If MAIL_PREFIX_FOR_EMAIL_ID is set and prefix is for email
  589. if ($mode == 'email' && ! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID))
  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. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"]))
  595. {
  596. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  597. // Use this for a "readable" cookie name
  598. //return dol_sanitizeFileName($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  599. }
  600. else return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  601. }
  602. }
  603. /**
  604. * Make an include_once using default root and alternate root if it fails.
  605. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  606. * To link to a module file from a module file, use include './mymodulefile';
  607. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  608. *
  609. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  610. * @param string $classname Class name (deprecated)
  611. * @return bool True if load is a success, False if it fails
  612. */
  613. function dol_include_once($relpath, $classname='')
  614. {
  615. 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']
  616. $fullpath = dol_buildpath($relpath);
  617. if (!file_exists($fullpath)) {
  618. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_ERR);
  619. return false;
  620. }
  621. if (! empty($classname) && ! class_exists($classname)) {
  622. return include $fullpath;
  623. } else {
  624. return include_once $fullpath;
  625. }
  626. }
  627. /**
  628. * Return path of url or filesystem. Return alternate root if exists.
  629. *
  630. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  631. * @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)
  632. * @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)
  633. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  634. * 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
  635. * @return string Full filesystem path (if path=0), Full url path (if mode=1)
  636. */
  637. function dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
  638. {
  639. global $conf;
  640. $path=preg_replace('/^\//','',$path);
  641. if (empty($type)) // For a filesystem path
  642. {
  643. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  644. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  645. {
  646. if ($key == 'main') continue;
  647. if (file_exists($dirroot.'/'.$path))
  648. {
  649. $res=$dirroot.'/'.$path;
  650. return $res;
  651. }
  652. }
  653. if ($returnemptyifnotfound) // Not found into alternate dir
  654. {
  655. if ($returnemptyifnotfound == 1 || ! file_exists($res)) return '';
  656. }
  657. }
  658. else // For an url path
  659. {
  660. // We try to get local path of file on filesystem from url
  661. // Note that trying to know if a file on disk exist by forging path on disk from url
  662. // works only for some web server and some setup. This is bugged when
  663. // using proxy, rewriting, virtual path, etc...
  664. $res='';
  665. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  666. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  667. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  668. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  669. {
  670. if ($key == 'main')
  671. {
  672. if ($type == 3)
  673. {
  674. global $dolibarr_main_url_root;
  675. // Define $urlwithroot
  676. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  677. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  678. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  679. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  680. }
  681. continue;
  682. }
  683. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  684. if (! empty($regs[1]))
  685. {
  686. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  687. if (file_exists($dirroot.'/'.$regs[1]))
  688. {
  689. if ($type == 1)
  690. {
  691. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  692. }
  693. if ($type == 2)
  694. {
  695. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  696. }
  697. if ($type == 3)
  698. {
  699. global $dolibarr_main_url_root;
  700. // Define $urlwithroot
  701. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  702. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  703. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  704. $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
  705. }
  706. break;
  707. }
  708. }
  709. }
  710. }
  711. return $res;
  712. }
  713. /**
  714. * Create a clone of instance of object (new instance with same value for properties)
  715. * With native = 0: Property that are reference are also new object (true clone). This means $this->db is not valid.
  716. * With native = 1: Use PHP clone. Property that are reference are same pointer. This means $this->db is still valid.
  717. *
  718. * @param object $object Object to clone
  719. * @param int $native Native method or true method
  720. * @return object Object clone
  721. * @see https://php.net/manual/language.oop5.cloning.php
  722. */
  723. function dol_clone($object, $native=0)
  724. {
  725. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  726. if (empty($native))
  727. {
  728. $myclone=unserialize(serialize($object));
  729. }
  730. else
  731. {
  732. $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)
  733. }
  734. return $myclone;
  735. }
  736. /**
  737. * Optimize a size for some browsers (phone, smarphone, ...)
  738. *
  739. * @param int $size Size we want
  740. * @param string $type Type of optimizing:
  741. * '' = function used to define a size for truncation
  742. * 'width' = function is used to define a width
  743. * @return int New size after optimizing
  744. */
  745. function dol_size($size,$type='')
  746. {
  747. global $conf;
  748. if (empty($conf->dol_optimize_smallscreen)) return $size;
  749. if ($type == 'width' && $size > 250) return 250;
  750. else return 10;
  751. }
  752. /**
  753. * Clean a string to use it as a file name
  754. *
  755. * @param string $str String to clean
  756. * @param string $newstr String to replace bad chars with
  757. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  758. * @return string String cleaned (a-zA-Z_)
  759. *
  760. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizePathName
  761. */
  762. function dol_sanitizeFileName($str,$newstr='_',$unaccent=1)
  763. {
  764. $filesystem_forbidden_chars = array('<','>','/','\\','?','*','|','"','°');
  765. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  766. }
  767. /**
  768. * Clean a string to use it as a path name
  769. *
  770. * @param string $str String to clean
  771. * @param string $newstr String to replace bad chars with
  772. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  773. * @return string String cleaned (a-zA-Z_)
  774. *
  775. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizeFileName
  776. */
  777. function dol_sanitizePathName($str,$newstr='_',$unaccent=1)
  778. {
  779. $filesystem_forbidden_chars = array('<','>','?','*','|','"','°');
  780. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  781. }
  782. /**
  783. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  784. *
  785. * @param string $str String to clean
  786. * @return string Cleaned string
  787. *
  788. * @see dol_sanitizeFilename, dol_string_nospecial
  789. */
  790. function dol_string_unaccent($str)
  791. {
  792. if (utf8_check($str))
  793. {
  794. // See http://www.utf8-chartable.de/
  795. $string = rawurlencode($str);
  796. $replacements = array(
  797. '%C3%80' => 'A','%C3%81' => 'A','%C3%82' => 'A','%C3%83' => 'A','%C3%84' => 'A','%C3%85' => 'A',
  798. '%C3%88' => 'E','%C3%89' => 'E','%C3%8A' => 'E','%C3%8B' => 'E',
  799. '%C3%8C' => 'I','%C3%8D' => 'I','%C3%8E' => 'I','%C3%8F' => 'I',
  800. '%C3%92' => 'O','%C3%93' => 'O','%C3%94' => 'O','%C3%95' => 'O','%C3%96' => 'O',
  801. '%C3%99' => 'U','%C3%9A' => 'U','%C3%9B' => 'U','%C3%9C' => 'U',
  802. '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a','%C3%A3' => 'a','%C3%A4' => 'a','%C3%A5' => 'a',
  803. '%C3%A7' => 'c',
  804. '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
  805. '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i','%C3%AF' => 'i',
  806. '%C3%B1' => 'n',
  807. '%C3%B2' => 'o','%C3%B3' => 'o','%C3%B4' => 'o','%C3%B5' => 'o','%C3%B6' => 'o',
  808. '%C3%B9' => 'u','%C3%BA' => 'u','%C3%BB' => 'u','%C3%BC' => 'u',
  809. '%C3%BF' => 'y'
  810. );
  811. $string=strtr($string, $replacements);
  812. return rawurldecode($string);
  813. }
  814. else
  815. {
  816. // See http://www.ascii-code.com/
  817. $string = strtr(
  818. $str,
  819. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  820. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  821. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  822. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  823. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  824. \xF9\xFA\xFB\xFC\xFD\xFF",
  825. "AAAAAAC
  826. EEEEIIIIDN
  827. OOOOOUUUY
  828. aaaaaaceeee
  829. iiiidnooooo
  830. uuuuyy"
  831. );
  832. $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"));
  833. return $string;
  834. }
  835. }
  836. /**
  837. * Clean a string from all punctuation characters to use it as a ref or login.
  838. * This is a more complete function than dol_sanitizeFileName.
  839. *
  840. * @param string $str String to clean
  841. * @param string $newstr String to replace forbidden chars with
  842. * @param array $badcharstoreplace List of forbidden characters
  843. * @return string Cleaned string
  844. *
  845. * @see dol_sanitizeFilename, dol_string_unaccent
  846. */
  847. function dol_string_nospecial($str,$newstr='_',$badcharstoreplace='')
  848. {
  849. $forbidden_chars_to_replace=array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  850. $forbidden_chars_to_remove=array();
  851. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace=$badcharstoreplace;
  852. //$forbidden_chars_to_remove=array("(",")");
  853. return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
  854. }
  855. /**
  856. * Encode string for xml usage
  857. *
  858. * @param string $string String to encode
  859. * @return string String encoded
  860. */
  861. function dolEscapeXML($string)
  862. {
  863. return strtr($string, array('\''=>'&apos;','"'=>'&quot;','&'=>'&amp;','<'=>'&lt;','>'=>'&gt;'));
  864. }
  865. /**
  866. * Returns text escaped for inclusion into javascript code
  867. *
  868. * @param string $stringtoescape String to escape
  869. * @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 \
  870. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  871. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  872. */
  873. function dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
  874. {
  875. // escape quotes and backslashes, newlines, etc.
  876. $substitjs=array("&#039;"=>"\\'","\r"=>'\\r');
  877. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  878. if (empty($noescapebackslashn)) { $substitjs["\n"]='\\n'; $substitjs['\\']='\\\\'; }
  879. if (empty($mode)) { $substitjs["'"]="\\'"; $substitjs['"']="\\'"; }
  880. else if ($mode == 1) $substitjs["'"]="\\'";
  881. else if ($mode == 2) { $substitjs['"']='\\"'; }
  882. else if ($mode == 3) { $substitjs["'"]="\\'"; $substitjs['"']="\\\""; }
  883. return strtr($stringtoescape, $substitjs);
  884. }
  885. /**
  886. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  887. *
  888. * @param string $stringtoescape String to escape
  889. * @param int $keepb 1=Preserve b tags (otherwise, remove them)
  890. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value)
  891. * @return string Escaped string
  892. * @see dol_string_nohtmltag, dol_string_nospecial, dol_string_unaccent
  893. */
  894. function dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0)
  895. {
  896. // escape quotes and backslashes, newlines, etc.
  897. $tmp=html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
  898. if (! $keepb) $tmp=strtr($tmp, array("<b>"=>'','</b>'=>''));
  899. if (! $keepn) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n'));
  900. return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html tags
  901. }
  902. /**
  903. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  904. *
  905. * @param string $utf8_string String to encode
  906. * @return string String converted
  907. */
  908. function dol_strtolower($utf8_string)
  909. {
  910. return mb_strtolower($utf8_string, "UTF-8");
  911. }
  912. /**
  913. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  914. *
  915. * @param string $utf8_string String to encode
  916. * @return string String converted
  917. */
  918. function dol_strtoupper($utf8_string)
  919. {
  920. return mb_strtoupper($utf8_string, "UTF-8");
  921. }
  922. /**
  923. * Write log message into outputs. Possible outputs can be:
  924. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  925. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  926. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  927. * this, use logging to files instead of syslog (see setup of module).
  928. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  929. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  930. * This function works only if syslog module is enabled.
  931. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  932. *
  933. * @param string $message Line to log. ''=Show nothing
  934. * @param int $level Log level
  935. * 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
  936. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  937. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  938. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  939. * @param string $restricttologhandler Output log only for this log handler
  940. * @return void
  941. */
  942. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename='', $restricttologhandler='')
  943. {
  944. global $conf, $user;
  945. // If syslog module enabled
  946. if (empty($conf->syslog->enabled)) return;
  947. if ($ident < 0)
  948. {
  949. foreach ($conf->loghandlers as $loghandlerinstance)
  950. {
  951. $loghandlerinstance->setIdent($ident);
  952. }
  953. }
  954. if (! empty($message))
  955. {
  956. // Test log level
  957. $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG);
  958. if (!in_array($level, $logLevels, true))
  959. {
  960. throw new Exception('Incorrect log level');
  961. }
  962. if ($level > $conf->global->SYSLOG_LEVEL) return;
  963. // If adding log inside HTML page is required
  964. if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility
  965. {
  966. $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
  967. }
  968. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  969. // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments
  970. if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"]))
  971. {
  972. print "\n\n<!-- Log start\n";
  973. print $message."\n";
  974. print "Log end -->\n";
  975. }
  976. $data = array(
  977. 'message' => $message,
  978. 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false),
  979. 'level' => $level,
  980. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  981. 'ip' => false
  982. );
  983. // This is when server run behind a reverse proxy
  984. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']);
  985. // This is when server run normally on a server
  986. else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR'];
  987. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  988. else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  989. // 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).
  990. else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']);
  991. // 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).
  992. else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  993. // Loop on each log handler and send output
  994. foreach ($conf->loghandlers as $loghandlerinstance)
  995. {
  996. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  997. $loghandlerinstance->export($data,$suffixinfilename);
  998. }
  999. unset($data);
  1000. }
  1001. if ($ident > 0)
  1002. {
  1003. foreach ($conf->loghandlers as $loghandlerinstance)
  1004. {
  1005. $loghandlerinstance->setIdent($ident);
  1006. }
  1007. }
  1008. }
  1009. /**
  1010. * Show tab header of a card
  1011. *
  1012. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1013. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1014. * @param string $title Title
  1015. * @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.
  1016. * @param string $picto Add a picto on tab title
  1017. * @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.
  1018. * @param string $morehtmlright Add more html content on right of tabs title
  1019. * @param string $morecss More Css
  1020. * @return void
  1021. */
  1022. function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='')
  1023. {
  1024. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss);
  1025. }
  1026. /**
  1027. * Show tab header of a card
  1028. *
  1029. * @param array $links Array of tabs
  1030. * @param string $active Active tab name
  1031. * @param string $title Title
  1032. * @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.
  1033. * @param string $picto Add a picto on tab title
  1034. * @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.
  1035. * @param string $morehtmlright Add more html content on right of tabs title
  1036. * @param string $morecss More Css
  1037. * @return string
  1038. */
  1039. function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='')
  1040. {
  1041. global $conf, $langs, $hookmanager;
  1042. $out="\n".'<div class="tabs" data-role="controlgroup" data-type="horizontal">'."\n";
  1043. 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.
  1044. // Show title
  1045. $showtitle=1;
  1046. if (! empty($conf->dol_optimize_smallscreen)) $showtitle=0;
  1047. if (! empty($title) && $showtitle)
  1048. {
  1049. $limittitle=30;
  1050. $out.='<a class="tabTitle">';
  1051. if ($picto) $out.=img_picto($title,($pictoisfullpath?'':'object_').$picto,'',$pictoisfullpath).' ';
  1052. $out.='<span class="tabTitleText">'.dol_trunc($title,$limittitle).'</span>';
  1053. $out.='</a>';
  1054. }
  1055. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1056. $maxkey=-1;
  1057. if (is_array($links) && ! empty($links))
  1058. {
  1059. $keys=array_keys($links);
  1060. if (count($keys)) $maxkey=max($keys);
  1061. }
  1062. if (! empty($conf->dol_optimize_smallscreen)) $conf->global->MAIN_MAXTABS_IN_CARD=2;
  1063. // Show tabs
  1064. $bactive=false;
  1065. // if =0 we don't use the feature
  1066. $limittoshow=(empty($conf->global->MAIN_MAXTABS_IN_CARD)?99:$conf->global->MAIN_MAXTABS_IN_CARD);
  1067. $displaytab=0;
  1068. $nbintab=0;
  1069. $popuptab=0; $outmore='';
  1070. for ($i = 0 ; $i <= $maxkey ; $i++)
  1071. {
  1072. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  1073. {
  1074. // If active tab is already present
  1075. if ($i >= $limittoshow) $limittoshow--;
  1076. }
  1077. }
  1078. for ($i = 0 ; $i <= $maxkey ; $i++)
  1079. {
  1080. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  1081. {
  1082. $isactive=true;
  1083. $bactive=true;
  1084. }
  1085. else
  1086. {
  1087. $isactive=false;
  1088. }
  1089. if ($i < $limittoshow || $isactive)
  1090. {
  1091. $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]).' -->';
  1092. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1093. {
  1094. if (!empty($links[$i][0]))
  1095. {
  1096. $out.='<a class="tabimage'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1097. }
  1098. else
  1099. {
  1100. $out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1101. }
  1102. }
  1103. else if (! empty($links[$i][1]))
  1104. {
  1105. //print "x $i $active ".$links[$i][2]." z";
  1106. if ($isactive)
  1107. {
  1108. $out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabactive tab inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1109. $out.=$links[$i][1];
  1110. $out.='</a>'."\n";
  1111. }
  1112. else
  1113. {
  1114. $out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabunactive tab inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1115. $out.=$links[$i][1];
  1116. $out.='</a>'."\n";
  1117. }
  1118. }
  1119. $out.='</div>';
  1120. }
  1121. else
  1122. {
  1123. // The popup with the other tabs
  1124. if (! $popuptab)
  1125. {
  1126. $popuptab=1;
  1127. $outmore.='<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1128. }
  1129. $outmore.='<div class="popuptab wordwrap" style="display:inherit;">';
  1130. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1131. {
  1132. if (!empty($links[$i][0]))
  1133. $outmore.='<a class="tabimage'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1134. else
  1135. $outmore.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1136. }
  1137. else if (! empty($links[$i][1]))
  1138. {
  1139. $outmore.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="wordwrap inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1140. $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.
  1141. $outmore.='</a>'."\n";
  1142. }
  1143. $outmore.='</div>';
  1144. $nbintab++;
  1145. }
  1146. $displaytab=$i;
  1147. }
  1148. if ($popuptab) $outmore.='</div>';
  1149. if ($displaytab > $limittoshow)
  1150. {
  1151. $left=($langs->trans("DIRECTION") == 'rtl'?'right':'left');
  1152. $right=($langs->trans("DIRECTION") == 'rtl'?'left':'right');
  1153. $tabsname=str_replace("@", "", $picto);
  1154. $out.='<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1155. $out.='<a href="#" class="tab moretab inline-block tabunactive reposition">'.$langs->trans("More").'... ('.$nbintab.')</a>';
  1156. $out.='<div id="moretabsList'.$tabsname.'" style="position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px">';
  1157. $out.=$outmore;
  1158. $out.='</div>';
  1159. $out.='<div></div>';
  1160. $out.="</div>\n";
  1161. $out.="<script>";
  1162. $out.="$('#moretabs".$tabsname."').mouseenter( function() { console.log('mouseenter ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','auto');});";
  1163. $out.="$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1164. $out.="</script>";
  1165. }
  1166. $out.="</div>\n";
  1167. if (! $notab || $notab == -1) $out.="\n".'<div class="tabBar'.($notab == -1 ? '' : ' tabBarWithBottom').'">'."\n";
  1168. $parameters=array('tabname' => $active, 'out' => $out);
  1169. $reshook=$hookmanager->executeHooks('printTabsHead',$parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1170. if ($reshook > 0)
  1171. {
  1172. $out = $hookmanager->resPrint;
  1173. }
  1174. return $out;
  1175. }
  1176. /**
  1177. * Show tab footer of a card
  1178. *
  1179. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1180. * @return void
  1181. */
  1182. function dol_fiche_end($notab=0)
  1183. {
  1184. print dol_get_fiche_end($notab);
  1185. }
  1186. /**
  1187. * Return tab footer of a card
  1188. *
  1189. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1190. * @return string
  1191. */
  1192. function dol_get_fiche_end($notab=0)
  1193. {
  1194. if (! $notab || $notab == -1) return "\n</div>\n";
  1195. else return '';
  1196. }
  1197. /**
  1198. * Show tab footer of a card.
  1199. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1200. *
  1201. * @param Object $object Object to show
  1202. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1203. * @param string $morehtml More html content to output just before the nav bar
  1204. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1205. * @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.
  1206. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1207. * @param string $morehtmlref More html to show after ref
  1208. * @param string $moreparam More param to add in nav link url.
  1209. * @param int $nodbprefix Do not include DB prefix to forge table name
  1210. * @param string $morehtmlleft More html code to show before ref
  1211. * @param string $morehtmlstatus More html code to show under navigation arrows
  1212. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1213. * @param string $morehtmlright More html code to show before navigation arrows
  1214. * @return void
  1215. */
  1216. function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
  1217. {
  1218. global $conf, $form, $user, $langs;
  1219. $error = 0;
  1220. $maxvisiblephotos=1;
  1221. $showimage=1;
  1222. $entity=(empty($object->entity)?$conf->entity:$object->entity);
  1223. $showbarcode=empty($conf->barcode->enabled)?0:($object->barcode?1:0);
  1224. if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;
  1225. $modulepart='unknown';
  1226. if ($object->element == 'societe') $modulepart='societe';
  1227. if ($object->element == 'contact') $modulepart='contact';
  1228. if ($object->element == 'member') $modulepart='memberphoto';
  1229. if ($object->element == 'user') $modulepart='userphoto';
  1230. if ($object->element == 'product') $modulepart='product';
  1231. if (class_exists("Imagick"))
  1232. {
  1233. if ($object->element == 'propal') $modulepart='propal';
  1234. if ($object->element == 'commande') $modulepart='commande';
  1235. if ($object->element == 'facture') $modulepart='facture';
  1236. if ($object->element == 'fichinter') $modulepart='ficheinter';
  1237. if ($object->element == 'contrat') $modulepart='contract';
  1238. if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal';
  1239. if ($object->element == 'order_supplier') $modulepart='supplier_order';
  1240. if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice';
  1241. if ($object->element == 'expensereport') $modulepart='expensereport';
  1242. }
  1243. if ($object->element == 'product')
  1244. {
  1245. $width=80; $cssclass='photoref';
  1246. $showimage=$object->is_photo_available($conf->product->multidir_output[$entity]);
  1247. $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5);
  1248. if ($conf->browser->phone) $maxvisiblephotos=1;
  1249. 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>';
  1250. else
  1251. {
  1252. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1253. $nophoto='';
  1254. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1255. }
  1256. //elseif ($conf->browser->layout != 'phone') { // Show no photo link
  1257. $nophoto='/public/theme/common/nophoto.png';
  1258. $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>';
  1259. //}
  1260. }
  1261. }
  1262. elseif ($object->element == 'ticket')
  1263. {
  1264. $width=80; $cssclass='photoref';
  1265. $showimage=$object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->track_id);
  1266. $maxvisiblephotos=(isset($conf->global->TICKETSUP_MAX_VISIBLE_PHOTO)?$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO:2);
  1267. if ($conf->browser->phone) $maxvisiblephotos=1;
  1268. 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>';
  1269. else
  1270. {
  1271. if (!empty($conf->global->TICKETSUP_NODISPLAYIFNOPHOTO)) {
  1272. $nophoto='';
  1273. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1274. }
  1275. //elseif ($conf->browser->layout != 'phone') { // Show no photo link
  1276. $nophoto='/public/theme/common/nophoto.png';
  1277. $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>';
  1278. //}
  1279. }
  1280. }
  1281. else
  1282. {
  1283. if ($showimage)
  1284. {
  1285. if ($modulepart != 'unknown')
  1286. {
  1287. $phototoshow='';
  1288. // Check if a preview file is available
  1289. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick"))
  1290. {
  1291. $objectref = dol_sanitizeFileName($object->ref);
  1292. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity]) . "/";
  1293. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1294. {
  1295. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1296. $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
  1297. }
  1298. else
  1299. {
  1300. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1301. }
  1302. if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1303. $filepath = $dir_output . $subdir . "/";
  1304. $file = $filepath . $objectref . ".pdf";
  1305. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1306. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1307. $fileimage = $file.'_preview.png'; // If PDF has 1 page
  1308. $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page
  1309. $relativepathimage = $relativepath.'_preview.png';
  1310. // Si fichier PDF existe
  1311. if (file_exists($file))
  1312. {
  1313. $encfile = urlencode($file);
  1314. // Conversion du PDF en image png si fichier png non existant
  1315. if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file)))
  1316. && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file)))
  1317. )
  1318. {
  1319. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experienc trouble with pdf thumb generation and imagick, you can disable here.
  1320. {
  1321. $ret = dol_convert_file($file, 'png', $fileimage);
  1322. if ($ret < 0) $error++;
  1323. }
  1324. }
  1325. $heightforphotref=70;
  1326. if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60;
  1327. // Si fichier png PDF d'1 page trouve
  1328. if (file_exists($fileimage))
  1329. {
  1330. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1331. $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1332. $phototoshow.= '</div></div>';
  1333. }
  1334. // Si fichier png PDF de plus d'1 page trouve
  1335. elseif (file_exists($fileimagebis))
  1336. {
  1337. $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png";
  1338. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1339. $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
  1340. $phototoshow.= '</div></div>';
  1341. }
  1342. }
  1343. }
  1344. else if (! $phototoshow)
  1345. {
  1346. $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos);
  1347. }
  1348. if ($phototoshow)
  1349. {
  1350. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1351. $morehtmlleft.=$phototoshow;
  1352. $morehtmlleft.='</div>';
  1353. }
  1354. }
  1355. if (! $phototoshow) // Show No photo link (picto of pbject)
  1356. {
  1357. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1358. if ($object->element == 'action')
  1359. {
  1360. $width=80;
  1361. $cssclass='photorefcenter';
  1362. $nophoto=img_picto('', 'title_agenda', '', false, 1);
  1363. }
  1364. else
  1365. {
  1366. $width=14; $cssclass='photorefcenter';
  1367. $picto = $object->picto;
  1368. if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub
  1369. $nophoto=img_picto('', 'object_'.$picto, '', false, 1);
  1370. }
  1371. $morehtmlleft.='<!-- No photo to show -->';
  1372. $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>';
  1373. $morehtmlleft.='</div>';
  1374. }
  1375. }
  1376. }
  1377. if ($showbarcode) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1378. if ($object->element == 'societe')
  1379. {
  1380. if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1381. {
  1382. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1383. }
  1384. else {
  1385. $morehtmlstatus.=$object->getLibStatut(6);
  1386. }
  1387. }
  1388. elseif ($object->element == 'product')
  1389. {
  1390. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1391. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1392. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1393. } else {
  1394. $morehtmlstatus.='<span class="statusrefsell">'.$object->getLibStatut(5,0).'</span>';
  1395. }
  1396. $morehtmlstatus.=' &nbsp; ';
  1397. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1398. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1399. $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1400. } else {
  1401. $morehtmlstatus.='<span class="statusrefbuy">'.$object->getLibStatut(5,1).'</span>';
  1402. }
  1403. }
  1404. elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan')))
  1405. {
  1406. $tmptxt=$object->getLibStatut(6, $object->totalpaye);
  1407. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye);
  1408. $morehtmlstatus.=$tmptxt;
  1409. }
  1410. elseif ($object->element == 'contrat' || $object->element == 'contract')
  1411. {
  1412. if ($object->statut == 0) $morehtmlstatus.=$object->getLibStatut(5);
  1413. else $morehtmlstatus.=$object->getLibStatut(4);
  1414. }
  1415. elseif ($object->element == 'facturerec')
  1416. {
  1417. if ($object->frequency == 0) $morehtmlstatus.=$object->getLibStatut(2);
  1418. else $morehtmlstatus.=$object->getLibStatut(5);
  1419. }
  1420. elseif ($object->element == 'project_task')
  1421. {
  1422. $object->fk_statut = 1;
  1423. if ($object->progress > 0) $object->fk_statut = 2;
  1424. if ($object->progress >= 100) $object->fk_statut = 3;
  1425. $tmptxt=$object->getLibStatut(5);
  1426. $morehtmlstatus.=$tmptxt; // No status on task
  1427. }
  1428. else { // Generic case
  1429. $tmptxt=$object->getLibStatut(6);
  1430. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5);
  1431. $morehtmlstatus.=$tmptxt;
  1432. }
  1433. // Add if object was dispatched "into accountancy"
  1434. if (! empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport')))
  1435. {
  1436. if (method_exists($object, 'getVentilExportCompta'))
  1437. {
  1438. $accounted = $object->getVentilExportCompta();
  1439. $langs->load("accountancy");
  1440. $morehtmlstatus.='</div><div class="statusref statusrefbis">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted"));
  1441. }
  1442. }
  1443. // Add alias for thirdparty
  1444. if (! empty($object->name_alias)) $morehtmlref.='<div class="refidno">'.$object->name_alias.'</div>';
  1445. // Add label
  1446. if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task')
  1447. {
  1448. if (! empty($object->label)) $morehtmlref.='<div class="refidno">'.$object->label.'</div>';
  1449. }
  1450. if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files')
  1451. {
  1452. $morehtmlref.='<div class="refidno">';
  1453. $morehtmlref.=$object->getBannerAddress('refaddress',$object);
  1454. $morehtmlref.='</div>';
  1455. }
  1456. if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product')))
  1457. {
  1458. $morehtmlref.='<div style="clear: both;"></div><div class="refidno">';
  1459. $morehtmlref.=$langs->trans("TechnicalID").': '.$object->id;
  1460. $morehtmlref.='</div>';
  1461. }
  1462. print '<div class="'.($onlybanner?'arearefnobottom ':'arearef ').'heightref valignmiddle" width="100%">';
  1463. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1464. print '</div>';
  1465. print '<div class="underrefbanner clearboth"></div>';
  1466. }
  1467. /**
  1468. * Show a string with the label tag dedicated to the HTML edit field.
  1469. *
  1470. * @param string $langkey Translation key
  1471. * @param string $fieldkey Key of the html select field the text refers to
  1472. * @param int $fieldrequired 1=Field is mandatory
  1473. * @deprecated Form::editfieldkey
  1474. */
  1475. function fieldLabel($langkey, $fieldkey, $fieldrequired=0)
  1476. {
  1477. global $conf, $langs;
  1478. $ret='';
  1479. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  1480. if (($conf->dol_use_jmobile != 4)) $ret.='<label for="'.$fieldkey.'">';
  1481. $ret.=$langs->trans($langkey);
  1482. if (($conf->dol_use_jmobile != 4)) $ret.='</label>';
  1483. if ($fieldrequired) $ret.='</span>';
  1484. return $ret;
  1485. }
  1486. /**
  1487. * Return string to add class property on html element with pair/impair.
  1488. *
  1489. * @param string $var 0 or 1
  1490. * @param string $moreclass More class to add
  1491. * @return string String to add class onto HTML element
  1492. */
  1493. function dol_bc($var,$moreclass='')
  1494. {
  1495. global $bc;
  1496. $ret=' '.$bc[$var];
  1497. if ($moreclass) $ret=preg_replace('/class=\"/','class="'.$moreclass.' ',$ret);
  1498. return $ret;
  1499. }
  1500. /**
  1501. * Return a formated address (part address/zip/town/state) according to country rules
  1502. *
  1503. * @param Object $object A company or contact object
  1504. * @param int $withcountry 1=Add country into address string
  1505. * @param string $sep Separator to use to build string
  1506. * @param Translate $outputlangs Object lang that contains language for text translation.
  1507. * @param int $mode 0=Standard output, 1=Remove address
  1508. * @return string Formated string
  1509. * @see dol_print_address
  1510. */
  1511. function dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs='', $mode=0)
  1512. {
  1513. global $conf,$langs;
  1514. $ret='';
  1515. $countriesusingstate=array('AU','CA','US','IN','GB','ES','UK','TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1516. // Address
  1517. if (empty($mode)) {
  1518. $ret .= $object->address;
  1519. }
  1520. // Zip/Town/State
  1521. 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
  1522. {
  1523. $ret .= ($ret ? $sep : '' ).$object->town;
  1524. if ($object->state)
  1525. {
  1526. $ret.=($ret?", ":'').$object->state;
  1527. }
  1528. if ($object->zip) $ret .= ($ret?", ":'').$object->zip;
  1529. }
  1530. else if (in_array($object->country_code,array('GB','UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country
  1531. {
  1532. $ret .= ($ret ? $sep : '' ).$object->town;
  1533. if ($object->state)
  1534. {
  1535. $ret.=($ret?", ":'').$object->state;
  1536. }
  1537. if ($object->zip) $ret .= ($ret ? $sep : '' ).$object->zip;
  1538. }
  1539. else if (in_array($object->country_code,array('ES','TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country
  1540. {
  1541. $ret .= ($ret ? $sep : '' ).$object->zip;
  1542. $ret .= ($object->town?(($object->zip?' ':'').$object->town):'');
  1543. if ($object->state)
  1544. {
  1545. $ret.="\n".$object->state;
  1546. }
  1547. }
  1548. else if (in_array($object->country_code,array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1549. {
  1550. $ret .= ($ret ? $sep : '' ).$object->zip;
  1551. $ret .= ($object->town?(($object->zip?' ':'').$object->town):'');
  1552. $ret .= ($object->departement_id?(' ('.($object->departement_id).')'):'');
  1553. }
  1554. else // Other: title firstname name \n address lines \n zip town \n country
  1555. {
  1556. $ret .= $object->zip ? (($ret ? $sep : '' ).$object->zip) : '';
  1557. $ret .= ($object->town?(($object->zip?' ':($ret ? $sep : '' )).$object->town):'');
  1558. if ($object->state && in_array($object->country_code,$countriesusingstate))
  1559. {
  1560. $ret.=($ret?", ":'').$object->state;
  1561. }
  1562. }
  1563. if (! is_object($outputlangs)) $outputlangs=$langs;
  1564. if ($withcountry)
  1565. {
  1566. $langs->load("dict");
  1567. $ret.=($object->country_code?($ret?$sep:'').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)):'');
  1568. }
  1569. return $ret;
  1570. }
  1571. /**
  1572. * Format a string.
  1573. *
  1574. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1575. * @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)
  1576. * @param int $is_gmt See comment of timestamp parameter
  1577. * @return string A formatted string
  1578. */
  1579. function dol_strftime($fmt, $ts=false, $is_gmt=false)
  1580. {
  1581. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1582. return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
  1583. }
  1584. else return 'Error date into a not supported range';
  1585. }
  1586. /**
  1587. * Output date in a string format according to outputlangs (or langs if not defined).
  1588. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1589. *
  1590. * @param int $time GM Timestamps date
  1591. * @param string $format Output date format (tag of strftime function)
  1592. * "%d %b %Y",
  1593. * "%d/%m/%Y %H:%M",
  1594. * "%d/%m/%Y %H:%M:%S",
  1595. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1596. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1597. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1598. * false or 'tzserver' => output string is for local PHP server TZ usage
  1599. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  1600. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  1601. * @param Translate $outputlangs Object lang that contains language for text translation.
  1602. * @param boolean $encodetooutput false=no convert into output pagecode
  1603. * @return string Formated date or '' if time is null
  1604. *
  1605. * @see dol_mktime, dol_stringtotime, dol_getdate
  1606. */
  1607. function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
  1608. {
  1609. global $conf,$langs;
  1610. // Clean parameters
  1611. $to_gmt=false;
  1612. $offsettz=$offsetdst=0;
  1613. if ($tzoutput)
  1614. {
  1615. $to_gmt=true; // For backward compatibility
  1616. if (is_string($tzoutput))
  1617. {
  1618. if ($tzoutput == 'tzserver')
  1619. {
  1620. $to_gmt=false;
  1621. $offsettzstring=@date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1622. $offsettz=0;
  1623. $offsetdst=0;
  1624. }
  1625. elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel')
  1626. {
  1627. $to_gmt=true;
  1628. $offsettzstring=(empty($_SESSION['dol_tz_string'])?'UTC':$_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1629. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60; // Will not be used anymore
  1630. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60; // Will not be used anymore
  1631. }
  1632. }
  1633. }
  1634. if (! is_object($outputlangs)) $outputlangs=$langs;
  1635. if (! $format) $format='daytextshort';
  1636. $reduceformat=(! empty($conf->dol_optimize_smallscreen) && in_array($format,array('day','dayhour')))?1:0;
  1637. $formatwithoutreduce = preg_replace('/reduceformat/','',$format);
  1638. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat=1; } // so format 'dayreduceformat' is processed like day
  1639. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1640. // TODO Add format daysmallyear and dayhoursmallyear
  1641. if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
  1642. else if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
  1643. else if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
  1644. else if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
  1645. else if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
  1646. else if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
  1647. else if ($format == 'dayhoursec') $format=($outputlangs->trans("FormatDateHourSecShort")!="FormatDateHourSecShort"?$outputlangs->trans("FormatDateHourSecShort"):$conf->format_date_hour_sec_short);
  1648. else if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
  1649. else if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
  1650. // Format not sensitive to language
  1651. else if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
  1652. else if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
  1653. else if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
  1654. else if ($format == 'dayxcard') $format='%Y%m%d';
  1655. else if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
  1656. else if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1657. else if ($format == 'standard') $format='%Y-%m-%d %H:%M:%S';
  1658. if ($reduceformat)
  1659. {
  1660. $format=str_replace('%Y','%y',$format);
  1661. $format=str_replace('yyyy','yy',$format);
  1662. }
  1663. // If date undefined or "", we return ""
  1664. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1665. // Clean format
  1666. if (preg_match('/%b/i',$format)) // There is some text to translate
  1667. {
  1668. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1669. $format=str_replace('%b','__b__',$format);
  1670. $format=str_replace('%B','__B__',$format);
  1671. }
  1672. if (preg_match('/%a/i',$format)) // There is some text to translate
  1673. {
  1674. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1675. $format=str_replace('%a','__a__',$format);
  1676. $format=str_replace('%A','__A__',$format);
  1677. }
  1678. // Analyze date
  1679. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
  1680. || 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
  1681. {
  1682. // TODO Remove this.
  1683. // This part of code should not be used.
  1684. dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_ERR);
  1685. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
  1686. $syear = (! empty($reg[1]) ? $reg[1] : '');
  1687. $smonth = (! empty($reg[2]) ? $reg[2] : '');
  1688. $sday = (! empty($reg[3]) ? $reg[3] : '');
  1689. $shour = (! empty($reg[4]) ? $reg[4] : '');
  1690. $smin = (! empty($reg[5]) ? $reg[5] : '');
  1691. $ssec = (! empty($reg[6]) ? $reg[6] : '');
  1692. $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
  1693. $ret=adodb_strftime($format, $time+$offsettz+$offsetdst, $to_gmt);
  1694. }
  1695. else
  1696. {
  1697. // Date is a timestamps
  1698. if ($time < 100000000000) // Protection against bad date values
  1699. {
  1700. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1701. $ret=adodb_strftime($format, $timetouse, $to_gmt);
  1702. }
  1703. else $ret='Bad value '.$time.' for date';
  1704. }
  1705. if (preg_match('/__b__/i',$format))
  1706. {
  1707. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1708. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1709. $month=adodb_strftime('%m', $timetouse);
  1710. $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  1711. if ($encodetooutput)
  1712. {
  1713. $monthtext=$outputlangs->transnoentities('Month'.$month);
  1714. $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
  1715. }
  1716. else
  1717. {
  1718. $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
  1719. $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1720. }
  1721. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1722. $ret=str_replace('__b__',$monthtextshort,$ret);
  1723. $ret=str_replace('__B__',$monthtext,$ret);
  1724. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1725. //return $ret;
  1726. }
  1727. if (preg_match('/__a__/i',$format))
  1728. {
  1729. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1730. $w=adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1731. $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
  1732. $ret=str_replace('__A__',$dayweek,$ret);
  1733. $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
  1734. }
  1735. return $ret;
  1736. }
  1737. /**
  1738. * Return an array with locale date info.
  1739. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1740. * WARNING: This function always use PHP server timezone to return locale informations !!!
  1741. * Usage must be avoid.
  1742. * FIXME: Replace this with PHP date function and a parameter $gm
  1743. *
  1744. * @param int $timestamp Timestamp
  1745. * @param boolean $fast Fast mode
  1746. * @return array Array of informations
  1747. * If no fast mode:
  1748. * 'seconds' => $secs,
  1749. * 'minutes' => $min,
  1750. * 'hours' => $hour,
  1751. * 'mday' => $day,
  1752. * 'wday' => $dow, 0=sunday, 6=saturday
  1753. * 'mon' => $month,
  1754. * 'year' => $year,
  1755. * 'yday' => floor($secsInYear/$_day_power),
  1756. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  1757. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  1758. * If fast mode:
  1759. * 'seconds' => $secs,
  1760. * 'minutes' => $min,
  1761. * 'hours' => $hour,
  1762. * 'mday' => $day,
  1763. * 'mon' => $month,
  1764. * 'year' => $year,
  1765. * 'yday' => floor($secsInYear/$_day_power),
  1766. * 'leap' => $leaf,
  1767. * 'ndays' => $ndays
  1768. * @see dol_print_date, dol_stringtotime, dol_mktime
  1769. */
  1770. function dol_getdate($timestamp,$fast=false)
  1771. {
  1772. global $conf;
  1773. $usealternatemethod=false;
  1774. if ($timestamp <= 0) $usealternatemethod=true; // <= 1970
  1775. if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038
  1776. if ($usealternatemethod)
  1777. {
  1778. $arrayinfo=adodb_getdate($timestamp,$fast);
  1779. }
  1780. else
  1781. {
  1782. $arrayinfo=getdate($timestamp);
  1783. }
  1784. return $arrayinfo;
  1785. }
  1786. /**
  1787. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  1788. * Replace function mktime not available under Windows if year < 1970
  1789. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1790. *
  1791. * @param int $hour Hour (can be -1 for undefined)
  1792. * @param int $minute Minute (can be -1 for undefined)
  1793. * @param int $second Second (can be -1 for undefined)
  1794. * @param int $month Month (1 to 12)
  1795. * @param int $day Day (1 to 31)
  1796. * @param int $year Year
  1797. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  1798. * False or 0 or 'server' = local to server TZ
  1799. * 'user' = local to user TZ
  1800. * 'tz,TimeZone' = use specified timezone
  1801. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  1802. * @return int|string Date as a timestamp, '' or false if error
  1803. * @see dol_print_date, dol_stringtotime, dol_getdate
  1804. */
  1805. function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
  1806. {
  1807. global $conf;
  1808. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  1809. // Clean parameters
  1810. if ($hour == -1 || empty($hour)) $hour=0;
  1811. if ($minute == -1 || empty($minute)) $minute=0;
  1812. if ($second == -1 || empty($second)) $second=0;
  1813. // Check parameters
  1814. if ($check)
  1815. {
  1816. if (! $month || ! $day) return '';
  1817. if ($day > 31) return '';
  1818. if ($month > 12) return '';
  1819. if ($hour < 0 || $hour > 24) return '';
  1820. if ($minute< 0 || $minute > 60) return '';
  1821. if ($second< 0 || $second > 60) return '';
  1822. }
  1823. if (method_exists('DateTime','getTimestamp'))
  1824. {
  1825. if (empty($gm) || $gm === 'server')
  1826. {
  1827. $default_timezone=@date_default_timezone_get(); // Example 'Europe/Berlin'
  1828. $localtz = new DateTimeZone($default_timezone);
  1829. }
  1830. else if ($gm === 'user')
  1831. {
  1832. // We use dol_tz_string first because it is more reliable.
  1833. $default_timezone=(empty($_SESSION["dol_tz_string"])?@date_default_timezone_get():$_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  1834. try {
  1835. $localtz = new DateTimeZone($default_timezone);
  1836. }
  1837. catch(Exception $e)
  1838. {
  1839. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  1840. $default_timezone=@date_default_timezone_get();
  1841. }
  1842. }
  1843. else if (strrpos($gm, "tz,") !== false)
  1844. {
  1845. $timezone=str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  1846. try
  1847. {
  1848. $localtz = new DateTimeZone($timezone);
  1849. }
  1850. catch(Exception $e)
  1851. {
  1852. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  1853. }
  1854. }
  1855. if (empty($localtz)) {
  1856. $localtz = new DateTimeZone('UTC');
  1857. }
  1858. //var_dump($localtz);
  1859. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  1860. $dt = new DateTime(null,$localtz);
  1861. $dt->setDate($year,$month,$day);
  1862. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  1863. $date=$dt->getTimestamp(); // should include daylight saving time
  1864. //var_dump($date);
  1865. return $date;
  1866. }
  1867. else
  1868. {
  1869. dol_print_error('','PHP version must be 5.4+');
  1870. return '';
  1871. }
  1872. }
  1873. /**
  1874. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  1875. *
  1876. * @param string $mode 'gmt' => we return GMT timestamp,
  1877. * 'tzserver' => we add the PHP server timezone
  1878. * 'tzref' => we add the company timezone
  1879. * 'tzuser' => we add the user timezone
  1880. * @return int $date Timestamp
  1881. */
  1882. function dol_now($mode='gmt')
  1883. {
  1884. $ret=0;
  1885. // Note that gmmktime and mktime return same value (GMT) when used without parameters
  1886. //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead
  1887. if ($mode == 'gmt') $ret=time(); // Time for now at greenwich.
  1888. else if ($mode == 'tzserver') // Time for now with PHP server timezone added
  1889. {
  1890. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1891. $tzsecond=getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  1892. $ret=(int) (dol_now('gmt')+($tzsecond*3600));
  1893. }
  1894. /*else if ($mode == 'tzref') // Time for now with parent company timezone is added
  1895. {
  1896. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1897. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  1898. $ret=dol_now('gmt')+($tzsecond*3600);
  1899. }*/
  1900. else if ($mode == 'tzuser') // Time for now with user timezone added
  1901. {
  1902. //print 'time: '.time().'-'.mktime().'-'.gmmktime();
  1903. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
  1904. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
  1905. $ret=(int) (dol_now('gmt')+($offsettz+$offsetdst));
  1906. }
  1907. return $ret;
  1908. }
  1909. /**
  1910. * Return string with formated size
  1911. *
  1912. * @param int $size Size to print
  1913. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1914. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  1915. * @return string Link
  1916. */
  1917. function dol_print_size($size,$shortvalue=0,$shortunit=0)
  1918. {
  1919. global $conf,$langs;
  1920. $level=1024;
  1921. if (! empty($conf->dol_optimize_smallscreen)) $shortunit=1;
  1922. // Set value text
  1923. if (empty($shortvalue) || $size < ($level*10))
  1924. {
  1925. $ret=$size;
  1926. $textunitshort=$langs->trans("b");
  1927. $textunitlong=$langs->trans("Bytes");
  1928. }
  1929. else
  1930. {
  1931. $ret=round($size/$level,0);
  1932. $textunitshort=$langs->trans("Kb");
  1933. $textunitlong=$langs->trans("KiloBytes");
  1934. }
  1935. // Use long or short text unit
  1936. if (empty($shortunit)) { $ret.=' '.$textunitlong; }
  1937. else { $ret.=' '.$textunitshort; }
  1938. return $ret;
  1939. }
  1940. /**
  1941. * Show Url link
  1942. *
  1943. * @param string $url Url to show
  1944. * @param string $target Target for link
  1945. * @param int $max Max number of characters to show
  1946. * @param int $withpicto With picto
  1947. * @return string HTML Link
  1948. */
  1949. function dol_print_url($url,$target='_blank',$max=32,$withpicto=0)
  1950. {
  1951. global $langs;
  1952. if (empty($url)) return '';
  1953. $link='<a href="';
  1954. if (! preg_match('/^http/i',$url)) $link.='http://';
  1955. $link.=$url;
  1956. $link.='"';
  1957. if ($target) $link.=' target="'.$target.'"';
  1958. $link.='>';
  1959. if (! preg_match('/^http/i',$url)) $link.='http://';
  1960. $link.=dol_trunc($url,$max);
  1961. $link.='</a>';
  1962. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("Url"), 'object_globe.png').' ':'').$link.'</div>';
  1963. }
  1964. /**
  1965. * Show EMail link
  1966. *
  1967. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  1968. * @param int $cid Id of contact if known
  1969. * @param int $socid Id of third party if known
  1970. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  1971. * @param int $max Max number of characters to show
  1972. * @param int $showinvalid Show warning if syntax email is wrong
  1973. * @param int $withpicto Show picto
  1974. * @return string HTML Link
  1975. */
  1976. function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1,$withpicto=0)
  1977. {
  1978. global $conf,$user,$langs,$hookmanager;
  1979. $newemail=$email;
  1980. if (empty($email)) return '&nbsp;';
  1981. if (! empty($addlink))
  1982. {
  1983. $newemail='<a style="text-overflow: ellipsis;" href="';
  1984. if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
  1985. $newemail.=$email;
  1986. $newemail.='">';
  1987. $newemail.=dol_trunc($email,$max);
  1988. $newemail.='</a>';
  1989. if ($showinvalid && ! isValidEmail($email))
  1990. {
  1991. $langs->load("errors");
  1992. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  1993. }
  1994. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  1995. {
  1996. $type='AC_EMAIL'; $link='';
  1997. 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>';
  1998. if ($link) $newemail='<div>'.$newemail.' '.$link.'</div>';
  1999. }
  2000. }
  2001. else
  2002. {
  2003. if ($showinvalid && ! isValidEmail($email))
  2004. {
  2005. $langs->load("errors");
  2006. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  2007. }
  2008. }
  2009. $rep = '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("EMail"), 'object_email.png').' ':'').$newemail.'</div>';
  2010. if ($hookmanager) {
  2011. $parameters = array('cid' => $cid, 'socid' => $socid,'addlink' => $addlink, 'picto' => $withpicto);
  2012. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2013. $rep.=$hookmanager->resPrint;
  2014. }
  2015. return $rep;
  2016. }
  2017. /**
  2018. * Show Skype link
  2019. *
  2020. * @param string $skype Skype to show (only skype, without 'Name of recipient' before)
  2021. * @param int $cid Id of contact if known
  2022. * @param int $socid Id of third party if known
  2023. * @param int $addlink 0=no link to create action
  2024. * @param int $max Max number of characters to show
  2025. * @return string HTML Link
  2026. */
  2027. function dol_print_skype($skype,$cid=0,$socid=0,$addlink=0,$max=64)
  2028. {
  2029. global $conf,$user,$langs;
  2030. $newskype=$skype;
  2031. if (empty($skype)) return '&nbsp;';
  2032. if (! empty($addlink))
  2033. {
  2034. $newskype =img_picto($langs->trans("Skype"), 'object_skype.png');
  2035. $newskype.= '&nbsp;';
  2036. $newskype.=dol_trunc($skype,$max);
  2037. $newskype.= '&nbsp;';
  2038. $newskype.='<a href="skype:';
  2039. $newskype.=dol_trunc($skype,$max);
  2040. $newskype.='?call" alt="'.$langs->trans("Call").'&nbsp;'.$skype.'" title="'.$langs->trans("Call").'&nbsp;'.$skype.'">';
  2041. $newskype.='<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2042. $newskype.='</a>&nbsp;&nbsp;&nbsp;<a href="skype:';
  2043. $newskype.=dol_trunc($skype,$max);
  2044. $newskype.='?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$skype.'" title="'.$langs->trans("Chat").'&nbsp;'.$skype.'">';
  2045. $newskype.='<img src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2046. $newskype.='</a>';
  2047. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2048. {
  2049. $type='AC_SKYPE'; $link='';
  2050. if (! empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $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>';
  2051. $newskype='<div class="divskype nowrap">'.$newskype.($link?' '.$link:'').'</div>';
  2052. }
  2053. }
  2054. else
  2055. {
  2056. $langs->load("errors");
  2057. $newskype.=img_warning($langs->trans("ErrorBadSkype",$skype));
  2058. }
  2059. return $newskype;
  2060. }
  2061. /**
  2062. * Format phone numbers according to country
  2063. *
  2064. * @param string $phone Phone number to format
  2065. * @param string $countrycode Country code to use for formatting
  2066. * @param int $cid Id of contact if known
  2067. * @param int $socid Id of third party if known
  2068. * @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)
  2069. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2070. * @param string $withpicto Show picto
  2071. * @param string $titlealt Text to show on alt
  2072. * @param int $adddivfloat Add div float around phone.
  2073. * @return string Formated phone number
  2074. */
  2075. function dol_print_phone($phone,$countrycode='',$cid=0,$socid=0,$addlink='',$separ="&nbsp;",$withpicto='',$titlealt='',$adddivfloat=0)
  2076. {
  2077. global $conf, $user, $langs, $mysoc, $hookmanager;
  2078. // Clean phone parameter
  2079. $phone = preg_replace("/[\s.-]/","",trim($phone));
  2080. if (empty($phone)) { return ''; }
  2081. if (empty($countrycode)) $countrycode=$mysoc->country_code;
  2082. // Short format for small screens
  2083. if ($conf->dol_optimize_smallscreen) $separ='';
  2084. $newphone=$phone;
  2085. if (strtoupper($countrycode) == "FR")
  2086. {
  2087. // France
  2088. if (dol_strlen($phone) == 10) {
  2089. $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);
  2090. }
  2091. elseif (dol_strlen($phone) == 7)
  2092. {
  2093. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
  2094. }
  2095. elseif (dol_strlen($phone) == 9)
  2096. {
  2097. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
  2098. }
  2099. elseif (dol_strlen($phone) == 11)
  2100. {
  2101. $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);
  2102. }
  2103. elseif (dol_strlen($phone) == 12)
  2104. {
  2105. $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);
  2106. }
  2107. }
  2108. elseif (strtoupper($countrycode) == "CA")
  2109. {
  2110. if (dol_strlen($phone) == 10) {
  2111. $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4);
  2112. }
  2113. }
  2114. elseif (strtoupper($countrycode) == "PT" )
  2115. {//Portugal
  2116. if (dol_strlen($phone) == 13)
  2117. {//ex: +351_ABC_DEF_GHI
  2118. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2119. }
  2120. }
  2121. elseif (strtoupper($countrycode) == "SR" )
  2122. {//Suriname
  2123. if (dol_strlen($phone) == 10)
  2124. {//ex: +597_ABC_DEF
  2125. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3);
  2126. }
  2127. elseif (dol_strlen($phone) == 11)
  2128. {//ex: +597_ABC_DEFG
  2129. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,4);
  2130. }
  2131. }
  2132. elseif (strtoupper($countrycode) == "DE" )
  2133. {//Allemagne
  2134. if (dol_strlen($phone) == 14)
  2135. {//ex: +49_ABCD_EFGH_IJK
  2136. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,4).$separ.substr($newphone,11,3);
  2137. }
  2138. elseif (dol_strlen($phone) == 13)
  2139. {//ex: +49_ABC_DEFG_HIJ
  2140. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,4).$separ.substr($newphone,10,3);
  2141. }
  2142. }
  2143. elseif (strtoupper($countrycode) == "ES")
  2144. {//Espagne
  2145. if (dol_strlen($phone) == 12)
  2146. {//ex: +34_ABC_DEF_GHI
  2147. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2148. }
  2149. }
  2150. elseif (strtoupper($countrycode) == "BF")
  2151. {// Burkina Faso
  2152. if (dol_strlen($phone) == 12)
  2153. {//ex : +22 A BC_DE_FG_HI
  2154. $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);
  2155. }
  2156. }
  2157. elseif (strtoupper($countrycode) == "RO")
  2158. {// Roumanie
  2159. if (dol_strlen($phone) == 12)
  2160. {//ex : +40 AB_CDE_FG_HI
  2161. $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);
  2162. }
  2163. }
  2164. elseif (strtoupper($countrycode) == "TR")
  2165. {//Turquie
  2166. if (dol_strlen($phone) == 13)
  2167. {//ex : +90 ABC_DEF_GHIJ
  2168. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,4);
  2169. }
  2170. }
  2171. elseif (strtoupper($countrycode) == "US")
  2172. {//Etat-Unis
  2173. if (dol_strlen($phone) == 12)
  2174. {//ex: +1 ABC_DEF_GHIJ
  2175. $newphone= substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,3).$separ.substr($newphone,8,4);
  2176. }
  2177. }
  2178. elseif (strtoupper($countrycode) == "MX")
  2179. {//Mexique
  2180. if (dol_strlen($phone) == 12)
  2181. {//ex: +52 ABCD_EFG_HI
  2182. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,3).$separ.substr($newphone,10,2);
  2183. }
  2184. elseif (dol_strlen($phone) == 11)
  2185. {//ex: +52 AB_CD_EF_GH
  2186. $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);
  2187. }
  2188. elseif (dol_strlen($phone) == 13)
  2189. {//ex: +52 ABC_DEF_GHIJ
  2190. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,4);
  2191. }
  2192. }
  2193. elseif (strtoupper($countrycode) == "ML")
  2194. {//Mali
  2195. if(dol_strlen($phone) == 12)
  2196. {//ex: +223 AB_CD_EF_GH
  2197. $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);
  2198. }
  2199. }
  2200. elseif (strtoupper($countrycode) == "TH")
  2201. {//Thaïlande
  2202. if(dol_strlen($phone) == 11)
  2203. {//ex: +66_ABC_DE_FGH
  2204. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,2).$separ.substr($newphone,8,3);
  2205. }
  2206. elseif(dol_strlen($phone) == 12)
  2207. {//ex: +66_A_BCD_EF_GHI
  2208. $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);
  2209. }
  2210. }
  2211. elseif (strtoupper($countrycode) == "MU")
  2212. {//Maurice
  2213. if(dol_strlen($phone) == 11)
  2214. {//ex: +230_ABC_DE_FG
  2215. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
  2216. }
  2217. elseif(dol_strlen($phone) == 12)
  2218. {//ex: +230_ABCD_EF_GH
  2219. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,4).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  2220. }
  2221. }
  2222. elseif (strtoupper($countrycode) == "ZA")
  2223. {//Afrique du sud
  2224. if(dol_strlen($phone) == 12)
  2225. {//ex: +27_AB_CDE_FG_HI
  2226. $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);
  2227. }
  2228. }
  2229. elseif (strtoupper($countrycode) == "SY")
  2230. {//Syrie
  2231. if(dol_strlen($phone) == 12)
  2232. {//ex: +963_AB_CD_EF_GH
  2233. $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);
  2234. }
  2235. elseif(dol_strlen($phone) == 13)
  2236. {//ex: +963_AB_CD_EF_GHI
  2237. $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);
  2238. }
  2239. }
  2240. elseif (strtoupper($countrycode) == "AE")
  2241. {//Emirats Arabes Unis
  2242. if(dol_strlen($phone) == 12)
  2243. {//ex: +971_ABC_DEF_GH
  2244. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,2);
  2245. }
  2246. elseif(dol_strlen($phone) == 13)
  2247. {//ex: +971_ABC_DEF_GHI
  2248. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2249. }
  2250. elseif(dol_strlen($phone) == 14)
  2251. {//ex: +971_ABC_DEF_GHIK
  2252. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,4);
  2253. }
  2254. }
  2255. elseif (strtoupper($countrycode) == "DZ")
  2256. {//Algérie
  2257. if(dol_strlen($phone) == 13)
  2258. {//ex: +213_ABC_DEF_GHI
  2259. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2260. }
  2261. }
  2262. elseif (strtoupper($countrycode) == "BE")
  2263. {//Belgique
  2264. if(dol_strlen($phone) == 11)
  2265. {//ex: +32_ABC_DE_FGH
  2266. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,2).$separ.substr($newphone,8,3);
  2267. }
  2268. elseif(dol_strlen($phone) == 12)
  2269. {//ex: +32_ABC_DEF_GHI
  2270. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2271. }
  2272. }
  2273. elseif (strtoupper($countrycode) == "PF")
  2274. {//Polynésie française
  2275. if(dol_strlen($phone) == 12)
  2276. {//ex: +689_AB_CD_EF_GH
  2277. $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);
  2278. }
  2279. }
  2280. elseif (strtoupper($countrycode) == "CO")
  2281. {//Colombie
  2282. if(dol_strlen($phone) == 13)
  2283. {//ex: +57_ABC_DEF_GH_IJ
  2284. $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);
  2285. }
  2286. }
  2287. elseif (strtoupper($countrycode) == "JO")
  2288. {//Jordanie
  2289. if(dol_strlen($phone) == 12)
  2290. {//ex: +962_A_BCD_EF_GH
  2291. $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);
  2292. }
  2293. }
  2294. elseif (strtoupper($countrycode) == "MG")
  2295. {//Madagascar
  2296. if(dol_strlen($phone) == 13)
  2297. {//ex: +261_AB_CD_EF_GHI
  2298. $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);
  2299. }
  2300. }
  2301. elseif (strtoupper($countrycode) == "GB")
  2302. {//Royaume uni
  2303. if(dol_strlen($phone) == 13)
  2304. {//ex: +44_ABCD_EFG_HIJ
  2305. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2306. }
  2307. }
  2308. elseif (strtoupper($countrycode) == "CH")
  2309. {//Suisse
  2310. if(dol_strlen($phone) == 12)
  2311. {//ex: +41_AB_CDE_FG_HI
  2312. $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);
  2313. }
  2314. elseif(dol_strlen($phone) == 15)
  2315. {// +41_AB_CDE_FGH_IJKL
  2316. $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);
  2317. }
  2318. }
  2319. elseif (strtoupper($countrycode) == "TN")
  2320. {//Tunisie
  2321. if(dol_strlen($phone) == 12)
  2322. {//ex: +216_AB_CDE_FGH
  2323. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2324. }
  2325. }
  2326. elseif (strtoupper($countrycode) == "GF")
  2327. {//Guyane francaise
  2328. if(dol_strlen($phone) == 13)
  2329. {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2330. $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);
  2331. }
  2332. }
  2333. elseif (strtoupper($countrycode) == "GP")
  2334. {//Guadeloupe
  2335. if(dol_strlen($phone) == 13)
  2336. {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2337. $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);
  2338. }
  2339. }
  2340. elseif (strtoupper($countrycode) == "MQ")
  2341. {//Martinique
  2342. if(dol_strlen($phone) == 13)
  2343. {//ex: +596_ABC_DE_FG_HI (ABC=596 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) == "IT")
  2348. {//Italie
  2349. if(dol_strlen($phone) == 12)
  2350. {//ex: +39_ABC_DEF_GHI
  2351. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2352. }
  2353. elseif(dol_strlen($phone) == 13)
  2354. {//ex: +39_ABC_DEF_GH_IJ
  2355. $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);
  2356. }
  2357. }
  2358. elseif(strtoupper($countrycode) == "AU")
  2359. {//Australie
  2360. if(dol_strlen($phone) == 12)
  2361. {//ex: +61_A_BCDE_FGHI
  2362. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,1).$separ.substr($newphone,4,4).$separ.substr($newphone,8,4);
  2363. }
  2364. }
  2365. if (! empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2366. {
  2367. if (! empty($conf->browser->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
  2368. {
  2369. $newphone ='<a href="tel:'.$phone.'"';
  2370. $newphone.='>'.$phone.'</a>';
  2371. }
  2372. else if (! empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  2373. {
  2374. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  2375. // Define urlmask
  2376. $urlmask='ErrorClickToDialModuleNotConfigured';
  2377. if (! empty($conf->global->CLICKTODIAL_URL)) $urlmask=$conf->global->CLICKTODIAL_URL;
  2378. if (! empty($user->clicktodial_url)) $urlmask=$user->clicktodial_url;
  2379. $clicktodial_poste=(! empty($user->clicktodial_poste)?urlencode($user->clicktodial_poste):'');
  2380. $clicktodial_login=(! empty($user->clicktodial_login)?urlencode($user->clicktodial_login):'');
  2381. $clicktodial_password=(! empty($user->clicktodial_password)?urlencode($user->clicktodial_password):'');
  2382. // This line is for backward compatibility
  2383. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2384. // Thoose lines are for substitution
  2385. $substitarray=array('__PHONEFROM__'=>$clicktodial_poste,
  2386. '__PHONETO__'=>urlencode($phone),
  2387. '__LOGIN__'=>$clicktodial_login,
  2388. '__PASS__'=>$clicktodial_password);
  2389. $url = make_substitutions($url, $substitarray);
  2390. $newphonesav=$newphone;
  2391. $newphone ='<a href="'.$url.'"';
  2392. if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
  2393. $newphone.='>'.$newphonesav.'</a>';
  2394. }
  2395. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2396. if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2397. {
  2398. $type='AC_TEL'; $link='';
  2399. if ($addlink == 'AC_FAX') $type='AC_FAX';
  2400. 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>';
  2401. if ($link) $newphone='<div>'.$newphone.' '.$link.'</div>';
  2402. }
  2403. }
  2404. if (empty($titlealt))
  2405. {
  2406. $titlealt=($withpicto=='fax'?$langs->trans("Fax"):$langs->trans("Phone"));
  2407. }
  2408. $rep='';
  2409. if ($hookmanager) {
  2410. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid,'titlealt' => $titlealt, 'picto' => $withpicto);
  2411. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2412. $rep.=$hookmanager->resPrint;
  2413. }
  2414. if (empty($reshook))
  2415. {
  2416. $picto = '';
  2417. if($withpicto){
  2418. if($withpicto=='fax'){
  2419. $picto = 'phoning_fax';
  2420. }elseif($withpicto=='phone'){
  2421. $picto = 'phoning';
  2422. }elseif($withpicto=='mobile'){
  2423. $picto = 'phoning_mobile';
  2424. }else{
  2425. $picto = '';
  2426. }
  2427. }
  2428. if ($adddivfloat) $rep.='<div class="nospan float" style="margin-right: 10px">';
  2429. else $rep.='<span style="margin-right: 10px;">';
  2430. $rep.=($withpicto?img_picto($titlealt, 'object_'.$picto.'.png').' ':'').$newphone;
  2431. if ($adddivfloat) $rep.='</div>';
  2432. else $rep.='</span>';
  2433. }
  2434. return $rep;
  2435. }
  2436. /**
  2437. * Return an IP formated to be shown on screen
  2438. *
  2439. * @param string $ip IP
  2440. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2441. * @return string Formated IP, with country if GeoIP module is enabled
  2442. */
  2443. function dol_print_ip($ip,$mode=0)
  2444. {
  2445. global $conf,$langs;
  2446. $ret='';
  2447. if (empty($mode)) $ret.=$ip;
  2448. if ($mode != 2)
  2449. {
  2450. $countrycode=dolGetCountryCodeFromIp($ip);
  2451. if ($countrycode) // If success, countrycode is us, fr, ...
  2452. {
  2453. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  2454. {
  2455. $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
  2456. }
  2457. else $ret.=' ('.$countrycode.')';
  2458. }
  2459. }
  2460. return $ret;
  2461. }
  2462. /**
  2463. * Return the IP of remote user.
  2464. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2465. * Then HTTP_CLIENT_IP if defined (rare)
  2466. * Then REMOTE_ADDR (not way to be modified by user but may be wrong if using proxy)
  2467. *
  2468. * @return string Ip of remote user.
  2469. */
  2470. function getUserRemoteIP()
  2471. {
  2472. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']?$_SERVER['HTTP_X_FORWARDED_FOR']:(($_SERVER['HTTP_CLIENT_IP']?$_SERVER['HTTP_CLIENT_IP']:$_SERVER['REMOTE_ADDR']));
  2473. return $ip;
  2474. }
  2475. /**
  2476. * Return a country code from IP. Empty string if not found.
  2477. *
  2478. * @param string $ip IP
  2479. * @return string Country code ('us', 'fr', ...)
  2480. */
  2481. function dolGetCountryCodeFromIp($ip)
  2482. {
  2483. global $conf;
  2484. $countrycode='';
  2485. if (! empty($conf->geoipmaxmind->enabled))
  2486. {
  2487. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2488. //$ip='24.24.24.24';
  2489. //$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)
  2490. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2491. $geoip=new DolGeoIP('country',$datafile);
  2492. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2493. //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
  2494. $countrycode=$geoip->getCountryCodeFromIP($ip);
  2495. }
  2496. return $countrycode;
  2497. }
  2498. /**
  2499. * Return country code for current user.
  2500. * If software is used inside a local network, detection may fails (we need a public ip)
  2501. *
  2502. * @return string Country code (fr, es, it, us, ...)
  2503. */
  2504. function dol_user_country()
  2505. {
  2506. global $conf,$langs,$user;
  2507. //$ret=$user->xxx;
  2508. $ret='';
  2509. if (! empty($conf->geoipmaxmind->enabled))
  2510. {
  2511. $ip=getUserRemoteIP();
  2512. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2513. //$ip='24.24.24.24';
  2514. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2515. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2516. $geoip=new DolGeoIP('country',$datafile);
  2517. $countrycode=$geoip->getCountryCodeFromIP($ip);
  2518. $ret=$countrycode;
  2519. }
  2520. return $ret;
  2521. }
  2522. /**
  2523. * Format address string
  2524. *
  2525. * @param string $address Address
  2526. * @param int $htmlid Html ID (for example 'gmap')
  2527. * @param int $mode thirdparty|contact|member|other
  2528. * @param int $id Id of object
  2529. * @param int $noprint No output. Result is the function return
  2530. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2531. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2532. * @see dol_format_address
  2533. */
  2534. function dol_print_address($address, $htmlid, $mode, $id, $noprint=0, $charfornl='')
  2535. {
  2536. global $conf, $user, $langs, $hookmanager;
  2537. $out = '';
  2538. if ($address)
  2539. {
  2540. if ($hookmanager) {
  2541. $parameters = array('element' => $mode, 'id' => $id);
  2542. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2543. $out.=$hookmanager->resPrint;
  2544. }
  2545. if (empty($reshook))
  2546. {
  2547. if (empty($charfornl)) $out.=nl2br($address);
  2548. else $out.=preg_replace('/[\r\n]+/', $charfornl, $address);
  2549. $showgmap=$showomap=0;
  2550. // TODO Add a hook here
  2551. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1;
  2552. if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1;
  2553. if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1;
  2554. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1;
  2555. if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1;
  2556. if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1;
  2557. if ($showgmap)
  2558. {
  2559. $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1);
  2560. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2561. }
  2562. if ($showomap)
  2563. {
  2564. $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1);
  2565. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2566. }
  2567. }
  2568. }
  2569. if ($noprint) return $out;
  2570. else print $out;
  2571. }
  2572. /**
  2573. * Return true if email syntax is ok
  2574. *
  2575. * @param string $address email (Ex: "toto@examle.com", "John Do <johndo@example.com>")
  2576. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2577. * @return boolean true if email syntax is OK, false if KO or empty string
  2578. */
  2579. function isValidEmail($address, $acceptsupervisorkey=0)
  2580. {
  2581. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2582. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2583. return false;
  2584. }
  2585. /**
  2586. * Return true if phone number syntax is ok
  2587. * TODO Decide what to do with this
  2588. *
  2589. * @param string $phone phone (Ex: "0601010101")
  2590. * @return boolean true if phone syntax is OK, false if KO or empty string
  2591. */
  2592. function isValidPhone($phone)
  2593. {
  2594. return true;
  2595. }
  2596. /**
  2597. * Make a strlen call. Works even if mbstring module not enabled
  2598. *
  2599. * @param string $string String to calculate length
  2600. * @param string $stringencoding Encoding of string
  2601. * @return int Length of string
  2602. */
  2603. function dol_strlen($string,$stringencoding='UTF-8')
  2604. {
  2605. if (function_exists('mb_strlen')) return mb_strlen($string,$stringencoding);
  2606. else return strlen($string);
  2607. }
  2608. /**
  2609. * Make a substring. Works even in mbstring module is not enabled.
  2610. *
  2611. * @param string $string String to scan
  2612. * @param string $start Start position
  2613. * @param int $length Length
  2614. * @param string $stringencoding Page code used for input string encoding
  2615. * @return string substring
  2616. */
  2617. function dol_substr($string,$start,$length,$stringencoding='')
  2618. {
  2619. global $langs;
  2620. if (empty($stringencoding)) $stringencoding=$langs->charset_output;
  2621. $ret='';
  2622. if (function_exists('mb_substr'))
  2623. {
  2624. $ret=mb_substr($string,$start,$length,$stringencoding);
  2625. }
  2626. else
  2627. {
  2628. $ret=substr($string,$start,$length);
  2629. }
  2630. return $ret;
  2631. }
  2632. /**
  2633. * Show a javascript graph.
  2634. * Do not use this function anymore. Use DolGraph class instead.
  2635. *
  2636. * @param string $htmlid Html id name
  2637. * @param int $width Width in pixel
  2638. * @param int $height Height in pixel
  2639. * @param array $data Data array
  2640. * @param int $showlegend 1 to show legend, 0 otherwise
  2641. * @param string $type Type of graph ('pie', 'barline')
  2642. * @param int $showpercent Show percent (with type='pie' only)
  2643. * @param string $url Param to add an url to click values
  2644. * @param int $combineother 0=No combine, 0.05=Combine if lower than 5%
  2645. * @param int $shownographyet Show graph to say there is not enough data
  2646. * @return void
  2647. * @deprecated
  2648. * @see DolGraph
  2649. */
  2650. function dol_print_graph($htmlid,$width,$height,$data,$showlegend=0,$type='pie',$showpercent=0,$url='',$combineother=0.05,$shownographyet=0)
  2651. {
  2652. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  2653. global $conf,$langs;
  2654. global $theme_datacolor; // To have var kept when function is called several times
  2655. if ($shownographyet)
  2656. {
  2657. print '<div class="nographyet" style="width:'.$width.'px;height:'.$height.'px;"></div>';
  2658. print '<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
  2659. return;
  2660. }
  2661. if (empty($conf->use_javascript_ajax)) return;
  2662. $jsgraphlib='flot';
  2663. $datacolor=array();
  2664. // Load colors of theme into $datacolor array
  2665. $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/graph-color.php";
  2666. if (is_readable($color_file))
  2667. {
  2668. include_once $color_file;
  2669. if (isset($theme_datacolor))
  2670. {
  2671. $datacolor=array();
  2672. foreach($theme_datacolor as $val)
  2673. {
  2674. $datacolor[]="#".sprintf("%02x",$val[0]).sprintf("%02x",$val[1]).sprintf("%02x",$val[2]);
  2675. }
  2676. }
  2677. }
  2678. print '<div id="'.$htmlid.'" style="width:'.$width.'px;height:'.$height.'px;"></div>';
  2679. // We use Flot js lib
  2680. if ($jsgraphlib == 'flot')
  2681. {
  2682. if ($type == 'pie')
  2683. {
  2684. // data is array('series'=>array(serie1,serie2,...),
  2685. // 'seriestype'=>array('bar','line',...),
  2686. // 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
  2687. // 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
  2688. // serieX is array('label'=>'label', data=>val)
  2689. print '
  2690. <script type="text/javascript">
  2691. $(function () {
  2692. var data = '.json_encode($data['series']).';
  2693. function plotWithOptions() {
  2694. $.plot($("#'.$htmlid.'"), data,
  2695. {
  2696. series: {
  2697. pie: {
  2698. show: true,
  2699. radius: 0.8,';
  2700. if ($combineother)
  2701. {
  2702. print '
  2703. combine: {
  2704. threshold: '.$combineother.'
  2705. },';
  2706. }
  2707. print '
  2708. label: {
  2709. show: true,
  2710. radius: 0.9,
  2711. formatter: function(label, series) {
  2712. var percent=Math.round(series.percent);
  2713. var number=series.data[0][1];
  2714. return \'';
  2715. print '<div style="font-size:8pt;text-align:center;padding:2px;color:black;">';
  2716. if ($url) print '<a style="color: #FFFFFF;" border="0" href="'.$url.'">';
  2717. print '\'+'.($showlegend?'number':'label+\' \'+number');
  2718. if (! empty($showpercent)) print '+\'<br/>\'+percent+\'%\'';
  2719. print '+\'';
  2720. if ($url) print '</a>';
  2721. print '</div>\';
  2722. },
  2723. background: {
  2724. opacity: 0.0,
  2725. color: \'#000000\'
  2726. },
  2727. }
  2728. }
  2729. },
  2730. zoom: {
  2731. interactive: true
  2732. },
  2733. pan: {
  2734. interactive: true
  2735. },';
  2736. if (count($datacolor))
  2737. {
  2738. print 'colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
  2739. }
  2740. print 'legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
  2741. });
  2742. }
  2743. plotWithOptions();
  2744. });
  2745. </script>';
  2746. }
  2747. else if ($type == 'barline')
  2748. {
  2749. // data is array('series'=>array(serie1,serie2,...),
  2750. // 'seriestype'=>array('bar','line',...),
  2751. // 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
  2752. // 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
  2753. // serieX is array('label'=>'label', data=>array(0=>y1,1=>y2,...)) with same nb of value than into xlabel
  2754. print '
  2755. <script type="text/javascript">
  2756. $(function () {
  2757. var data = [';
  2758. $i=0; $outputserie=0;
  2759. foreach($data['series'] as $serie)
  2760. {
  2761. if ($data['seriestype'][$i]=='line') { $i++; continue; };
  2762. if ($outputserie > 0) print ',';
  2763. print '{ bars: { stack: 0, show: true, barWidth: 0.9, align: \'center\' }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
  2764. $outputserie++; $i++;
  2765. }
  2766. if ($outputserie) print ', ';
  2767. //print '];
  2768. //var datalines = [';
  2769. $i=0; $outputserie=0;
  2770. foreach($data['series'] as $serie)
  2771. {
  2772. if (empty($data['seriestype'][$i]) || $data['seriestype'][$i]=='bar') { $i++; continue; };
  2773. if ($outputserie > 0) print ',';
  2774. print '{ lines: { show: true }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
  2775. $outputserie++; $i++;
  2776. }
  2777. print '];
  2778. var dataticks = '.json_encode($data['xlabel']).'
  2779. function plotWithOptions() {
  2780. $.plot(jQuery("#'.$htmlid.'"), data,
  2781. {
  2782. series: {
  2783. stack: 0
  2784. },
  2785. zoom: {
  2786. interactive: true
  2787. },
  2788. pan: {
  2789. interactive: true
  2790. },';
  2791. if (count($datacolor))
  2792. {
  2793. print 'colors: '.json_encode($datacolor).',';
  2794. }
  2795. print 'legend: {show: '.($showlegend?'true':'false').'},
  2796. xaxis: {ticks: dataticks}
  2797. });
  2798. }
  2799. plotWithOptions();
  2800. });
  2801. </script>';
  2802. }
  2803. else print 'BadValueForParameterType';
  2804. }
  2805. }
  2806. /**
  2807. * Truncate a string to a particular length adding '...' if string larger than length.
  2808. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2809. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2810. *
  2811. * @param string $string String to truncate
  2812. * @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 ...)
  2813. * @param string $trunc Where to trunc: right, left, middle (size must be a 2 power), wrap
  2814. * @param string $stringencoding Tell what is source string encoding
  2815. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2816. * @param int $display Trunc is use to display and can be changed for small screen. TODO Remove this param (must be dealt with CSS)
  2817. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  2818. */
  2819. function dol_trunc($string,$size=40,$trunc='right',$stringencoding='UTF-8',$nodot=0, $display=0)
  2820. {
  2821. global $conf;
  2822. if ($size==0 || ! empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2823. if (empty($stringencoding)) $stringencoding='UTF-8';
  2824. // reduce for small screen
  2825. if ($conf->dol_optimize_smallscreen==1 && $display==1) $size = round($size/3);
  2826. // We go always here
  2827. if ($trunc == 'right')
  2828. {
  2829. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2830. 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 ...
  2831. return dol_substr($newstring,0,$size,$stringencoding).($nodot?'':'...');
  2832. else
  2833. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  2834. return $string;
  2835. }
  2836. elseif ($trunc == 'middle')
  2837. {
  2838. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2839. if (dol_strlen($newstring,$stringencoding) > 2 && dol_strlen($newstring,$stringencoding) > ($size+1))
  2840. {
  2841. $size1=round($size/2);
  2842. $size2=round($size/2);
  2843. return dol_substr($newstring,0,$size1,$stringencoding).'...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size2,$size2,$stringencoding);
  2844. }
  2845. else
  2846. return $string;
  2847. }
  2848. elseif ($trunc == 'left')
  2849. {
  2850. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2851. 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 ...
  2852. return '...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size,$size,$stringencoding);
  2853. else
  2854. return $string;
  2855. }
  2856. elseif ($trunc == 'wrap')
  2857. {
  2858. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2859. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  2860. return dol_substr($newstring,0,$size,$stringencoding)."\n".dol_trunc(dol_substr($newstring,$size,dol_strlen($newstring,$stringencoding)-$size,$stringencoding),$size,$trunc);
  2861. else
  2862. return $string;
  2863. }
  2864. else return 'BadParam3CallingDolTrunc';
  2865. }
  2866. /**
  2867. * Show picto whatever it's its name (generic function)
  2868. *
  2869. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  2870. * @param string $picto Name of image file to show ('filenew', ...)
  2871. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2872. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2873. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2874. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2875. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2876. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  2877. * @param int $srconly Return only content of the src attribute of img.
  2878. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2879. * @param string $alt Force alt for bind peoplae
  2880. * @param string $morecss Add more class css on img tag (For example 'myclascss')
  2881. * @return string Return img tag
  2882. * @see #img_object, #img_picto_common
  2883. */
  2884. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0, $alt='', $morecss='')
  2885. {
  2886. global $conf, $langs;
  2887. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2888. $url = DOL_URL_ROOT;
  2889. $theme = $conf->theme;
  2890. $path = 'theme/'.$theme;
  2891. // Define fullpathpicto to use into src
  2892. if ($pictoisfullpath) {
  2893. // Clean parameters
  2894. if (! preg_match('/(\.png|\.gif|\.svg)$/i',$picto)) {
  2895. $picto .= '.png';
  2896. }
  2897. $fullpathpicto = $picto;
  2898. }
  2899. else {
  2900. $pictowithoutext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  2901. //if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on')))
  2902. if (empty($srconly) && in_array($pictowithoutext, array(
  2903. 'bank', 'close_title', 'delete', 'edit', 'ellipsis-h', 'filter', 'grip', 'grip_title', 'off', 'on', 'play', 'playdisabled', 'printer', 'resize',
  2904. 'switch_off', 'switch_on', 'unlink', 'uparrow')
  2905. )) {
  2906. $fakey = $pictowithoutext;
  2907. $facolor = '';
  2908. $fasize = '';
  2909. if ($pictowithoutext == 'switch_off') {
  2910. $fakey = 'fa-toggle-off';
  2911. $facolor = '#999';
  2912. $fasize = '2em';
  2913. }
  2914. elseif ($pictowithoutext == 'switch_on') {
  2915. $fakey = 'fa-toggle-on';
  2916. $facolor = '#227722';
  2917. $fasize = '2em';
  2918. }
  2919. elseif ($pictowithoutext == 'off') {
  2920. $fakey = 'fa-square-o';
  2921. $fasize = '1.3em';
  2922. }
  2923. elseif ($pictowithoutext == 'on') {
  2924. $fakey = 'fa-check-square-o';
  2925. $fasize = '1.3em';
  2926. }
  2927. elseif ($pictowithoutext == 'bank') {
  2928. $fakey = 'fa-bank';
  2929. $facolor = '#444';
  2930. }
  2931. elseif ($pictowithoutext == 'close_title') {
  2932. $fakey = 'fa-window-close';
  2933. }
  2934. elseif ($pictowithoutext == 'delete') {
  2935. $fakey = 'fa-trash';
  2936. $facolor = '#444';
  2937. }
  2938. elseif ($pictowithoutext == 'edit') {
  2939. $fakey = 'fa-pencil';
  2940. $facolor = '#444';
  2941. }
  2942. elseif ($pictowithoutext == 'filter') {
  2943. $fakey = 'fa-'.$pictowithoutext;
  2944. }
  2945. elseif ($pictowithoutext == 'grip_title' || $pictowithoutext == 'grip') {
  2946. $fakey = 'fa-arrows';
  2947. }
  2948. elseif ($pictowithoutext == 'printer') {
  2949. $fakey = 'fa-print';
  2950. $fasize = '1.2em';
  2951. $facolor = '#444';
  2952. }
  2953. elseif ($pictowithoutext == 'resize') {
  2954. $fakey = 'fa-crop';
  2955. $facolor = '#444';
  2956. }
  2957. elseif ($pictowithoutext == 'uparrow') {
  2958. $fakey = 'fa-mail-forward';
  2959. $facolor = '#555';
  2960. }
  2961. elseif ($pictowithoutext == 'unlink') {
  2962. $fakey = 'fa-chain-broken';
  2963. $facolor = '#555';
  2964. }
  2965. elseif ($pictowithoutext == 'playdisabled') {
  2966. $fakey = 'fa-play';
  2967. $facolor = '#ccc';
  2968. }
  2969. else {
  2970. $fakey = 'fa-'.$pictowithoutext;
  2971. $facolor = '#444';
  2972. }
  2973. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2974. $morecss.= ($morecss?' ':'').$reg[1];
  2975. }
  2976. $enabledisablehtml = '<span class="fa '.$fakey.' marginleftonly valignmiddle'.($morecss?' '.$morecss:'').'" style="'.($fasize?('font-size: '.$fasize.';'):'').($facolor?(' color: '.$facolor.';'):'').'" alt="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'"'.($moreatt?' '.$moreatt:'').'>';
  2977. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2978. $enabledisablehtml.= $titlealt;
  2979. }
  2980. $enabledisablehtml.= '</span>';
  2981. return $enabledisablehtml;
  2982. }
  2983. if (! empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  2984. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  2985. }
  2986. else if (! empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  2987. $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
  2988. }
  2989. else if (! empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  2990. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  2991. }
  2992. // If we ask an image into $url/$mymodule/img (instead of default path)
  2993. if (preg_match('/^([^@]+)@([^@]+)$/i',$picto,$regs)) {
  2994. $picto = $regs[1];
  2995. $path = $regs[2]; // $path is $mymodule
  2996. }
  2997. // Clean parameters
  2998. if (! preg_match('/(\.png|\.gif|\.svg)$/i',$picto)) {
  2999. $picto .= '.png';
  3000. }
  3001. // If alt path are defined, define url where img file is, according to physical path
  3002. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3003. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3004. if ($type == 'main') {
  3005. continue;
  3006. }
  3007. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3008. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3009. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3010. break;
  3011. }
  3012. }
  3013. // $url is '' or '/custom', $path is current theme or
  3014. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3015. }
  3016. if ($srconly) {
  3017. return $fullpathpicto;
  3018. }
  3019. else {
  3020. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for bind people
  3021. //$tmparray=array(0=>$titlealt);
  3022. //if (empty($notitle) && preg_match('/:[^\s0-9]/',$titlealt)) $tmparray=explode(':',$titlealt); // We explode if we have TextA:TextB. Not if we have TextA: TextB
  3023. //$title=$tmparray[0];
  3024. //$alt=empty($tmparray[1])?'':$tmparray[1];
  3025. $title = $titlealt;
  3026. return '<img src="'.$fullpathpicto.'" alt="'.dol_escape_htmltag($alt).'"'.(($notitle || empty($title))?'':' title="'.dol_escape_htmltag($title).'"').($moreatt?' '.$moreatt:' class="inline-block"').'>'; // Alt is used for accessibility, title for popup
  3027. }
  3028. }
  3029. /**
  3030. * Show a picto called object_picto (generic function)
  3031. *
  3032. * @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.
  3033. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3034. * For external modules use imagename@mymodule to search into directory "img" of module.
  3035. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3036. * @param int $pictoisfullpath If 1, image path is a full path
  3037. * @param int $srconly Return only content of the src attribute of img.
  3038. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3039. * @return string Return img tag
  3040. * @see #img_picto, #img_picto_common
  3041. */
  3042. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0)
  3043. {
  3044. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3045. }
  3046. /**
  3047. * Show weather picto
  3048. *
  3049. * @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.
  3050. * @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.
  3051. * @param string $moreatt Add more attribute on img tag
  3052. * @param int $pictoisfullpath If 1, image path is a full path
  3053. * @return string Return img tag
  3054. * @see #img_object, #img_picto
  3055. */
  3056. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  3057. {
  3058. global $conf;
  3059. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  3060. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3061. return img_picto($titlealt, $path, $moreatt, 1);
  3062. }
  3063. /**
  3064. * Show picto (generic function)
  3065. *
  3066. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3067. * @param string $picto Name of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory.
  3068. * @param string $moreatt Add more attribute on img tag
  3069. * @param int $pictoisfullpath If 1, image path is a full path
  3070. * @return string Return img tag
  3071. * @see #img_object, #img_picto
  3072. */
  3073. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  3074. {
  3075. global $conf;
  3076. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  3077. if ($pictoisfullpath) $path = $picto;
  3078. else
  3079. {
  3080. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3081. if (! empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  3082. {
  3083. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3084. if (file_exists($themepath)) $path = $themepath;
  3085. }
  3086. }
  3087. return img_picto($titlealt, $path, $moreatt, 1);
  3088. }
  3089. /**
  3090. * Show logo action
  3091. *
  3092. * @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.
  3093. * @param string $numaction Action id or code to show
  3094. * @return string Return an img tag
  3095. */
  3096. function img_action($titlealt, $numaction)
  3097. {
  3098. global $conf, $langs;
  3099. if (empty($titlealt) || $titlealt == 'default')
  3100. {
  3101. if ($numaction == '-1' || $numaction == 'ST_NO') { $numaction = -1; $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); }
  3102. elseif ($numaction == '0' || $numaction == 'ST_NEVER') { $numaction = 0; $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); }
  3103. elseif ($numaction == '1' || $numaction == 'ST_TODO') { $numaction = 1; $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); }
  3104. elseif ($numaction == '2' || $numaction == 'ST_PEND') { $numaction = 2; $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); }
  3105. elseif ($numaction == '3' || $numaction == 'ST_DONE') { $numaction = 3; $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); }
  3106. else { $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction); $numaction = 0; }
  3107. }
  3108. if (! is_numeric($numaction)) $numaction=0;
  3109. return img_picto($titlealt, 'stcomm'.$numaction.'.png');
  3110. }
  3111. /**
  3112. * Show pdf logo
  3113. *
  3114. * @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.
  3115. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3116. * @return string Retourne tag img
  3117. */
  3118. function img_pdf($titlealt = 'default', $size = 3)
  3119. {
  3120. global $conf, $langs;
  3121. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  3122. return img_picto($titlealt, 'pdf'.$size.'.png');
  3123. }
  3124. /**
  3125. * Show logo +
  3126. *
  3127. * @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.
  3128. * @param string $other Add more attributes on img
  3129. * @return string Return tag img
  3130. */
  3131. function img_edit_add($titlealt = 'default', $other = '')
  3132. {
  3133. global $conf, $langs;
  3134. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  3135. return img_picto($titlealt, 'edit_add.png', $other);
  3136. }
  3137. /**
  3138. * Show logo -
  3139. *
  3140. * @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.
  3141. * @param string $other Add more attributes on img
  3142. * @return string Return tag img
  3143. */
  3144. function img_edit_remove($titlealt = 'default', $other='')
  3145. {
  3146. global $conf, $langs;
  3147. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  3148. return img_picto($titlealt, 'edit_remove.png', $other);
  3149. }
  3150. /**
  3151. * Show logo editer/modifier fiche
  3152. *
  3153. * @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.
  3154. * @param integer $float Si il faut y mettre le style "float: right"
  3155. * @param string $other Add more attributes on img
  3156. * @return string Return tag img
  3157. */
  3158. function img_edit($titlealt = 'default', $float = 0, $other = 'class="pictoedit"')
  3159. {
  3160. global $conf, $langs;
  3161. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  3162. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl'?'left':'right').'"' : "") . ($other?' '.$other:''));
  3163. }
  3164. /**
  3165. * Show logo view card
  3166. *
  3167. * @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.
  3168. * @param integer $float Si il faut y mettre le style "float: right"
  3169. * @param string $other Add more attributes on img
  3170. * @return string Return tag img
  3171. */
  3172. function img_view($titlealt = 'default', $float = 0, $other = '')
  3173. {
  3174. global $conf, $langs;
  3175. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  3176. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3177. return img_picto($titlealt, 'view.png', $moreatt);
  3178. }
  3179. /**
  3180. * Show delete logo
  3181. *
  3182. * @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.
  3183. * @param string $other Add more attributes on img
  3184. * @return string Retourne tag img
  3185. */
  3186. function img_delete($titlealt = 'default', $other = 'class="pictodelete"')
  3187. {
  3188. global $conf, $langs;
  3189. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  3190. return img_picto($titlealt, 'delete.png', $other);
  3191. //return '<span class="fa fa-trash fa-2x fa-fw" style="font-size: 1.7em;" title="'.$titlealt.'"></span>';
  3192. }
  3193. /**
  3194. * Show printer logo
  3195. *
  3196. * @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.
  3197. * @param string $other Add more attributes on img
  3198. * @return string Retourne tag img
  3199. */
  3200. function img_printer($titlealt = "default", $other='')
  3201. {
  3202. global $conf,$langs;
  3203. if ($titlealt=="default") $titlealt=$langs->trans("Print");
  3204. return img_picto($titlealt,'printer.png',$other);
  3205. }
  3206. /**
  3207. * Show split logo
  3208. *
  3209. * @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.
  3210. * @param string $other Add more attributes on img
  3211. * @return string Retourne tag img
  3212. */
  3213. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3214. {
  3215. global $conf, $langs;
  3216. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  3217. return img_picto($titlealt, 'split.png', $other);
  3218. }
  3219. /**
  3220. * Show help logo with cursor "?"
  3221. *
  3222. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3223. * @param int|string $usealttitle Text to use as alt title
  3224. * @return string Return tag img
  3225. */
  3226. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3227. {
  3228. global $conf, $langs;
  3229. if ($usealttitle)
  3230. {
  3231. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  3232. else $usealttitle = $langs->trans('Info');
  3233. }
  3234. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help': ($usehelpcursor == 2 ? ' cursor: pointer':'')).'"');
  3235. }
  3236. /**
  3237. * Show info 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. * @return string Return img tag
  3241. */
  3242. function img_info($titlealt = 'default')
  3243. {
  3244. global $conf, $langs;
  3245. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  3246. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3247. }
  3248. /**
  3249. * Show warning logo
  3250. *
  3251. * @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.
  3252. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3253. * @return string Return img tag
  3254. */
  3255. function img_warning($titlealt = 'default', $moreatt = '')
  3256. {
  3257. global $conf, $langs;
  3258. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  3259. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3260. return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): ''));
  3261. }
  3262. /**
  3263. * Show error logo
  3264. *
  3265. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3266. * @return string Return img tag
  3267. */
  3268. function img_error($titlealt = 'default')
  3269. {
  3270. global $conf, $langs;
  3271. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  3272. return img_picto($titlealt, 'error.png', 'class="valigntextbottom"');
  3273. }
  3274. /**
  3275. * Show next logo
  3276. *
  3277. * @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.
  3278. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3279. * @return string Return img tag
  3280. */
  3281. function img_next($titlealt = 'default', $moreatt='')
  3282. {
  3283. global $conf, $langs;
  3284. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  3285. //return img_picto($titlealt, 'next.png', $moreatt);
  3286. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3287. }
  3288. /**
  3289. * Show previous logo
  3290. *
  3291. * @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.
  3292. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3293. * @return string Return img tag
  3294. */
  3295. function img_previous($titlealt = 'default', $moreatt='')
  3296. {
  3297. global $conf, $langs;
  3298. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  3299. //return img_picto($titlealt, 'previous.png', $moreatt);
  3300. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3301. }
  3302. /**
  3303. * Show down arrow logo
  3304. *
  3305. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3306. * @param int $selected Selected
  3307. * @param string $moreclass Add more CSS classes
  3308. * @return string Return img tag
  3309. */
  3310. function img_down($titlealt = 'default', $selected = 0, $moreclass='')
  3311. {
  3312. global $conf, $langs;
  3313. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  3314. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass?" ".$moreclass:"").'"');
  3315. }
  3316. /**
  3317. * Show top arrow logo
  3318. *
  3319. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3320. * @param int $selected Selected
  3321. * @param string $moreclass Add more CSS classes
  3322. * @return string Return img tag
  3323. */
  3324. function img_up($titlealt = 'default', $selected = 0, $moreclass='')
  3325. {
  3326. global $conf, $langs;
  3327. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  3328. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass?" ".$moreclass:"").'"');
  3329. }
  3330. /**
  3331. * Show left arrow logo
  3332. *
  3333. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3334. * @param int $selected Selected
  3335. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3336. * @return string Return img tag
  3337. */
  3338. function img_left($titlealt = 'default', $selected = 0, $moreatt='')
  3339. {
  3340. global $conf, $langs;
  3341. if ($titlealt == 'default') $titlealt = $langs->trans('Left');
  3342. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3343. }
  3344. /**
  3345. * Show right arrow logo
  3346. *
  3347. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3348. * @param int $selected Selected
  3349. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3350. * @return string Return img tag
  3351. */
  3352. function img_right($titlealt = 'default', $selected = 0, $moreatt='')
  3353. {
  3354. global $conf, $langs;
  3355. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  3356. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3357. }
  3358. /**
  3359. * Show tick logo if allowed
  3360. *
  3361. * @param string $allow Allow
  3362. * @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.
  3363. * @return string Return img tag
  3364. */
  3365. function img_allow($allow, $titlealt = 'default')
  3366. {
  3367. global $conf, $langs;
  3368. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  3369. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  3370. return '-';
  3371. }
  3372. /**
  3373. * Return image of a credit card according to its brand name
  3374. *
  3375. * @param string $brand Brand name of credit card
  3376. * @return string Return img tag
  3377. */
  3378. function img_credit_card($brand)
  3379. {
  3380. if ($brand == 'Visa') {$brand='cc-visa';}
  3381. elseif ($brand == 'MasterCard') {$brand='cc-mastercard';}
  3382. elseif ($brand == 'American Express') {$brand='cc-amex';}
  3383. elseif ($brand == 'Discover') {$brand='cc-discover';}
  3384. elseif ($brand == 'JCB') {$brand='cc-jcb';}
  3385. elseif ($brand == 'Diners Club') {$brand='cc-diners-club';}
  3386. elseif (! in_array($brand, array('cc-visa','cc-mastercard','cc-amex','cc-discover','cc-jcb','cc-diners-club'))) {$brand='credit-card';}
  3387. return '<span class="fa fa-'.$brand.' fa-2x fa-fw"></span>';
  3388. }
  3389. /**
  3390. * Show MIME img of a file
  3391. *
  3392. * @param string $file Filename
  3393. * @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.
  3394. * @param string $morecss More css
  3395. * @return string Return img tag
  3396. */
  3397. function img_mime($file, $titlealt = '', $morecss='')
  3398. {
  3399. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3400. $mimetype = dol_mimetype($file, '', 1);
  3401. $mimeimg = dol_mimetype($file, '', 2);
  3402. $mimefa = dol_mimetype($file, '', 4);
  3403. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  3404. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3405. return '<i class="fa fa-'.$mimefa.' paddingright"></i>';
  3406. }
  3407. /**
  3408. * Show phone logo.
  3409. * Use img_picto instead.
  3410. *
  3411. * @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.
  3412. * @param int $option Option
  3413. * @return string Return img tag
  3414. * @deprecated
  3415. * @see img_picto
  3416. */
  3417. function img_phone($titlealt = 'default', $option = 0)
  3418. {
  3419. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  3420. global $conf,$langs;
  3421. if ($titlealt == 'default') $titlealt = $langs->trans('Call');
  3422. if ($option == 1) $img = 'call';
  3423. else $img = 'call_out';
  3424. return img_picto($titlealt, $img);
  3425. }
  3426. /**
  3427. * Show search logo
  3428. *
  3429. * @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.
  3430. * @param string $other Add more attributes on img
  3431. * @return string Retourne tag img
  3432. */
  3433. function img_search($titlealt = 'default', $other = '')
  3434. {
  3435. global $conf, $langs;
  3436. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3437. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3438. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3439. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3440. return $input;
  3441. }
  3442. /**
  3443. * Show search logo
  3444. *
  3445. * @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.
  3446. * @param string $other Add more attributes on img
  3447. * @return string Retourne tag img
  3448. */
  3449. function img_searchclear($titlealt = 'default', $other = '')
  3450. {
  3451. global $conf, $langs;
  3452. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3453. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3454. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3455. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3456. return $input;
  3457. }
  3458. /**
  3459. * Show information for admin users or standard users
  3460. *
  3461. * @param string $text Text info
  3462. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3463. * @param int $nodiv No div
  3464. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'xxx'=Other
  3465. * @param string $morecss More CSS
  3466. * @return string String with info text
  3467. */
  3468. function info_admin($text, $infoonimgalt = 0, $nodiv=0, $admin='1', $morecss='')
  3469. {
  3470. global $conf, $langs;
  3471. if ($infoonimgalt)
  3472. {
  3473. return img_picto($text, 'info', 'class="hideonsmartphone'.($morecss?' '.$morecss:'').'"');
  3474. }
  3475. 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>');
  3476. }
  3477. /**
  3478. * Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
  3479. * On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
  3480. * Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
  3481. * renvoyer leur erreur par l'intermediaire de leur propriete "error".
  3482. *
  3483. * @param DoliDB $db Database handler
  3484. * @param mixed $error String or array of errors strings to show
  3485. * @param array $errors Array of errors
  3486. * @return void
  3487. * @see dol_htmloutput_errors
  3488. */
  3489. function dol_print_error($db='',$error='',$errors=null)
  3490. {
  3491. global $conf,$langs,$argv;
  3492. global $dolibarr_main_prod;
  3493. $out = '';
  3494. $syslog = '';
  3495. // Si erreur intervenue avant chargement langue
  3496. if (! $langs)
  3497. {
  3498. require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
  3499. $langs = new Translate('', $conf);
  3500. $langs->load("main");
  3501. }
  3502. $langs->load("main");
  3503. $langs->load("errors");
  3504. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3505. {
  3506. $out.=$langs->trans("DolibarrHasDetectedError").".<br>\n";
  3507. 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";
  3508. $out.=$langs->trans("InformationToHelpDiagnose").":<br>\n";
  3509. $out.="<b>".$langs->trans("Date").":</b> ".dol_print_date(time(),'dayhourlog')."<br>\n";
  3510. $out.="<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";
  3511. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  3512. if (function_exists("phpversion"))
  3513. {
  3514. $out.="<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  3515. }
  3516. $out.="<b>".$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";
  3517. if (function_exists("php_uname"))
  3518. {
  3519. $out.="<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  3520. }
  3521. $out.="<b>".$langs->trans("UserAgent").":</b> ".$_SERVER["HTTP_USER_AGENT"]."<br>\n";
  3522. $out.="<br>\n";
  3523. $out.="<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"],ENT_COMPAT,'UTF-8')."<br>\n";
  3524. $out.="<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"])?dol_htmlentities($_SERVER["HTTP_REFERER"],ENT_COMPAT,'UTF-8'):'')."<br>\n";
  3525. $out.="<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu)?$conf->standard_menu:'')."<br>\n";
  3526. $out.="<br>\n";
  3527. $syslog.="url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  3528. $syslog.=", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  3529. }
  3530. else // Mode CLI
  3531. {
  3532. $out.='> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  3533. $syslog.="pid=".dol_getmypid();
  3534. }
  3535. if (is_object($db))
  3536. {
  3537. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3538. {
  3539. $out.="<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  3540. $out.="<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror()?dol_escape_htmltag($db->lastqueryerror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3541. $out.="<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno()?dol_escape_htmltag($db->lasterrno()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3542. $out.="<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror()?dol_escape_htmltag($db->lasterror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3543. $out.="<br>\n";
  3544. }
  3545. else // Mode CLI
  3546. {
  3547. // No dol_escape_htmltag for output, we are in CLI mode
  3548. $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  3549. $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3550. $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3551. $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3552. }
  3553. $syslog.=", sql=".$db->lastquery();
  3554. $syslog.=", db_error=".$db->lasterror();
  3555. }
  3556. if ($error || $errors)
  3557. {
  3558. $langs->load("errors");
  3559. // Merge all into $errors array
  3560. if (is_array($error) && is_array($errors)) $errors=array_merge($error,$errors);
  3561. elseif (is_array($error)) $errors=$error;
  3562. elseif (is_array($errors)) $errors=array_merge(array($error),$errors);
  3563. else $errors=array_merge(array($error));
  3564. foreach($errors as $msg)
  3565. {
  3566. if (empty($msg)) continue;
  3567. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3568. {
  3569. $out.="<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n" ;
  3570. }
  3571. else // Mode CLI
  3572. {
  3573. $out.='> '.$langs->transnoentities("Message").":\n".$msg."\n" ;
  3574. }
  3575. $syslog.=", msg=".$msg;
  3576. }
  3577. }
  3578. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  3579. {
  3580. xdebug_print_function_stack();
  3581. $out.='<b>XDebug informations:</b>'."<br>\n";
  3582. $out.='File: '.xdebug_call_file()."<br>\n";
  3583. $out.='Line: '.xdebug_call_line()."<br>\n";
  3584. $out.='Function: '.xdebug_call_function()."<br>\n";
  3585. $out.="<br>\n";
  3586. }
  3587. if (empty($dolibarr_main_prod)) print $out;
  3588. else
  3589. {
  3590. print $langs->trans("DolibarrHasDetectedError").'. ';
  3591. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  3592. define("MAIN_CORE_ERROR", 1);
  3593. }
  3594. //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.';
  3595. dol_syslog("Error ".$syslog, LOG_ERR);
  3596. }
  3597. /**
  3598. * Show a public email and error code to contact if technical error
  3599. *
  3600. * @param string $prefixcode Prefix of public error code
  3601. * @param string $errormessage Complete error message
  3602. * @param array $errormessages Array of error messages
  3603. * @param string $morecss More css
  3604. * @param string $email Email
  3605. * @return void
  3606. */
  3607. function dol_print_error_email($prefixcode, $errormessage='', $errormessages=array(), $morecss='error', $email='')
  3608. {
  3609. global $langs,$conf;
  3610. if (empty($email)) $email=$conf->global->MAIN_INFO_SOCIETE_MAIL;
  3611. $langs->load("errors");
  3612. $now=dol_now();
  3613. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  3614. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now,'%Y%m%d'));
  3615. if ($errormessage) print '<br><br>'.$errormessage;
  3616. if (is_array($errormessages) && count($errormessages))
  3617. {
  3618. foreach($errormessages as $mesgtoshow)
  3619. {
  3620. print '<br><br>'.$mesgtoshow;
  3621. }
  3622. }
  3623. print '</div></div>';
  3624. }
  3625. /**
  3626. * Show title line of an array
  3627. *
  3628. * @param string $name Label of field
  3629. * @param string $file Url used when we click on sort picto
  3630. * @param string $field Field to use for new sorting
  3631. * @param string $begin ("" by defaut)
  3632. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3633. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  3634. * @param string $sortfield Current field used to sort
  3635. * @param string $sortorder Current sort order
  3636. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  3637. * @param string $tooltip Tooltip
  3638. * @return void
  3639. */
  3640. function print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="")
  3641. {
  3642. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip);
  3643. }
  3644. /**
  3645. * Get title line of an array
  3646. *
  3647. * @param string $name Translation key of field
  3648. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  3649. * @param string $file Url used when we click on sort picto
  3650. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  3651. * @param string $begin ("" by defaut)
  3652. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3653. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  3654. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  3655. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  3656. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  3657. * @param string $disablesortlink 1=Disable sort link
  3658. * @param string $tooltip Tooltip
  3659. * @return string
  3660. */
  3661. function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $disablesortlink=0, $tooltip='')
  3662. {
  3663. global $conf, $langs, $form;
  3664. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  3665. $sortorder=strtoupper($sortorder);
  3666. $out='';
  3667. $sortimg='';
  3668. $tag='th';
  3669. if ($thead==2) $tag='div';
  3670. $tmpsortfield=explode(',',$sortfield);
  3671. $sortfield1=trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  3672. $tmpfield=explode(',',$field);
  3673. $field1=trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  3674. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  3675. // If field is used as sort criteria we use a specific css class liste_titre_sel
  3676. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  3677. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./","",$field1))) $out.= '<'.$tag.' class="'.$prefix.'liste_titre_sel" '. $moreattrib.'>';
  3678. else $out.= '<'.$tag.' class="'.$prefix.'liste_titre" '. $moreattrib.'>';
  3679. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3680. {
  3681. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  3682. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  3683. $options=preg_replace('/&+/i','&',$options);
  3684. if (! preg_match('/^&/',$options)) $options='&'.$options;
  3685. $sortordertouseinlink='';
  3686. if ($field1 != $sortfield1) // We are on another field than current sorted field
  3687. {
  3688. if (preg_match('/^DESC/i', $sortorder))
  3689. {
  3690. $sortordertouseinlink.=str_repeat('desc,', count(explode(',',$field)));
  3691. }
  3692. else // We reverse the var $sortordertouseinlink
  3693. {
  3694. $sortordertouseinlink.=str_repeat('asc,', count(explode(',',$field)));
  3695. }
  3696. }
  3697. else // We are on field that is the first current sorting criteria
  3698. {
  3699. if (preg_match('/^ASC/i', $sortorder)) // We reverse the var $sortordertouseinlink
  3700. {
  3701. $sortordertouseinlink.=str_repeat('desc,', count(explode(',',$field)));
  3702. }
  3703. else
  3704. {
  3705. $sortordertouseinlink.=str_repeat('asc,', count(explode(',',$field)));
  3706. }
  3707. }
  3708. $sortordertouseinlink=preg_replace('/,$/', '', $sortordertouseinlink);
  3709. $out.= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'">';
  3710. }
  3711. if ($tooltip) $out.=$form->textwithpicto($langs->trans($name), $langs->trans($tooltip));
  3712. else $out.=$langs->trans($name);
  3713. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3714. {
  3715. $out.='</a>';
  3716. }
  3717. if (empty($thead) && $field) // If this is a sort field
  3718. {
  3719. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  3720. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  3721. $options=preg_replace('/&+/i','&',$options);
  3722. if (! preg_match('/^&/',$options)) $options='&'.$options;
  3723. if (! $sortorder || $field1 != $sortfield1)
  3724. {
  3725. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3726. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3727. }
  3728. else
  3729. {
  3730. if (preg_match('/^DESC/', $sortorder)) {
  3731. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3732. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3733. $sortimg.= '<span class="nowrap">'.img_up("Z-A",0).'</span>';
  3734. }
  3735. if (preg_match('/^ASC/', $sortorder)) {
  3736. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3737. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3738. $sortimg.= '<span class="nowrap">'.img_down("A-Z",0).'</span>';
  3739. }
  3740. }
  3741. }
  3742. $out.=$sortimg;
  3743. $out.='</'.$tag.'>';
  3744. return $out;
  3745. }
  3746. /**
  3747. * Show a title.
  3748. *
  3749. * @param string $title Title to show
  3750. * @return string Title to show
  3751. * @deprecated Use load_fiche_titre instead
  3752. * @see load_fiche_titre
  3753. */
  3754. function print_titre($title)
  3755. {
  3756. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  3757. print '<div class="titre">'.$title.'</div>';
  3758. }
  3759. /**
  3760. * Show a title with picto
  3761. *
  3762. * @param string $title Title to show
  3763. * @param string $mesg Added message to show on right
  3764. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3765. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3766. * @param int $id To force an id on html objects
  3767. * @return void
  3768. * @deprecated Use print load_fiche_titre instead
  3769. */
  3770. function print_fiche_titre($title, $mesg='', $picto='title_generic.png', $pictoisfullpath=0, $id='')
  3771. {
  3772. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3773. }
  3774. /**
  3775. * Load a title with picto
  3776. *
  3777. * @param string $titre Title to show
  3778. * @param string $morehtmlright Added message to show on right
  3779. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3780. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3781. * @param string $id To force an id on html objects
  3782. * @param string $morecssontable More css on table
  3783. * @param string $morehtmlcenter Added message to show on center
  3784. * @return string
  3785. * @see print_barre_liste
  3786. */
  3787. function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
  3788. {
  3789. global $conf;
  3790. $return='';
  3791. if ($picto == 'setup') $picto='title_generic.png';
  3792. $return.= "\n";
  3793. $return.= '<table '.($id?'id="'.$id.'" ':'').'summary="" class="centpercent notopnoleftnoright'.($morecssontable?' '.$morecssontable:'').'" style="margin-bottom: 2px;"><tr>';
  3794. if ($picto) $return.= '<td class="nobordernopadding widthpictotitle opacityhigh" valign="middle">'.img_picto('',$picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  3795. $return.= '<td class="nobordernopadding" valign="middle">';
  3796. $return.= '<div class="titre">'.$titre.'</div>';
  3797. $return.= '</td>';
  3798. if (dol_strlen($morehtmlcenter))
  3799. {
  3800. $return.= '<td class="nobordernopadding" align="center" valign="middle">'.$morehtmlcenter.'</td>';
  3801. }
  3802. if (dol_strlen($morehtmlright))
  3803. {
  3804. $return.= '<td class="nobordernopadding titre_right wordbreak" align="right" valign="middle">'.$morehtmlright.'</td>';
  3805. }
  3806. $return.= '</tr></table>'."\n";
  3807. return $return;
  3808. }
  3809. /**
  3810. * Print a title with navigation controls for pagination
  3811. *
  3812. * @param string $titre Title to show (required)
  3813. * @param int $page Numero of page to show in navigation links (required)
  3814. * @param string $file Url of page (required)
  3815. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  3816. * @param string $sortfield Field to sort on ('' by default)
  3817. * @param string $sortorder Order to sort ('' by default)
  3818. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  3819. * @param int $num Number of records found by select with limit+1
  3820. * @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.
  3821. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3822. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3823. * @param string $morehtmlright More html to show
  3824. * @param string $morecss More css to the table
  3825. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  3826. * @param int $hideselectlimit Force to hide select limit
  3827. * @param int $hidenavigation Force to hide all navigation tools
  3828. * @return void
  3829. */
  3830. 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)
  3831. {
  3832. global $conf,$langs;
  3833. $savlimit = $limit;
  3834. $savtotalnboflines = $totalnboflines;
  3835. $totalnboflines=abs($totalnboflines);
  3836. if ($picto == 'setup') $picto='title_setup.png';
  3837. if (($conf->browser->name == 'ie') && $picto=='title_generic.png') $picto='title.gif';
  3838. if ($limit < 0) $limit = $conf->liste_limit;
  3839. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  3840. {
  3841. $nextpage = 1;
  3842. }
  3843. else
  3844. {
  3845. $nextpage = 0;
  3846. }
  3847. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  3848. print "\n";
  3849. print "<!-- Begin title '".$titre."' -->\n";
  3850. print '<table width="100%" border="0" class="notopnoleftnoright'.($morecss?' '.$morecss:'').'" style="margin-bottom: 6px;"><tr>';
  3851. // Left
  3852. //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
  3853. print '<td class="nobordernopadding valignmiddle">';
  3854. if ($picto && $titre) print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh widthpictotitle" id="pictotitle"', $pictoisfullpath);
  3855. print '<div class="titre inline-block">'.$titre;
  3856. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print ' ('.$totalnboflines.')';
  3857. print '</div></td>';
  3858. // Center
  3859. if ($morehtmlcenter)
  3860. {
  3861. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3862. }
  3863. // Right
  3864. print '<td class="nobordernopadding valignmiddle" align="right">';
  3865. if ($sortfield) $options .= "&sortfield=".urlencode($sortfield);
  3866. if ($sortorder) $options .= "&sortorder=".urlencode($sortorder);
  3867. // Show navigation bar
  3868. $pagelist = '';
  3869. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  3870. {
  3871. if ($totalnboflines) // If we know total nb of lines
  3872. {
  3873. // Define nb of extra page links before and after selected page + ... + first or last
  3874. $maxnbofpage=(empty($conf->dol_optimize_smallscreen) ? 4 : 1);
  3875. if ($limit > 0) $nbpages=ceil($totalnboflines/$limit);
  3876. else $nbpages=1;
  3877. $cpt=($page-$maxnbofpage);
  3878. if ($cpt < 0) { $cpt=0; }
  3879. if ($cpt>=1)
  3880. {
  3881. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  3882. if ($cpt > 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3883. else if ($cpt == 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  3884. }
  3885. do
  3886. {
  3887. if ($cpt==$page)
  3888. {
  3889. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1).'</span></li>';
  3890. }
  3891. else
  3892. {
  3893. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt+1).'</a></li>';
  3894. }
  3895. $cpt++;
  3896. }
  3897. while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage);
  3898. if ($cpt<$nbpages)
  3899. {
  3900. if ($cpt<$nbpages-2) $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3901. 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>';
  3902. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.($nbpages-1).$options.'">'.$nbpages.'</a></li>';
  3903. }
  3904. }
  3905. else
  3906. {
  3907. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1)."</li>";
  3908. }
  3909. }
  3910. 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
  3911. print '</td>';
  3912. print '</tr></table>'."\n";
  3913. print "<!-- End title -->\n\n";
  3914. }
  3915. /**
  3916. * Function to show navigation arrows into lists
  3917. *
  3918. * @param int $page Number of page
  3919. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  3920. * @param string $options Other url paramaters to propagate ("" by default, may include sortfield and sortorder)
  3921. * @param integer $nextpage Do we show a next page button
  3922. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  3923. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  3924. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  3925. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  3926. * @param int $hideselectlimit Force to hide select limit
  3927. * @return void
  3928. */
  3929. function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0)
  3930. {
  3931. global $conf, $langs;
  3932. print '<div class="pagination"><ul>';
  3933. if ((int) $limit >= 0 && empty($hideselectlimit))
  3934. {
  3935. $pagesizechoices='10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  3936. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  3937. //$pagesizechoices.=',2:2';
  3938. if (! empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices=$conf->global->MAIN_PAGESIZE_CHOICES;
  3939. print '<li class="pagination">';
  3940. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  3941. $tmpchoice=explode(',',$pagesizechoices);
  3942. $tmpkey=$limit.':'.$limit;
  3943. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3944. $tmpkey=$conf->liste_limit.':'.$conf->liste_limit;
  3945. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3946. asort($tmpchoice, SORT_NUMERIC);
  3947. $found=false;
  3948. foreach($tmpchoice as $val)
  3949. {
  3950. $selected='';
  3951. $tmp=explode(':',$val);
  3952. $key=$tmp[0];
  3953. $val=$tmp[1];
  3954. if ($key != '' && $val != '')
  3955. {
  3956. if ((int) $key == (int) $limit)
  3957. {
  3958. $selected = ' selected="selected"';
  3959. $found = true;
  3960. }
  3961. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  3962. }
  3963. }
  3964. print '</select>';
  3965. if ($conf->use_javascript_ajax)
  3966. {
  3967. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  3968. <script type="text/javascript">
  3969. jQuery(document).ready(function () {
  3970. jQuery(".selectlimit").change(function() {
  3971. console.log("Change limit. Send submit");
  3972. $(this).parents(\'form:first\').submit();
  3973. });
  3974. });
  3975. </script>
  3976. ';
  3977. }
  3978. print '</li>';
  3979. }
  3980. if ($page > 0)
  3981. {
  3982. 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>';
  3983. }
  3984. if ($betweenarrows)
  3985. {
  3986. print $betweenarrows;
  3987. }
  3988. if ($nextpage > 0)
  3989. {
  3990. 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>';
  3991. }
  3992. if ($afterarrows)
  3993. {
  3994. print '<li class="paginationafterarrows">';
  3995. print $afterarrows;
  3996. print '</li>';
  3997. }
  3998. print '</ul></div>'."\n";
  3999. }
  4000. /**
  4001. * Return a string with VAT rate label formated for view output
  4002. * Used into pdf and HTML pages
  4003. *
  4004. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4005. * @param boolean $addpercent Add a percent % sign in output
  4006. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4007. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4008. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4009. */
  4010. function vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
  4011. {
  4012. $morelabel='';
  4013. if (preg_match('/%/',$rate))
  4014. {
  4015. $rate=str_replace('%','',$rate);
  4016. $addpercent=true;
  4017. }
  4018. if (preg_match('/\((.*)\)/',$rate,$reg))
  4019. {
  4020. $morelabel=' ('.$reg[1].')';
  4021. $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate);
  4022. }
  4023. if (preg_match('/\*/',$rate))
  4024. {
  4025. $rate=str_replace('*','',$rate);
  4026. $info_bits |= 1;
  4027. }
  4028. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4029. if (! preg_match('/\//', $rate)) $ret=price($rate,0,'',0,0).($addpercent?'%':'');
  4030. else
  4031. {
  4032. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4033. $ret=$rate.($addpercent?'%':'');
  4034. }
  4035. if (($info_bits & 1) && $usestarfornpr >= 0) $ret.=' *';
  4036. $ret.=$morelabel;
  4037. return $ret;
  4038. }
  4039. /**
  4040. * Function to format a value into an amount for visual output
  4041. * Function used into PDF and HTML pages
  4042. *
  4043. * @param float $amount Amount to format
  4044. * @param integer $form Type of format, HTML or not (not by default)
  4045. * @param Translate $outlangs Object langs for output
  4046. * @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.
  4047. * @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)
  4048. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4049. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4050. * @return string Chaine avec montant formate
  4051. *
  4052. * @see price2num Revert function of price
  4053. */
  4054. function price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
  4055. {
  4056. global $langs,$conf;
  4057. // Clean parameters
  4058. if (empty($amount)) $amount=0; // To have a numeric value if amount not defined or = ''
  4059. $amount = (is_numeric($amount)?$amount:0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4060. if ($rounding < 0) $rounding=min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
  4061. $nbdecimal=$rounding;
  4062. // Output separators by default (french)
  4063. $dec=','; $thousand=' ';
  4064. // If $outlangs not forced, we use use language
  4065. if (! is_object($outlangs)) $outlangs=$langs;
  4066. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4067. if ($outlangs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$outlangs->transnoentitiesnoconv("SeparatorThousand");
  4068. if ($thousand == 'None') $thousand='';
  4069. else if ($thousand == 'Space') $thousand=' ';
  4070. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4071. //print "amount=".$amount."-";
  4072. $amount = str_replace(',','.',$amount); // should be useless
  4073. //print $amount."-";
  4074. $datas = explode('.',$amount);
  4075. $decpart = isset($datas[1])?$datas[1]:'';
  4076. $decpart = preg_replace('/0+$/i','',$decpart); // Supprime les 0 de fin de partie decimale
  4077. //print "decpart=".$decpart."<br>";
  4078. $end='';
  4079. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4080. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal=dol_strlen($decpart);
  4081. // Si on depasse max
  4082. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  4083. {
  4084. $nbdecimal=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4085. if (preg_match('/\.\.\./i',$conf->global->MAIN_MAX_DECIMALS_SHOWN))
  4086. {
  4087. // Si un affichage est tronque, on montre des ...
  4088. $end='...';
  4089. }
  4090. }
  4091. // If force rounding
  4092. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  4093. // Format number
  4094. $output=number_format($amount, $nbdecimal, $dec, $thousand);
  4095. if ($form)
  4096. {
  4097. $output=preg_replace('/\s/','&nbsp;',$output);
  4098. $output=preg_replace('/\'/','&#039;',$output);
  4099. }
  4100. // Add symbol of currency if requested
  4101. $cursymbolbefore=$cursymbolafter='';
  4102. if ($currency_code)
  4103. {
  4104. if ($currency_code == 'auto') $currency_code=$conf->currency;
  4105. $listofcurrenciesbefore=array('USD','GBP','AUD','MXN','PEN','CNY');
  4106. if (in_array($currency_code,$listofcurrenciesbefore)) $cursymbolbefore.=$outlangs->getCurrencySymbol($currency_code);
  4107. else
  4108. {
  4109. $tmpcur=$outlangs->getCurrencySymbol($currency_code);
  4110. $cursymbolafter.=($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4111. }
  4112. }
  4113. $output=$cursymbolbefore.$output.$end.($cursymbolafter?' ':'').$cursymbolafter;
  4114. return $output;
  4115. }
  4116. /**
  4117. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4118. * Function to use on each input amount before any numeric test or database insert
  4119. *
  4120. * @param float $amount Amount to convert/clean
  4121. * @param string $rounding ''=No rounding
  4122. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4123. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4124. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4125. * Numeric = Nb of digits for rounding
  4126. * @param int $alreadysqlnb Put 1 if you know that content is already universal format number
  4127. * @return string Amount with universal numeric format (Example: '99.99999') or unchanged text if conversion fails. If amount is null or '', it returns ''.
  4128. *
  4129. * @see price Opposite function of price2num
  4130. */
  4131. function price2num($amount,$rounding='',$alreadysqlnb=0)
  4132. {
  4133. global $langs,$conf;
  4134. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4135. // Numbers must be '1234.56'
  4136. // Decimal delimiter for PHP and database SQL requests must be '.'
  4137. $dec=','; $thousand=' ';
  4138. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$langs->transnoentitiesnoconv("SeparatorDecimal");
  4139. if ($langs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$langs->transnoentitiesnoconv("SeparatorThousand");
  4140. if ($thousand == 'None') $thousand='';
  4141. elseif ($thousand == 'Space') $thousand=' ';
  4142. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4143. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4144. if ($alreadysqlnb != 1) // If not a PHP number or unknown, we change format
  4145. {
  4146. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4147. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4148. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4149. if (is_numeric($amount))
  4150. {
  4151. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4152. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4153. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  4154. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  4155. $amount=number_format($amount,$nbofdec,$dec,$thousand);
  4156. }
  4157. //print "QQ".$amount.'<br>';
  4158. // Now make replace (the main goal of function)
  4159. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  4160. $amount=str_replace(' ','',$amount); // To avoid spaces
  4161. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4162. $amount=str_replace($dec,'.',$amount);
  4163. }
  4164. // Now, make a rounding if required
  4165. if ($rounding)
  4166. {
  4167. $nbofdectoround='';
  4168. if ($rounding == 'MU') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_UNIT;
  4169. elseif ($rounding == 'MT') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_TOT;
  4170. elseif ($rounding == 'MS') $nbofdectoround=empty($conf->global->MAIN_MAX_DECIMALS_STOCK)?5:$conf->global->MAIN_MAX_DECIMALS_STOCK;
  4171. elseif (is_numeric($rounding)) $nbofdectoround=$rounding;
  4172. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  4173. if (dol_strlen($nbofdectoround)) $amount = round($amount,$nbofdectoround); // $nbofdectoround can be 0.
  4174. else return 'ErrorBadParameterProvidedToFunction';
  4175. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4176. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4177. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4178. if (is_numeric($amount))
  4179. {
  4180. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4181. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4182. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  4183. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  4184. $amount=number_format($amount,min($nbofdec,$nbofdectoround),$dec,$thousand); // Convert amount to format with dolibarr dec and thousand
  4185. }
  4186. //print "TT".$amount.'<br>';
  4187. // Always make replace because each math function (like round) replace
  4188. // with local values and we want a number that has a SQL string format x.y
  4189. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  4190. $amount=str_replace(' ','',$amount); // To avoid spaces
  4191. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4192. $amount=str_replace($dec,'.',$amount);
  4193. }
  4194. return $amount;
  4195. }
  4196. /**
  4197. * Output a dimension with best unit
  4198. *
  4199. * @param float $dimension Dimension
  4200. * @param int $unit Unit of dimension (0, -3, ...)
  4201. * @param string $type 'weight', 'volume', ...
  4202. * @param Translate $outputlangs Translate language object
  4203. * @param int $round -1 = non rounding, x = number of decimal
  4204. * @param string $forceunitoutput 'no' or numeric (-3, -6, ...) compared to $unit
  4205. * @return string String to show dimensions
  4206. */
  4207. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no')
  4208. {
  4209. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4210. if (($forceunitoutput == 'no' && $dimension < 1/10000) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  4211. {
  4212. $dimension = $dimension * 1000000;
  4213. $unit = $unit - 6;
  4214. }
  4215. elseif (($forceunitoutput == 'no' && $dimension < 1/10) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  4216. {
  4217. $dimension = $dimension * 1000;
  4218. $unit = $unit - 3;
  4219. }
  4220. elseif (($forceunitoutput == 'no' && $dimension > 100000000) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  4221. {
  4222. $dimension = $dimension / 1000000;
  4223. $unit = $unit + 6;
  4224. }
  4225. elseif (($forceunitoutput == 'no' && $dimension > 100000) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  4226. {
  4227. $dimension = $dimension / 1000;
  4228. $unit = $unit + 3;
  4229. }
  4230. $ret=price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type);
  4231. return $ret;
  4232. }
  4233. /**
  4234. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4235. * Note: This function applies same rules than get_default_tva
  4236. *
  4237. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4238. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4239. * @param Societe $thirdparty_buyer Object of buying third party
  4240. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4241. * @param int $vatnpr If vat rate is NPR or not
  4242. * @return mixed 0 if not found, localtax rate if found
  4243. * @see get_default_tva
  4244. */
  4245. function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
  4246. {
  4247. global $db, $conf, $mysoc;
  4248. if (empty($thirdparty_seller) || ! is_object($thirdparty_seller)) $thirdparty_seller=$mysoc;
  4249. 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);
  4250. $vatratecleaned = $vatrate;
  4251. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4252. {
  4253. $vatratecleaned = trim($reg[1]);
  4254. $vatratecode = $reg[2];
  4255. }
  4256. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4257. {
  4258. return 0;
  4259. }*/
  4260. // Some test to guess with no need to make database access
  4261. if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4262. {
  4263. if ($local == 1)
  4264. {
  4265. if (! $mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  4266. if ($thirdparty_seller->id == $mysoc->id)
  4267. {
  4268. if (! $thirdparty_buyer->localtax1_assuj) return 0;
  4269. }
  4270. else
  4271. {
  4272. if (! $thirdparty_seller->localtax1_assuj) return 0;
  4273. }
  4274. }
  4275. if ($local == 2)
  4276. {
  4277. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4278. if (! $mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0.
  4279. if ($thirdparty_seller->id == $mysoc->id)
  4280. {
  4281. if (! $thirdparty_buyer->localtax2_assuj) return 0;
  4282. }
  4283. else
  4284. {
  4285. if (! $thirdparty_seller->localtax2_assuj) return 0;
  4286. }
  4287. }
  4288. }
  4289. else
  4290. {
  4291. if ($local == 1 && ! $thirdparty_seller->localtax1_assuj) return 0;
  4292. if ($local == 2 && ! $thirdparty_seller->localtax2_assuj) return 0;
  4293. }
  4294. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4295. if (in_array($mysoc->country_code, array('ES')))
  4296. {
  4297. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4298. }
  4299. // Search local taxes
  4300. if (! empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  4301. {
  4302. if ($local==1)
  4303. {
  4304. if ($thirdparty_seller != $mysoc)
  4305. {
  4306. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4307. {
  4308. return $thirdparty_seller->localtax1_value;
  4309. }
  4310. }
  4311. else // i am the seller
  4312. {
  4313. if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4314. {
  4315. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4316. }
  4317. }
  4318. }
  4319. if ($local==2)
  4320. {
  4321. if ($thirdparty_seller != $mysoc)
  4322. {
  4323. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4324. // TODO We should also return value defined on thirdparty only if defined
  4325. {
  4326. return $thirdparty_seller->localtax2_value;
  4327. }
  4328. }
  4329. else // i am the seller
  4330. {
  4331. if (in_array($mysoc->country_code, array('ES')))
  4332. {
  4333. return $thirdparty_buyer->localtax2_value;
  4334. }
  4335. else
  4336. {
  4337. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4338. }
  4339. }
  4340. }
  4341. }
  4342. // By default, search value of local tax on line of common tax
  4343. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4344. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4345. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$thirdparty_seller->country_code."'";
  4346. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4347. if ($vatratecode) $sql.= " AND t.code ='".$vatratecode."'"; // If we have the code, we use it in priority
  4348. else $sql.= " AND t.recuperableonly ='".$vatnpr."'";
  4349. dol_syslog("get_localtax", LOG_DEBUG);
  4350. $resql=$db->query($sql);
  4351. if ($resql)
  4352. {
  4353. $obj = $db->fetch_object($resql);
  4354. if ($local==1) return $obj->localtax1;
  4355. elseif ($local==2) return $obj->localtax2;
  4356. }
  4357. return 0;
  4358. }
  4359. /**
  4360. * Return true if LocalTax (1 or 2) is unique.
  4361. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  4362. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  4363. *
  4364. * @param int $local Local tax to test (1 or 2)
  4365. * @return boolean True if LocalTax have multiple values, False if not
  4366. */
  4367. function isOnlyOneLocalTax($local)
  4368. {
  4369. $tax=get_localtax_by_third($local);
  4370. $valors=explode(":", $tax);
  4371. if (count($valors)>1)
  4372. {
  4373. return false;
  4374. }
  4375. else
  4376. {
  4377. return true;
  4378. }
  4379. }
  4380. /**
  4381. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  4382. *
  4383. * @param int $local LocalTax to get
  4384. * @return number Values of localtax
  4385. */
  4386. function get_localtax_by_third($local)
  4387. {
  4388. global $db, $mysoc;
  4389. $sql ="SELECT t.localtax1, t.localtax2 ";
  4390. $sql.=" FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  4391. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND t.active = 1 AND t.taux=(";
  4392. $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";
  4393. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND tt.active = 1";
  4394. $sql.=" )";
  4395. $resql=$db->query($sql);
  4396. if ($resql)
  4397. {
  4398. $obj = $db->fetch_object($resql);
  4399. if ($local==1) return $obj->localtax1;
  4400. elseif ($local==2) return $obj->localtax2;
  4401. }
  4402. return 0;
  4403. }
  4404. /**
  4405. * Get vat main information from Id.
  4406. * You can call getLocalTaxesFromRate after to get other fields.
  4407. *
  4408. * @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.
  4409. * @param Societe $buyer Company object
  4410. * @param Societe $seller Company object
  4411. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  4412. * @return array array('rowid'=> , 'code'=> ...)
  4413. * @see getLocalTaxesFromRate
  4414. */
  4415. function getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
  4416. {
  4417. global $db, $mysoc;
  4418. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  4419. // Search local taxes
  4420. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
  4421. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4422. if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate;
  4423. else
  4424. {
  4425. $vatratecleaned = $vatrate;
  4426. $vatratecode = '';
  4427. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4428. {
  4429. $vatratecleaned = $reg[1];
  4430. $vatratecode = $reg[2];
  4431. }
  4432. $sql.=", ".MAIN_DB_PREFIX."c_country as c";
  4433. /*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 ??
  4434. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";*/
  4435. $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
  4436. $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4437. if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'";
  4438. }
  4439. $resql=$db->query($sql);
  4440. if ($resql)
  4441. {
  4442. $obj = $db->fetch_object($resql);
  4443. 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);
  4444. else return array();
  4445. }
  4446. else dol_print_error($db);
  4447. return array();
  4448. }
  4449. /**
  4450. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  4451. * This does not take into account the seller setup if subject to vat or not, only country.
  4452. * TODO
  4453. * This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  4454. * Instead this function must be called when adding a line to get the array of localtax and type, and then
  4455. * provide it to the function calcul_price_total.
  4456. *
  4457. * @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.
  4458. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  4459. * @param Societe $buyer Company object
  4460. * @param Societe $seller Company object
  4461. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  4462. * @return array array(localtax_type1(1-6/0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  4463. * @see getTaxesFromId
  4464. */
  4465. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
  4466. {
  4467. global $db, $mysoc;
  4468. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  4469. // Search local taxes
  4470. $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
  4471. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4472. if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate;
  4473. else
  4474. {
  4475. $vatratecleaned = $vatrate;
  4476. $vatratecode = '';
  4477. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "x.x (yy)"
  4478. {
  4479. $vatratecleaned = $reg[1];
  4480. $vatratecode = $reg[2];
  4481. }
  4482. $sql.=", ".MAIN_DB_PREFIX."c_country as c";
  4483. 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 ??
  4484. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
  4485. $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4486. if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'";
  4487. }
  4488. $resql=$db->query($sql);
  4489. if ($resql)
  4490. {
  4491. $obj = $db->fetch_object($resql);
  4492. if ($local == 1)
  4493. {
  4494. return array($obj->localtax1_type, get_localtax($vatrate, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4495. }
  4496. elseif ($local == 2)
  4497. {
  4498. return array($obj->localtax2_type, get_localtax($vatrate, $local, $buyer, $seller),$obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4499. }
  4500. else
  4501. {
  4502. 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);
  4503. }
  4504. }
  4505. return 0;
  4506. }
  4507. /**
  4508. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  4509. * Function called by get_default_tva
  4510. *
  4511. * @param int $idprod Id of product or 0 if not a predefined product
  4512. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4513. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  4514. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  4515. * @see get_product_localtax_for_country
  4516. */
  4517. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice=0)
  4518. {
  4519. global $db,$conf,$mysoc;
  4520. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4521. $ret=0;
  4522. $found=0;
  4523. if ($idprod > 0)
  4524. {
  4525. // Load product
  4526. $product=new Product($db);
  4527. $result=$product->fetch($idprod);
  4528. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4529. {
  4530. if ($idprodfournprice > 0) // We want vat for product for a "supplier" object
  4531. {
  4532. $product->get_buyprice($idprodfournprice,0,0,0);
  4533. $ret=$product->vatrate_supplier;
  4534. if ($product->default_vat_code) $ret.=' ('.$product->default_vat_code.')';
  4535. }
  4536. else
  4537. {
  4538. $ret=$product->tva_tx; // Default vat of product we defined
  4539. if ($product->default_vat_code) $ret.=' ('.$product->default_vat_code.')';
  4540. }
  4541. $found=1;
  4542. }
  4543. else
  4544. {
  4545. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  4546. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  4547. }
  4548. }
  4549. if (! $found)
  4550. {
  4551. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  4552. {
  4553. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  4554. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  4555. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4556. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  4557. $sql.= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  4558. $sql.= $db->plimit(1);
  4559. $resql=$db->query($sql);
  4560. if ($resql)
  4561. {
  4562. $obj=$db->fetch_object($resql);
  4563. if ($obj)
  4564. {
  4565. $ret=$obj->vat_rate;
  4566. if ($obj->default_vat_code) $ret.=' ('.$obj->default_vat_code.')';
  4567. }
  4568. $db->free($sql);
  4569. }
  4570. else dol_print_error($db);
  4571. }
  4572. else $ret=$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  4573. }
  4574. dol_syslog("get_product_vat_for_country: ret=".$ret);
  4575. return $ret;
  4576. }
  4577. /**
  4578. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  4579. *
  4580. * @param int $idprod Id of product
  4581. * @param int $local 1 for localtax1, 2 for localtax 2
  4582. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4583. * @return int <0 if KO, Vat rate if OK
  4584. * @see get_product_vat_for_country
  4585. */
  4586. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  4587. {
  4588. global $db,$mysoc;
  4589. if (! class_exists('Product')) {
  4590. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4591. }
  4592. $ret=0;
  4593. $found=0;
  4594. if ($idprod > 0)
  4595. {
  4596. // Load product
  4597. $product=new Product($db);
  4598. $result=$product->fetch($idprod);
  4599. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4600. {
  4601. /* Not defined yet, so we don't use this
  4602. if ($local==1) $ret=$product->localtax1_tx;
  4603. elseif ($local==2) $ret=$product->localtax2_tx;
  4604. $found=1;
  4605. */
  4606. }
  4607. else
  4608. {
  4609. // TODO Read default product vat according to countrycode and product
  4610. }
  4611. }
  4612. if (! $found)
  4613. {
  4614. // If vat of product for the country not found or not defined, we return higher vat of country.
  4615. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  4616. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4617. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  4618. $sql.= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  4619. $sql.= $db->plimit(1);
  4620. $resql=$db->query($sql);
  4621. if ($resql)
  4622. {
  4623. $obj=$db->fetch_object($resql);
  4624. if ($obj)
  4625. {
  4626. if ($local==1) $ret=$obj->localtax1;
  4627. elseif ($local==2) $ret=$obj->localtax2;
  4628. }
  4629. }
  4630. else dol_print_error($db);
  4631. }
  4632. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  4633. return $ret;
  4634. }
  4635. /**
  4636. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  4637. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4638. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4639. * 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.
  4640. * 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
  4641. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  4642. * Sinon TVA proposee par defaut=0. Fin de regle.
  4643. *
  4644. * @param Societe $thirdparty_seller Objet societe vendeuse
  4645. * @param Societe $thirdparty_buyer Objet societe acheteuse
  4646. * @param int $idprod Id product
  4647. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  4648. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  4649. * @see get_default_npr, get_default_localtax
  4650. */
  4651. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  4652. {
  4653. global $conf;
  4654. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4655. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  4656. $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;
  4657. $seller_country_code = $thirdparty_seller->country_code;
  4658. $seller_in_cee = isInEEC($thirdparty_seller);
  4659. $buyer_country_code = $thirdparty_buyer->country_code;
  4660. $buyer_in_cee = isInEEC($thirdparty_buyer);
  4661. dol_syslog("get_default_tva: seller use vat=".$seller_use_vat.", seller country=".$seller_country_code.", seller in cee=".$seller_in_cee.", 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:''));
  4662. // 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)
  4663. // we use the buyer VAT.
  4664. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  4665. {
  4666. if ($seller_in_cee && $buyer_in_cee && ! $thirdparty_buyer->isACompany())
  4667. {
  4668. //print 'VATRULE 0';
  4669. return get_product_vat_for_country($idprod,$thirdparty_buyer,$idprodfournprice);
  4670. }
  4671. }
  4672. // If seller does not use VAT
  4673. if (! $seller_use_vat)
  4674. {
  4675. //print 'VATRULE 1';
  4676. return 0;
  4677. }
  4678. // 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.
  4679. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4680. if (($seller_country_code == $buyer_country_code)
  4681. || (in_array($seller_country_code,array('FR,MC')) && in_array($buyer_country_code,array('FR','MC')))) // Warning ->country_code not always defined
  4682. {
  4683. //print 'VATRULE 2';
  4684. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4685. }
  4686. // 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.
  4687. // Not supported
  4688. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  4689. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4690. if (($seller_in_cee && $buyer_in_cee))
  4691. {
  4692. $isacompany=$thirdparty_buyer->isACompany();
  4693. if ($isacompany)
  4694. {
  4695. //print 'VATRULE 3';
  4696. return 0;
  4697. }
  4698. else
  4699. {
  4700. //print 'VATRULE 4';
  4701. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4702. }
  4703. }
  4704. // Si (vendeur en France et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4705. if (! empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee) && !$thirdparty_buyer->isACompany())
  4706. {
  4707. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4708. }
  4709. // Sinon la TVA proposee par defaut=0. Fin de regle.
  4710. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  4711. //print 'VATRULE 5';
  4712. return 0;
  4713. }
  4714. /**
  4715. * Fonction qui renvoie si tva doit etre tva percue recuperable
  4716. *
  4717. * @param Societe $thirdparty_seller Thirdparty seller
  4718. * @param Societe $thirdparty_buyer Thirdparty buyer
  4719. * @param int $idprod Id product
  4720. * @param int $idprodfournprice Id supplier price for product
  4721. * @return float 0 or 1
  4722. * @see get_default_tva, get_default_localtax
  4723. */
  4724. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  4725. {
  4726. global $db;
  4727. if ($idprodfournprice > 0)
  4728. {
  4729. if (! class_exists('ProductFournisseur'))
  4730. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  4731. $prodprice = new ProductFournisseur($db);
  4732. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  4733. return $prodprice->fourn_tva_npr;
  4734. }
  4735. elseif ($idprod > 0)
  4736. {
  4737. if (! class_exists('Product'))
  4738. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4739. $prod = new Product($db);
  4740. $prod->fetch($idprod);
  4741. return $prod->tva_npr;
  4742. }
  4743. return 0;
  4744. }
  4745. /**
  4746. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4747. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4748. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4749. * Sinon TVA proposee par defaut=0. Fin de regle.
  4750. *
  4751. * @param Societe $thirdparty_seller Thirdparty seller
  4752. * @param Societe $thirdparty_buyer Thirdparty buyer
  4753. * @param int $local Localtax to process (1 or 2)
  4754. * @param int $idprod Id product
  4755. * @return integer localtax, -1 si ne peut etre determine
  4756. * @see get_default_tva, get_default_npr
  4757. */
  4758. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod=0)
  4759. {
  4760. global $mysoc;
  4761. if (!is_object($thirdparty_seller)) return -1;
  4762. if (!is_object($thirdparty_buyer)) return -1;
  4763. if ($local==1) // Localtax 1
  4764. {
  4765. if ($mysoc->country_code == 'ES')
  4766. {
  4767. if (is_numeric($thirdparty_buyer->localtax1_assuj) && ! $thirdparty_buyer->localtax1_assuj) return 0;
  4768. }
  4769. else
  4770. {
  4771. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  4772. if (is_numeric($thirdparty_seller->localtax1_assuj) && ! $thirdparty_seller->localtax1_assuj) return 0;
  4773. if (! is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj=='localtax1off') return 0;
  4774. }
  4775. }
  4776. elseif ($local==2) //I Localtax 2
  4777. {
  4778. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  4779. if (is_numeric($thirdparty_seller->localtax2_assuj) && ! $thirdparty_seller->localtax2_assuj) return 0;
  4780. if (! is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj=='localtax2off') return 0;
  4781. }
  4782. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  4783. {
  4784. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  4785. }
  4786. return 0;
  4787. }
  4788. /**
  4789. * Return yes or no in current language
  4790. *
  4791. * @param string $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  4792. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  4793. * @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.
  4794. * @return string HTML string
  4795. */
  4796. function yn($yesno, $case=1, $color=0)
  4797. {
  4798. global $langs;
  4799. $result='unknown'; $classname='';
  4800. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  4801. {
  4802. $result=$langs->trans('yes');
  4803. if ($case == 1 || $case == 3) $result=$langs->trans("Yes");
  4804. if ($case == 2) $result='<input type="checkbox" value="1" checked disabled>';
  4805. if ($case == 3) $result='<input type="checkbox" value="1" checked disabled> '.$result;
  4806. $classname='ok';
  4807. }
  4808. elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  4809. {
  4810. $result=$langs->trans("no");
  4811. if ($case == 1 || $case == 3) $result=$langs->trans("No");
  4812. if ($case == 2) $result='<input type="checkbox" value="0" disabled>';
  4813. if ($case == 3) $result='<input type="checkbox" value="0" disabled> '.$result;
  4814. if ($color == 2) $classname='ok';
  4815. else $classname='error';
  4816. }
  4817. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  4818. return $result;
  4819. }
  4820. /**
  4821. * Return a path to have a the directory according to object where files are stored.
  4822. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart)
  4823. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, $modulepart) if multidir_output not defined.
  4824. * Example our with new usage: $object is invoice -> 'INYYMM-ABCD'
  4825. * 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/"
  4826. *
  4827. * @param string $num Id of object (deprecated, $object will be used in future)
  4828. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  4829. * @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)
  4830. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  4831. * @param Object $object Object
  4832. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...')
  4833. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  4834. */
  4835. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
  4836. {
  4837. global $conf;
  4838. $path = '';
  4839. $arrayforoldpath=array('cheque','user','category','holiday','supplier_invoice','invoice_supplier','mailing','supplier_payment');
  4840. if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[]='product';
  4841. if (! empty($level) && in_array($modulepart, $arrayforoldpath))
  4842. {
  4843. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  4844. if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
  4845. else $num = preg_replace('/^.*\-/i','',$num);
  4846. $num = substr("000".$num, -$level);
  4847. if ($level == 1) $path = substr($num,0,1);
  4848. if ($level == 2) $path = substr($num,1,1).'/'.substr($num,0,1);
  4849. if ($level == 3) $path = substr($num,2,1).'/'.substr($num,1,1).'/'.substr($num,0,1);
  4850. }
  4851. else
  4852. {
  4853. // TODO
  4854. // We will enhance here a common way of forging path for document storage
  4855. // Here, object->id, object->ref and modulepart are required.
  4856. //var_dump($modulepart);
  4857. if (in_array($modulepart, array('thirdparty','contact','member','propal','proposal','commande','order','facture','invoice',
  4858. 'supplier_order','supplier_proposal','shipment','contract','expensereport')))
  4859. {
  4860. $path=($object->ref?$object->ref:$object->id);
  4861. }
  4862. }
  4863. if (empty($withoutslash) && ! empty($path)) $path.='/';
  4864. return $path;
  4865. }
  4866. /**
  4867. * Creation of a directory (this can create recursive subdir)
  4868. *
  4869. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  4870. * @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)
  4871. * @param int $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  4872. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  4873. */
  4874. function dol_mkdir($dir, $dataroot='', $newmask=null)
  4875. {
  4876. global $conf;
  4877. dol_syslog("functions.lib::dol_mkdir: dir=".$dir,LOG_INFO);
  4878. $dir_osencoded=dol_osencode($dir);
  4879. if (@is_dir($dir_osencoded)) return 0;
  4880. $nberr=0;
  4881. $nbcreated=0;
  4882. $ccdir='';
  4883. if (! empty($dataroot)) {
  4884. // Remove data root from loop
  4885. $dir = str_replace($dataroot.'/', '', $dir);
  4886. $ccdir = $dataroot.'/';
  4887. }
  4888. $cdir = explode("/", $dir);
  4889. $num=count($cdir);
  4890. for ($i = 0; $i < $num; $i++)
  4891. {
  4892. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  4893. else $ccdir .= $cdir[$i];
  4894. if (preg_match("/^.:$/",$ccdir,$regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  4895. // Attention, le is_dir() peut echouer bien que le rep existe.
  4896. // (ex selon config de open_basedir)
  4897. if ($ccdir)
  4898. {
  4899. $ccdir_osencoded=dol_osencode($ccdir);
  4900. if (! @is_dir($ccdir_osencoded))
  4901. {
  4902. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.",LOG_DEBUG);
  4903. umask(0);
  4904. $dirmaskdec=octdec($newmask);
  4905. if (empty($newmask)) {
  4906. $dirmaskdec = empty( $conf->global->MAIN_UMASK ) ? octdec( '0755' ) : octdec( $conf->global->MAIN_UMASK );
  4907. }
  4908. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  4909. if (! @mkdir($ccdir_osencoded, $dirmaskdec))
  4910. {
  4911. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  4912. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING);
  4913. $nberr++;
  4914. }
  4915. else
  4916. {
  4917. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created",LOG_DEBUG);
  4918. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  4919. $nbcreated++;
  4920. }
  4921. }
  4922. else
  4923. {
  4924. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  4925. }
  4926. }
  4927. }
  4928. return ($nberr ? -$nberr : $nbcreated);
  4929. }
  4930. /**
  4931. * Return picto saying a field is required
  4932. *
  4933. * @return string Chaine avec picto obligatoire
  4934. */
  4935. function picto_required()
  4936. {
  4937. return '<span class="fieldrequired">*</span>';
  4938. }
  4939. /**
  4940. * Clean a string from all HTML tags and entities.
  4941. * This function differs from strip_tags because:
  4942. * - <br> are replaced with \n if removelinefeed=0 or 1
  4943. * - if entities are found, they are decoded BEFORE the strip
  4944. * - you can decide to convert line feed into a space
  4945. *
  4946. * @param string $stringtoclean String to clean
  4947. * @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..."
  4948. * @param string $pagecodeto Encoding of input/output string
  4949. * @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)
  4950. * @return string String cleaned
  4951. *
  4952. * @see dol_escape_htmltag strip_tags dol_string_onlythesehtmltags dol_string_neverthesehtmltags
  4953. */
  4954. function dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0)
  4955. {
  4956. if ($removelinefeed == 2) $stringtoclean = preg_replace('/<br[^>]*>\n+/ims', '<br>', $stringtoclean);
  4957. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  4958. if ($strip_tags) {
  4959. $temp = strip_tags($temp);
  4960. } else {
  4961. $pattern = "/<[^<>]+>/";
  4962. // Exemple of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  4963. $temp = preg_replace($pattern,"",$temp); // pass 1
  4964. // $temp after pass 1: <a href="/myurl" title="A title">0000-021
  4965. $temp = preg_replace($pattern,"",$temp); // pass 2
  4966. // $temp after pass 2: 0000-021
  4967. }
  4968. $temp = dol_html_entity_decode($temp,ENT_COMPAT,$pagecodeto);
  4969. // Supprime aussi les retours
  4970. if ($removelinefeed == 1) $temp=str_replace(array("\r\n","\r","\n")," ",$temp);
  4971. // et les espaces doubles
  4972. while (strpos($temp," "))
  4973. {
  4974. $temp = str_replace(" "," ",$temp);
  4975. }
  4976. return trim($temp);
  4977. }
  4978. /**
  4979. * Clean a string to keep only desirable HTML tags.
  4980. *
  4981. * @param string $stringtoclean String to clean
  4982. * @return string String cleaned
  4983. *
  4984. * @see dol_escape_htmltag strip_tags dol_string_nohtmltag dol_string_neverthesehtmltags
  4985. */
  4986. function dol_string_onlythesehtmltags($stringtoclean)
  4987. {
  4988. $allowed_tags = array(
  4989. "html", "head", "meta", "body", "article", "a", "b", "br", "div", "em", "font", "img", "ins", "hr", "i", "li", "link",
  4990. "ol", "p", "s", "section", "span", "strong", "title",
  4991. "table", "tr", "th", "td", "u", "ul"
  4992. );
  4993. $allowed_tags_string = join("><", $allowed_tags);
  4994. $allowed_tags_string = preg_replace('/^>/','',$allowed_tags_string);
  4995. $allowed_tags_string = preg_replace('/<$/','',$allowed_tags_string);
  4996. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  4997. return $temp;
  4998. }
  4999. /**
  5000. * Clean a string from some undesirable HTML tags.
  5001. *
  5002. * @param string $stringtoclean String to clean
  5003. * @param array $disallowed_tags Array of tags not allowed
  5004. * @return string String cleaned
  5005. *
  5006. * @see dol_escape_htmltag strip_tags dol_string_nohtmltag dol_string_onlythesehtmltags
  5007. */
  5008. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags=array('textarea'))
  5009. {
  5010. $temp = $stringtoclean;
  5011. foreach($disallowed_tags as $tagtoremove)
  5012. {
  5013. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5014. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5015. }
  5016. return $temp;
  5017. }
  5018. /**
  5019. * Return first line of text. Cut will depends if content is HTML or not.
  5020. *
  5021. * @param string $text Input text
  5022. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5023. * @return string Output text
  5024. * @see dol_nboflines_bis, dol_string_nohtmltag, dol_escape_htmltag
  5025. */
  5026. function dolGetFirstLineOfText($text, $nboflines=1)
  5027. {
  5028. if ($nboflines == 1)
  5029. {
  5030. if (dol_textishtml($text))
  5031. {
  5032. $firstline=preg_replace('/<br[^>]*>.*$/s','',$text); // The s pattern modifier means the . can match newline characters
  5033. $firstline=preg_replace('/<div[^>]*>.*$/s','',$firstline); // The s pattern modifier means the . can match newline characters
  5034. }
  5035. else
  5036. {
  5037. $firstline=preg_replace('/[\n\r].*/','',$text);
  5038. }
  5039. return $firstline.((strlen($firstline) != strlen($text))?'...':'');
  5040. }
  5041. else
  5042. {
  5043. $ishtml=0;
  5044. if (dol_textishtml($text))
  5045. {
  5046. $text=preg_replace('/\n/','',$text);
  5047. $ishtml=1;
  5048. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5049. }
  5050. else
  5051. {
  5052. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5053. }
  5054. $text = strtr($text, $repTable);
  5055. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5056. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5057. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5058. $firstline='';
  5059. $i=0;
  5060. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5061. while (($i < $nba) && ($i < ($nboflines * 2)))
  5062. {
  5063. if ($i % 2 == 0) $firstline .= $a[$i];
  5064. elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) $firstline .= ($ishtml?"<br>\n":"\n");
  5065. $i++;
  5066. }
  5067. unset($a);
  5068. return $firstline.(($i < $nba)?'...':'');
  5069. }
  5070. }
  5071. /**
  5072. * Replace CRLF in string with a HTML BR tag
  5073. *
  5074. * @param string $stringtoencode String to encode
  5075. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5076. * @param bool $forxml false=Use <br>, true=Use <br />
  5077. * @return string String encoded
  5078. * @see dol_nboflines, dolGetFirstLineOfText
  5079. */
  5080. function dol_nl2br($stringtoencode,$nl2brmode=0,$forxml=false)
  5081. {
  5082. if (!$nl2brmode) {
  5083. return nl2br($stringtoencode, $forxml);
  5084. } else {
  5085. $ret=preg_replace('/(\r\n|\r|\n)/i', ($forxml?'<br />':'<br>'), $stringtoencode);
  5086. return $ret;
  5087. }
  5088. }
  5089. /**
  5090. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5091. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,> are converted.
  5092. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5093. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5094. * For PDF usage, you can show text by 2 ways:
  5095. * - writeHTMLCell -> param must be encoded into HTML.
  5096. * - MultiCell -> param must not be encoded into HTML.
  5097. * Because writeHTMLCell convert also \n into <br>, if function
  5098. * is used to build PDF, nl2brmode must be 1.
  5099. *
  5100. * @param string $stringtoencode String to encode
  5101. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5102. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5103. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5104. * @return string String encoded
  5105. */
  5106. function dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
  5107. {
  5108. $newstring=$stringtoencode;
  5109. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  5110. {
  5111. $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.
  5112. if ($removelasteolbr) $newstring=preg_replace('/<br>$/i','',$newstring); // Remove last <br> (remove only last one)
  5113. $newstring=strtr($newstring,array('&'=>'__and__','<'=>'__lt__','>'=>'__gt__','"'=>'__dquot__'));
  5114. $newstring=dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom); // Make entity encoding
  5115. $newstring=strtr($newstring,array('__and__'=>'&','__lt__'=>'<','__gt__'=>'>','__dquot__'=>'"'));
  5116. }
  5117. else
  5118. {
  5119. if ($removelasteolbr) $newstring=preg_replace('/(\r\n|\r|\n)$/i','',$newstring); // Remove last \n (may remove several)
  5120. $newstring=dol_nl2br(dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom),$nl2brmode);
  5121. }
  5122. // Other substitutions that htmlentities does not do
  5123. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5124. return $newstring;
  5125. }
  5126. /**
  5127. * This function is called to decode a HTML string (it decodes entities and br tags)
  5128. *
  5129. * @param string $stringtodecode String to decode
  5130. * @param string $pagecodeto Page code for result
  5131. * @return string String decoded
  5132. */
  5133. function dol_htmlentitiesbr_decode($stringtodecode,$pagecodeto='UTF-8')
  5134. {
  5135. $ret=dol_html_entity_decode($stringtodecode,ENT_COMPAT,$pagecodeto);
  5136. $ret=preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i',"<br>",$ret);
  5137. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i',"\r\n",$ret);
  5138. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i',"\n",$ret);
  5139. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i',"\n",$ret);
  5140. return $ret;
  5141. }
  5142. /**
  5143. * This function remove all ending \n and br at end
  5144. *
  5145. * @param string $stringtodecode String to decode
  5146. * @return string String decoded
  5147. */
  5148. function dol_htmlcleanlastbr($stringtodecode)
  5149. {
  5150. $ret=preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i',"",$stringtodecode);
  5151. return $ret;
  5152. }
  5153. /**
  5154. * Replace html_entity_decode functions to manage errors
  5155. *
  5156. * @param string $a Operand a
  5157. * @param string $b Operand b (ENT_QUOTES=convert simple and double quotes)
  5158. * @param string $c Operand c
  5159. * @return string String decoded
  5160. */
  5161. function dol_html_entity_decode($a,$b,$c='UTF-8')
  5162. {
  5163. return html_entity_decode($a,$b,$c);
  5164. }
  5165. /**
  5166. * Replace htmlentities functions.
  5167. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5168. *
  5169. * @param string $string The input string to encode
  5170. * @param int $flags Flags (see PHP doc above)
  5171. * @param string $encoding Encoding page code
  5172. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5173. * @return string $ret Encoded string
  5174. */
  5175. function dol_htmlentities($string, $flags=null, $encoding='UTF-8', $double_encode=false)
  5176. {
  5177. return htmlentities($string, $flags, $encoding, $double_encode);
  5178. }
  5179. /**
  5180. * Check if a string is a correct iso string
  5181. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5182. * Example, if string contains euro symbol that has ascii code 128
  5183. *
  5184. * @param string $s String to check
  5185. * @return int 0 if bad iso, 1 if good iso
  5186. */
  5187. function dol_string_is_good_iso($s)
  5188. {
  5189. $len=dol_strlen($s);
  5190. $ok=1;
  5191. for($scursor=0;$scursor<$len;$scursor++)
  5192. {
  5193. $ordchar=ord($s{$scursor});
  5194. //print $scursor.'-'.$ordchar.'<br>';
  5195. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok=0; break; }
  5196. if ($ordchar > 126 && $ordchar < 160) { $ok=0; break; }
  5197. }
  5198. return $ok;
  5199. }
  5200. /**
  5201. * Return nb of lines of a clear text
  5202. *
  5203. * @param string $s String to check
  5204. * @param int $maxchar Not yet used
  5205. * @return int Number of lines
  5206. * @see dol_nboflines_bis, dolGetFirstLineOfText
  5207. */
  5208. function dol_nboflines($s,$maxchar=0)
  5209. {
  5210. if ($s == '') return 0;
  5211. $arraystring=explode("\n",$s);
  5212. $nb=count($arraystring);
  5213. return $nb;
  5214. }
  5215. /**
  5216. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  5217. *
  5218. * @param string $text Text
  5219. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  5220. * @param string $charset Give the charset used to encode the $text variable in memory.
  5221. * @return int Number of lines
  5222. * @see dol_nboflines, dolGetFirstLineOfText
  5223. */
  5224. function dol_nboflines_bis($text,$maxlinesize=0,$charset='UTF-8')
  5225. {
  5226. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5227. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5228. $text = strtr($text, $repTable);
  5229. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5230. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5231. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5232. $nblines = (int) floor((count($a)+1)/2);
  5233. // count possible auto line breaks
  5234. if($maxlinesize)
  5235. {
  5236. foreach ($a as $line)
  5237. {
  5238. if (dol_strlen($line)>$maxlinesize)
  5239. {
  5240. //$line_dec = html_entity_decode(strip_tags($line));
  5241. $line_dec = html_entity_decode($line);
  5242. if(dol_strlen($line_dec)>$maxlinesize)
  5243. {
  5244. $line_dec=wordwrap($line_dec,$maxlinesize,'\n',true);
  5245. $nblines+=substr_count($line_dec,'\n');
  5246. }
  5247. }
  5248. }
  5249. }
  5250. unset($a);
  5251. return $nblines;
  5252. }
  5253. /**
  5254. * Same function than microtime in PHP 5 but compatible with PHP4
  5255. *
  5256. * @return float Time (millisecondes) with microsecondes in decimal part
  5257. * @deprecated Dolibarr does not support PHP4, you should use native function
  5258. * @see microtime()
  5259. */
  5260. function dol_microtime_float()
  5261. {
  5262. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  5263. return microtime(true);
  5264. }
  5265. /**
  5266. * Return if a text is a html content
  5267. *
  5268. * @param string $msg Content to check
  5269. * @param int $option 0=Full detection, 1=Fast check
  5270. * @return boolean true/false
  5271. * @see dol_concatdesc
  5272. */
  5273. function dol_textishtml($msg,$option=0)
  5274. {
  5275. if ($option == 1)
  5276. {
  5277. if (preg_match('/<html/i',$msg)) return true;
  5278. elseif (preg_match('/<body/i',$msg)) return true;
  5279. elseif (preg_match('/<br/i',$msg)) return true;
  5280. return false;
  5281. }
  5282. else
  5283. {
  5284. if (preg_match('/<html/i',$msg)) return true;
  5285. elseif (preg_match('/<body/i',$msg)) return true;
  5286. elseif (preg_match('/<(b|em|i|u)>/i',$msg)) return true;
  5287. elseif (preg_match('/<br\/>/i',$msg)) return true;
  5288. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i',$msg)) return true;
  5289. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i',$msg)) return true;
  5290. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i',$msg)) return true;
  5291. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i',$msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  5292. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i',$msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  5293. elseif (preg_match('/<h[0-9]>/i',$msg)) return true;
  5294. elseif (preg_match('/&[A-Z0-9]{1,6};/i',$msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  5295. elseif (preg_match('/&#[0-9]{2,3};/i',$msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  5296. return false;
  5297. }
  5298. }
  5299. /**
  5300. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  5301. * text1 html + text2 html => text1 + '<br>' + text2
  5302. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  5303. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  5304. * text1 txt + text2 txt => text1 + '\n' + text2
  5305. *
  5306. * @param string $text1 Text 1
  5307. * @param string $text2 Text 2
  5308. * @param bool $forxml false=Use <br>, true=Use <br />
  5309. * @return string Text 1 + new line + Text2
  5310. * @see dol_textishtml
  5311. */
  5312. function dol_concatdesc($text1,$text2,$forxml=false)
  5313. {
  5314. $ret='';
  5315. $ret.= (! dol_textishtml($text1) && dol_textishtml($text2))?dol_nl2br($text1, 0, $forxml):$text1;
  5316. $ret.= (! empty($text1) && ! empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2))?($forxml?"<br \>\n":"<br>\n") : "\n") : "";
  5317. $ret.= (dol_textishtml($text1) && ! dol_textishtml($text2))?dol_nl2br($text2, 0, $forxml):$text2;
  5318. return $ret;
  5319. }
  5320. /**
  5321. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  5322. *
  5323. * @param Translate $outputlangs Output language
  5324. * @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)
  5325. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  5326. * @param Object $object Object for keys on object
  5327. * @return array Array of substitutions
  5328. * @see setSubstitFromObject
  5329. */
  5330. function getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
  5331. {
  5332. global $db, $conf, $mysoc, $user, $extrafields;
  5333. $substitutionarray=array();
  5334. if (empty($exclude) || ! in_array('user', $exclude))
  5335. {
  5336. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  5337. // this will include signature content first and then replace var found into content of signature
  5338. $signature = $user->signature;
  5339. $substitutionarray=array_merge($substitutionarray, array(
  5340. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  5341. )
  5342. );
  5343. // For backward compatibility
  5344. if ($onlykey != 2)
  5345. {
  5346. $substitutionarray['__SIGNATURE__'] = (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '');
  5347. }
  5348. $substitutionarray=array_merge($substitutionarray, array(
  5349. '__USER_ID__' => (string) $user->id,
  5350. '__USER_LOGIN__' => (string) $user->login,
  5351. '__USER_LASTNAME__' => (string) $user->lastname,
  5352. '__USER_FIRSTNAME__' => (string) $user->firstname,
  5353. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  5354. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  5355. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  5356. )
  5357. );
  5358. }
  5359. if ((empty($exclude) || ! in_array('mycompany', $exclude)) && is_object($mysoc))
  5360. {
  5361. $substitutionarray=array_merge($substitutionarray, array(
  5362. '__MYCOMPANY_NAME__' => $mysoc->name,
  5363. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  5364. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  5365. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  5366. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  5367. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  5368. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  5369. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  5370. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  5371. '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '),
  5372. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  5373. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  5374. '__MYCOMPANY_TOWN__' => $mysoc->town,
  5375. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  5376. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  5377. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  5378. ));
  5379. }
  5380. if (($onlykey || is_object($object)) && (empty($exclude) || ! in_array('object', $exclude)))
  5381. {
  5382. if ($onlykey)
  5383. {
  5384. $substitutionarray['__ID__'] = '__ID__';
  5385. $substitutionarray['__REF__'] = '__REF__';
  5386. $substitutionarray['__REFCLIENT__'] = '__REFCLIENT__';
  5387. $substitutionarray['__REFSUPPLIER__'] = '__REFSUPPLIER__';
  5388. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  5389. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  5390. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  5391. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  5392. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  5393. if (is_object($object) && $object->element == 'member')
  5394. {
  5395. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  5396. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  5397. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  5398. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  5399. }
  5400. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  5401. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  5402. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  5403. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  5404. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  5405. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  5406. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  5407. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  5408. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  5409. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  5410. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  5411. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  5412. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  5413. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  5414. if (is_object($object) && $object->element == 'shipping')
  5415. {
  5416. $substitutionarray['__SHIPPINGTRACKNUM__']='Shipping tacking number';
  5417. $substitutionarray['__SHIPPINGTRACKNUMURL__']='Shipping tracking url';
  5418. }
  5419. }
  5420. else
  5421. {
  5422. $substitutionarray['__ID__'] = $object->id;
  5423. $substitutionarray['__REF__'] = $object->ref;
  5424. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : ''));
  5425. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : '');
  5426. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs): '');
  5427. // TODO Use this ?
  5428. $msgishtml = 0;
  5429. $birthday = dol_print_date($object->birth,'day');
  5430. $substitutionarray['__MEMBER_ID__']=$object->id;
  5431. if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  5432. $substitutionarray['__MEMBER_FIRSTNAME__']=$msgishtml?dol_htmlentitiesbr($object->firstname):$object->firstname;
  5433. $substitutionarray['__MEMBER_LASTNAME__']=$msgishtml?dol_htmlentitiesbr($object->lastname):$object->lastname;
  5434. if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__']=$msgishtml?dol_htmlentitiesbr($object->getFullName($outputlangs)):$object->getFullName($outputlangs);
  5435. $substitutionarray['__MEMBER_COMPANY__']=$msgishtml?dol_htmlentitiesbr($object->societe):$object->societe;
  5436. $substitutionarray['__MEMBER_ADDRESS__']=$msgishtml?dol_htmlentitiesbr($object->address):$object->address;
  5437. $substitutionarray['__MEMBER_ZIP__']=$msgishtml?dol_htmlentitiesbr($object->zip):$object->zip;
  5438. $substitutionarray['__MEMBER_TOWN__']=$msgishtml?dol_htmlentitiesbr($object->town):$object->town;
  5439. $substitutionarray['__MEMBER_COUNTRY__']=$msgishtml?dol_htmlentitiesbr($object->country):$object->country;
  5440. $substitutionarray['__MEMBER_EMAIL__']=$msgishtml?dol_htmlentitiesbr($object->email):$object->email;
  5441. $substitutionarray['__MEMBER_BIRTH__']=$msgishtml?dol_htmlentitiesbr($birthday):$birthday;
  5442. $substitutionarray['__MEMBER_PHOTO__']=$msgishtml?dol_htmlentitiesbr($object->photo):$object->photo;
  5443. $substitutionarray['__MEMBER_LOGIN__']=$msgishtml?dol_htmlentitiesbr($object->login):$object->login;
  5444. $substitutionarray['__MEMBER_PASSWORD__']=$msgishtml?dol_htmlentitiesbr($object->pass):$object->pass;
  5445. $substitutionarray['__MEMBER_PHONE__']=$msgishtml?dol_htmlentitiesbr($object->phone):$object->phone;
  5446. $substitutionarray['__MEMBER_PHONEPRO__']=$msgishtml?dol_htmlentitiesbr($object->phone_perso):$object->phone_perso;
  5447. $substitutionarray['__MEMBER_PHONEMOBILE__']=$msgishtml?dol_htmlentitiesbr($object->phone_mobile):$object->phone_mobile;
  5448. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  5449. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  5450. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  5451. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  5452. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  5453. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  5454. if (is_object($object) && $object->element == 'societe')
  5455. {
  5456. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object)?$object->id:'');
  5457. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object)?$object->name:'');
  5458. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object)?$object->name_alias:'');
  5459. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object)?$object->email:'');
  5460. }
  5461. elseif (is_object($object->thirdparty) && $object->thirdparty->id > 0)
  5462. {
  5463. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty)?$object->thirdparty->id:'');
  5464. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty)?$object->thirdparty->name:'');
  5465. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty)?$object->thirdparty->name_alias:'');
  5466. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty)?$object->thirdparty->email:'');
  5467. }
  5468. if (is_object($object->projet) && $object->projet->id > 0)
  5469. {
  5470. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet)?$object->projet->id:'');
  5471. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:'');
  5472. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet)?$object->projet->title:'');
  5473. }
  5474. if (is_object($object) && $object->element == 'shipping')
  5475. {
  5476. $substitutionarray['__SHIPPINGTRACKNUM__']=$object->tracking_number;
  5477. $substitutionarray['__SHIPPINGTRACKNUMURL__']=$object->tracking_url;
  5478. }
  5479. if (is_object($object) && $object->element == 'contrat' && is_array($object->lines))
  5480. {
  5481. $dateplannedstart='';
  5482. $datenextexpiration='';
  5483. foreach($object->lines as $line)
  5484. {
  5485. if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue;
  5486. if ($line->statut == 4 && $line->date_fin_prevue && (! $datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue;
  5487. }
  5488. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  5489. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  5490. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  5491. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  5492. }
  5493. // Create dynamic tags for __EXTRAFIELD_FIELD__
  5494. if ($object->table_element && $object->id > 0)
  5495. {
  5496. if (! is_object($extrafields)) $extrafields = new ExtraFields($db);
  5497. $extrafields->fetch_name_optionals_label($object->table_element, true);
  5498. if ($object->fetch_optionals() > 0)
  5499. {
  5500. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
  5501. {
  5502. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  5503. $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
  5504. }
  5505. }
  5506. }
  5507. }
  5508. // Complete substitution array with the url to make online payment
  5509. $paymenturl='';
  5510. if (empty($substitutionarray['__REF__']))
  5511. {
  5512. $paymenturl='';
  5513. }
  5514. else
  5515. {
  5516. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  5517. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  5518. $outputlangs->loadLangs(array('paypal','other'));
  5519. $typeforonlinepayment='free';
  5520. if (is_object($object) && $object->element == 'commande') $typeforonlinepayment='order';
  5521. if (is_object($object) && $object->element == 'facture') $typeforonlinepayment='invoice';
  5522. if (is_object($object) && $object->element == 'member') $typeforonlinepayment='member';
  5523. $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  5524. $paymenturl=$url;
  5525. }
  5526. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__']=($paymenturl?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)):'');
  5527. $substitutionarray['__ONLINE_PAYMENT_URL__']=$paymenturl;
  5528. }
  5529. }
  5530. if (empty($exclude) || ! in_array('objectamount', $exclude))
  5531. {
  5532. $substitutionarray['__DATE_YMD__'] = is_object($object)?(isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : '') : '';
  5533. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object)?(isset($object->date_lim_reglement)? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : '') : '';
  5534. $substitutionarray['__AMOUNT__'] = is_object($object)?$object->total_ttc:'';
  5535. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object)?$object->total_ht:'';
  5536. $substitutionarray['__AMOUNT_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):'';
  5537. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2__'] = is_object($object)?$object->total_localtax1:'';
  5538. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3__'] = is_object($object)?$object->total_localtax2:'';
  5539. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object)?price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency):'';
  5540. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object)?price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency):'';
  5541. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object)?($object->total_vat?price($object->total_vat, 0, $outputlangs, 0, 0, -1, $conf->currency):price($object->total_tva, 0, $outputlangs, 0, 0, -1, $conf->currency)):'';
  5542. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object)?price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, $conf->currency):'';
  5543. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object)?price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, $conf->currency):'';
  5544. // TODO Add keys for foreign multicurrency
  5545. // For backward compatibility
  5546. if ($onlykey != 2)
  5547. {
  5548. $substitutionarray['__TOTAL_TTC__'] = is_object($object)?$object->total_ttc:'';
  5549. $substitutionarray['__TOTAL_HT__'] = is_object($object)?$object->total_ht:'';
  5550. $substitutionarray['__TOTAL_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):'';
  5551. }
  5552. }
  5553. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  5554. if (empty($exclude) || ! in_array('date', $exclude))
  5555. {
  5556. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5557. $tmp=dol_getdate(dol_now(), true);
  5558. $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5559. $tmp3=dol_get_prev_month($tmp['mon'], $tmp['year']);
  5560. $tmp4=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5561. $tmp5=dol_get_next_month($tmp['mon'], $tmp['year']);
  5562. $substitutionarray=array_merge($substitutionarray, array(
  5563. '__DAY__' => (string) $tmp['mday'],
  5564. '__MONTH__' => (string) $tmp['mon'],
  5565. '__YEAR__' => (string) $tmp['year'],
  5566. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  5567. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  5568. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  5569. '__NEXT_DAY__' => (string) $tmp4['day'],
  5570. '__NEXT_MONTH__' => (string) $tmp5['month'],
  5571. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  5572. ));
  5573. }
  5574. if (empty($exclude) || ! in_array('system', $exclude))
  5575. {
  5576. $substitutionarray['__(AnyTranslationKey)__']=$outputlangs->trans('TranslationOfKey');
  5577. $substitutionarray['__[AnyConstantKey]__']=$outputlangs->trans('ValueOfConstant');
  5578. $substitutionarray['__DOL_MAIN_URL_ROOT__']=DOL_MAIN_URL_ROOT;
  5579. }
  5580. if (! empty($conf->multicompany->enabled))
  5581. {
  5582. $substitutionarray=array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  5583. }
  5584. return $substitutionarray;
  5585. }
  5586. /**
  5587. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  5588. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  5589. * Example of usage:
  5590. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  5591. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  5592. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  5593. *
  5594. * @param string $text Source string in which we must do substitution
  5595. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  5596. * @param Translate $outputlangs Output language
  5597. * @return string Output string after substitutions
  5598. * @see complete_substitutions_array, getCommonSubstitutionArray
  5599. */
  5600. function make_substitutions($text, $substitutionarray, $outputlangs=null)
  5601. {
  5602. global $conf, $langs;
  5603. if (! is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  5604. if (empty($outputlangs)) $outputlangs=$langs;
  5605. // Make substitution for language keys
  5606. if (is_object($outputlangs))
  5607. {
  5608. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg))
  5609. {
  5610. $msgishtml = 0;
  5611. if (dol_textishtml($text,1)) $msgishtml = 1;
  5612. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  5613. $tmp=explode('|',$reg[1]);
  5614. if (! empty($tmp[1])) $outputlangs->load($tmp[1]);
  5615. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])):$outputlangs->transnoentitiesnoconv($reg[1]), $text);
  5616. }
  5617. }
  5618. // Make substitution for constant keys. Must be after the substitution of translation, so if text of translation contains a constant,
  5619. // it is also converted.
  5620. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg))
  5621. {
  5622. $msgishtml = 0;
  5623. if (dol_textishtml($text,1)) $msgishtml = 1;
  5624. $keyfound = $reg[1];
  5625. if (preg_match('/(_pass|password|secret|_key|key$)/i', $keyfound)) $newval = '*****forbidden*****';
  5626. else $newval=empty($conf->global->$keyfound)?'':$conf->global->$keyfound;
  5627. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml?dol_htmlentitiesbr($newval):$newval, $text);
  5628. }
  5629. // Make substitition for array $substitutionarray
  5630. foreach ($substitutionarray as $key => $value)
  5631. {
  5632. if ($key == '__SIGNATURE__' && (! empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value=''; // Protection
  5633. if ($key == '__USER_SIGNATURE__' && (! empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value=''; // Protection
  5634. $text=str_replace("$key","$value",$text); // We must keep the " to work when value is 123.5 for example
  5635. }
  5636. return $text;
  5637. }
  5638. /**
  5639. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  5640. * In this case, method completesubstitutionarray provided by module is called.
  5641. *
  5642. * @param array $substitutionarray Array substitution old value => new value value
  5643. * @param Translate $outputlangs Output language
  5644. * @param Object $object Source object
  5645. * @param mixed $parameters Add more parameters (useful to pass product lines)
  5646. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  5647. * @return void
  5648. * @see make_substitutions
  5649. */
  5650. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
  5651. {
  5652. global $conf,$user;
  5653. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5654. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  5655. // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
  5656. /*if (is_object($object) && is_array($object->array_options))
  5657. {
  5658. foreach($object->array_options as $key => $val)
  5659. {
  5660. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  5661. $substitutionarray['__EXTRAFIELD_'.$keyshort.'__']=$val;
  5662. // For backward compatibiliy
  5663. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  5664. }
  5665. }*/
  5666. // Check if there is external substitution to do, requested by plugins
  5667. $dirsubstitutions=array_merge(array(),(array) $conf->modules_parts['substitutions']);
  5668. foreach($dirsubstitutions as $reldir)
  5669. {
  5670. $dir=dol_buildpath($reldir,0);
  5671. // Check if directory exists
  5672. if (! dol_is_dir($dir)) continue;
  5673. $substitfiles=dol_dir_list($dir,'files',0,'functions_');
  5674. foreach($substitfiles as $substitfile)
  5675. {
  5676. if (preg_match('/functions_(.*)\.lib\.php/i',$substitfile['name'],$reg))
  5677. {
  5678. $module=$reg[1];
  5679. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  5680. // Include the user's functions file
  5681. require_once $dir.$substitfile['name'];
  5682. // Call the user's function, and only if it is defined
  5683. $function_name=$module."_".$callfunc;
  5684. if (function_exists($function_name)) $function_name($substitutionarray,$outputlangs,$object,$parameters);
  5685. }
  5686. }
  5687. }
  5688. }
  5689. /**
  5690. * Format output for start and end date
  5691. *
  5692. * @param int $date_start Start date
  5693. * @param int $date_end End date
  5694. * @param string $format Output format
  5695. * @param Translate $outputlangs Output language
  5696. * @return void
  5697. */
  5698. function print_date_range($date_start,$date_end,$format = '',$outputlangs='')
  5699. {
  5700. print get_date_range($date_start,$date_end,$format,$outputlangs);
  5701. }
  5702. /**
  5703. * Format output for start and end date
  5704. *
  5705. * @param int $date_start Start date
  5706. * @param int $date_end End date
  5707. * @param string $format Output format
  5708. * @param Translate $outputlangs Output language
  5709. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  5710. * @return string String
  5711. */
  5712. function get_date_range($date_start,$date_end,$format = '',$outputlangs='', $withparenthesis=1)
  5713. {
  5714. global $langs;
  5715. $out='';
  5716. if (! is_object($outputlangs)) $outputlangs=$langs;
  5717. if ($date_start && $date_end)
  5718. {
  5719. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFromTo',dol_print_date($date_start, $format, false, $outputlangs),dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  5720. }
  5721. if ($date_start && ! $date_end)
  5722. {
  5723. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFrom',dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis?')':'');
  5724. }
  5725. if (! $date_start && $date_end)
  5726. {
  5727. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateUntil',dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  5728. }
  5729. return $out;
  5730. }
  5731. /**
  5732. * Return firstname and lastname in correct order
  5733. *
  5734. * @param string $firstname Firstname
  5735. * @param string $lastname Lastname
  5736. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
  5737. * @return string Firstname + lastname or Lastname + firstname
  5738. */
  5739. function dolGetFirstLastname($firstname,$lastname,$nameorder=-1)
  5740. {
  5741. global $conf;
  5742. $ret='';
  5743. // If order not defined, we use the setup
  5744. if ($nameorder < 0) $nameorder=(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?1:0);
  5745. if ($nameorder && ((string) $nameorder != '2'))
  5746. {
  5747. $ret.=$firstname;
  5748. if ($firstname && $lastname) $ret.=' ';
  5749. $ret.=$lastname;
  5750. }
  5751. else if ($nameorder == 2)
  5752. {
  5753. $ret.=$firstname;
  5754. }
  5755. else
  5756. {
  5757. $ret.=$lastname;
  5758. if ($firstname && $lastname) $ret.=' ';
  5759. $ret.=$firstname;
  5760. }
  5761. return $ret;
  5762. }
  5763. /**
  5764. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  5765. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5766. * Note: Prefer to use setEventMessages instead.
  5767. *
  5768. * @param mixed $mesgs Message string or array
  5769. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5770. * @return void
  5771. * @see dol_htmloutput_events
  5772. */
  5773. function setEventMessage($mesgs, $style='mesgs')
  5774. {
  5775. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  5776. if (! is_array($mesgs)) // If mesgs is a string
  5777. {
  5778. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  5779. }
  5780. else // If mesgs is an array
  5781. {
  5782. foreach($mesgs as $mesg)
  5783. {
  5784. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  5785. }
  5786. }
  5787. }
  5788. /**
  5789. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  5790. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5791. *
  5792. * @param string $mesg Message string
  5793. * @param array $mesgs Message array
  5794. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5795. * @return void
  5796. * @see dol_htmloutput_events
  5797. */
  5798. function setEventMessages($mesg, $mesgs, $style='mesgs')
  5799. {
  5800. if (empty($mesg) && empty($mesgs))
  5801. {
  5802. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  5803. }
  5804. else
  5805. {
  5806. if (! in_array((string) $style, array('mesgs','warnings','errors'))) dol_print_error('','Bad parameter style='.$style.' for setEventMessages');
  5807. if (empty($mesgs)) setEventMessage($mesg, $style);
  5808. else
  5809. {
  5810. if (! empty($mesg) && ! in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  5811. setEventMessage($mesgs, $style);
  5812. }
  5813. }
  5814. }
  5815. /**
  5816. * Print formated messages to output (Used to show messages on html output).
  5817. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  5818. * no need to call it explicitely.
  5819. *
  5820. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  5821. * @return void
  5822. * @see dol_htmloutput_mesg
  5823. */
  5824. function dol_htmloutput_events($disabledoutputofmessages=0)
  5825. {
  5826. // Show mesgs
  5827. if (isset($_SESSION['dol_events']['mesgs'])) {
  5828. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  5829. unset($_SESSION['dol_events']['mesgs']);
  5830. }
  5831. // Show errors
  5832. if (isset($_SESSION['dol_events']['errors'])) {
  5833. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  5834. unset($_SESSION['dol_events']['errors']);
  5835. }
  5836. // Show warnings
  5837. if (isset($_SESSION['dol_events']['warnings'])) {
  5838. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  5839. unset($_SESSION['dol_events']['warnings']);
  5840. }
  5841. }
  5842. /**
  5843. * Get formated messages to output (Used to show messages on html output).
  5844. * This include also the translation of the message key.
  5845. *
  5846. * @param string $mesgstring Message string or message key
  5847. * @param string[] $mesgarray Array of message strings or message keys
  5848. * @param string $style Style of message output ('ok' or 'error')
  5849. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5850. * @return string Return html output
  5851. *
  5852. * @see dol_print_error
  5853. * @see dol_htmloutput_errors
  5854. * @see setEventMessages
  5855. */
  5856. function get_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
  5857. {
  5858. global $conf, $langs;
  5859. $ret=0; $return='';
  5860. $out='';
  5861. $divstart=$divend='';
  5862. // If inline message with no format, we add it.
  5863. if ((empty($conf->use_javascript_ajax) || ! empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && ! preg_match('/<div class=".*">/i',$out))
  5864. {
  5865. $divstart='<div class="'.$style.' clearboth">';
  5866. $divend='</div>';
  5867. }
  5868. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  5869. {
  5870. $langs->load("errors");
  5871. $out.=$divstart;
  5872. if (is_array($mesgarray) && count($mesgarray))
  5873. {
  5874. foreach($mesgarray as $message)
  5875. {
  5876. $ret++;
  5877. $out.= $langs->trans($message);
  5878. if ($ret < count($mesgarray)) $out.= "<br>\n";
  5879. }
  5880. }
  5881. if ($mesgstring)
  5882. {
  5883. $langs->load("errors");
  5884. $ret++;
  5885. $out.= $langs->trans($mesgstring);
  5886. }
  5887. $out.=$divend;
  5888. }
  5889. if ($out)
  5890. {
  5891. if (! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  5892. {
  5893. $return = '<script type="text/javascript">
  5894. $(document).ready(function() {
  5895. var block = '.(! empty($conf->global->MAIN_USE_JQUERY_BLOCKUI)?"true":"false").'
  5896. if (block) {
  5897. $.dolEventValid("","'.dol_escape_js($out).'");
  5898. } else {
  5899. /* jnotify(message, preset of message type, keepmessage) */
  5900. $.jnotify("'.dol_escape_js($out).'",
  5901. "'.($style=="ok" ? 3000 : $style).'",
  5902. '.($style=="ok" ? "false" : "true").',
  5903. { remove: function (){} } );
  5904. }
  5905. });
  5906. </script>';
  5907. }
  5908. else
  5909. {
  5910. $return = $out;
  5911. }
  5912. }
  5913. return $return;
  5914. }
  5915. /**
  5916. * Get formated error messages to output (Used to show messages on html output).
  5917. *
  5918. * @param string $mesgstring Error message
  5919. * @param array $mesgarray Error messages array
  5920. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5921. * @return string Return html output
  5922. *
  5923. * @see dol_print_error
  5924. * @see dol_htmloutput_mesg
  5925. */
  5926. function get_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
  5927. {
  5928. return get_htmloutput_mesg($mesgstring, $mesgarray,'error',$keepembedded);
  5929. }
  5930. /**
  5931. * Print formated messages to output (Used to show messages on html output).
  5932. *
  5933. * @param string $mesgstring Message string or message key
  5934. * @param string[] $mesgarray Array of message strings or message keys
  5935. * @param string $style Which style to use ('ok', 'warning', 'error')
  5936. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  5937. * @return void
  5938. *
  5939. * @see dol_print_error
  5940. * @see dol_htmloutput_errors
  5941. * @see setEventMessages
  5942. */
  5943. function dol_htmloutput_mesg($mesgstring = '',$mesgarray = array(), $style = 'ok', $keepembedded=0)
  5944. {
  5945. if (empty($mesgstring) && (! is_array($mesgarray) || count($mesgarray) == 0)) return;
  5946. $iserror=0;
  5947. $iswarning=0;
  5948. if (is_array($mesgarray))
  5949. {
  5950. foreach($mesgarray as $val)
  5951. {
  5952. if ($val && preg_match('/class="error"/i',$val)) { $iserror++; break; }
  5953. if ($val && preg_match('/class="warning"/i',$val)) { $iswarning++; break; }
  5954. }
  5955. }
  5956. else if ($mesgstring && preg_match('/class="error"/i',$mesgstring)) $iserror++;
  5957. else if ($mesgstring && preg_match('/class="warning"/i',$mesgstring)) $iswarning++;
  5958. if ($style=='error') $iserror++;
  5959. if ($style=='warning') $iswarning++;
  5960. if ($iserror || $iswarning)
  5961. {
  5962. // Remove div from texts
  5963. $mesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$mesgstring);
  5964. $mesgstring=preg_replace('/<div class="(error|warning)">/','',$mesgstring);
  5965. $mesgstring=preg_replace('/<\/div>/','',$mesgstring);
  5966. // Remove div from texts array
  5967. if (is_array($mesgarray))
  5968. {
  5969. $newmesgarray=array();
  5970. foreach($mesgarray as $val)
  5971. {
  5972. $tmpmesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$val);
  5973. $tmpmesgstring=preg_replace('/<div class="(error|warning)">/','',$tmpmesgstring);
  5974. $tmpmesgstring=preg_replace('/<\/div>/','',$tmpmesgstring);
  5975. $newmesgarray[]=$tmpmesgstring;
  5976. }
  5977. $mesgarray=$newmesgarray;
  5978. }
  5979. print get_htmloutput_mesg($mesgstring,$mesgarray,($iserror?'error':'warning'),$keepembedded);
  5980. }
  5981. else print get_htmloutput_mesg($mesgstring,$mesgarray,'ok',$keepembedded);
  5982. }
  5983. /**
  5984. * Print formated error messages to output (Used to show messages on html output).
  5985. *
  5986. * @param string $mesgstring Error message
  5987. * @param array $mesgarray Error messages array
  5988. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5989. * @return void
  5990. *
  5991. * @see dol_print_error
  5992. * @see dol_htmloutput_mesg
  5993. */
  5994. function dol_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
  5995. {
  5996. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  5997. }
  5998. /**
  5999. * Advanced sort array by second index function, which produces ascending (default)
  6000. * or descending output and uses optionally natural case insensitive sorting (which
  6001. * can be optionally case sensitive as well).
  6002. *
  6003. * @param array $array Array to sort (array of array('key','otherkey1','otherkey2'...))
  6004. * @param string $index Key in array to use for sorting criteria
  6005. * @param int $order Sort order ('asc' or 'desc')
  6006. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  6007. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  6008. * @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.
  6009. * @return array Sorted array
  6010. */
  6011. function dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
  6012. {
  6013. // Clean parameters
  6014. $order=strtolower($order);
  6015. if (is_array($array))
  6016. {
  6017. $sizearray=count($array);
  6018. if ($sizearray>0)
  6019. {
  6020. $temp = array();
  6021. foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
  6022. if (!$natsort) ($order=='asc') ? asort($temp) : arsort($temp);
  6023. else
  6024. {
  6025. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  6026. if($order!='asc') $temp=array_reverse($temp, true);
  6027. }
  6028. $sorted = array();
  6029. foreach(array_keys($temp) as $key)
  6030. {
  6031. (is_numeric($key) && empty($keepindex)) ? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
  6032. }
  6033. return $sorted;
  6034. }
  6035. }
  6036. return $array;
  6037. }
  6038. /**
  6039. * Check if a string is in UTF8
  6040. *
  6041. * @param string $str String to check
  6042. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  6043. */
  6044. function utf8_check($str)
  6045. {
  6046. // We must use here a binary strlen function (so not dol_strlen)
  6047. $strLength = dol_strlen($str);
  6048. for ($i=0; $i<$strLength; $i++)
  6049. {
  6050. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  6051. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n=1; // 110bbbbb
  6052. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n=2; // 1110bbbb
  6053. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n=3; // 11110bbb
  6054. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n=4; // 111110bb
  6055. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n=5; // 1111110b
  6056. else return false; // Does not match any model
  6057. for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
  6058. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  6059. return false;
  6060. }
  6061. }
  6062. return true;
  6063. }
  6064. /**
  6065. * Return a string encoded into OS filesystem encoding. This function is used to define
  6066. * value to pass to filesystem PHP functions.
  6067. *
  6068. * @param string $str String to encode (UTF-8)
  6069. * @return string Encoded string (UTF-8, ISO-8859-1)
  6070. */
  6071. function dol_osencode($str)
  6072. {
  6073. global $conf;
  6074. $tmp=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  6075. if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1'; // By default for windows
  6076. if (empty($tmp)) $tmp='utf-8'; // By default for other
  6077. if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING;
  6078. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  6079. return $str;
  6080. }
  6081. /**
  6082. * Return an id or code from a code or id.
  6083. * Store also Code-Id into a cache to speed up next request on same key.
  6084. *
  6085. * @param DoliDB $db Database handler
  6086. * @param string $key Code or Id to get Id or Code
  6087. * @param string $tablename Table name without prefix
  6088. * @param string $fieldkey Field to search the key into
  6089. * @param string $fieldid Field to get
  6090. * @param int $entityfilter Filter by entity
  6091. * @return int <0 if KO, Id of code if OK
  6092. * @see $langs->getLabelFromKey
  6093. */
  6094. function dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0)
  6095. {
  6096. global $cache_codes;
  6097. // If key empty
  6098. if ($key == '') return '';
  6099. // Check in cache
  6100. if (isset($cache_codes[$tablename][$key])) // Can be defined to 0 or ''
  6101. {
  6102. return $cache_codes[$tablename][$key]; // Found in cache
  6103. }
  6104. $sql = "SELECT ".$fieldid." as valuetoget";
  6105. $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
  6106. $sql.= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  6107. if (! empty($entityfilter))
  6108. $sql.= " AND entity IN (" . getEntity($tablename) . ")";
  6109. dol_syslog('dol_getIdFromCode', LOG_DEBUG);
  6110. $resql = $db->query($sql);
  6111. if ($resql)
  6112. {
  6113. $obj = $db->fetch_object($resql);
  6114. if ($obj) $cache_codes[$tablename][$key]=$obj->valuetoget;
  6115. else $cache_codes[$tablename][$key]='';
  6116. $db->free($resql);
  6117. return $cache_codes[$tablename][$key];
  6118. }
  6119. else
  6120. {
  6121. return -1;
  6122. }
  6123. }
  6124. /**
  6125. * Verify if condition in string is ok or not
  6126. *
  6127. * @param string $strRights String with condition to check
  6128. * @return boolean True or False. Return true if strRights is ''
  6129. */
  6130. function verifCond($strRights)
  6131. {
  6132. global $user,$conf,$langs;
  6133. global $leftmenu;
  6134. global $rights; // To export to dol_eval function
  6135. //print $strRights."<br>\n";
  6136. $rights = true;
  6137. if ($strRights != '')
  6138. {
  6139. //$tab_rights = explode('&&', $strRights);
  6140. //$i = 0;
  6141. //while (($i < count($tab_rights)) && ($rights == true)) {
  6142. $str = 'if(!(' . $strRights . ')) { $rights = false; }';
  6143. dol_eval($str);
  6144. // $i++;
  6145. //}
  6146. }
  6147. return $rights;
  6148. }
  6149. /**
  6150. * Replace eval function to add more security.
  6151. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  6152. *
  6153. * @param string $s String to evaluate
  6154. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  6155. * @param int $hideerrors 1=Hide errors
  6156. * @return mixed Nothing or return of eval
  6157. */
  6158. function dol_eval($s, $returnvalue=0, $hideerrors=1)
  6159. {
  6160. // Only global variables can be changed by eval function and returned to caller
  6161. global $db, $langs, $user, $conf;
  6162. global $mainmenu, $leftmenu;
  6163. global $rights;
  6164. global $object;
  6165. global $mysoc;
  6166. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  6167. global $soc; // For backward compatibility
  6168. //print $s."<br>\n";
  6169. if ($returnvalue)
  6170. {
  6171. if ($hideerrors) return @eval('return '.$s.';');
  6172. else return eval('return '.$s.';');
  6173. }
  6174. else
  6175. {
  6176. if ($hideerrors) @eval($s);
  6177. else eval($s);
  6178. }
  6179. }
  6180. /**
  6181. * Return if var element is ok
  6182. *
  6183. * @param string $element Variable to check
  6184. * @return boolean Return true of variable is not empty
  6185. */
  6186. function dol_validElement($element)
  6187. {
  6188. return (trim($element) != '');
  6189. }
  6190. /**
  6191. * Return img flag of country for a language code or country code
  6192. *
  6193. * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR)
  6194. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  6195. * @return string HTML img string with flag.
  6196. */
  6197. function picto_from_langcode($codelang, $moreatt = '')
  6198. {
  6199. global $langs;
  6200. if (empty($codelang)) return '';
  6201. if (empty($codelang)) return '';
  6202. if ($codelang == 'auto')
  6203. {
  6204. return '<span class="fa fa-globe"></span>';
  6205. }
  6206. $langtocountryflag = array(
  6207. 'ar_AR' => '',
  6208. 'ca_ES' => 'catalonia',
  6209. 'da_DA' => 'dk',
  6210. 'fr_CA' => 'mq',
  6211. 'sv_SV' => 'se'
  6212. );
  6213. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  6214. else
  6215. {
  6216. $tmparray = explode('_', $codelang);
  6217. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  6218. }
  6219. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  6220. }
  6221. /**
  6222. * Return default language from country code
  6223. *
  6224. * @param string $countrycode Country code like 'US', 'FR', 'CA', ...
  6225. * @return string Value of locale like 'en_US', 'fr_FR', ...
  6226. */
  6227. function getLanguageCodeFromCountryCode($countrycode)
  6228. {
  6229. $countrycodetolanguage = array(
  6230. 'SA' => 'ar_AR',
  6231. 'DK' => 'da_DA',
  6232. 'CA' => 'en_CA',
  6233. 'SE' => 'sv_SV'
  6234. );
  6235. if (! empty($countrycodetolanguage[$countrycode])) return $countrycodetolanguage[$countrycode];
  6236. // Locale list taken from:
  6237. // http://stackoverflow.com/questions/3191664/
  6238. // list-of-all-locales-and-their-short-codes
  6239. $locales = array(
  6240. 'af-ZA',
  6241. 'am-ET',
  6242. 'ar-AE',
  6243. 'ar-BH',
  6244. 'ar-DZ',
  6245. 'ar-EG',
  6246. 'ar-IQ',
  6247. 'ar-JO',
  6248. 'ar-KW',
  6249. 'ar-LB',
  6250. 'ar-LY',
  6251. 'ar-MA',
  6252. 'arn-CL',
  6253. 'ar-OM',
  6254. 'ar-QA',
  6255. 'ar-SA',
  6256. 'ar-SY',
  6257. 'ar-TN',
  6258. 'ar-YE',
  6259. 'as-IN',
  6260. 'az-Cyrl-AZ',
  6261. 'az-Latn-AZ',
  6262. 'ba-RU',
  6263. 'be-BY',
  6264. 'bg-BG',
  6265. 'bn-BD',
  6266. 'bn-IN',
  6267. 'bo-CN',
  6268. 'br-FR',
  6269. 'bs-Cyrl-BA',
  6270. 'bs-Latn-BA',
  6271. 'ca-ES',
  6272. 'co-FR',
  6273. 'cs-CZ',
  6274. 'cy-GB',
  6275. 'da-DK',
  6276. 'de-AT',
  6277. 'de-CH',
  6278. 'de-DE',
  6279. 'de-LI',
  6280. 'de-LU',
  6281. 'dsb-DE',
  6282. 'dv-MV',
  6283. 'el-GR',
  6284. 'en-029',
  6285. 'en-AU',
  6286. 'en-BZ',
  6287. 'en-CA',
  6288. 'en-GB',
  6289. 'en-IE',
  6290. 'en-IN',
  6291. 'en-JM',
  6292. 'en-MY',
  6293. 'en-NZ',
  6294. 'en-PH',
  6295. 'en-SG',
  6296. 'en-TT',
  6297. 'en-US',
  6298. 'en-ZA',
  6299. 'en-ZW',
  6300. 'es-AR',
  6301. 'es-BO',
  6302. 'es-CL',
  6303. 'es-CO',
  6304. 'es-CR',
  6305. 'es-DO',
  6306. 'es-EC',
  6307. 'es-ES',
  6308. 'es-GT',
  6309. 'es-HN',
  6310. 'es-MX',
  6311. 'es-NI',
  6312. 'es-PA',
  6313. 'es-PE',
  6314. 'es-PR',
  6315. 'es-PY',
  6316. 'es-SV',
  6317. 'es-US',
  6318. 'es-UY',
  6319. 'es-VE',
  6320. 'et-EE',
  6321. 'eu-ES',
  6322. 'fa-IR',
  6323. 'fi-FI',
  6324. 'fil-PH',
  6325. 'fo-FO',
  6326. 'fr-BE',
  6327. 'fr-CA',
  6328. 'fr-CH',
  6329. 'fr-FR',
  6330. 'fr-LU',
  6331. 'fr-MC',
  6332. 'fy-NL',
  6333. 'ga-IE',
  6334. 'gd-GB',
  6335. 'gl-ES',
  6336. 'gsw-FR',
  6337. 'gu-IN',
  6338. 'ha-Latn-NG',
  6339. 'he-IL',
  6340. 'hi-IN',
  6341. 'hr-BA',
  6342. 'hr-HR',
  6343. 'hsb-DE',
  6344. 'hu-HU',
  6345. 'hy-AM',
  6346. 'id-ID',
  6347. 'ig-NG',
  6348. 'ii-CN',
  6349. 'is-IS',
  6350. 'it-CH',
  6351. 'it-IT',
  6352. 'iu-Cans-CA',
  6353. 'iu-Latn-CA',
  6354. 'ja-JP',
  6355. 'ka-GE',
  6356. 'kk-KZ',
  6357. 'kl-GL',
  6358. 'km-KH',
  6359. 'kn-IN',
  6360. 'kok-IN',
  6361. 'ko-KR',
  6362. 'ky-KG',
  6363. 'lb-LU',
  6364. 'lo-LA',
  6365. 'lt-LT',
  6366. 'lv-LV',
  6367. 'mi-NZ',
  6368. 'mk-MK',
  6369. 'ml-IN',
  6370. 'mn-MN',
  6371. 'mn-Mong-CN',
  6372. 'moh-CA',
  6373. 'mr-IN',
  6374. 'ms-BN',
  6375. 'ms-MY',
  6376. 'mt-MT',
  6377. 'nb-NO',
  6378. 'ne-NP',
  6379. 'nl-BE',
  6380. 'nl-NL',
  6381. 'nn-NO',
  6382. 'nso-ZA',
  6383. 'oc-FR',
  6384. 'or-IN',
  6385. 'pa-IN',
  6386. 'pl-PL',
  6387. 'prs-AF',
  6388. 'ps-AF',
  6389. 'pt-BR',
  6390. 'pt-PT',
  6391. 'qut-GT',
  6392. 'quz-BO',
  6393. 'quz-EC',
  6394. 'quz-PE',
  6395. 'rm-CH',
  6396. 'ro-RO',
  6397. 'ru-RU',
  6398. 'rw-RW',
  6399. 'sah-RU',
  6400. 'sa-IN',
  6401. 'se-FI',
  6402. 'se-NO',
  6403. 'se-SE',
  6404. 'si-LK',
  6405. 'sk-SK',
  6406. 'sl-SI',
  6407. 'sma-NO',
  6408. 'sma-SE',
  6409. 'smj-NO',
  6410. 'smj-SE',
  6411. 'smn-FI',
  6412. 'sms-FI',
  6413. 'sq-AL',
  6414. 'sr-Cyrl-BA',
  6415. 'sr-Cyrl-CS',
  6416. 'sr-Cyrl-ME',
  6417. 'sr-Cyrl-RS',
  6418. 'sr-Latn-BA',
  6419. 'sr-Latn-CS',
  6420. 'sr-Latn-ME',
  6421. 'sr-Latn-RS',
  6422. 'sv-FI',
  6423. 'sv-SE',
  6424. 'sw-KE',
  6425. 'syr-SY',
  6426. 'ta-IN',
  6427. 'te-IN',
  6428. 'tg-Cyrl-TJ',
  6429. 'th-TH',
  6430. 'tk-TM',
  6431. 'tn-ZA',
  6432. 'tr-TR',
  6433. 'tt-RU',
  6434. 'tzm-Latn-DZ',
  6435. 'ug-CN',
  6436. 'uk-UA',
  6437. 'ur-PK',
  6438. 'uz-Cyrl-UZ',
  6439. 'uz-Latn-UZ',
  6440. 'vi-VN',
  6441. 'wo-SN',
  6442. 'xh-ZA',
  6443. 'yo-NG',
  6444. 'zh-CN',
  6445. 'zh-HK',
  6446. 'zh-MO',
  6447. 'zh-SG',
  6448. 'zh-TW',
  6449. 'zu-ZA',
  6450. );
  6451. foreach ($locales as $locale)
  6452. {
  6453. $locale_region = locale_get_region($locale);
  6454. $locale_language = locale_get_primary_language($locale);
  6455. $locale_array = array('language' => $locale_language, 'region' => $locale_region);
  6456. if (strtoupper($countrycode) == $locale_region)
  6457. {
  6458. return locale_compose($locale_array);
  6459. }
  6460. }
  6461. return null;
  6462. }
  6463. /**
  6464. * Complete or removed entries into a head array (used to build tabs).
  6465. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  6466. * Or by change using hook completeTabsHead
  6467. *
  6468. * @param Conf $conf Object conf
  6469. * @param Translate $langs Object langs
  6470. * @param object|null $object Object object
  6471. * @param array $head Object head
  6472. * @param int $h New position to fill
  6473. * @param string $type Value for object where objectvalue can be
  6474. * 'thirdparty' to add a tab in third party view
  6475. * 'intervention' to add a tab in intervention view
  6476. * 'supplier_order' to add a tab in supplier order view
  6477. * 'supplier_invoice' to add a tab in supplier invoice view
  6478. * 'invoice' to add a tab in customer invoice view
  6479. * 'order' to add a tab in customer order view
  6480. * 'contract' to add a tabl in contract view
  6481. * 'product' to add a tab in product view
  6482. * 'propal' to add a tab in propal view
  6483. * 'user' to add a tab in user view
  6484. * 'group' to add a tab in group view
  6485. * 'member' to add a tab in fundation member view
  6486. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  6487. * 'ecm' to add a tab for another ecm view
  6488. * 'stock' to add a tab for warehouse view
  6489. * @param string $mode 'add' to complete head, 'remove' to remove entries
  6490. * @return void
  6491. */
  6492. function complete_head_from_modules($conf,$langs,$object,&$head,&$h,$type,$mode='add')
  6493. {
  6494. global $hookmanager;
  6495. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  6496. {
  6497. foreach ($conf->modules_parts['tabs'][$type] as $value)
  6498. {
  6499. $values=explode(':',$value);
  6500. if ($mode == 'add' && ! preg_match('/^\-/',$values[1]))
  6501. {
  6502. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  6503. {
  6504. if ($values[0] != $type) continue;
  6505. if (verifCond($values[4]))
  6506. {
  6507. if ($values[3]) $langs->load($values[3]);
  6508. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  6509. {
  6510. $substitutionarray=array();
  6511. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  6512. $label=make_substitutions($reg[1], $substitutionarray);
  6513. }
  6514. else $label=$langs->trans($values[2]);
  6515. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[5]), 1);
  6516. $head[$h][1] = $label;
  6517. $head[$h][2] = str_replace('+','',$values[1]);
  6518. $h++;
  6519. }
  6520. }
  6521. else if (count($values) == 5) // deprecated
  6522. {
  6523. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  6524. if ($values[0] != $type) continue;
  6525. if ($values[3]) $langs->load($values[3]);
  6526. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  6527. {
  6528. $substitutionarray=array();
  6529. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  6530. $label=make_substitutions($reg[1], $substitutionarray);
  6531. }
  6532. else $label=$langs->trans($values[2]);
  6533. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[4]), 1);
  6534. $head[$h][1] = $label;
  6535. $head[$h][2] = str_replace('+','',$values[1]);
  6536. $h++;
  6537. }
  6538. }
  6539. else if ($mode == 'remove' && preg_match('/^\-/',$values[1]))
  6540. {
  6541. if ($values[0] != $type) continue;
  6542. $tabname=str_replace('-','',$values[1]);
  6543. foreach($head as $key => $val)
  6544. {
  6545. $condition = (! empty($values[3]) ? verifCond($values[3]) : 1);
  6546. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$condition);
  6547. if ($head[$key][2]==$tabname && $condition)
  6548. {
  6549. unset($head[$key]);
  6550. break;
  6551. }
  6552. }
  6553. }
  6554. }
  6555. }
  6556. // No need to make a return $head. Var is modified as a reference
  6557. if (! empty($hookmanager))
  6558. {
  6559. $parameters=array('object' => $object, 'mode' => $mode, 'head' => $head);
  6560. $reshook=$hookmanager->executeHooks('completeTabsHead', $parameters);
  6561. if ($reshook > 0)
  6562. {
  6563. $head = $hookmanager->resArray;
  6564. $h = count($head);
  6565. }
  6566. }
  6567. }
  6568. /**
  6569. * Print common footer :
  6570. * conf->global->MAIN_HTML_FOOTER
  6571. * js for switch of menu hider
  6572. * js for conf->global->MAIN_GOOGLE_AN_ID
  6573. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  6574. * js for conf->logbuffer
  6575. *
  6576. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  6577. * @return void
  6578. */
  6579. function printCommonFooter($zone='private')
  6580. {
  6581. global $conf, $hookmanager;
  6582. global $micro_start_time;
  6583. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  6584. else print "\n".'<!-- Common footer for public page -->'."\n";
  6585. // A div to store page_y POST parameter so we can read it using javascript
  6586. print "\n<!-- A div to store page_y POST paramater -->\n";
  6587. print '<div id="page_y" style="display: none;">'.$_POST['page_y'].'</div>'."\n";
  6588. $parameters=array();
  6589. $reshook=$hookmanager->executeHooks('printCommonFooter',$parameters); // Note that $action and $object may have been modified by some hooks
  6590. if (empty($reshook))
  6591. {
  6592. if (! empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  6593. print "\n";
  6594. if (! empty($conf->use_javascript_ajax))
  6595. {
  6596. print '<script type="text/javascript" language="javascript">'."\n";
  6597. if ($zone == 'private' && empty($conf->dol_use_jmobile))
  6598. {
  6599. print "\n";
  6600. print '/* JS CODE TO ENABLE to enable handler to switch left menu page (menuhider) */'."\n";
  6601. print 'jQuery(".menuhider").click(function() {';
  6602. print ' console.log("We click on .menuhider");'."\n";
  6603. //print " $('.side-nav').animate({width:'toggle'},200);\n"; // OK with eldy theme but not with md
  6604. print " $('.side-nav').toggle()\n";
  6605. print " $('.login_block').toggle()\n";
  6606. print '});'."\n";
  6607. }
  6608. // Google Analytics (need Google module)
  6609. if (! empty($conf->google->enabled) && ! empty($conf->global->MAIN_GOOGLE_AN_ID))
  6610. {
  6611. if (($conf->dol_use_jmobile != 4))
  6612. {
  6613. print "\n";
  6614. print "/* JS CODE TO ENABLE for google analtics tag */\n";
  6615. print ' var _gaq = _gaq || [];'."\n";
  6616. print ' _gaq.push([\'_setAccount\', \''.$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
  6617. print ' _gaq.push([\'_trackPageview\']);'."\n";
  6618. print ''."\n";
  6619. print ' (function() {'."\n";
  6620. print ' var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
  6621. print ' ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
  6622. print ' var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
  6623. print ' })();'."\n";
  6624. }
  6625. }
  6626. // End of tuning
  6627. if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || ! empty($conf->global->MAIN_SHOW_TUNING_INFO))
  6628. {
  6629. print "\n";
  6630. print "/* JS CODE TO ENABLE to add memory info */\n";
  6631. print 'window.console && console.log("';
  6632. if (! empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  6633. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED)?$conf->global->MAIN_OPTIMIZE_SPEED:'off');
  6634. if (! empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  6635. {
  6636. $micro_end_time = microtime(true);
  6637. print ' - Build time: '.ceil(1000*($micro_end_time-$micro_start_time)).' ms';
  6638. }
  6639. if (function_exists("memory_get_usage"))
  6640. {
  6641. print ' - Mem: '.memory_get_usage();
  6642. }
  6643. if (function_exists("xdebug_memory_usage"))
  6644. {
  6645. print ' - XDebug time: '.ceil(1000*xdebug_time_index()).' ms';
  6646. print ' - XDebug mem: '.xdebug_memory_usage();
  6647. print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
  6648. }
  6649. if (function_exists("zend_loader_file_encoded"))
  6650. {
  6651. print ' - Zend encoded file: '.(zend_loader_file_encoded()?'yes':'no');
  6652. }
  6653. print '");'."\n";
  6654. }
  6655. print "\n".'</script>'."\n";
  6656. }
  6657. // Add Xdebug coverage of code
  6658. if (defined('XDEBUGCOVERAGE'))
  6659. {
  6660. print_r(xdebug_get_code_coverage());
  6661. }
  6662. // If there is some logs in buffer to show
  6663. if (count($conf->logbuffer))
  6664. {
  6665. print "\n";
  6666. print "<!-- Start of log output\n";
  6667. //print '<div class="hidden">'."\n";
  6668. foreach($conf->logbuffer as $logline)
  6669. {
  6670. print $logline."<br>\n";
  6671. }
  6672. //print '</div>'."\n";
  6673. print "End of log output -->\n";
  6674. }
  6675. }
  6676. }
  6677. /**
  6678. * Split a string with 2 keys into key array.
  6679. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  6680. *
  6681. * @param string $string String to explode
  6682. * @param string $delimiter Delimiter between each couple of data
  6683. * @param string $kv Delimiter between key and value
  6684. * @return array Array of data exploded
  6685. */
  6686. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  6687. {
  6688. if ($a = explode($delimiter, $string))
  6689. {
  6690. $ka = array();
  6691. foreach ($a as $s) { // each part
  6692. if ($s) {
  6693. if ($pos = strpos($s, $kv)) { // key/value delimiter
  6694. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  6695. } else { // key delimiter not found
  6696. $ka[] = trim($s);
  6697. }
  6698. }
  6699. }
  6700. return $ka;
  6701. }
  6702. return array();
  6703. }
  6704. /**
  6705. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  6706. *
  6707. * @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.
  6708. * @return string HTML code to set focus
  6709. */
  6710. function dol_set_focus($selector)
  6711. {
  6712. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  6713. print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  6714. }
  6715. /**
  6716. * Return getmypid() or random PID when function is disabled
  6717. * Some web hosts disable this php function for security reasons
  6718. * and sometimes we can't redeclare function
  6719. *
  6720. * @return int
  6721. */
  6722. function dol_getmypid()
  6723. {
  6724. if (! function_exists('getmypid')) {
  6725. return mt_rand(1,32768);
  6726. } else {
  6727. return getmypid();
  6728. }
  6729. }
  6730. /**
  6731. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  6732. *
  6733. * @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")
  6734. * @param string $value The value to look for.
  6735. * If param $mode is 0, can contains several keywords separated with a space or |
  6736. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  6737. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  6738. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  6739. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  6740. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  6741. * @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')
  6742. * @param integer $nofirstand 1=Do not output the first 'AND'
  6743. * @return string $res The statement to append to the SQL query
  6744. */
  6745. function natural_search($fields, $value, $mode=0, $nofirstand=0)
  6746. {
  6747. global $db,$langs;
  6748. $value=trim($value);
  6749. if ($mode == 0)
  6750. {
  6751. $value=preg_replace('/\*/','%',$value); // Replace * with %
  6752. }
  6753. if ($mode == 1)
  6754. {
  6755. $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
  6756. }
  6757. $value = preg_replace('/\s*\|\s*/','|', $value);
  6758. $crits = explode(' ', $value);
  6759. $res = '';
  6760. if (! is_array($fields)) $fields = array($fields);
  6761. $nboffields = count($fields);
  6762. $end2 = count($crits);
  6763. $j = 0;
  6764. foreach ($crits as $crit)
  6765. {
  6766. $i = 0; $i2 = 0;
  6767. $newres = '';
  6768. foreach ($fields as $field)
  6769. {
  6770. if ($mode == 1)
  6771. {
  6772. $operator='=';
  6773. $newcrit = preg_replace('/([<>=]+)/','',trim($crit));
  6774. preg_match('/([<>=]+)/',trim($crit), $reg);
  6775. if ($reg[1])
  6776. {
  6777. $operator = $reg[1];
  6778. }
  6779. if ($newcrit != '')
  6780. {
  6781. $numnewcrit = price2num($newcrit);
  6782. if (is_numeric($numnewcrit))
  6783. {
  6784. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' '.$operator.' '.$numnewcrit;
  6785. }
  6786. else
  6787. {
  6788. $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false
  6789. }
  6790. $i2++; // a criteria was added to string
  6791. }
  6792. }
  6793. else if ($mode == 2)
  6794. {
  6795. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $db->escape(trim($crit)) . ")";
  6796. $i2++; // a criteria was added to string
  6797. }
  6798. else if ($mode == 3)
  6799. {
  6800. $tmparray=explode(',',trim($crit));
  6801. if (count($tmparray))
  6802. {
  6803. $listofcodes='';
  6804. foreach($tmparray as $val)
  6805. {
  6806. if ($val)
  6807. {
  6808. $listofcodes.=($listofcodes?',':'');
  6809. $listofcodes.="'".$db->escape(trim($val))."'";
  6810. }
  6811. }
  6812. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $listofcodes . ")";
  6813. $i2++; // a criteria was added to string
  6814. }
  6815. }
  6816. else if ($mode == 4)
  6817. {
  6818. $tmparray=explode(',',trim($crit));
  6819. if (count($tmparray))
  6820. {
  6821. $listofcodes='';
  6822. foreach($tmparray as $val)
  6823. {
  6824. if ($val)
  6825. {
  6826. $newres .= ($i2 > 0 ? ' OR (' : '(') . $field . ' LIKE \'' . $db->escape(trim($val)) . ',%\'';
  6827. $newres .= ' OR '. $field . ' = \'' . $db->escape(trim($val)) . '\'';
  6828. $newres .= ' OR '. $field . ' LIKE \'%,' . $db->escape(trim($val)) . '\'';
  6829. $newres .= ' OR '. $field . ' LIKE \'%,' . $db->escape(trim($val)) . ',%\'';
  6830. $newres .= ')';
  6831. $i2++;
  6832. }
  6833. }
  6834. }
  6835. }
  6836. else // $mode=0
  6837. {
  6838. $textcrit = '';
  6839. $tmpcrits = explode('|',$crit);
  6840. $i3 = 0;
  6841. foreach($tmpcrits as $tmpcrit)
  6842. {
  6843. if(empty($tmpcrit)) continue;
  6844. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  6845. if (preg_match('/\.(id|rowid)$/', $field)) // Special case for rowid that is sometimes a ref so used as a search field
  6846. {
  6847. $newres .= $field . " = " . (is_numeric(trim($tmpcrit))?trim($tmpcrit):'0');
  6848. }
  6849. else
  6850. {
  6851. $newres .= $field . " LIKE '";
  6852. $tmpcrit=trim($tmpcrit);
  6853. $tmpcrit2=$tmpcrit;
  6854. $tmpbefore='%'; $tmpafter='%';
  6855. if (preg_match('/^[\^\$]/', $tmpcrit))
  6856. {
  6857. $tmpbefore='';
  6858. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  6859. }
  6860. if (preg_match('/[\^\$]$/', $tmpcrit))
  6861. {
  6862. $tmpafter='';
  6863. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  6864. }
  6865. $newres .= $tmpbefore;
  6866. $newres .= $db->escape($tmpcrit2);
  6867. $newres .= $tmpafter;
  6868. $newres .= "'";
  6869. if ($tmpcrit2 == '')
  6870. {
  6871. $newres .= ' OR ' . $field . " IS NULL";
  6872. }
  6873. }
  6874. $i3++;
  6875. }
  6876. $i2++; // a criteria was added to string
  6877. }
  6878. $i++;
  6879. }
  6880. if ($newres) $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') .$newres . ($i2 > 1 ? ')' : '');
  6881. $j++;
  6882. }
  6883. $res = ($nofirstand?"":" AND ")."(" . $res . ")";
  6884. //print 'xx'.$res.'yy';
  6885. return $res;
  6886. }
  6887. /**
  6888. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  6889. *
  6890. * @param Object $object Object
  6891. * @return string Url string
  6892. */
  6893. function showDirectDownloadLink($object)
  6894. {
  6895. global $conf, $langs;
  6896. $out='';
  6897. $url = $object->getLastMainDocLink($object->element);
  6898. if ($url)
  6899. {
  6900. $out.= img_picto('','object_globe.png').' '.$langs->trans("DirectDownloadLink").'<br>';
  6901. $out.= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
  6902. $out.= ajax_autoselect("directdownloadlink", 0);
  6903. }
  6904. return $out;
  6905. }
  6906. /**
  6907. * Return the filename of file to get the thumbs
  6908. *
  6909. * @param string $file Original filename (full or relative path)
  6910. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  6911. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  6912. * @return string New file name (full or relative path, including the thumbs/)
  6913. */
  6914. function getImageFileNameForSize($file, $extName, $extImgTarget='')
  6915. {
  6916. $dirName = dirname($file);
  6917. if ($dirName == '.') $dirName='';
  6918. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i','',$file); // We remove extension, whatever is its case
  6919. $fileName = basename($fileName);
  6920. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i',$file)?'.jpg':'');
  6921. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i',$file)?'.jpeg':'');
  6922. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i',$file)?'.gif':'');
  6923. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i',$file)?'.png':'');
  6924. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i',$file)?'.bmp':'');
  6925. if (! $extImgTarget) return $file;
  6926. $subdir='';
  6927. if ($extName) $subdir = 'thumbs/';
  6928. return ($dirName?$dirName.'/':'').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  6929. }
  6930. /**
  6931. * Return URL we can use for advanced preview links
  6932. *
  6933. * @param string $modulepart propal, facture, facture_fourn, ...
  6934. * @param string $relativepath Relative path of docs.
  6935. * @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)
  6936. * @param string $param More param on http links
  6937. * @return string|array Output string with href link or array with all components of link
  6938. */
  6939. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
  6940. {
  6941. global $conf, $langs;
  6942. if (empty($conf->use_javascript_ajax)) return '';
  6943. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'svg+xml');
  6944. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  6945. //$mime_preview[]='archive';
  6946. $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview);
  6947. if ($alldata == 1)
  6948. {
  6949. 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), );
  6950. else return array();
  6951. }
  6952. // old behavior
  6953. 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')).'\')';
  6954. else return '';
  6955. }
  6956. /**
  6957. * Make content of an input box selected when we click into input field.
  6958. *
  6959. * @param string $htmlname Id of html object
  6960. * @param string $addlink Add a 'link to' after
  6961. */
  6962. function ajax_autoselect($htmlname, $addlink='')
  6963. {
  6964. global $langs;
  6965. $out = '<script type="text/javascript">
  6966. jQuery(document).ready(function () {
  6967. jQuery("#'.$htmlname.'").click(function() { jQuery(this).select(); } );
  6968. });
  6969. </script>';
  6970. if ($addlink) $out.=' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  6971. return $out;
  6972. }
  6973. /**
  6974. * Return mime type of a file
  6975. *
  6976. * @param string $file Filename we looking for MIME type
  6977. * @param string $default Default mime type if extension not found in known list
  6978. * @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
  6979. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  6980. * @see image_format_supported (images.lib.php)
  6981. */
  6982. function dol_mimetype($file, $default='application/octet-stream', $mode=0)
  6983. {
  6984. $mime=$default;
  6985. $imgmime='other.png';
  6986. $famime='file-o';
  6987. $srclang='';
  6988. $tmpfile=preg_replace('/\.noexe$/','',$file);
  6989. // Text files
  6990. if (preg_match('/\.txt$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6991. if (preg_match('/\.rtx$/i',$tmpfile)) { $mime='text/richtext'; $imgmime='text.png'; $famime='file-text-o'; }
  6992. if (preg_match('/\.csv$/i',$tmpfile)) { $mime='text/csv'; $imgmime='text.png'; $famime='file-text-o'; }
  6993. if (preg_match('/\.tsv$/i',$tmpfile)) { $mime='text/tab-separated-values'; $imgmime='text.png'; $famime='file-text-o'; }
  6994. if (preg_match('/\.(cf|conf|log)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6995. if (preg_match('/\.ini$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='ini'; $famime='file-text-o'; }
  6996. if (preg_match('/\.css$/i',$tmpfile)) { $mime='text/css'; $imgmime='css.png'; $srclang='css'; $famime='file-text-o'; }
  6997. // Certificate files
  6998. if (preg_match('/\.(crt|cer|key|pub)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6999. // HTML/XML
  7000. if (preg_match('/\.(html|htm|shtml)$/i',$tmpfile)) { $mime='text/html'; $imgmime='html.png'; $srclang='html'; $famime='file-text-o'; }
  7001. if (preg_match('/\.(xml|xhtml)$/i',$tmpfile)) { $mime='text/xml'; $imgmime='other.png'; $srclang='xml'; $famime='file-text-o'; }
  7002. // Languages
  7003. if (preg_match('/\.bas$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='bas'; $famime='file-code-o'; }
  7004. if (preg_match('/\.(c)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='c'; $famime='file-code-o'; }
  7005. if (preg_match('/\.(cpp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='cpp'; $famime='file-code-o'; }
  7006. if (preg_match('/\.(h)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='h'; $famime='file-code-o'; }
  7007. if (preg_match('/\.(java|jsp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='java'; $famime='file-code-o'; }
  7008. if (preg_match('/\.php([0-9]{1})?$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; $famime='file-code-o'; }
  7009. if (preg_match('/\.phtml$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; $famime='file-code-o'; }
  7010. if (preg_match('/\.(pl|pm)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='pl.png'; $srclang='perl'; $famime='file-code-o'; }
  7011. if (preg_match('/\.sql$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='sql'; $famime='file-code-o'; }
  7012. if (preg_match('/\.js$/i',$tmpfile)) { $mime='text/x-javascript'; $imgmime='jscript.png'; $srclang='js'; $famime='file-code-o'; }
  7013. // Open office
  7014. if (preg_match('/\.odp$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.presentation'; $imgmime='ooffice.png'; $famime='file-powerpoint-o'; }
  7015. if (preg_match('/\.ods$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.spreadsheet'; $imgmime='ooffice.png'; $famime='file-excel-o'; }
  7016. if (preg_match('/\.odt$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.text'; $imgmime='ooffice.png'; $famime='file-word-o'; }
  7017. // MS Office
  7018. if (preg_match('/\.mdb$/i',$tmpfile)) { $mime='application/msaccess'; $imgmime='mdb.png'; $famime='file-o'; }
  7019. if (preg_match('/\.doc(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; $famime='file-word-o'; }
  7020. if (preg_match('/\.dot(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; $famime='file-word-o'; }
  7021. if (preg_match('/\.xlt(x)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7022. if (preg_match('/\.xla(m)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7023. if (preg_match('/\.xls$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7024. if (preg_match('/\.xls(b|m|x)$/i',$tmpfile)) { $mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7025. if (preg_match('/\.pps(m|x)?$/i',$tmpfile)) { $mime='application/vnd.ms-powerpoint'; $imgmime='ppt.png'; $famime='file-powerpoint-o'; }
  7026. if (preg_match('/\.ppt(m|x)?$/i',$tmpfile)) { $mime='application/x-mspowerpoint'; $imgmime='ppt.png'; $famime='file-powerpoint-o'; }
  7027. // Other
  7028. if (preg_match('/\.pdf$/i',$tmpfile)) { $mime='application/pdf'; $imgmime='pdf.png'; $famime='file-pdf-o'; }
  7029. // Scripts
  7030. if (preg_match('/\.bat$/i',$tmpfile)) { $mime='text/x-bat'; $imgmime='script.png'; $srclang='dos'; $famime='file-code-o'; }
  7031. if (preg_match('/\.sh$/i',$tmpfile)) { $mime='text/x-sh'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7032. if (preg_match('/\.ksh$/i',$tmpfile)) { $mime='text/x-ksh'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7033. if (preg_match('/\.bash$/i',$tmpfile)) { $mime='text/x-bash'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7034. // Images
  7035. if (preg_match('/\.ico$/i',$tmpfile)) { $mime='image/x-icon'; $imgmime='image.png'; $famime='file-image-o'; }
  7036. if (preg_match('/\.(jpg|jpeg)$/i',$tmpfile)) { $mime='image/jpeg'; $imgmime='image.png'; $famime='file-image-o'; }
  7037. if (preg_match('/\.png$/i',$tmpfile)) { $mime='image/png'; $imgmime='image.png'; $famime='file-image-o'; }
  7038. if (preg_match('/\.gif$/i',$tmpfile)) { $mime='image/gif'; $imgmime='image.png'; $famime='file-image-o'; }
  7039. if (preg_match('/\.bmp$/i',$tmpfile)) { $mime='image/bmp'; $imgmime='image.png'; $famime='file-image-o'; }
  7040. if (preg_match('/\.(tif|tiff)$/i',$tmpfile)) { $mime='image/tiff'; $imgmime='image.png'; $famime='file-image-o'; }
  7041. if (preg_match('/\.svg$/i',$tmpfile)) { $mime='image/svg+xml';$imgmime='image.png'; $famime='file-image-o'; }
  7042. // Calendar
  7043. if (preg_match('/\.vcs$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; $famime='file-text-o'; }
  7044. if (preg_match('/\.ics$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; $famime='file-text-o'; }
  7045. // Other
  7046. if (preg_match('/\.torrent$/i',$tmpfile)) { $mime='application/x-bittorrent'; $imgmime='other.png'; $famime='file-o'; }
  7047. // Audio
  7048. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i',$tmpfile)) { $mime='audio'; $imgmime='audio.png'; $famime='file-audio-o'; }
  7049. // Video
  7050. if (preg_match('/\.ogv$/i',$tmpfile)) { $mime='video/ogg'; $imgmime='video.png'; $famime='file-video-o'; }
  7051. if (preg_match('/\.webm$/i',$tmpfile)) { $mime='video/webm'; $imgmime='video.png'; $famime='file-video-o'; }
  7052. if (preg_match('/\.avi$/i',$tmpfile)) { $mime='video/x-msvideo'; $imgmime='video.png'; $famime='file-video-o'; }
  7053. if (preg_match('/\.divx$/i',$tmpfile)) { $mime='video/divx'; $imgmime='video.png'; $famime='file-video-o'; }
  7054. if (preg_match('/\.xvid$/i',$tmpfile)) { $mime='video/xvid'; $imgmime='video.png'; $famime='file-video-o'; }
  7055. if (preg_match('/\.(wmv|mpg|mpeg)$/i',$tmpfile)) { $mime='video'; $imgmime='video.png'; $famime='file-video-o'; }
  7056. // Archive
  7057. 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, ...
  7058. // Exe
  7059. if (preg_match('/\.(exe|com)$/i',$tmpfile)) { $mime='application/octet-stream'; $imgmime='other.png'; $famime='file-o'; }
  7060. // Lib
  7061. if (preg_match('/\.(dll|lib|o|so|a)$/i',$tmpfile)) { $mime='library'; $imgmime='library.png'; $famime='file-o'; }
  7062. // Err
  7063. if (preg_match('/\.err$/i',$tmpfile)) { $mime='error'; $imgmime='error.png'; $famime='file-text-o'; }
  7064. // Return string
  7065. if ($mode == 1)
  7066. {
  7067. $tmp=explode('/',$mime);
  7068. return (! empty($tmp[1])?$tmp[1]:$tmp[0]);
  7069. }
  7070. if ($mode == 2)
  7071. {
  7072. return $imgmime;
  7073. }
  7074. if ($mode == 3)
  7075. {
  7076. return $srclang;
  7077. }
  7078. if ($mode == 4)
  7079. {
  7080. return $famime;
  7081. }
  7082. return $mime;
  7083. }
  7084. /**
  7085. * Return value from dictionary
  7086. *
  7087. * @param string $tablename name of dictionary
  7088. * @param string $field the value to return
  7089. * @param int $id id of line
  7090. * @param bool $checkentity add filter on entity
  7091. * @param string $rowidfield name of the column rowid
  7092. */
  7093. function getDictvalue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
  7094. {
  7095. global $dictvalues,$db,$langs;
  7096. if (!isset($dictvalues[$tablename]))
  7097. {
  7098. $dictvalues[$tablename] = array();
  7099. $sql = 'SELECT * FROM '.$tablename.' WHERE 1';
  7100. if ($checkentity) $sql.= ' entity IN (0,'.getEntity('').')';
  7101. $resql = $db->query($sql);
  7102. if ($resql)
  7103. {
  7104. while ($obj = $db->fetch_object($resql))
  7105. {
  7106. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  7107. }
  7108. }
  7109. else
  7110. {
  7111. dol_print_error($db);
  7112. }
  7113. }
  7114. if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
  7115. else // Not found
  7116. {
  7117. if ($id > 0) return $id;
  7118. return '';
  7119. }
  7120. }
  7121. /**
  7122. * Return true if the color is light
  7123. *
  7124. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  7125. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  7126. */
  7127. function colorIsLight($stringcolor)
  7128. {
  7129. $res = -1;
  7130. if (!empty($stringcolor))
  7131. {
  7132. $res = 0;
  7133. $tmp=explode(',', $stringcolor);
  7134. if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
  7135. {
  7136. $r = $tmp[0];
  7137. $g = $tmp[1];
  7138. $b = $tmp[2];
  7139. }
  7140. else
  7141. {
  7142. $hexr=$stringcolor[0].$stringcolor[1];
  7143. $hexg=$stringcolor[2].$stringcolor[3];
  7144. $hexb=$stringcolor[4].$stringcolor[5];
  7145. $r = hexdec($hexr);
  7146. $g = hexdec($hexg);
  7147. $b = hexdec($hexb);
  7148. }
  7149. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  7150. if ($bright > 0.6) $res = 1;
  7151. }
  7152. return $res;
  7153. }
  7154. /**
  7155. * Function to test if an entry is enabled or not
  7156. *
  7157. * @param string $type_user 0=We test for internal user, 1=We test for external user
  7158. * @param array $menuentry Array for feature entry to test
  7159. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  7160. * @return int 0=Hide, 1=Show, 2=Show gray
  7161. */
  7162. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  7163. {
  7164. global $conf;
  7165. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  7166. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  7167. if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
  7168. if ($type_user && $menuentry['module'])
  7169. {
  7170. $tmploops=explode('|',$menuentry['module']);
  7171. $found=0;
  7172. foreach($tmploops as $tmploop)
  7173. {
  7174. if (in_array($tmploop, $listofmodulesforexternal)) {
  7175. $found++; break;
  7176. }
  7177. }
  7178. if (! $found) return 0; // Entry is for menus all excluded to external users
  7179. }
  7180. if (! $menuentry['perms'] && $type_user) return 0; // No permissions and user is external
  7181. 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
  7182. if (! $menuentry['perms']) return 2; // No permissions and user is external
  7183. return 1;
  7184. }
  7185. /**
  7186. * Round to next multiple.
  7187. *
  7188. * @param double $n Number to round up
  7189. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  7190. * @return integer Value rounded.
  7191. */
  7192. function roundUpToNextMultiple($n, $x=5)
  7193. {
  7194. return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
  7195. }