functions.lib.php 367 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2017 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. * or see https://www.gnu.org/
  33. */
  34. /**
  35. * \file htdocs/core/lib/functions.lib.php
  36. * \brief A set of functions for Dolibarr
  37. * This file contains all frequently used functions.
  38. */
  39. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  40. /**
  41. * Return a DoliDB instance (database handler).
  42. *
  43. * @param string $type Type of database (mysql, pgsql...)
  44. * @param string $host Address of database server
  45. * @param string $user Authorized username
  46. * @param string $pass Password
  47. * @param string $name Name of database
  48. * @param int $port Port of database server
  49. * @return DoliDB A DoliDB instance
  50. */
  51. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  52. {
  53. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  54. $class = 'DoliDB'.ucfirst($type);
  55. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  56. return $dolidb;
  57. }
  58. /**
  59. * Get list of entity id to use.
  60. *
  61. * @param string $element Current element
  62. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  63. * 'product', 'productprice', 'stock', 'bom', 'mo',
  64. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  65. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  66. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  67. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  68. * 'email_template', 'event', 'donation'
  69. * 'c_paiement', 'c_payment_term', ...
  70. * @param int $shared 0=Return id of current entity only,
  71. * 1=Return id of current entity + shared entities (default)
  72. * @param object $currentobject Current object if needed
  73. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  74. */
  75. function getEntity($element, $shared = 1, $currentobject = null)
  76. {
  77. global $conf, $mc;
  78. // fix different element names (France to English)
  79. switch ($element) {
  80. case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php"
  81. case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php"
  82. }
  83. if (is_object($mc))
  84. {
  85. return $mc->getEntity($element, $shared, $currentobject);
  86. } else {
  87. $out = '';
  88. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  89. if (in_array($element, $addzero)) $out .= '0,';
  90. $out .= ((int) $conf->entity);
  91. return $out;
  92. }
  93. }
  94. /**
  95. * Set entity id to use when to create an object
  96. *
  97. * @param object $currentobject Current object
  98. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  99. */
  100. function setEntity($currentobject)
  101. {
  102. global $conf, $mc;
  103. if (is_object($mc) && method_exists($mc, 'setEntity'))
  104. {
  105. return $mc->setEntity($currentobject);
  106. } else {
  107. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  108. }
  109. }
  110. /**
  111. * Return information about user browser
  112. *
  113. * Returns array with the following format:
  114. * array(
  115. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  116. * 'browserversion' => Browser version. Empty if unknown
  117. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  118. * 'layout' => (tablet|phone|classic)
  119. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  120. * 'tablet' => true/false
  121. * )
  122. *
  123. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  124. * @return array Check function documentation
  125. */
  126. function getBrowserInfo($user_agent)
  127. {
  128. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  129. $name = 'unknown';
  130. $version = '';
  131. $os = 'unknown';
  132. $phone = '';
  133. $detectmobile = new Mobile_Detect(null, $user_agent);
  134. $tablet = $detectmobile->isTablet();
  135. if ($detectmobile->isMobile()) {
  136. $phone = 'unknown';
  137. // If phone/smartphone, we set phone os name.
  138. if ($detectmobile->is('AndroidOS')) {
  139. $os = $phone = 'android';
  140. } elseif ($detectmobile->is('BlackBerryOS')) {
  141. $os = $phone = 'blackberry';
  142. } elseif ($detectmobile->is('iOS')) {
  143. $os = 'ios';
  144. $phone = 'iphone';
  145. } elseif ($detectmobile->is('PalmOS')) {
  146. $os = $phone = 'palm';
  147. } elseif ($detectmobile->is('SymbianOS')) {
  148. $os = 'symbian';
  149. } elseif ($detectmobile->is('webOS')) {
  150. $os = 'webos';
  151. } elseif ($detectmobile->is('MaemoOS')) {
  152. $os = 'maemo';
  153. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  154. $os = 'windows';
  155. }
  156. }
  157. // OS
  158. if (preg_match('/linux/i', $user_agent)) { $os = 'linux'; } elseif (preg_match('/macintosh/i', $user_agent)) { $os = 'macintosh'; } elseif (preg_match('/windows/i', $user_agent)) { $os = 'windows'; }
  159. // Name
  160. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'firefox'; $version = $reg[2]; } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'edge'; $version = $reg[2]; } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name = 'chrome'; $version = $reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string
  161. elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name = 'chrome'; } elseif (preg_match('/iceweasel/i', $user_agent)) { $name = 'iceweasel'; } elseif (preg_match('/epiphany/i', $user_agent)) { $name = 'epiphany'; } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'safari'; $version = $reg[2]; } // Safari is often present in string for mobile but its not.
  162. elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'opera'; $version = $reg[2]; } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end
  163. elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end
  164. elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name = 'lynxlinks'; $version = $reg[4]; }
  165. if ($tablet) {
  166. $layout = 'tablet';
  167. } elseif ($phone) {
  168. $layout = 'phone';
  169. } else {
  170. $layout = 'classic';
  171. }
  172. return array(
  173. 'browsername' => $name,
  174. 'browserversion' => $version,
  175. 'browseros' => $os,
  176. 'layout' => $layout,
  177. 'phone' => $phone,
  178. 'tablet' => $tablet
  179. );
  180. }
  181. /**
  182. * Function called at end of web php process
  183. *
  184. * @return void
  185. */
  186. function dol_shutdown()
  187. {
  188. global $conf, $user, $langs, $db;
  189. $disconnectdone = false; $depth = 0;
  190. if (is_object($db) && !empty($db->connected)) { $depth = $db->transaction_opened; $disconnectdone = $db->close(); }
  191. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  192. }
  193. /**
  194. * Return true if we are in a context of submitting a parameter
  195. *
  196. * @param string $paramname Name or parameter to test
  197. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  198. */
  199. function GETPOSTISSET($paramname)
  200. {
  201. $isset = 0;
  202. $relativepathstring = $_SERVER["PHP_SELF"];
  203. // Clean $relativepathstring
  204. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  205. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  206. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  207. //var_dump($relativepathstring);
  208. //var_dump($user->default_values);
  209. // Code for search criteria persistence.
  210. // Retrieve values if restore_lastsearch_values
  211. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  212. {
  213. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  214. {
  215. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  216. if (is_array($tmp))
  217. {
  218. foreach ($tmp as $key => $val)
  219. {
  220. if ($key == $paramname) // We are on the requested parameter
  221. {
  222. $isset = 1;
  223. break;
  224. }
  225. }
  226. }
  227. }
  228. // If there is saved contextpage, page or limit
  229. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  230. {
  231. $isset = 1;
  232. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  233. {
  234. $isset = 1;
  235. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  236. {
  237. $isset = 1;
  238. }
  239. } else {
  240. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname]));
  241. }
  242. return $isset;
  243. }
  244. /**
  245. * Return value of a param into GET or POST supervariable.
  246. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  247. * Note: The property $user->default_values is loaded by main.php when loading the user.
  248. *
  249. * @param string $paramname Name of parameter to found
  250. * @param string $check Type of check
  251. * ''=no check (deprecated)
  252. * 'none'=no check (only for param that should have very rich content)
  253. * 'int'=check it's numeric (integer or float)
  254. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  255. * 'alpha'=Same than alphanohtml since v13
  256. * 'alphanohtml'=check there is no html content and no " and no ../
  257. * 'aZ'=check it's a-z only
  258. * 'aZ09'=check it's simple alpha string (recommended for keys)
  259. * 'array'=check it's array
  260. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  261. * 'nohtml'=check there is no html content and no " and no ../
  262. * 'restricthtml'=check html content is restricted to some tags only
  263. * 'custom'= custom filter specify $filter and $options)
  264. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  265. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  266. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  267. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  268. * @return string|array Value found (string or array), or '' if check fails
  269. */
  270. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  271. {
  272. global $mysoc, $user, $conf;
  273. if (empty($paramname)) return 'BadFirstParameterForGETPOST';
  274. if (empty($check))
  275. {
  276. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  277. // Enable this line to know who call the GETPOST with '' $check parameter.
  278. //var_dump(debug_backtrace()[0]);
  279. }
  280. if (empty($method)) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  281. elseif ($method == 1) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  282. elseif ($method == 2) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  283. elseif ($method == 3) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  284. else return 'BadThirdParameterForGETPOST';
  285. if (empty($method) || $method == 3 || $method == 4)
  286. {
  287. $relativepathstring = $_SERVER["PHP_SELF"];
  288. // Clean $relativepathstring
  289. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  290. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  291. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  292. //var_dump($relativepathstring);
  293. //var_dump($user->default_values);
  294. // Code for search criteria persistence.
  295. // Retrieve values if restore_lastsearch_values
  296. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  297. {
  298. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  299. {
  300. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  301. if (is_array($tmp))
  302. {
  303. foreach ($tmp as $key => $val)
  304. {
  305. if ($key == $paramname) // We are on the requested parameter
  306. {
  307. $out = $val;
  308. break;
  309. }
  310. }
  311. }
  312. }
  313. // If there is saved contextpage, page or limit
  314. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  315. {
  316. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  317. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  318. {
  319. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  320. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  321. {
  322. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  323. }
  324. } // Else, retreive default values if we are not doing a sort
  325. elseif (!isset($_GET['sortfield'])) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
  326. {
  327. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  328. {
  329. // Search default value from $object->field
  330. global $object;
  331. if (is_object($object) && isset($object->fields[$paramname]['default']))
  332. {
  333. $out = $object->fields[$paramname]['default'];
  334. }
  335. }
  336. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
  337. {
  338. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  339. {
  340. // Now search in setup to overwrite default values
  341. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  342. {
  343. if (isset($user->default_values[$relativepathstring]['createform']))
  344. {
  345. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval)
  346. {
  347. $qualified = 0;
  348. if ($defkey != '_noquery_')
  349. {
  350. $tmpqueryarraytohave = explode('&', $defkey);
  351. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  352. $foundintru = 0;
  353. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  354. {
  355. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  356. }
  357. if (!$foundintru) $qualified = 1;
  358. //var_dump($defkey.'-'.$qualified);
  359. } else $qualified = 1;
  360. if ($qualified)
  361. {
  362. //var_dump($user->default_values[$relativepathstring][$defkey]['createform']);
  363. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname]))
  364. {
  365. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  366. break;
  367. }
  368. }
  369. }
  370. }
  371. }
  372. } // Management of default search_filters and sort order
  373. //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  374. elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  375. {
  376. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  377. {
  378. //var_dump($user->default_values[$relativepathstring]);
  379. if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ?
  380. {
  381. if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...']
  382. {
  383. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval)
  384. {
  385. $qualified = 0;
  386. if ($defkey != '_noquery_')
  387. {
  388. $tmpqueryarraytohave = explode('&', $defkey);
  389. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  390. $foundintru = 0;
  391. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  392. {
  393. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  394. }
  395. if (!$foundintru) $qualified = 1;
  396. //var_dump($defkey.'-'.$qualified);
  397. } else $qualified = 1;
  398. if ($qualified)
  399. {
  400. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  401. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val)
  402. {
  403. if ($out) $out .= ', ';
  404. if ($paramname == 'sortfield')
  405. {
  406. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  407. }
  408. if ($paramname == 'sortorder')
  409. {
  410. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  411. }
  412. }
  413. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  414. }
  415. }
  416. }
  417. } elseif (isset($user->default_values[$relativepathstring]['filters']))
  418. {
  419. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  420. {
  421. $qualified = 0;
  422. if ($defkey != '_noquery_')
  423. {
  424. $tmpqueryarraytohave = explode('&', $defkey);
  425. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  426. $foundintru = 0;
  427. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  428. {
  429. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  430. }
  431. if (!$foundintru) $qualified = 1;
  432. //var_dump($defkey.'-'.$qualified);
  433. } else $qualified = 1;
  434. if ($qualified)
  435. {
  436. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all']))
  437. {
  438. // We made a search from quick search menu, do we still use default filter ?
  439. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH))
  440. {
  441. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  442. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  443. }
  444. } else {
  445. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  446. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  447. }
  448. break;
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. }
  456. }
  457. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  458. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  459. // 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.
  460. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace))
  461. {
  462. $reg = array();
  463. $maxloop = 20; $loopnb = 0; // Protection against infinite loop
  464. 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.
  465. {
  466. $loopnb++; $newout = '';
  467. if ($reg[1] == 'DAY') {
  468. $tmp = dol_getdate(dol_now(), true);
  469. $newout = $tmp['mday'];
  470. } elseif ($reg[1] == 'MONTH') {
  471. $tmp = dol_getdate(dol_now(), true);
  472. $newout = $tmp['mon'];
  473. } elseif ($reg[1] == 'YEAR') {
  474. $tmp = dol_getdate(dol_now(), true);
  475. $newout = $tmp['year'];
  476. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  477. $tmp = dol_getdate(dol_now(), true);
  478. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  479. $newout = $tmp2['day'];
  480. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  481. $tmp = dol_getdate(dol_now(), true);
  482. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  483. $newout = $tmp2['month'];
  484. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  485. $tmp = dol_getdate(dol_now(), true);
  486. $newout = ($tmp['year'] - 1);
  487. } elseif ($reg[1] == 'NEXT_DAY') {
  488. $tmp = dol_getdate(dol_now(), true);
  489. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  490. $newout = $tmp2['day'];
  491. } elseif ($reg[1] == 'NEXT_MONTH') {
  492. $tmp = dol_getdate(dol_now(), true);
  493. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  494. $newout = $tmp2['month'];
  495. } elseif ($reg[1] == 'NEXT_YEAR') {
  496. $tmp = dol_getdate(dol_now(), true);
  497. $newout = ($tmp['year'] + 1);
  498. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  499. $newout = $mysoc->country_id;
  500. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  501. $newout = $user->id;
  502. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  503. $newout = $user->fk_user;
  504. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  505. $newout = $conf->entity;
  506. } else {
  507. $newout = ''; // Key not found, we replace with empty string
  508. }
  509. //var_dump('__'.$reg[1].'__ -> '.$newout);
  510. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  511. }
  512. }
  513. // Check rule
  514. if ($check == 'array') {
  515. if (!is_array($out) || empty($out)) {
  516. $out = array();
  517. } else {
  518. foreach ($out as $outkey => $outval) {
  519. $out[$outkey] = checkVal($outval, 'alphanohtml', $filter, $options);
  520. }
  521. }
  522. }
  523. else {
  524. $out = checkVal($out, $check, $filter, $options);
  525. }
  526. // Sanitizing for special parameters. There is no reason to allow the backtopage parameter to contains an external URL.
  527. if ($paramname == 'backtopage') {
  528. $out = preg_replace(array('!(\\\|/)+!', '/^[a-z]*:/'), '', $out);
  529. }
  530. // Code for search criteria persistence.
  531. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  532. if (empty($method) || $method == 3 || $method == 4)
  533. {
  534. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield')))
  535. {
  536. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  537. // We save search key only if $out not empty that means:
  538. // - posted value not empty, or
  539. // - 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).
  540. if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep
  541. {
  542. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  543. }
  544. }
  545. }
  546. return $out;
  547. }
  548. /**
  549. * Return a value after checking on a rule.
  550. *
  551. * @param string $out Value to get/check
  552. * @param string $check Type of check
  553. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  554. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  555. * @return string|array Value found (string or array), or '' if check fails
  556. */
  557. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  558. {
  559. // Check is done after replacement
  560. switch ($check)
  561. {
  562. case 'none':
  563. break;
  564. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  565. if (!is_numeric($out)) { $out = ''; }
  566. break;
  567. case 'intcomma':
  568. if (preg_match('/[^0-9,-]+/i', $out)) $out = '';
  569. break;
  570. case 'san_alpha':
  571. $out = filter_var($out, FILTER_SANITIZE_STRING);
  572. break;
  573. case 'aZ':
  574. if (!is_array($out))
  575. {
  576. $out = trim($out);
  577. if (preg_match('/[^a-z]+/i', $out)) $out = '';
  578. }
  579. break;
  580. case 'aZ09':
  581. if (!is_array($out))
  582. {
  583. $out = trim($out);
  584. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) $out = '';
  585. }
  586. break;
  587. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  588. if (!is_array($out))
  589. {
  590. $out = trim($out);
  591. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out = '';
  592. }
  593. break;
  594. case 'nohtml':
  595. $out = dol_string_nohtmltag($out, 0);
  596. break;
  597. case 'alpha': // No html and no " and no ../
  598. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  599. if (!is_array($out))
  600. {
  601. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  602. // '../' is dangerous because it allows dir transversals
  603. $out = str_replace(array('&quot;', '"', '../'), '', trim($out));
  604. $out = dol_string_nohtmltag($out, 0);
  605. }
  606. break;
  607. case 'restricthtml': // Recommended for most html textarea
  608. $out = dol_string_onlythesehtmltags($out, 0);
  609. // TODO We can also remove all javascripts reference
  610. break;
  611. case 'custom':
  612. if (empty($filter)) return 'BadFourthParameterForGETPOST';
  613. $out = filter_var($out, $filter, $options);
  614. break;
  615. }
  616. return $out;
  617. }
  618. if (!function_exists('dol_getprefix'))
  619. {
  620. /**
  621. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  622. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  623. * or two instances in same virtual servers.
  624. *
  625. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  626. * @return string A calculated prefix
  627. */
  628. function dol_getprefix($mode = '')
  629. {
  630. global $conf;
  631. // If prefix is for email
  632. if ($mode == 'email')
  633. {
  634. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  635. {
  636. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  637. elseif (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"];
  638. }
  639. // The recommended value (may be not defined for old versions)
  640. if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id;
  641. // For backward compatibility
  642. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  643. }
  644. // The recommended value (may be not defined for old versions)
  645. if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id;
  646. // For backward compatibility
  647. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"]))
  648. {
  649. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  650. }
  651. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  652. }
  653. }
  654. /**
  655. * Make an include_once using default root and alternate root if it fails.
  656. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  657. * To link to a module file from a module file, use include './mymodulefile';
  658. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  659. *
  660. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  661. * @param string $classname Class name (deprecated)
  662. * @return bool True if load is a success, False if it fails
  663. */
  664. function dol_include_once($relpath, $classname = '')
  665. {
  666. 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']
  667. $fullpath = dol_buildpath($relpath);
  668. if (!file_exists($fullpath)) {
  669. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  670. return false;
  671. }
  672. if (!empty($classname) && !class_exists($classname)) {
  673. return include $fullpath;
  674. } else {
  675. return include_once $fullpath;
  676. }
  677. }
  678. /**
  679. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  680. *
  681. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  682. * @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)
  683. * @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)
  684. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  685. * 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
  686. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  687. */
  688. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  689. {
  690. global $conf;
  691. $path = preg_replace('/^\//', '', $path);
  692. if (empty($type)) // For a filesystem path
  693. {
  694. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  695. if (is_array($conf->file->dol_document_root))
  696. {
  697. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  698. {
  699. if ($key == 'main')
  700. {
  701. continue;
  702. }
  703. if (file_exists($dirroot.'/'.$path))
  704. {
  705. $res = $dirroot.'/'.$path;
  706. return $res;
  707. }
  708. }
  709. }
  710. if ($returnemptyifnotfound) // Not found into alternate dir
  711. {
  712. if ($returnemptyifnotfound == 1 || !file_exists($res)) return '';
  713. }
  714. } else // For an url path
  715. {
  716. // We try to get local path of file on filesystem from url
  717. // Note that trying to know if a file on disk exist by forging path on disk from url
  718. // works only for some web server and some setup. This is bugged when
  719. // using proxy, rewriting, virtual path, etc...
  720. $res = '';
  721. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  722. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  723. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  724. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  725. {
  726. if ($key == 'main')
  727. {
  728. if ($type == 3)
  729. {
  730. global $dolibarr_main_url_root;
  731. // Define $urlwithroot
  732. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  733. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  734. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  735. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  736. }
  737. continue;
  738. }
  739. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  740. if (!empty($regs[1]))
  741. {
  742. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  743. if (file_exists($dirroot.'/'.$regs[1]))
  744. {
  745. if ($type == 1)
  746. {
  747. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  748. }
  749. if ($type == 2)
  750. {
  751. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  752. }
  753. if ($type == 3)
  754. {
  755. global $dolibarr_main_url_root;
  756. // Define $urlwithroot
  757. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  758. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  759. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  760. $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
  761. }
  762. break;
  763. }
  764. }
  765. }
  766. }
  767. return $res;
  768. }
  769. /**
  770. * Create a clone of instance of object (new instance with same value for properties)
  771. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  772. * With native = 1: Use PHP clone. Property that are reference are same pointer. This means $this->db of new object is still valid but point to same this->db than original object.
  773. *
  774. * @param object $object Object to clone
  775. * @param int $native 0=Full isolation method, 1=Native PHP method
  776. * @return object Clone object
  777. * @see https://php.net/manual/language.oop5.cloning.php
  778. */
  779. function dol_clone($object, $native = 0)
  780. {
  781. if (empty($native))
  782. {
  783. $myclone = unserialize(serialize($object));
  784. } else {
  785. $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)
  786. }
  787. return $myclone;
  788. }
  789. /**
  790. * Optimize a size for some browsers (phone, smarphone, ...)
  791. *
  792. * @param int $size Size we want
  793. * @param string $type Type of optimizing:
  794. * '' = function used to define a size for truncation
  795. * 'width' = function is used to define a width
  796. * @return int New size after optimizing
  797. */
  798. function dol_size($size, $type = '')
  799. {
  800. global $conf;
  801. if (empty($conf->dol_optimize_smallscreen)) return $size;
  802. if ($type == 'width' && $size > 250) return 250;
  803. else return 10;
  804. }
  805. /**
  806. * Clean a string to use it as a file name
  807. *
  808. * @param string $str String to clean
  809. * @param string $newstr String to replace bad chars with
  810. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  811. * @return string String cleaned (a-zA-Z_)
  812. *
  813. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  814. */
  815. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  816. {
  817. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  818. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  819. // Char '/' and '\' are file delimiters.
  820. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  821. return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  822. }
  823. /**
  824. * Clean a string to use it as a path name
  825. *
  826. * @param string $str String to clean
  827. * @param string $newstr String to replace bad chars with
  828. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  829. * @return string String cleaned (a-zA-Z_)
  830. *
  831. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  832. */
  833. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  834. {
  835. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°');
  836. return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  837. }
  838. /**
  839. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  840. *
  841. * @param string $str String to clean
  842. * @return string Cleaned string
  843. *
  844. * @see dol_sanitizeFilename(), dol_string_nospecial()
  845. */
  846. function dol_string_unaccent($str)
  847. {
  848. if (utf8_check($str))
  849. {
  850. // See http://www.utf8-chartable.de/
  851. $string = rawurlencode($str);
  852. $replacements = array(
  853. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  854. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  855. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  856. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  857. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  858. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  859. '%C3%A7' => 'c',
  860. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  861. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  862. '%C3%B1' => 'n',
  863. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  864. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  865. '%C3%BF' => 'y'
  866. );
  867. $string = strtr($string, $replacements);
  868. return rawurldecode($string);
  869. } else {
  870. // See http://www.ascii-code.com/
  871. $string = strtr(
  872. $str,
  873. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  874. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  875. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  876. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  877. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  878. \xF9\xFA\xFB\xFC\xFD\xFF",
  879. "AAAAAAC
  880. EEEEIIIIDN
  881. OOOOOUUUY
  882. aaaaaaceeee
  883. iiiidnooooo
  884. uuuuyy"
  885. );
  886. $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"));
  887. return $string;
  888. }
  889. }
  890. /**
  891. * Clean a string from all punctuation characters to use it as a ref or login.
  892. * This is a more complete function than dol_sanitizeFileName.
  893. *
  894. * @param string $str String to clean
  895. * @param string $newstr String to replace forbidden chars with
  896. * @param array $badcharstoreplace List of forbidden characters
  897. * @return string Cleaned string
  898. *
  899. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  900. */
  901. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
  902. {
  903. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  904. $forbidden_chars_to_remove = array();
  905. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace = $badcharstoreplace;
  906. //$forbidden_chars_to_remove=array("(",")");
  907. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  908. }
  909. /**
  910. * Clean a string from all non printable ascii chars (0x00-0x1F and 0x7F). It removes also CR-LF
  911. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  912. *
  913. * @param string $str String to clean
  914. * @return string Cleaned string
  915. *
  916. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  917. */
  918. function dol_string_nounprintableascii($str)
  919. {
  920. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str);
  921. }
  922. /**
  923. * Returns text escaped for inclusion into javascript code
  924. *
  925. * @param string $stringtoescape String to escape
  926. * @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 \
  927. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  928. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  929. */
  930. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  931. {
  932. // escape quotes and backslashes, newlines, etc.
  933. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  934. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  935. if (empty($noescapebackslashn)) { $substitjs["\n"] = '\\n'; $substitjs['\\'] = '\\\\'; }
  936. if (empty($mode)) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\'"; } elseif ($mode == 1) $substitjs["'"] = "\\'";
  937. elseif ($mode == 2) { $substitjs['"'] = '\\"'; } elseif ($mode == 3) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\\""; }
  938. return strtr($stringtoescape, $substitjs);
  939. }
  940. /**
  941. * Returns text escaped for inclusion into javascript code
  942. *
  943. * @param string $stringtoescape String to escape
  944. * @return string Escaped string for json content.
  945. */
  946. function dol_escape_json($stringtoescape)
  947. {
  948. return str_replace('"', '\"', $stringtoescape);
  949. }
  950. /**
  951. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  952. *
  953. * @param string $stringtoescape String to escape
  954. * @param int $keepb 1=Preserve b tags (otherwise, remove them)
  955. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  956. * @param string $keepmoretags '' or 'common' or list of tags
  957. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  958. * @return string Escaped string
  959. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  960. */
  961. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $keepmoretags = '', $escapeonlyhtmltags = 0)
  962. {
  963. if ($keepmoretags == 'common') $keepmoretags = 'html,body,a,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  964. // TODO Implement $keepmoretags
  965. // escape quotes and backslashes, newlines, etc.
  966. if ($escapeonlyhtmltags) {
  967. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  968. } else {
  969. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  970. }
  971. if (!$keepb) $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  972. if (!$keepn) $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  973. if ($escapeonlyhtmltags) {
  974. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  975. } else {
  976. return htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  977. }
  978. }
  979. /**
  980. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  981. *
  982. * @param string $utf8_string String to encode
  983. * @return string String converted
  984. */
  985. function dol_strtolower($utf8_string)
  986. {
  987. return mb_strtolower($utf8_string, "UTF-8");
  988. }
  989. /**
  990. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  991. *
  992. * @param string $utf8_string String to encode
  993. * @return string String converted
  994. */
  995. function dol_strtoupper($utf8_string)
  996. {
  997. return mb_strtoupper($utf8_string, "UTF-8");
  998. }
  999. /**
  1000. * Write log message into outputs. Possible outputs can be:
  1001. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1002. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1003. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1004. * this, use logging to files instead of syslog (see setup of module).
  1005. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1006. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1007. * This function works only if syslog module is enabled.
  1008. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1009. *
  1010. * @param string $message Line to log. ''=Show nothing
  1011. * @param int $level Log level
  1012. * 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
  1013. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  1014. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1015. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1016. * @param string $restricttologhandler Force output of log only to this log handler
  1017. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1018. * @return void
  1019. */
  1020. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1021. {
  1022. global $conf, $user, $debugbar;
  1023. // If syslog module enabled
  1024. if (empty($conf->syslog->enabled)) return;
  1025. // Check if we are into execution of code of a website
  1026. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1027. global $website, $websitekey;
  1028. if (is_object($website) && !empty($website->ref)) $suffixinfilename .= '_website_'.$website->ref;
  1029. elseif (!empty($websitekey)) $suffixinfilename .= '_website_'.$websitekey;
  1030. }
  1031. if ($ident < 0)
  1032. {
  1033. foreach ($conf->loghandlers as $loghandlerinstance)
  1034. {
  1035. $loghandlerinstance->setIdent($ident);
  1036. }
  1037. }
  1038. if (!empty($message))
  1039. {
  1040. // Test log level
  1041. $logLevels = array(LOG_EMERG=>'EMERG', LOG_ALERT=>'ALERT', LOG_CRIT=>'CRITICAL', LOG_ERR=>'ERR', LOG_WARNING=>'WARN', LOG_NOTICE=>'NOTICE', LOG_INFO=>'INFO', LOG_DEBUG=>'DEBUG');
  1042. if (!array_key_exists($level, $logLevels))
  1043. {
  1044. throw new Exception('Incorrect log level');
  1045. }
  1046. if ($level > $conf->global->SYSLOG_LEVEL) return;
  1047. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1048. // If adding log inside HTML page is required
  1049. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1050. || (!empty($user->rights->debugbar->read) && is_object($debugbar)))
  1051. {
  1052. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1053. }
  1054. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1055. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1056. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"]))
  1057. {
  1058. print "\n\n<!-- Log start\n";
  1059. print $message."\n";
  1060. print "Log end -->\n";
  1061. }
  1062. $data = array(
  1063. 'message' => $message,
  1064. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1065. 'level' => $level,
  1066. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1067. 'ip' => false
  1068. );
  1069. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1070. if (!empty($remoteip)) {
  1071. $data['ip'] = $remoteip;
  1072. // This is when server run behind a reverse proxy
  1073. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1074. elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1075. } // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1076. elseif (!empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  1077. // 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).
  1078. elseif (!empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1079. // 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).
  1080. elseif (!empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1081. // Loop on each log handler and send output
  1082. foreach ($conf->loghandlers as $loghandlerinstance)
  1083. {
  1084. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  1085. $loghandlerinstance->export($data, $suffixinfilename);
  1086. }
  1087. unset($data);
  1088. }
  1089. if ($ident > 0)
  1090. {
  1091. foreach ($conf->loghandlers as $loghandlerinstance)
  1092. {
  1093. $loghandlerinstance->setIdent($ident);
  1094. }
  1095. }
  1096. }
  1097. /**
  1098. * Show tab header of a card
  1099. *
  1100. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1101. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1102. * @param string $title Title
  1103. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using dol_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1104. * @param string $picto Add a picto on tab title
  1105. * @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.
  1106. * @param string $morehtmlright Add more html content on right of tabs title
  1107. * @param string $morecss More Css
  1108. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1109. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1110. * @return void
  1111. */
  1112. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1113. {
  1114. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1115. }
  1116. /**
  1117. * Show tabs of a record
  1118. *
  1119. * @param array $links Array of tabs
  1120. * @param string $active Active tab name
  1121. * @param string $title Title
  1122. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using dol_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1123. * @param string $picto Add a picto on tab title
  1124. * @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.
  1125. * @param string $morehtmlright Add more html content on right of tabs title
  1126. * @param string $morecss More Css
  1127. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1128. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1129. * @return string
  1130. */
  1131. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1132. {
  1133. global $conf, $langs, $hookmanager;
  1134. // Show title
  1135. $showtitle = 1;
  1136. if (!empty($conf->dol_optimize_smallscreen)) $showtitle = 0;
  1137. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1138. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1139. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1140. }
  1141. // Show right part
  1142. 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.
  1143. // Show title
  1144. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1145. {
  1146. $limittitle = 30;
  1147. $out .= '<a class="tabTitle">';
  1148. if ($picto) $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1149. $out .= '<span class="tabTitleText">'.dol_trunc($title, $limittitle).'</span>';
  1150. $out .= '</a>';
  1151. }
  1152. // Show tabs
  1153. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1154. $maxkey = -1;
  1155. if (is_array($links) && !empty($links))
  1156. {
  1157. $keys = array_keys($links);
  1158. if (count($keys)) $maxkey = max($keys);
  1159. }
  1160. // Show tabs
  1161. // if =0 we don't use the feature
  1162. if (empty($limittoshow)) {
  1163. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1164. }
  1165. if (!empty($conf->dol_optimize_smallscreen)) $limittoshow = 2;
  1166. $displaytab = 0;
  1167. $nbintab = 0;
  1168. $popuptab = 0;
  1169. $outmore = '';
  1170. for ($i = 0; $i <= $maxkey; $i++)
  1171. {
  1172. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1173. // If active tab is already present
  1174. if ($i >= $limittoshow) $limittoshow--;
  1175. }
  1176. }
  1177. for ($i = 0; $i <= $maxkey; $i++)
  1178. {
  1179. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1180. $isactive = true;
  1181. } else {
  1182. $isactive = false;
  1183. }
  1184. if ($i < $limittoshow || $isactive)
  1185. {
  1186. $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]).' -->';
  1187. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1188. {
  1189. if (!empty($links[$i][0]))
  1190. {
  1191. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1192. } else {
  1193. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1194. }
  1195. } elseif (!empty($links[$i][1]))
  1196. {
  1197. //print "x $i $active ".$links[$i][2]." z";
  1198. if ($isactive)
  1199. {
  1200. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1201. $out .= $links[$i][1];
  1202. $out .= '</a>'."\n";
  1203. } else {
  1204. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabunactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1205. $out .= $links[$i][1];
  1206. $out .= '</a>'."\n";
  1207. }
  1208. }
  1209. $out .= '</div>';
  1210. } else {
  1211. // The popup with the other tabs
  1212. if (!$popuptab)
  1213. {
  1214. $popuptab = 1;
  1215. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1216. }
  1217. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1218. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1219. {
  1220. if (!empty($links[$i][0]))
  1221. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1222. else $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1223. } elseif (!empty($links[$i][1]))
  1224. {
  1225. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1226. $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.
  1227. $outmore .= '</a>'."\n";
  1228. }
  1229. $outmore .= '</div>';
  1230. $nbintab++;
  1231. }
  1232. $displaytab = $i;
  1233. }
  1234. if ($popuptab) $outmore .= '</div>';
  1235. if ($popuptab) // If there is some tabs not shown
  1236. {
  1237. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1238. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1239. $tabsname = $moretabssuffix;
  1240. if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); }
  1241. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1242. $out .= '<a href="#" class="tab moretab inline-block tabunactive reposition">'.$langs->trans("More").'... ('.$nbintab.')</a>';
  1243. $out .= '<div id="moretabsList'.$tabsname.'" style="position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1244. $out .= $outmore;
  1245. $out .= '</div>';
  1246. $out .= '<div></div>';
  1247. $out .= "</div>\n";
  1248. $out .= "<script>";
  1249. $out .= "$('#moretabs".$tabsname."').mouseenter( function() { console.log('mouseenter ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','auto');});";
  1250. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1251. $out .= "</script>";
  1252. }
  1253. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1254. $out .= "</div>\n";
  1255. }
  1256. if (!$notab || $notab == -1 || $notab == -2) $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1257. $parameters = array('tabname' => $active, 'out' => $out);
  1258. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1259. if ($reshook > 0)
  1260. {
  1261. $out = $hookmanager->resPrint;
  1262. }
  1263. return $out;
  1264. }
  1265. /**
  1266. * Show tab footer of a card
  1267. *
  1268. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1269. * @return void
  1270. */
  1271. function dol_fiche_end($notab = 0)
  1272. {
  1273. print dol_get_fiche_end($notab);
  1274. }
  1275. /**
  1276. * Return tab footer of a card
  1277. *
  1278. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1279. * @return string
  1280. */
  1281. function dol_get_fiche_end($notab = 0)
  1282. {
  1283. if (!$notab || $notab == -1) return "\n</div>\n";
  1284. else return '';
  1285. }
  1286. /**
  1287. * Show tab footer of a card.
  1288. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1289. *
  1290. * @param Object $object Object to show
  1291. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1292. * @param string $morehtml More html content to output just before the nav bar
  1293. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1294. * @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.
  1295. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1296. * @param string $morehtmlref More html to show after ref
  1297. * @param string $moreparam More param to add in nav link url.
  1298. * @param int $nodbprefix Do not include DB prefix to forge table name
  1299. * @param string $morehtmlleft More html code to show before ref
  1300. * @param string $morehtmlstatus More html code to show under navigation arrows
  1301. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1302. * @param string $morehtmlright More html code to show before navigation arrows
  1303. * @return void
  1304. */
  1305. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1306. {
  1307. global $conf, $form, $user, $langs;
  1308. $error = 0;
  1309. $maxvisiblephotos = 1;
  1310. $showimage = 1;
  1311. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1312. $showbarcode = empty($conf->barcode->enabled) ? 0 : ($object->barcode ? 1 : 0);
  1313. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0;
  1314. $modulepart = 'unknown';
  1315. if ($object->element == 'societe') $modulepart = 'societe';
  1316. if ($object->element == 'contact') $modulepart = 'contact';
  1317. if ($object->element == 'member') $modulepart = 'memberphoto';
  1318. if ($object->element == 'user') $modulepart = 'userphoto';
  1319. if ($object->element == 'product') $modulepart = 'product';
  1320. if ($object->element == 'ticket') $modulepart = 'ticket';
  1321. if (class_exists("Imagick"))
  1322. {
  1323. if ($object->element == 'propal') $modulepart = 'propal';
  1324. if ($object->element == 'commande') $modulepart = 'commande';
  1325. if ($object->element == 'facture') $modulepart = 'facture';
  1326. if ($object->element == 'fichinter') $modulepart = 'ficheinter';
  1327. if ($object->element == 'contrat') $modulepart = 'contract';
  1328. if ($object->element == 'supplier_proposal') $modulepart = 'supplier_proposal';
  1329. if ($object->element == 'order_supplier') $modulepart = 'supplier_order';
  1330. if ($object->element == 'invoice_supplier') $modulepart = 'supplier_invoice';
  1331. if ($object->element == 'expensereport') $modulepart = 'expensereport';
  1332. }
  1333. if ($object->element == 'product')
  1334. {
  1335. $width = 80; $cssclass = 'photoref';
  1336. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1337. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1338. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1339. 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>';
  1340. else {
  1341. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1342. $nophoto = '';
  1343. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1344. } else { // Show no photo link
  1345. $nophoto = '/public/theme/common/nophoto.png';
  1346. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1347. }
  1348. }
  1349. } elseif ($object->element == 'ticket') {
  1350. $width = 80; $cssclass = 'photoref';
  1351. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1352. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1353. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1354. if ($showimage)
  1355. {
  1356. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1357. if ($object->nbphoto > 0)
  1358. {
  1359. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1360. } else {
  1361. $showimage = 0;
  1362. }
  1363. }
  1364. if (!$showimage)
  1365. {
  1366. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1367. $nophoto = '';
  1368. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1369. } else { // Show no photo link
  1370. $nophoto = '/public/theme/common/nophoto.png';
  1371. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" border="0"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1372. }
  1373. }
  1374. } else {
  1375. if ($showimage)
  1376. {
  1377. if ($modulepart != 'unknown')
  1378. {
  1379. $phototoshow = '';
  1380. // Check if a preview file is available
  1381. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick"))
  1382. {
  1383. $objectref = dol_sanitizeFileName($object->ref);
  1384. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1385. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1386. {
  1387. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1388. $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
  1389. } else {
  1390. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1391. }
  1392. if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1393. $filepath = $dir_output.$subdir."/";
  1394. $filepdf = $filepath.$objectref.".pdf";
  1395. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1396. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1397. $fileimage = $filepdf.'_preview.png';
  1398. $relativepathimage = $relativepath.'_preview.png';
  1399. $pdfexists = file_exists($filepdf);
  1400. // If PDF file exists
  1401. if ($pdfexists)
  1402. {
  1403. // Conversion du PDF en image png si fichier png non existant
  1404. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
  1405. {
  1406. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1407. {
  1408. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1409. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1410. if ($ret < 0) $error++;
  1411. }
  1412. }
  1413. }
  1414. if ($pdfexists && !$error)
  1415. {
  1416. $heightforphotref = 70;
  1417. if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
  1418. // If the preview file is found
  1419. if (file_exists($fileimage))
  1420. {
  1421. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1422. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1423. $phototoshow .= '</div></div>';
  1424. }
  1425. }
  1426. } elseif (!$phototoshow)
  1427. {
  1428. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1429. }
  1430. if ($phototoshow)
  1431. {
  1432. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1433. $morehtmlleft .= $phototoshow;
  1434. $morehtmlleft .= '</div>';
  1435. }
  1436. }
  1437. if (!$phototoshow) // Show No photo link (picto of object)
  1438. {
  1439. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1440. if ($object->element == 'action')
  1441. {
  1442. $width = 80;
  1443. $cssclass = 'photorefcenter';
  1444. $nophoto = img_picto('No photo', 'title_agenda');
  1445. } else {
  1446. $width = 14; $cssclass = 'photorefcenter';
  1447. $picto = $object->picto;
  1448. if ($object->element == 'project' && !$object->public) $picto = 'project'; // instead of projectpub
  1449. $nophoto = img_picto('No photo', 'object_'.$picto);
  1450. }
  1451. $morehtmlleft .= '<!-- No photo to show -->';
  1452. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1453. $morehtmlleft .= $nophoto;
  1454. $morehtmlleft .= '</div></div>';
  1455. $morehtmlleft .= '</div>';
  1456. }
  1457. }
  1458. }
  1459. if ($showbarcode) $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1460. if ($object->element == 'societe')
  1461. {
  1462. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1463. {
  1464. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1465. } else {
  1466. $morehtmlstatus .= $object->getLibStatut(6);
  1467. }
  1468. } elseif ($object->element == 'product')
  1469. {
  1470. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1471. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1472. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1473. } else {
  1474. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1475. }
  1476. $morehtmlstatus .= ' &nbsp; ';
  1477. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1478. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1479. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1480. } else {
  1481. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1482. }
  1483. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan')))
  1484. {
  1485. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1486. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1487. $morehtmlstatus .= $tmptxt;
  1488. } elseif ($object->element == 'contrat' || $object->element == 'contract')
  1489. {
  1490. if ($object->statut == 0) $morehtmlstatus .= $object->getLibStatut(5);
  1491. else $morehtmlstatus .= $object->getLibStatut(4);
  1492. } elseif ($object->element == 'facturerec')
  1493. {
  1494. if ($object->frequency == 0) $morehtmlstatus .= $object->getLibStatut(2);
  1495. else $morehtmlstatus .= $object->getLibStatut(5);
  1496. } elseif ($object->element == 'project_task')
  1497. {
  1498. $object->fk_statut = 1;
  1499. if ($object->progress > 0) $object->fk_statut = 2;
  1500. if ($object->progress >= 100) $object->fk_statut = 3;
  1501. $tmptxt = $object->getLibStatut(5);
  1502. $morehtmlstatus .= $tmptxt; // No status on task
  1503. } else { // Generic case
  1504. $tmptxt = $object->getLibStatut(6);
  1505. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5);
  1506. $morehtmlstatus .= $tmptxt;
  1507. }
  1508. // Add if object was dispatched "into accountancy"
  1509. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various')))
  1510. {
  1511. if (method_exists($object, 'getVentilExportCompta'))
  1512. {
  1513. $accounted = $object->getVentilExportCompta();
  1514. $langs->load("accountancy");
  1515. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1516. }
  1517. }
  1518. // Add alias for thirdparty
  1519. if (!empty($object->name_alias)) $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1520. // Add label
  1521. if (in_array($object->element, array('product', 'bank_account', 'project_task')))
  1522. {
  1523. if (!empty($object->label)) $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1524. }
  1525. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files')))
  1526. {
  1527. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1528. if ($moreaddress) {
  1529. $morehtmlref .= '<div class="refidno">';
  1530. $morehtmlref .= $moreaddress;
  1531. $morehtmlref .= '</div>';
  1532. }
  1533. }
  1534. if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && ($conf->global->MAIN_SHOW_TECHNICAL_ID == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id))
  1535. {
  1536. $morehtmlref .= '<div style="clear: both;"></div>';
  1537. $morehtmlref .= '<div class="refidno">';
  1538. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1539. $morehtmlref .= '</div>';
  1540. }
  1541. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1542. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1543. print '</div>';
  1544. print '<div class="underrefbanner clearboth"></div>';
  1545. }
  1546. /**
  1547. * Show a string with the label tag dedicated to the HTML edit field.
  1548. *
  1549. * @param string $langkey Translation key
  1550. * @param string $fieldkey Key of the html select field the text refers to
  1551. * @param int $fieldrequired 1=Field is mandatory
  1552. * @return string
  1553. * @deprecated Form::editfieldkey
  1554. */
  1555. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1556. {
  1557. global $langs;
  1558. $ret = '';
  1559. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  1560. $ret .= '<label for="'.$fieldkey.'">';
  1561. $ret .= $langs->trans($langkey);
  1562. $ret .= '</label>';
  1563. if ($fieldrequired) $ret .= '</span>';
  1564. return $ret;
  1565. }
  1566. /**
  1567. * Return string to add class property on html element with pair/impair.
  1568. *
  1569. * @param string $var 0 or 1
  1570. * @param string $moreclass More class to add
  1571. * @return string String to add class onto HTML element
  1572. */
  1573. function dol_bc($var, $moreclass = '')
  1574. {
  1575. global $bc;
  1576. $ret = ' '.$bc[$var];
  1577. if ($moreclass) $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  1578. return $ret;
  1579. }
  1580. /**
  1581. * Return a formated address (part address/zip/town/state) according to country rules.
  1582. * See https://en.wikipedia.org/wiki/Address
  1583. *
  1584. * @param Object $object A company or contact object
  1585. * @param int $withcountry 1=Add country into address string
  1586. * @param string $sep Separator to use to build string
  1587. * @param Translate $outputlangs Object lang that contains language for text translation.
  1588. * @param int $mode 0=Standard output, 1=Remove address
  1589. * @param string $extralangcode User extralanguage $langcode as values for address, town
  1590. * @return string Formated string
  1591. * @see dol_print_address()
  1592. */
  1593. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  1594. {
  1595. global $conf, $langs;
  1596. $ret = '';
  1597. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1598. // See format of addresses on https://en.wikipedia.org/wiki/Address
  1599. // Address
  1600. if (empty($mode)) {
  1601. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : $object->address);
  1602. }
  1603. // Zip/Town/State
  1604. 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
  1605. {
  1606. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1607. $ret .= ($ret ? $sep : '').$town;
  1608. if ($object->state)
  1609. {
  1610. $ret .= ($ret ? ", " : '').$object->state;
  1611. }
  1612. if ($object->zip) $ret .= ($ret ? ", " : '').$object->zip;
  1613. } elseif (in_array($object->country_code, array('GB', 'UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country
  1614. {
  1615. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1616. $ret .= ($ret ? $sep : '').$town;
  1617. if ($object->state)
  1618. {
  1619. $ret .= ($ret ? ", " : '').$object->state;
  1620. }
  1621. if ($object->zip) $ret .= ($ret ? $sep : '').$object->zip;
  1622. } elseif (in_array($object->country_code, array('ES', 'TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country
  1623. {
  1624. $ret .= ($ret ? $sep : '').$object->zip;
  1625. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1626. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1627. if ($object->state)
  1628. {
  1629. $ret .= "\n".$object->state;
  1630. }
  1631. } elseif (in_array($object->country_code, array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1632. {
  1633. $ret .= ($ret ? $sep : '').$object->zip;
  1634. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1635. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1636. $ret .= ($object->state_code ? (' '.($object->state_code)) : '');
  1637. } else // Other: title firstname name \n address lines \n zip town \n country
  1638. {
  1639. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1640. $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : '';
  1641. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  1642. if ($object->state && in_array($object->country_code, $countriesusingstate))
  1643. {
  1644. $ret .= ($ret ? ", " : '').$object->state;
  1645. }
  1646. }
  1647. if (!is_object($outputlangs)) $outputlangs = $langs;
  1648. if ($withcountry)
  1649. {
  1650. $langs->load("dict");
  1651. $ret .= ($object->country_code ? ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)) : '');
  1652. }
  1653. return $ret;
  1654. }
  1655. /**
  1656. * Format a string.
  1657. *
  1658. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1659. * @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)
  1660. * @param int $is_gmt See comment of timestamp parameter
  1661. * @return string A formatted string
  1662. */
  1663. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  1664. {
  1665. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1666. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  1667. } else return 'Error date into a not supported range';
  1668. }
  1669. /**
  1670. * Output date in a string format according to outputlangs (or langs if not defined).
  1671. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1672. *
  1673. * @param int $time GM Timestamps date
  1674. * @param string $format Output date format (tag of strftime function)
  1675. * "%d %b %Y",
  1676. * "%d/%m/%Y %H:%M",
  1677. * "%d/%m/%Y %H:%M:%S",
  1678. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1679. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1680. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1681. * false or 'tzserver' => output string is for local PHP server TZ usage
  1682. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  1683. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  1684. * @param Translate $outputlangs Object lang that contains language for text translation.
  1685. * @param boolean $encodetooutput false=no convert into output pagecode
  1686. * @return string Formated date or '' if time is null
  1687. *
  1688. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  1689. */
  1690. function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlangs = '', $encodetooutput = false)
  1691. {
  1692. global $conf, $langs;
  1693. // Clean parameters
  1694. $to_gmt = false;
  1695. $offsettz = $offsetdst = 0;
  1696. if ($tzoutput)
  1697. {
  1698. $to_gmt = true; // For backward compatibility
  1699. if (is_string($tzoutput))
  1700. {
  1701. if ($tzoutput == 'tzserver')
  1702. {
  1703. $to_gmt = false;
  1704. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1705. $offsettz = 0;
  1706. $offsetdst = 0;
  1707. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel')
  1708. {
  1709. $to_gmt = true;
  1710. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1711. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  1712. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  1713. }
  1714. }
  1715. }
  1716. if (!is_object($outputlangs)) $outputlangs = $langs;
  1717. if (!$format) $format = 'daytextshort';
  1718. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0;
  1719. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  1720. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat = 1; } // so format 'dayreduceformat' is processed like day
  1721. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1722. // TODO Add format daysmallyear and dayhoursmallyear
  1723. if ($format == 'day') $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  1724. elseif ($format == 'hour') $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  1725. elseif ($format == 'hourduration') $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  1726. elseif ($format == 'daytext') $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  1727. elseif ($format == 'daytextshort') $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  1728. elseif ($format == 'dayhour') $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  1729. elseif ($format == 'dayhoursec') $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  1730. elseif ($format == 'dayhourtext') $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  1731. elseif ($format == 'dayhourtextshort') $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  1732. // Format not sensitive to language
  1733. elseif ($format == 'dayhourlog') $format = '%Y%m%d%H%M%S';
  1734. elseif ($format == 'dayhourldap') $format = '%Y%m%d%H%M%SZ';
  1735. elseif ($format == 'dayhourxcard') $format = '%Y%m%dT%H%M%SZ';
  1736. elseif ($format == 'dayxcard') $format = '%Y%m%d';
  1737. elseif ($format == 'dayrfc') $format = '%Y-%m-%d'; // DATE_RFC3339
  1738. elseif ($format == 'dayhourrfc') $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1739. elseif ($format == 'standard') $format = '%Y-%m-%d %H:%M:%S';
  1740. if ($reduceformat)
  1741. {
  1742. $format = str_replace('%Y', '%y', $format);
  1743. $format = str_replace('yyyy', 'yy', $format);
  1744. }
  1745. // If date undefined or "", we return ""
  1746. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1747. // Clean format
  1748. if (preg_match('/%b/i', $format)) // There is some text to translate
  1749. {
  1750. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1751. $format = str_replace('%b', '__b__', $format);
  1752. $format = str_replace('%B', '__B__', $format);
  1753. }
  1754. if (preg_match('/%a/i', $format)) // There is some text to translate
  1755. {
  1756. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1757. $format = str_replace('%a', '__a__', $format);
  1758. $format = str_replace('%A', '__A__', $format);
  1759. }
  1760. // Analyze date
  1761. $reg = array();
  1762. if (preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i', $time, $reg)) // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
  1763. {
  1764. dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  1765. return '';
  1766. } elseif (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $time, $reg)) // Still available to solve problems in extrafields of type date
  1767. {
  1768. // This part of code should not be used.
  1769. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  1770. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  1771. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  1772. $syear = (!empty($reg[1]) ? $reg[1] : '');
  1773. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  1774. $sday = (!empty($reg[3]) ? $reg[3] : '');
  1775. $shour = (!empty($reg[4]) ? $reg[4] : '');
  1776. $smin = (!empty($reg[5]) ? $reg[5] : '');
  1777. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  1778. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  1779. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  1780. } else {
  1781. // Date is a timestamps
  1782. if ($time < 100000000000) // Protection against bad date values
  1783. {
  1784. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1785. $ret = adodb_strftime($format, $timetouse, $to_gmt);
  1786. } else $ret = 'Bad value '.$time.' for date';
  1787. }
  1788. if (preg_match('/__b__/i', $format))
  1789. {
  1790. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1791. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1792. $month = adodb_strftime('%m', $timetouse);
  1793. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  1794. if ($encodetooutput)
  1795. {
  1796. $monthtext = $outputlangs->transnoentities('Month'.$month);
  1797. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  1798. } else {
  1799. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  1800. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1801. }
  1802. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1803. $ret = str_replace('__b__', $monthtextshort, $ret);
  1804. $ret = str_replace('__B__', $monthtext, $ret);
  1805. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1806. //return $ret;
  1807. }
  1808. if (preg_match('/__a__/i', $format))
  1809. {
  1810. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1811. $w = adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1812. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  1813. $ret = str_replace('__A__', $dayweek, $ret);
  1814. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  1815. }
  1816. return $ret;
  1817. }
  1818. /**
  1819. * Return an array with locale date info.
  1820. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1821. * WARNING: This function always use PHP server timezone to return locale informations !!!
  1822. * Usage must be avoid.
  1823. * FIXME: Replace this with PHP date function and a parameter $gm
  1824. *
  1825. * @param int $timestamp Timestamp
  1826. * @param boolean $fast Fast mode
  1827. * @return array Array of informations
  1828. * If no fast mode:
  1829. * 'seconds' => $secs,
  1830. * 'minutes' => $min,
  1831. * 'hours' => $hour,
  1832. * 'mday' => $day,
  1833. * 'wday' => $dow, 0=sunday, 6=saturday
  1834. * 'mon' => $month,
  1835. * 'year' => $year,
  1836. * 'yday' => floor($secsInYear/$_day_power),
  1837. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  1838. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  1839. * If fast mode:
  1840. * 'seconds' => $secs,
  1841. * 'minutes' => $min,
  1842. * 'hours' => $hour,
  1843. * 'mday' => $day,
  1844. * 'mon' => $month,
  1845. * 'year' => $year,
  1846. * 'yday' => floor($secsInYear/$_day_power),
  1847. * 'leap' => $leaf,
  1848. * 'ndays' => $ndays
  1849. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  1850. */
  1851. function dol_getdate($timestamp, $fast = false)
  1852. {
  1853. global $conf;
  1854. $usealternatemethod = false;
  1855. if ($timestamp <= 0) $usealternatemethod = true; // <= 1970
  1856. if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038
  1857. if ($usealternatemethod)
  1858. {
  1859. $arrayinfo = adodb_getdate($timestamp, $fast);
  1860. } else {
  1861. $arrayinfo = getdate($timestamp);
  1862. }
  1863. return $arrayinfo;
  1864. }
  1865. /**
  1866. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  1867. * Replace function mktime not available under Windows if year < 1970
  1868. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1869. *
  1870. * @param int $hour Hour (can be -1 for undefined)
  1871. * @param int $minute Minute (can be -1 for undefined)
  1872. * @param int $second Second (can be -1 for undefined)
  1873. * @param int $month Month (1 to 12)
  1874. * @param int $day Day (1 to 31)
  1875. * @param int $year Year
  1876. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  1877. * False or 0 or 'server' = local to server TZ
  1878. * 'user' = local to user TZ
  1879. * 'tz,TimeZone' = use specified timezone
  1880. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  1881. * @return int|string Date as a timestamp, '' or false if error
  1882. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  1883. */
  1884. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $check = 1)
  1885. {
  1886. global $conf;
  1887. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  1888. // Clean parameters
  1889. if ($hour == -1 || empty($hour)) $hour = 0;
  1890. if ($minute == -1 || empty($minute)) $minute = 0;
  1891. if ($second == -1 || empty($second)) $second = 0;
  1892. // Check parameters
  1893. if ($check)
  1894. {
  1895. if (!$month || !$day) return '';
  1896. if ($day > 31) return '';
  1897. if ($month > 12) return '';
  1898. if ($hour < 0 || $hour > 24) return '';
  1899. if ($minute < 0 || $minute > 60) return '';
  1900. if ($second < 0 || $second > 60) return '';
  1901. }
  1902. if (empty($gm) || $gm === 'server')
  1903. {
  1904. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  1905. $localtz = new DateTimeZone($default_timezone);
  1906. } elseif ($gm === 'user')
  1907. {
  1908. // We use dol_tz_string first because it is more reliable.
  1909. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  1910. try {
  1911. $localtz = new DateTimeZone($default_timezone);
  1912. } catch (Exception $e)
  1913. {
  1914. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  1915. $default_timezone = @date_default_timezone_get();
  1916. }
  1917. } elseif (strrpos($gm, "tz,") !== false)
  1918. {
  1919. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  1920. try {
  1921. $localtz = new DateTimeZone($timezone);
  1922. } catch (Exception $e)
  1923. {
  1924. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  1925. }
  1926. }
  1927. if (empty($localtz)) {
  1928. $localtz = new DateTimeZone('UTC');
  1929. }
  1930. //var_dump($localtz);
  1931. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  1932. $dt = new DateTime(null, $localtz);
  1933. $dt->setDate((int) $year, (int) $month, (int) $day);
  1934. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  1935. $date = $dt->getTimestamp(); // should include daylight saving time
  1936. //var_dump($date);
  1937. return $date;
  1938. }
  1939. /**
  1940. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  1941. *
  1942. * @param string $mode 'gmt' => we return GMT timestamp,
  1943. * 'tzserver' => we add the PHP server timezone
  1944. * 'tzref' => we add the company timezone
  1945. * 'tzuser' => we add the user timezone
  1946. * @return int $date Timestamp
  1947. */
  1948. function dol_now($mode = 'gmt')
  1949. {
  1950. $ret = 0;
  1951. if ($mode == 'gmt') $ret = time(); // Time for now at greenwich.
  1952. elseif ($mode == 'tzserver') // Time for now with PHP server timezone added
  1953. {
  1954. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1955. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  1956. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  1957. } /*elseif ($mode == 'tzref') // Time for now with parent company timezone is added
  1958. {
  1959. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1960. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  1961. $ret=dol_now('gmt')+($tzsecond*3600);
  1962. }*/
  1963. elseif ($mode == 'tzuser') // Time for now with user timezone added
  1964. {
  1965. //print 'time: '.time();
  1966. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  1967. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  1968. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  1969. }
  1970. return $ret;
  1971. }
  1972. /**
  1973. * Return string with formated size
  1974. *
  1975. * @param int $size Size to print
  1976. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1977. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  1978. * @return string Link
  1979. */
  1980. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  1981. {
  1982. global $conf, $langs;
  1983. $level = 1024;
  1984. if (!empty($conf->dol_optimize_smallscreen)) $shortunit = 1;
  1985. // Set value text
  1986. if (empty($shortvalue) || $size < ($level * 10))
  1987. {
  1988. $ret = $size;
  1989. $textunitshort = $langs->trans("b");
  1990. $textunitlong = $langs->trans("Bytes");
  1991. } else {
  1992. $ret = round($size / $level, 0);
  1993. $textunitshort = $langs->trans("Kb");
  1994. $textunitlong = $langs->trans("KiloBytes");
  1995. }
  1996. // Use long or short text unit
  1997. if (empty($shortunit)) { $ret .= ' '.$textunitlong; } else { $ret .= ' '.$textunitshort; }
  1998. return $ret;
  1999. }
  2000. /**
  2001. * Show Url link
  2002. *
  2003. * @param string $url Url to show
  2004. * @param string $target Target for link
  2005. * @param int $max Max number of characters to show
  2006. * @param int $withpicto With picto
  2007. * @return string HTML Link
  2008. */
  2009. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2010. {
  2011. global $langs;
  2012. if (empty($url)) return '';
  2013. $link = '<a href="';
  2014. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2015. $link .= $url;
  2016. $link .= '"';
  2017. if ($target) $link .= ' target="'.$target.'"';
  2018. $link .= '>';
  2019. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2020. $link .= dol_trunc($url, $max);
  2021. $link .= '</a>';
  2022. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2023. }
  2024. /**
  2025. * Show EMail link
  2026. *
  2027. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2028. * @param int $cid Id of contact if known
  2029. * @param int $socid Id of third party if known
  2030. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2031. * @param int $max Max number of characters to show
  2032. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2033. * @param int $withpicto Show picto
  2034. * @return string HTML Link
  2035. */
  2036. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2037. {
  2038. global $conf, $user, $langs, $hookmanager;
  2039. $newemail = $email;
  2040. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0;
  2041. if (empty($email)) return '&nbsp;';
  2042. if (!empty($addlink))
  2043. {
  2044. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2045. if (!preg_match('/^mailto:/i', $email)) $newemail .= 'mailto:';
  2046. $newemail .= $email;
  2047. $newemail .= '">';
  2048. $newemail .= dol_trunc($email, $max);
  2049. $newemail .= '</a>';
  2050. if ($showinvalid && !isValidEmail($email))
  2051. {
  2052. $langs->load("errors");
  2053. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2054. }
  2055. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2056. {
  2057. $type = 'AC_EMAIL'; $link = '';
  2058. 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>';
  2059. if ($link) $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2060. }
  2061. } else {
  2062. if ($showinvalid && !isValidEmail($email))
  2063. {
  2064. $langs->load("errors");
  2065. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2066. }
  2067. }
  2068. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2069. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2070. //$rep .= '</div>';
  2071. if ($hookmanager) {
  2072. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2073. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2074. if ($reshook > 0) {
  2075. $rep = '';
  2076. }
  2077. $rep .= $hookmanager->resPrint;
  2078. }
  2079. return $rep;
  2080. }
  2081. /**
  2082. * Get array of social network dictionary
  2083. *
  2084. * @return array Array of Social Networks Dictionary
  2085. */
  2086. function getArrayOfSocialNetworks()
  2087. {
  2088. global $conf, $db;
  2089. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2090. $sql .= " WHERE entity=".$conf->entity;
  2091. $socialnetworks = array();
  2092. $resql = $db->query($sql);
  2093. if ($resql) {
  2094. while ($obj = $db->fetch_object($resql)) {
  2095. $socialnetworks[$obj->code] = array(
  2096. 'rowid' => $obj->rowid,
  2097. 'label' => $obj->label,
  2098. 'url' => $obj->url,
  2099. 'icon' => $obj->icon,
  2100. 'active' => $obj->active,
  2101. );
  2102. }
  2103. }
  2104. return $socialnetworks;
  2105. }
  2106. /**
  2107. * Show social network link
  2108. *
  2109. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2110. * @param int $cid Id of contact if known
  2111. * @param int $socid Id of third party if known
  2112. * @param string $type 'skype','facebook',...
  2113. * @return string HTML Link
  2114. */
  2115. function dol_print_socialnetworks($value, $cid, $socid, $type)
  2116. {
  2117. global $conf, $user, $langs;
  2118. $htmllink = $value;
  2119. if (empty($value)) return '&nbsp;';
  2120. if (!empty($type))
  2121. {
  2122. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2123. $htmllink .= img_picto($langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright', 0);
  2124. $htmllink .= $value;
  2125. if ($type == 'skype')
  2126. {
  2127. $htmllink .= '&nbsp;';
  2128. $htmllink .= '<a href="skype:';
  2129. $htmllink .= $value;
  2130. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2131. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2132. $htmllink .= '</a><a href="skype:';
  2133. $htmllink .= $value;
  2134. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2135. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2136. $htmllink .= '</a>';
  2137. }
  2138. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype')
  2139. {
  2140. $addlink = 'AC_SKYPE';
  2141. $link = '';
  2142. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$addlink.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  2143. $htmllink .= ($link ? ' '.$link : '');
  2144. }
  2145. $htmllink .= '</div>';
  2146. } else {
  2147. $langs->load("errors");
  2148. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2149. }
  2150. return $htmllink;
  2151. }
  2152. /**
  2153. * Format phone numbers according to country
  2154. *
  2155. * @param string $phone Phone number to format
  2156. * @param string $countrycode Country code to use for formatting
  2157. * @param int $cid Id of contact if known
  2158. * @param int $socid Id of third party if known
  2159. * @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)
  2160. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2161. * @param string $withpicto Show picto
  2162. * @param string $titlealt Text to show on alt
  2163. * @param int $adddivfloat Add div float around phone.
  2164. * @return string Formated phone number
  2165. */
  2166. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2167. {
  2168. global $conf, $user, $langs, $mysoc, $hookmanager;
  2169. // Clean phone parameter
  2170. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2171. if (empty($phone)) { return ''; }
  2172. if ($conf->global->MAIN_PHONE_SEPAR) $separ = $conf->global->MAIN_PHONE_SEPAR;
  2173. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2174. // Short format for small screens
  2175. if ($conf->dol_optimize_smallscreen) $separ = '';
  2176. $newphone = $phone;
  2177. if (strtoupper($countrycode) == "FR")
  2178. {
  2179. // France
  2180. if (dol_strlen($phone) == 10) {
  2181. $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);
  2182. } elseif (dol_strlen($phone) == 7)
  2183. {
  2184. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2185. } elseif (dol_strlen($phone) == 9)
  2186. {
  2187. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2188. } elseif (dol_strlen($phone) == 11)
  2189. {
  2190. $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);
  2191. } elseif (dol_strlen($phone) == 12)
  2192. {
  2193. $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);
  2194. }
  2195. } elseif (strtoupper($countrycode) == "CA")
  2196. {
  2197. if (dol_strlen($phone) == 10) {
  2198. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2199. }
  2200. } elseif (strtoupper($countrycode) == "PT")
  2201. {//Portugal
  2202. if (dol_strlen($phone) == 13)
  2203. {//ex: +351_ABC_DEF_GHI
  2204. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2205. }
  2206. } elseif (strtoupper($countrycode) == "SR")
  2207. {//Suriname
  2208. if (dol_strlen($phone) == 10)
  2209. {//ex: +597_ABC_DEF
  2210. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2211. } elseif (dol_strlen($phone) == 11)
  2212. {//ex: +597_ABC_DEFG
  2213. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2214. }
  2215. } elseif (strtoupper($countrycode) == "DE")
  2216. {//Allemagne
  2217. if (dol_strlen($phone) == 14)
  2218. {//ex: +49_ABCD_EFGH_IJK
  2219. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2220. } elseif (dol_strlen($phone) == 13)
  2221. {//ex: +49_ABC_DEFG_HIJ
  2222. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2223. }
  2224. } elseif (strtoupper($countrycode) == "ES")
  2225. {//Espagne
  2226. if (dol_strlen($phone) == 12)
  2227. {//ex: +34_ABC_DEF_GHI
  2228. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2229. }
  2230. } elseif (strtoupper($countrycode) == "BF")
  2231. {// Burkina Faso
  2232. if (dol_strlen($phone) == 12)
  2233. {//ex : +22 A BC_DE_FG_HI
  2234. $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);
  2235. }
  2236. } elseif (strtoupper($countrycode) == "RO")
  2237. {// Roumanie
  2238. if (dol_strlen($phone) == 12)
  2239. {//ex : +40 AB_CDE_FG_HI
  2240. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2241. }
  2242. } elseif (strtoupper($countrycode) == "TR")
  2243. {//Turquie
  2244. if (dol_strlen($phone) == 13)
  2245. {//ex : +90 ABC_DEF_GHIJ
  2246. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2247. }
  2248. } elseif (strtoupper($countrycode) == "US")
  2249. {//Etat-Unis
  2250. if (dol_strlen($phone) == 12)
  2251. {//ex: +1 ABC_DEF_GHIJ
  2252. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2253. }
  2254. } elseif (strtoupper($countrycode) == "MX")
  2255. {//Mexique
  2256. if (dol_strlen($phone) == 12)
  2257. {//ex: +52 ABCD_EFG_HI
  2258. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2259. } elseif (dol_strlen($phone) == 11)
  2260. {//ex: +52 AB_CD_EF_GH
  2261. $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);
  2262. } elseif (dol_strlen($phone) == 13)
  2263. {//ex: +52 ABC_DEF_GHIJ
  2264. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2265. }
  2266. } elseif (strtoupper($countrycode) == "ML")
  2267. {//Mali
  2268. if (dol_strlen($phone) == 12)
  2269. {//ex: +223 AB_CD_EF_GH
  2270. $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);
  2271. }
  2272. } elseif (strtoupper($countrycode) == "TH")
  2273. {//Thaïlande
  2274. if (dol_strlen($phone) == 11)
  2275. {//ex: +66_ABC_DE_FGH
  2276. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2277. } elseif (dol_strlen($phone) == 12)
  2278. {//ex: +66_A_BCD_EF_GHI
  2279. $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);
  2280. }
  2281. } elseif (strtoupper($countrycode) == "MU")
  2282. {
  2283. //Maurice
  2284. if (dol_strlen($phone) == 11)
  2285. {//ex: +230_ABC_DE_FG
  2286. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2287. } elseif (dol_strlen($phone) == 12)
  2288. {//ex: +230_ABCD_EF_GH
  2289. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2290. }
  2291. } elseif (strtoupper($countrycode) == "ZA")
  2292. {//Afrique du sud
  2293. if (dol_strlen($phone) == 12)
  2294. {//ex: +27_AB_CDE_FG_HI
  2295. $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);
  2296. }
  2297. } elseif (strtoupper($countrycode) == "SY")
  2298. {//Syrie
  2299. if (dol_strlen($phone) == 12)
  2300. {//ex: +963_AB_CD_EF_GH
  2301. $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);
  2302. } elseif (dol_strlen($phone) == 13)
  2303. {//ex: +963_AB_CD_EF_GHI
  2304. $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);
  2305. }
  2306. } elseif (strtoupper($countrycode) == "AE")
  2307. {//Emirats Arabes Unis
  2308. if (dol_strlen($phone) == 12)
  2309. {//ex: +971_ABC_DEF_GH
  2310. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2311. } elseif (dol_strlen($phone) == 13)
  2312. {//ex: +971_ABC_DEF_GHI
  2313. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2314. } elseif (dol_strlen($phone) == 14)
  2315. {//ex: +971_ABC_DEF_GHIK
  2316. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2317. }
  2318. } elseif (strtoupper($countrycode) == "DZ")
  2319. {//Algérie
  2320. if (dol_strlen($phone) == 13)
  2321. {//ex: +213_ABC_DEF_GHI
  2322. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2323. }
  2324. } elseif (strtoupper($countrycode) == "BE")
  2325. {//Belgique
  2326. if (dol_strlen($phone) == 11)
  2327. {//ex: +32_ABC_DE_FGH
  2328. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2329. } elseif (dol_strlen($phone) == 12)
  2330. {//ex: +32_ABC_DEF_GHI
  2331. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2332. }
  2333. } elseif (strtoupper($countrycode) == "PF")
  2334. {//Polynésie française
  2335. if (dol_strlen($phone) == 12)
  2336. {//ex: +689_AB_CD_EF_GH
  2337. $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);
  2338. }
  2339. } elseif (strtoupper($countrycode) == "CO")
  2340. {//Colombie
  2341. if (dol_strlen($phone) == 13)
  2342. {//ex: +57_ABC_DEF_GH_IJ
  2343. $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);
  2344. }
  2345. } elseif (strtoupper($countrycode) == "JO")
  2346. {//Jordanie
  2347. if (dol_strlen($phone) == 12)
  2348. {//ex: +962_A_BCD_EF_GH
  2349. $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);
  2350. }
  2351. } elseif (strtoupper($countrycode) == "JM")
  2352. {//Jamaïque
  2353. if (dol_strlen($newphone) == 12)
  2354. {//ex: +1867_ABC_DEFG
  2355. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2356. }
  2357. } elseif (strtoupper($countrycode) == "MG")
  2358. {//Madagascar
  2359. if (dol_strlen($phone) == 13)
  2360. {//ex: +261_AB_CD_EF_GHI
  2361. $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);
  2362. }
  2363. } elseif (strtoupper($countrycode) == "GB")
  2364. {//Royaume uni
  2365. if (dol_strlen($phone) == 13)
  2366. {//ex: +44_ABCD_EFG_HIJ
  2367. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2368. }
  2369. } elseif (strtoupper($countrycode) == "CH")
  2370. {//Suisse
  2371. if (dol_strlen($phone) == 12)
  2372. {//ex: +41_AB_CDE_FG_HI
  2373. $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);
  2374. } elseif (dol_strlen($phone) == 15)
  2375. {// +41_AB_CDE_FGH_IJKL
  2376. $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);
  2377. }
  2378. } elseif (strtoupper($countrycode) == "TN")
  2379. {//Tunisie
  2380. if (dol_strlen($phone) == 12)
  2381. {//ex: +216_AB_CDE_FGH
  2382. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2383. }
  2384. } elseif (strtoupper($countrycode) == "GF")
  2385. {//Guyane francaise
  2386. if (dol_strlen($phone) == 13)
  2387. {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2388. $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);
  2389. }
  2390. } elseif (strtoupper($countrycode) == "GP")
  2391. {//Guadeloupe
  2392. if (dol_strlen($phone) == 13)
  2393. {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2394. $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);
  2395. }
  2396. } elseif (strtoupper($countrycode) == "MQ")
  2397. {//Martinique
  2398. if (dol_strlen($phone) == 13)
  2399. {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2400. $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);
  2401. }
  2402. } elseif (strtoupper($countrycode) == "IT")
  2403. {//Italie
  2404. if (dol_strlen($phone) == 12)
  2405. {//ex: +39_ABC_DEF_GHI
  2406. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2407. } elseif (dol_strlen($phone) == 13)
  2408. {//ex: +39_ABC_DEF_GH_IJ
  2409. $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);
  2410. }
  2411. } elseif (strtoupper($countrycode) == "AU")
  2412. {
  2413. //Australie
  2414. if (dol_strlen($phone) == 12)
  2415. {
  2416. //ex: +61_A_BCDE_FGHI
  2417. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2418. }
  2419. }
  2420. if (!empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2421. {
  2422. if ($conf->browser->layout == 'phone' || (!empty($conf->clicktodial->enabled) && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) // If phone or option for, we use link of phone
  2423. {
  2424. $newphoneform = $newphone;
  2425. $newphone = '<a href="tel:'.$phone.'"';
  2426. $newphone .= '>'.$newphoneform.'</a>';
  2427. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  2428. {
  2429. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  2430. // Define urlmask
  2431. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2432. if (!empty($conf->global->CLICKTODIAL_URL)) $urlmask = $conf->global->CLICKTODIAL_URL;
  2433. if (!empty($user->clicktodial_url)) $urlmask = $user->clicktodial_url;
  2434. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2435. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2436. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2437. // This line is for backward compatibility
  2438. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2439. // Thoose lines are for substitution
  2440. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2441. '__PHONETO__'=>urlencode($phone),
  2442. '__LOGIN__'=>$clicktodial_login,
  2443. '__PASS__'=>$clicktodial_password);
  2444. $url = make_substitutions($url, $substitarray);
  2445. $newphonesav = $newphone;
  2446. $newphone = '<a href="'.$url.'"';
  2447. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone .= ' target="_blank"';
  2448. $newphone .= '>'.$newphonesav.'</a>';
  2449. }
  2450. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2451. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2452. {
  2453. $type = 'AC_TEL'; $link = '';
  2454. if ($addlink == 'AC_FAX') $type = 'AC_FAX';
  2455. 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>';
  2456. if ($link) $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2457. }
  2458. }
  2459. if (empty($titlealt))
  2460. {
  2461. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2462. }
  2463. $rep = '';
  2464. if ($hookmanager) {
  2465. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2466. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2467. $rep .= $hookmanager->resPrint;
  2468. }
  2469. if (empty($reshook))
  2470. {
  2471. $picto = '';
  2472. if ($withpicto) {
  2473. if ($withpicto == 'fax') {
  2474. $picto = 'phoning_fax';
  2475. } elseif ($withpicto == 'phone') {
  2476. $picto = 'phoning';
  2477. } elseif ($withpicto == 'mobile') {
  2478. $picto = 'phoning_mobile';
  2479. } else {
  2480. $picto = '';
  2481. }
  2482. }
  2483. if ($adddivfloat) $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2484. else $rep .= '<span style="margin-right: 10px;">';
  2485. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2486. if ($adddivfloat) $rep .= '</div>';
  2487. else $rep .= '</span>';
  2488. }
  2489. return $rep;
  2490. }
  2491. /**
  2492. * Return an IP formated to be shown on screen
  2493. *
  2494. * @param string $ip IP
  2495. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2496. * @return string Formated IP, with country if GeoIP module is enabled
  2497. */
  2498. function dol_print_ip($ip, $mode = 0)
  2499. {
  2500. global $conf, $langs;
  2501. $ret = '';
  2502. if (empty($mode)) $ret .= $ip;
  2503. if ($mode != 2)
  2504. {
  2505. $countrycode = dolGetCountryCodeFromIp($ip);
  2506. if ($countrycode) // If success, countrycode is us, fr, ...
  2507. {
  2508. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  2509. {
  2510. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2511. } else $ret .= ' ('.$countrycode.')';
  2512. } else {
  2513. // Nothing
  2514. }
  2515. }
  2516. return $ret;
  2517. }
  2518. /**
  2519. * Return the IP of remote user.
  2520. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2521. * Then HTTP_CLIENT_IP if defined (rare)
  2522. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2523. *
  2524. * @return string Ip of remote user.
  2525. */
  2526. function getUserRemoteIP()
  2527. {
  2528. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  2529. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  2530. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']);
  2531. } else {
  2532. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here
  2533. }
  2534. } else {
  2535. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here
  2536. }
  2537. return $ip;
  2538. }
  2539. /**
  2540. * Return a country code from IP. Empty string if not found.
  2541. *
  2542. * @param string $ip IP
  2543. * @return string Country code ('us', 'fr', ...)
  2544. */
  2545. function dolGetCountryCodeFromIp($ip)
  2546. {
  2547. global $conf;
  2548. $countrycode = '';
  2549. if (!empty($conf->geoipmaxmind->enabled))
  2550. {
  2551. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2552. //$ip='24.24.24.24';
  2553. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  2554. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2555. $geoip = new DolGeoIP('country', $datafile);
  2556. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2557. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2558. }
  2559. return $countrycode;
  2560. }
  2561. /**
  2562. * Return country code for current user.
  2563. * If software is used inside a local network, detection may fails (we need a public ip)
  2564. *
  2565. * @return string Country code (fr, es, it, us, ...)
  2566. */
  2567. function dol_user_country()
  2568. {
  2569. global $conf, $langs, $user;
  2570. //$ret=$user->xxx;
  2571. $ret = '';
  2572. if (!empty($conf->geoipmaxmind->enabled))
  2573. {
  2574. $ip = getUserRemoteIP();
  2575. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2576. //$ip='24.24.24.24';
  2577. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2578. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2579. $geoip = new DolGeoIP('country', $datafile);
  2580. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2581. $ret = $countrycode;
  2582. }
  2583. return $ret;
  2584. }
  2585. /**
  2586. * Format address string
  2587. *
  2588. * @param string $address Address string, already formatted with dol_format_address()
  2589. * @param int $htmlid Html ID (for example 'gmap')
  2590. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  2591. * @param int $id Id of object
  2592. * @param int $noprint No output. Result is the function return
  2593. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2594. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2595. * @see dol_format_address()
  2596. */
  2597. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  2598. {
  2599. global $conf, $user, $langs, $hookmanager;
  2600. $out = '';
  2601. if ($address)
  2602. {
  2603. if ($hookmanager) {
  2604. $parameters = array('element' => $element, 'id' => $id);
  2605. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2606. $out .= $hookmanager->resPrint;
  2607. }
  2608. if (empty($reshook))
  2609. {
  2610. if (empty($charfornl)) $out .= nl2br($address);
  2611. else $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  2612. // TODO Remove this block, we can add this using the hook now
  2613. $showgmap = $showomap = 0;
  2614. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap = 1;
  2615. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap = 1;
  2616. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap = 1;
  2617. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap = 1;
  2618. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap = 1;
  2619. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap = 1;
  2620. if ($showgmap)
  2621. {
  2622. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  2623. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2624. }
  2625. if ($showomap)
  2626. {
  2627. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  2628. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2629. }
  2630. }
  2631. }
  2632. if ($noprint) return $out;
  2633. else print $out;
  2634. }
  2635. /**
  2636. * Return true if email syntax is ok
  2637. *
  2638. * @param string $address email (Ex: "toto@examle.com", "John Do <johndo@example.com>")
  2639. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2640. * @return boolean true if email syntax is OK, false if KO or empty string
  2641. */
  2642. function isValidEmail($address, $acceptsupervisorkey = 0)
  2643. {
  2644. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2645. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2646. return false;
  2647. }
  2648. /**
  2649. * Return if the domain name has a valid MX record.
  2650. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  2651. *
  2652. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  2653. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  2654. */
  2655. function isValidMXRecord($domain)
  2656. {
  2657. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr'))
  2658. {
  2659. if (!checkdnsrr(idn_to_ascii($domain), 'MX'))
  2660. {
  2661. return 0;
  2662. }
  2663. if (function_exists('getmxrr'))
  2664. {
  2665. $mxhosts = array();
  2666. $weight = array();
  2667. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  2668. if (count($mxhosts) > 1) return 1;
  2669. if (count($mxhosts) == 1 && !empty($mxhosts[0])) return 1;
  2670. return 0;
  2671. }
  2672. }
  2673. return -1;
  2674. }
  2675. /**
  2676. * Return true if phone number syntax is ok
  2677. * TODO Decide what to do with this
  2678. *
  2679. * @param string $phone phone (Ex: "0601010101")
  2680. * @return boolean true if phone syntax is OK, false if KO or empty string
  2681. */
  2682. function isValidPhone($phone)
  2683. {
  2684. return true;
  2685. }
  2686. /**
  2687. * Make a strlen call. Works even if mbstring module not enabled
  2688. *
  2689. * @param string $string String to calculate length
  2690. * @param string $stringencoding Encoding of string
  2691. * @return int Length of string
  2692. */
  2693. function dol_strlen($string, $stringencoding = 'UTF-8')
  2694. {
  2695. if (function_exists('mb_strlen')) return mb_strlen($string, $stringencoding);
  2696. else return strlen($string);
  2697. }
  2698. /**
  2699. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  2700. *
  2701. * @param string $string String to scan
  2702. * @param string $start Start position
  2703. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  2704. * @param string $stringencoding Page code used for input string encoding
  2705. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  2706. * @return string substring
  2707. */
  2708. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  2709. {
  2710. global $langs;
  2711. if (empty($stringencoding)) $stringencoding = $langs->charset_output;
  2712. $ret = '';
  2713. if (empty($trunconbytes))
  2714. {
  2715. if (function_exists('mb_substr'))
  2716. {
  2717. $ret = mb_substr($string, $start, $length, $stringencoding);
  2718. } else {
  2719. $ret = substr($string, $start, $length);
  2720. }
  2721. } else {
  2722. if (function_exists('mb_strcut'))
  2723. {
  2724. $ret = mb_strcut($string, $start, $length, $stringencoding);
  2725. } else {
  2726. $ret = substr($string, $start, $length);
  2727. }
  2728. }
  2729. return $ret;
  2730. }
  2731. /**
  2732. * Truncate a string to a particular length adding '...' if string larger than length.
  2733. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2734. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2735. *
  2736. * @param string $string String to truncate
  2737. * @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 ...)
  2738. * @param string $trunc Where to trunc: right, left, middle (size must be a 2 power), wrap
  2739. * @param string $stringencoding Tell what is source string encoding
  2740. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2741. * @param int $display Trunc is used to display data and can be changed for small screen. TODO Remove this param (must be dealt with CSS)
  2742. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  2743. */
  2744. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  2745. {
  2746. global $conf;
  2747. if ($size == 0 || !empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2748. if (empty($stringencoding)) $stringencoding = 'UTF-8';
  2749. // reduce for small screen
  2750. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) $size = round($size / 3);
  2751. // We go always here
  2752. if ($trunc == 'right')
  2753. {
  2754. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2755. 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 ...
  2756. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...');
  2757. else //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  2758. return $string;
  2759. } elseif ($trunc == 'middle')
  2760. {
  2761. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2762. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1))
  2763. {
  2764. $size1 = round($size / 2);
  2765. $size2 = round($size / 2);
  2766. return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  2767. } else return $string;
  2768. } elseif ($trunc == 'left')
  2769. {
  2770. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2771. 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 ...
  2772. return '...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  2773. else return $string;
  2774. } elseif ($trunc == 'wrap')
  2775. {
  2776. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2777. if (dol_strlen($newstring, $stringencoding) > ($size + 1))
  2778. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  2779. else return $string;
  2780. } else return 'BadParam3CallingDolTrunc';
  2781. }
  2782. /**
  2783. * Show picto whatever it's its name (generic function)
  2784. *
  2785. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  2786. * @param string $picto Name of image file to show ('filenew', ...)
  2787. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2788. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2789. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2790. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2791. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2792. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  2793. * @param int $srconly Return only content of the src attribute of img.
  2794. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2795. * @param string $alt Force alt for bind people
  2796. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  2797. * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No margin left. Works for fontawesome picto only.
  2798. * @return string Return img tag
  2799. * @see img_object(), img_picto_common()
  2800. */
  2801. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  2802. {
  2803. global $conf, $langs;
  2804. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2805. $url = DOL_URL_ROOT;
  2806. $theme = $conf->theme;
  2807. $path = 'theme/'.$theme;
  2808. // Define fullpathpicto to use into src
  2809. if ($pictoisfullpath) {
  2810. // Clean parameters
  2811. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  2812. $picto .= '.png';
  2813. }
  2814. $fullpathpicto = $picto;
  2815. $reg = array();
  2816. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2817. $morecss .= ($morecss ? ' ' : '').$reg[1];
  2818. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  2819. }
  2820. } else {
  2821. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  2822. if (empty($srconly) && in_array($pictowithouttext, array(
  2823. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  2824. 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'bank_account', 'barcode', 'bank', 'bill', 'bookmark', 'bom', 'building',
  2825. 'cash-register', 'category', 'check', 'clock', 'close_title', 'company', 'contact', 'contract', 'cubes',
  2826. 'delete', 'dolly', 'dollyrevert', 'edit', 'ellipsis-h', 'email', 'external-link-alt', 'external-link-square-alt',
  2827. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title',
  2828. 'help', 'holiday',
  2829. 'intervention', 'label', 'language', 'list', 'listlight', 'lot',
  2830. 'map-marker-alt', 'money-bill-alt', 'mrp', 'note',
  2831. 'object_accounting', 'object_account', 'object_accountline', 'object_action', 'object_barcode', 'object_bill', 'object_billa', 'object_billd', 'object_bom',
  2832. 'object_category', 'object_conversation', 'object_bookmark', 'object_bug', 'object_dolly', 'object_dollyrevert', 'object_generic', 'object_folder',
  2833. 'object_list-alt', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser',
  2834. 'object_cash-register', 'object_company', 'object_contact', 'object_contract', 'object_donation', 'object_dynamicprice',
  2835. 'object_globe', 'object_holiday', 'object_hrm', 'object_invoice', 'object_intervention', 'object_label',
  2836. 'object_margin', 'object_money-bill-alt', 'object_multicurrency', 'object_order', 'object_payment',
  2837. 'object_lot', 'object_mrp', 'object_payment', 'object_product', 'object_propal',
  2838. 'object_other', 'object_paragraph', 'object_poll', 'object_printer', 'object_project', 'object_projectpub', 'object_propal', 'object_resource', 'object_rss', 'object_projecttask',
  2839. 'object_recruitmentjobposition', 'object_recruitmentcandidature',
  2840. 'object_shipment', 'object_share-alt', 'object_supplier_invoice', 'object_supplier_invoicea', 'object_supplier_invoiced', 'object_supplier_order', 'object_supplier_proposal', 'object_service', 'object_stock',
  2841. 'object_technic', 'object_ticket', 'object_trip', 'object_user', 'object_group', 'object_member',
  2842. 'object_phoning', 'object_phoning_mobile', 'object_phoning_fax', 'object_email', 'object_website',
  2843. 'off', 'on', 'order',
  2844. 'paiment', 'play', 'playdisabled', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip',
  2845. 'setup', 'share-alt', 'sign-out', 'split', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  2846. 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  2847. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  2848. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  2849. 'payment', 'pencil-ruler', 'preview', 'project', 'projectpub', 'refresh', 'supplier_invoice', 'ticket',
  2850. 'error', 'warning',
  2851. 'recruitmentcandidature', 'recruitmentjobposition', 'resource',
  2852. 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  2853. 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda'
  2854. )
  2855. )) {
  2856. $fakey = $pictowithouttext;
  2857. $facolor = ''; $fasize = '';
  2858. $fa = 'fas';
  2859. if (in_array($pictowithouttext, array('clock', 'object_generic', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  2860. $fa = 'far';
  2861. }
  2862. if (in_array($pictowithouttext, array('black-tie', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  2863. $fa = 'fab';
  2864. }
  2865. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  2866. $arrayconvpictotofa = array(
  2867. 'account'=>'university', 'accountline'=>'receipt', 'accountancy'=>'money-check-alt', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book',
  2868. 'bank_account'=>'university', 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'supplier_invoicea'=>'file-excel', 'billd'=>'file-medical', 'supplier_invoiced'=>'file-medical', 'bom'=>'cubes',
  2869. 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'conversation'=>'comments', 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  2870. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  2871. 'accounting'=>'chart-line', 'category'=>'tag', 'dollyrevert'=>'dolly',
  2872. 'hrm'=>'user-tie', 'margin'=>'calculator', 'members'=>'users', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  2873. 'email'=>'at',
  2874. 'edit'=>'pencil-alt', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  2875. 'generic'=>'file', 'holiday'=>'umbrella-beach', 'label'=>'layer-group',
  2876. 'member'=>'users', 'mrp'=>'cubes', 'trip'=>'wallet', 'group'=>'users',
  2877. 'sign-out'=>'sign-out-alt',
  2878. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star',
  2879. 'bank'=>'university', 'close_title'=>'window-close', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter',
  2880. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  2881. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  2882. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  2883. 'other'=>'square',
  2884. 'playdisabled'=>'play', 'poll'=>'check-double', 'preview'=>'binoculars', 'project'=>'sitemap', 'projectpub'=>'sitemap', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  2885. 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  2886. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  2887. 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell',
  2888. 'refresh'=>'redo', 'resource'=>'laptop-house',
  2889. 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt',
  2890. 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  2891. 'title_agenda'=>'calendar-alt',
  2892. 'uparrow'=>'mail-forward', 'vcard'=>'address-card',
  2893. 'jabber'=>'comment-o',
  2894. 'website'=>'globe-americas'
  2895. );
  2896. if ($pictowithouttext == 'off') {
  2897. $fakey = 'fa-square';
  2898. $fasize = '1.3em';
  2899. } elseif ($pictowithouttext == 'on') {
  2900. $fakey = 'fa-check-square';
  2901. $fasize = '1.3em';
  2902. } elseif ($pictowithouttext == 'listlight') {
  2903. $fakey = 'fa-download';
  2904. $marginleftonlyshort = 1;
  2905. } elseif ($pictowithouttext == 'printer') {
  2906. $fakey = 'fa-print';
  2907. $fasize = '1.2em';
  2908. } elseif ($pictowithouttext == 'note') {
  2909. $fakey = 'fa-sticky-note';
  2910. $marginleftonlyshort = 1;
  2911. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  2912. $convertarray = array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right');
  2913. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  2914. if (preg_match('/selected/', $pictowithouttext)) $facolor = '#888';
  2915. $marginleftonlyshort = 1;
  2916. } elseif (!empty($arrayconvpictotofa[$pictowithouttext]))
  2917. {
  2918. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  2919. } else {
  2920. $fakey = 'fa-'.$pictowithouttext;
  2921. }
  2922. // Define $marginleftonlyshort
  2923. $arrayconvpictotomarginleftonly = array(
  2924. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  2925. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_off',
  2926. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  2927. );
  2928. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  2929. $marginleftonlyshort = 0;
  2930. }
  2931. // Add CSS
  2932. $arrayconvpictotomorcess = array(
  2933. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account',
  2934. 'bank_account'=>'bg-infobox-bank_account',
  2935. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billd'=>'infobox-commande',
  2936. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'conversation'=>'infobox-contrat',
  2937. 'donation'=>'infobox-commande', 'dollyrevert'=>'flip', 'ecm'=>'infobox-action',
  2938. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  2939. 'multicurrency'=>'infobox-bank_account',
  2940. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  2941. 'order'=>'infobox-commande',
  2942. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  2943. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4',
  2944. 'holiday'=>'infobox-holiday', 'invoice'=>'infobox-commande',
  2945. 'payment'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  2946. 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  2947. 'resource'=>'infobox-action',
  2948. 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  2949. 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  2950. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  2951. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  2952. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  2953. );
  2954. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  2955. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  2956. }
  2957. // Define $color
  2958. $arrayconvpictotocolor = array(
  2959. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  2960. 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#37a', 'dynamicprice'=>'#a69944',
  2961. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999',
  2962. 'dolly'=>'#a69944', 'dollyrevert'=>'#a69944', 'lot'=>'#a69944',
  2963. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'stock'=>'#a69944',
  2964. 'other'=>'#ddd',
  2965. 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'resize'=>'#444', 'rss'=>'#cba',
  2966. 'shipment'=>'#a69944', 'stats'=>'#444', 'switch_off'=>'#999', 'uparrow'=>'#555', 'globe-americas'=>'#aaa',
  2967. 'website'=>'#304'
  2968. );
  2969. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  2970. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  2971. }
  2972. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  2973. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  2974. $reg = array();
  2975. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2976. $morecss .= ($morecss ? ' ' : '').$reg[1];
  2977. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  2978. }
  2979. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  2980. $morestyle = ' '.$reg[1];
  2981. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  2982. }
  2983. $moreatt = trim($moreatt);
  2984. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  2985. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  2986. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2987. $enabledisablehtml .= $titlealt;
  2988. }
  2989. $enabledisablehtml .= '</span>';
  2990. return $enabledisablehtml;
  2991. }
  2992. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  2993. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  2994. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  2995. $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
  2996. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  2997. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  2998. }
  2999. // If we ask an image into $url/$mymodule/img (instead of default path)
  3000. $regs = array();
  3001. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3002. $picto = $regs[1];
  3003. $path = $regs[2]; // $path is $mymodule
  3004. }
  3005. // Clean parameters
  3006. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3007. $picto .= '.png';
  3008. }
  3009. // If alt path are defined, define url where img file is, according to physical path
  3010. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3011. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3012. if ($type == 'main') {
  3013. continue;
  3014. }
  3015. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3016. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3017. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3018. break;
  3019. }
  3020. }
  3021. // $url is '' or '/custom', $path is current theme or
  3022. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3023. }
  3024. if ($srconly) {
  3025. return $fullpathpicto;
  3026. }
  3027. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3028. return '<img src="'.$fullpathpicto.'" alt="'.dol_escape_htmltag($alt).'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
  3029. }
  3030. /**
  3031. * Show a picto called object_picto (generic function)
  3032. *
  3033. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3034. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3035. * For external modules use imagename@mymodule to search into directory "img" of module.
  3036. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3037. * @param int $pictoisfullpath If 1, image path is a full path
  3038. * @param int $srconly Return only content of the src attribute of img.
  3039. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3040. * @return string Return img tag
  3041. * @see img_picto(), img_picto_common()
  3042. */
  3043. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3044. {
  3045. if (strpos($picto, '^') === 0) return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3046. else return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3047. }
  3048. /**
  3049. * Show weather picto
  3050. *
  3051. * @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.
  3052. * @param string|int $picto Name of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory. Or level of meteo image (0-4).
  3053. * @param string $moreatt Add more attribute on img tag
  3054. * @param int $pictoisfullpath If 1, image path is a full path
  3055. * @param string $morecss More CSS
  3056. * @return string Return img tag
  3057. * @see img_object(), img_picto()
  3058. */
  3059. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3060. {
  3061. global $conf;
  3062. if (is_numeric($picto)) {
  3063. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3064. //$picto = $leveltopicto[$picto];
  3065. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3066. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3067. $picto .= '.png';
  3068. }
  3069. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3070. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3071. }
  3072. /**
  3073. * Show picto (generic function)
  3074. *
  3075. * @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.
  3076. * @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.
  3077. * @param string $moreatt Add more attribute on img tag
  3078. * @param int $pictoisfullpath If 1, image path is a full path
  3079. * @return string Return img tag
  3080. * @see img_object(), img_picto()
  3081. */
  3082. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  3083. {
  3084. global $conf;
  3085. if (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  3086. if ($pictoisfullpath) $path = $picto;
  3087. else {
  3088. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3089. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  3090. {
  3091. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3092. if (file_exists($themepath)) $path = $themepath;
  3093. }
  3094. }
  3095. return img_picto($titlealt, $path, $moreatt, 1);
  3096. }
  3097. /**
  3098. * Show logo action
  3099. *
  3100. * @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.
  3101. * @param string $numaction Action id or code to show
  3102. * @param string $picto Name of image file to show ('filenew', ...)
  3103. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3104. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3105. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3106. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3107. * @return string Return an img tag
  3108. */
  3109. function img_action($titlealt, $numaction, $picto = '')
  3110. {
  3111. global $langs;
  3112. if (empty($titlealt) || $titlealt == 'default')
  3113. {
  3114. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3115. $numaction = -1;
  3116. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3117. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3118. $numaction = 0;
  3119. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3120. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3121. $numaction = 1;
  3122. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3123. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3124. $numaction = 2;
  3125. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3126. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3127. $numaction = 3;
  3128. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3129. } else {
  3130. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3131. $numaction = 0;
  3132. }
  3133. }
  3134. if (!is_numeric($numaction)) $numaction = 0;
  3135. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3136. }
  3137. /**
  3138. * Show pdf 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 int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3142. * @return string Retourne tag img
  3143. */
  3144. function img_pdf($titlealt = 'default', $size = 3)
  3145. {
  3146. global $langs;
  3147. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  3148. return img_picto($titlealt, 'pdf'.$size.'.png');
  3149. }
  3150. /**
  3151. * Show logo +
  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 string $other Add more attributes on img
  3155. * @return string Return tag img
  3156. */
  3157. function img_edit_add($titlealt = 'default', $other = '')
  3158. {
  3159. global $langs;
  3160. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  3161. return img_picto($titlealt, 'edit_add.png', $other);
  3162. }
  3163. /**
  3164. * Show logo -
  3165. *
  3166. * @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.
  3167. * @param string $other Add more attributes on img
  3168. * @return string Return tag img
  3169. */
  3170. function img_edit_remove($titlealt = 'default', $other = '')
  3171. {
  3172. global $langs;
  3173. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  3174. return img_picto($titlealt, 'edit_remove.png', $other);
  3175. }
  3176. /**
  3177. * Show logo editer/modifier fiche
  3178. *
  3179. * @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.
  3180. * @param integer $float If you have to put the style "float: right"
  3181. * @param string $other Add more attributes on img
  3182. * @return string Return tag img
  3183. */
  3184. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3185. {
  3186. global $langs;
  3187. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  3188. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3189. }
  3190. /**
  3191. * Show logo view card
  3192. *
  3193. * @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.
  3194. * @param integer $float If you have to put the style "float: right"
  3195. * @param string $other Add more attributes on img
  3196. * @return string Return tag img
  3197. */
  3198. function img_view($titlealt = 'default', $float = 0, $other = '')
  3199. {
  3200. global $langs;
  3201. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  3202. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3203. return img_picto($titlealt, 'view.png', $moreatt);
  3204. }
  3205. /**
  3206. * Show delete logo
  3207. *
  3208. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3209. * @param string $other Add more attributes on img
  3210. * @param string $morecss More CSS
  3211. * @return string Retourne tag img
  3212. */
  3213. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3214. {
  3215. global $langs;
  3216. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  3217. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3218. }
  3219. /**
  3220. * Show printer logo
  3221. *
  3222. * @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.
  3223. * @param string $other Add more attributes on img
  3224. * @return string Retourne tag img
  3225. */
  3226. function img_printer($titlealt = "default", $other = '')
  3227. {
  3228. global $langs;
  3229. if ($titlealt == "default") $titlealt = $langs->trans("Print");
  3230. return img_picto($titlealt, 'printer.png', $other);
  3231. }
  3232. /**
  3233. * Show split logo
  3234. *
  3235. * @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.
  3236. * @param string $other Add more attributes on img
  3237. * @return string Retourne tag img
  3238. */
  3239. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3240. {
  3241. global $langs;
  3242. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  3243. return img_picto($titlealt, 'split.png', $other);
  3244. }
  3245. /**
  3246. * Show help logo with cursor "?"
  3247. *
  3248. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3249. * @param int|string $usealttitle Text to use as alt title
  3250. * @return string Return tag img
  3251. */
  3252. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3253. {
  3254. global $langs;
  3255. if ($usealttitle)
  3256. {
  3257. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  3258. else $usealttitle = $langs->trans('Info');
  3259. }
  3260. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3261. }
  3262. /**
  3263. * Show info 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_info($titlealt = 'default')
  3269. {
  3270. global $langs;
  3271. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  3272. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3273. }
  3274. /**
  3275. * Show warning 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"'). If 1, add float: right. Can't be "class" attribute.
  3279. * @param string $morecss Add more CSS
  3280. * @return string Return img tag
  3281. */
  3282. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3283. {
  3284. global $langs;
  3285. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  3286. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3287. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3288. }
  3289. /**
  3290. * Show error logo
  3291. *
  3292. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3293. * @return string Return img tag
  3294. */
  3295. function img_error($titlealt = 'default')
  3296. {
  3297. global $langs;
  3298. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  3299. return img_picto($titlealt, 'error.png');
  3300. }
  3301. /**
  3302. * Show next logo
  3303. *
  3304. * @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.
  3305. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3306. * @return string Return img tag
  3307. */
  3308. function img_next($titlealt = 'default', $moreatt = '')
  3309. {
  3310. global $langs;
  3311. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  3312. //return img_picto($titlealt, 'next.png', $moreatt);
  3313. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3314. }
  3315. /**
  3316. * Show previous logo
  3317. *
  3318. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3319. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3320. * @return string Return img tag
  3321. */
  3322. function img_previous($titlealt = 'default', $moreatt = '')
  3323. {
  3324. global $langs;
  3325. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  3326. //return img_picto($titlealt, 'previous.png', $moreatt);
  3327. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3328. }
  3329. /**
  3330. * Show down arrow logo
  3331. *
  3332. * @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.
  3333. * @param int $selected Selected
  3334. * @param string $moreclass Add more CSS classes
  3335. * @return string Return img tag
  3336. */
  3337. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3338. {
  3339. global $langs;
  3340. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  3341. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3342. }
  3343. /**
  3344. * Show top arrow logo
  3345. *
  3346. * @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.
  3347. * @param int $selected Selected
  3348. * @param string $moreclass Add more CSS classes
  3349. * @return string Return img tag
  3350. */
  3351. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3352. {
  3353. global $langs;
  3354. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  3355. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3356. }
  3357. /**
  3358. * Show left arrow logo
  3359. *
  3360. * @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.
  3361. * @param int $selected Selected
  3362. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3363. * @return string Return img tag
  3364. */
  3365. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3366. {
  3367. global $langs;
  3368. if ($titlealt == 'default') {
  3369. $titlealt = $langs->trans('Left');
  3370. }
  3371. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3372. }
  3373. /**
  3374. * Show right arrow logo
  3375. *
  3376. * @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.
  3377. * @param int $selected Selected
  3378. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3379. * @return string Return img tag
  3380. */
  3381. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3382. {
  3383. global $langs;
  3384. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  3385. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3386. }
  3387. /**
  3388. * Show tick logo if allowed
  3389. *
  3390. * @param string $allow Allow
  3391. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  3392. * @return string Return img tag
  3393. */
  3394. function img_allow($allow, $titlealt = 'default')
  3395. {
  3396. global $langs;
  3397. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  3398. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  3399. return '-';
  3400. }
  3401. /**
  3402. * Return image of a credit card according to its brand name
  3403. *
  3404. * @param string $brand Brand name of credit card
  3405. * @param string $morecss More CSS
  3406. * @return string Return img tag
  3407. */
  3408. function img_credit_card($brand, $morecss = null)
  3409. {
  3410. if (is_null($morecss)) $morecss = 'fa-2x';
  3411. if ($brand == 'visa' || $brand == 'Visa') {
  3412. $brand = 'cc-visa';
  3413. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  3414. $brand = 'cc-mastercard';
  3415. } elseif ($brand == 'amex' || $brand == 'American Express') {
  3416. $brand = 'cc-amex';
  3417. } elseif ($brand == 'discover' || $brand == 'Discover') {
  3418. $brand = 'cc-discover';
  3419. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  3420. $brand = 'cc-jcb';
  3421. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  3422. $brand = 'cc-diners-club';
  3423. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  3424. $brand = 'credit-card';
  3425. }
  3426. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  3427. }
  3428. /**
  3429. * Show MIME img of a file
  3430. *
  3431. * @param string $file Filename
  3432. * @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.
  3433. * @param string $morecss More css
  3434. * @return string Return img tag
  3435. */
  3436. function img_mime($file, $titlealt = '', $morecss = '')
  3437. {
  3438. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3439. $mimetype = dol_mimetype($file, '', 1);
  3440. $mimeimg = dol_mimetype($file, '', 2);
  3441. $mimefa = dol_mimetype($file, '', 4);
  3442. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  3443. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3444. return '<i class="fa fa-'.$mimefa.' paddingright"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  3445. }
  3446. /**
  3447. * Show search logo
  3448. *
  3449. * @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.
  3450. * @param string $other Add more attributes on img
  3451. * @return string Retourne tag img
  3452. */
  3453. function img_search($titlealt = 'default', $other = '')
  3454. {
  3455. global $conf, $langs;
  3456. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3457. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3458. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3459. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3460. return $input;
  3461. }
  3462. /**
  3463. * Show search logo
  3464. *
  3465. * @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.
  3466. * @param string $other Add more attributes on img
  3467. * @return string Retourne tag img
  3468. */
  3469. function img_searchclear($titlealt = 'default', $other = '')
  3470. {
  3471. global $conf, $langs;
  3472. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3473. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3474. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3475. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3476. return $input;
  3477. }
  3478. /**
  3479. * Show information for admin users or standard users
  3480. *
  3481. * @param string $text Text info
  3482. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3483. * @param int $nodiv No div
  3484. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error','xxx'=Other
  3485. * @param string $morecss More CSS ('', 'warning', 'error')
  3486. * @param string $textfordropdown Show a text to click to dropdown the info box.
  3487. * @return string String with info text
  3488. */
  3489. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  3490. {
  3491. global $conf, $langs;
  3492. if ($infoonimgalt)
  3493. {
  3494. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  3495. } else {
  3496. if (empty($conf->use_javascript_ajax)) $textfordropdown = '';
  3497. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  3498. $result = ($nodiv ? '' : '<div class="'.$class.' hideonsmartphone'.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  3499. if ($textfordropdown) {
  3500. $tmpresult .= '<span class="'.$class.'text opacitymedium">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  3501. $tmpresult .= '<script type="text/javascript" language="javascript">
  3502. jQuery(document).ready(function() {
  3503. jQuery(".'.$class.'text").click(function() {
  3504. console.log("toggle text");
  3505. jQuery(".'.$class.'").toggle();
  3506. });
  3507. });
  3508. </script>';
  3509. $result = $tmpresult.$result;
  3510. }
  3511. }
  3512. return $result;
  3513. }
  3514. /**
  3515. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  3516. * This function must be called when a blocking technical error is encountered.
  3517. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  3518. *
  3519. * @param DoliDB $db Database handler
  3520. * @param mixed $error String or array of errors strings to show
  3521. * @param array $errors Array of errors
  3522. * @return void
  3523. * @see dol_htmloutput_errors()
  3524. */
  3525. function dol_print_error($db = '', $error = '', $errors = null)
  3526. {
  3527. global $conf, $langs, $argv;
  3528. global $dolibarr_main_prod;
  3529. $out = '';
  3530. $syslog = '';
  3531. // Si erreur intervenue avant chargement langue
  3532. if (!$langs)
  3533. {
  3534. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  3535. $langs = new Translate('', $conf);
  3536. $langs->load("main");
  3537. }
  3538. // Load translation files required by the page
  3539. $langs->loadLangs(array('main', 'errors'));
  3540. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3541. {
  3542. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  3543. 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";
  3544. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  3545. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  3546. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  3547. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  3548. if (function_exists("phpversion"))
  3549. {
  3550. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  3551. }
  3552. $out .= "<b>".$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";
  3553. if (function_exists("php_uname"))
  3554. {
  3555. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  3556. }
  3557. $out .= "<b>".$langs->trans("UserAgent").":</b> ".dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3558. $out .= "<br>\n";
  3559. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3560. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ?dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '')."<br>\n";
  3561. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? $conf->standard_menu : '')."<br>\n";
  3562. $out .= "<br>\n";
  3563. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  3564. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  3565. } else // Mode CLI
  3566. {
  3567. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  3568. $syslog .= "pid=".dol_getmypid();
  3569. }
  3570. if (!empty($conf->modules))
  3571. {
  3572. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  3573. }
  3574. if (is_object($db))
  3575. {
  3576. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3577. {
  3578. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  3579. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ?dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3580. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ?dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3581. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ?dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3582. $out .= "<br>\n";
  3583. } else // Mode CLI
  3584. {
  3585. // No dol_escape_htmltag for output, we are in CLI mode
  3586. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  3587. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3588. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3589. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3590. }
  3591. $syslog .= ", sql=".$db->lastquery();
  3592. $syslog .= ", db_error=".$db->lasterror();
  3593. }
  3594. if ($error || $errors)
  3595. {
  3596. $langs->load("errors");
  3597. // Merge all into $errors array
  3598. if (is_array($error) && is_array($errors)) $errors = array_merge($error, $errors);
  3599. elseif (is_array($error)) $errors = $error;
  3600. elseif (is_array($errors)) $errors = array_merge(array($error), $errors);
  3601. else $errors = array_merge(array($error));
  3602. foreach ($errors as $msg)
  3603. {
  3604. if (empty($msg)) continue;
  3605. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3606. {
  3607. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  3608. } else // Mode CLI
  3609. {
  3610. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  3611. }
  3612. $syslog .= ", msg=".$msg;
  3613. }
  3614. }
  3615. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  3616. {
  3617. xdebug_print_function_stack();
  3618. $out .= '<b>XDebug informations:</b>'."<br>\n";
  3619. $out .= 'File: '.xdebug_call_file()."<br>\n";
  3620. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  3621. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  3622. $out .= "<br>\n";
  3623. }
  3624. if (empty($dolibarr_main_prod)) print $out;
  3625. else {
  3626. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  3627. print 'This website or feature is currently temporarly not available or failed after a technical error.<br><br>This may be due to a maintenance operation. Current status of operation are on next line...<br><br>'."\n";
  3628. $langs->load("errors");
  3629. print $langs->trans("DolibarrHasDetectedError").'. ';
  3630. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  3631. define("MAIN_CORE_ERROR", 1);
  3632. }
  3633. //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.';
  3634. dol_syslog("Error ".$syslog, LOG_ERR);
  3635. }
  3636. /**
  3637. * Show a public email and error code to contact if technical error
  3638. *
  3639. * @param string $prefixcode Prefix of public error code
  3640. * @param string $errormessage Complete error message
  3641. * @param array $errormessages Array of error messages
  3642. * @param string $morecss More css
  3643. * @param string $email Email
  3644. * @return void
  3645. */
  3646. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  3647. {
  3648. global $langs, $conf;
  3649. if (empty($email)) $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  3650. $langs->load("errors");
  3651. $now = dol_now();
  3652. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  3653. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  3654. if ($errormessage) print '<br><br>'.$errormessage;
  3655. if (is_array($errormessages) && count($errormessages))
  3656. {
  3657. foreach ($errormessages as $mesgtoshow)
  3658. {
  3659. print '<br><br>'.$mesgtoshow;
  3660. }
  3661. }
  3662. print '</div></div>';
  3663. }
  3664. /**
  3665. * Show title line of an array
  3666. *
  3667. * @param string $name Label of field
  3668. * @param string $file Url used when we click on sort picto
  3669. * @param string $field Field to use for new sorting
  3670. * @param string $begin ("" by defaut)
  3671. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3672. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  3673. * @param string $sortfield Current field used to sort
  3674. * @param string $sortorder Current sort order
  3675. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  3676. * @param string $tooltip Tooltip
  3677. * @return void
  3678. */
  3679. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "")
  3680. {
  3681. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip);
  3682. }
  3683. /**
  3684. * Get title line of an array
  3685. *
  3686. * @param string $name Translation key of field
  3687. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  3688. * @param string $file Url used when we click on sort picto
  3689. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  3690. * @param string $begin ("" by defaut)
  3691. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3692. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  3693. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  3694. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  3695. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  3696. * @param string $disablesortlink 1=Disable sort link
  3697. * @param string $tooltip Tooltip
  3698. * @return string
  3699. */
  3700. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '')
  3701. {
  3702. global $conf, $langs, $form;
  3703. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  3704. if ($moreattrib == 'class="right"') $prefix .= 'right '; // For backward compatibility
  3705. $sortorder = strtoupper($sortorder);
  3706. $out = '';
  3707. $sortimg = '';
  3708. $tag = 'th';
  3709. if ($thead == 2) $tag = 'div';
  3710. $tmpsortfield = explode(',', $sortfield);
  3711. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  3712. $tmpfield = explode(',', $field);
  3713. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  3714. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE)) {
  3715. $prefix = 'wrapcolumntitle '.$prefix;
  3716. }
  3717. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  3718. // If field is used as sort criteria we use a specific css class liste_titre_sel
  3719. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  3720. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  3721. $out .= '<'.$tag.' class="'.$prefix.'liste_titre_sel" '.$moreattrib;
  3722. $out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && preg_match('/^[a-zA-Z_0-9\s\.\-:&;]*$/', $name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3723. $out .= '>';
  3724. } else {
  3725. $out .= '<'.$tag.' class="'.$prefix.'liste_titre" '.$moreattrib;
  3726. $out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && preg_match('/^[a-zA-Z_0-9\s\.\-:&;]*$/', $name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3727. $out .= '>';
  3728. }
  3729. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3730. {
  3731. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', $moreparam);
  3732. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3733. $options = preg_replace('/&+/i', '&', $options);
  3734. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3735. $sortordertouseinlink = '';
  3736. if ($field1 != $sortfield1) // We are on another field than current sorted field
  3737. {
  3738. if (preg_match('/^DESC/i', $sortorder))
  3739. {
  3740. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3741. } else // We reverse the var $sortordertouseinlink
  3742. {
  3743. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3744. }
  3745. } else // We are on field that is the first current sorting criteria
  3746. {
  3747. if (preg_match('/^ASC/i', $sortorder)) // We reverse the var $sortordertouseinlink
  3748. {
  3749. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3750. } else {
  3751. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3752. }
  3753. }
  3754. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  3755. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  3756. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3757. $out .= '>';
  3758. }
  3759. if ($tooltip) $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tooltip));
  3760. else $out .= $langs->trans($name);
  3761. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3762. {
  3763. $out .= '</a>';
  3764. }
  3765. if (empty($thead) && $field) // If this is a sort field
  3766. {
  3767. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', $moreparam);
  3768. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3769. $options = preg_replace('/&+/i', '&', $options);
  3770. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3771. if (!$sortorder || $field1 != $sortfield1)
  3772. {
  3773. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3774. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3775. } else {
  3776. if (preg_match('/^DESC/', $sortorder)) {
  3777. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3778. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3779. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  3780. }
  3781. if (preg_match('/^ASC/', $sortorder)) {
  3782. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3783. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3784. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  3785. }
  3786. }
  3787. }
  3788. $out .= $sortimg;
  3789. $out .= '</'.$tag.'>';
  3790. return $out;
  3791. }
  3792. /**
  3793. * Show a title.
  3794. *
  3795. * @param string $title Title to show
  3796. * @return string Title to show
  3797. * @deprecated Use load_fiche_titre instead
  3798. * @see load_fiche_titre()
  3799. */
  3800. function print_titre($title)
  3801. {
  3802. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  3803. print '<div class="titre">'.$title.'</div>';
  3804. }
  3805. /**
  3806. * Show a title with picto
  3807. *
  3808. * @param string $title Title to show
  3809. * @param string $mesg Added message to show on right
  3810. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3811. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3812. * @param int $id To force an id on html objects
  3813. * @return void
  3814. * @deprecated Use print load_fiche_titre instead
  3815. */
  3816. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  3817. {
  3818. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3819. }
  3820. /**
  3821. * Load a title with picto
  3822. *
  3823. * @param string $titre Title to show
  3824. * @param string $morehtmlright Added message to show on right
  3825. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3826. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3827. * @param string $id To force an id on html objects
  3828. * @param string $morecssontable More css on table
  3829. * @param string $morehtmlcenter Added message to show on center
  3830. * @return string
  3831. * @see print_barre_liste()
  3832. */
  3833. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  3834. {
  3835. global $conf;
  3836. $return = '';
  3837. if ($picto == 'setup') $picto = 'generic';
  3838. $return .= "\n";
  3839. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  3840. $return .= '<tr class="titre">';
  3841. if ($picto) $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  3842. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  3843. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  3844. $return .= '</td>';
  3845. if (dol_strlen($morehtmlcenter))
  3846. {
  3847. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3848. }
  3849. if (dol_strlen($morehtmlright))
  3850. {
  3851. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  3852. }
  3853. $return .= '</tr></table>'."\n";
  3854. return $return;
  3855. }
  3856. /**
  3857. * Print a title with navigation controls for pagination
  3858. *
  3859. * @param string $titre Title to show (required)
  3860. * @param int $page Numero of page to show in navigation links (required)
  3861. * @param string $file Url of page (required)
  3862. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  3863. * @param string $sortfield Field to sort on ('' by default)
  3864. * @param string $sortorder Order to sort ('' by default)
  3865. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  3866. * @param int $num Number of records found by select with limit+1
  3867. * @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.
  3868. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3869. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3870. * @param string $morehtmlright More html to show (after arrows)
  3871. * @param string $morecss More css to the table
  3872. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  3873. * @param int $hideselectlimit Force to hide select limit
  3874. * @param int $hidenavigation Force to hide all navigation tools
  3875. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  3876. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  3877. * @return void
  3878. */
  3879. function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'generic', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $hideselectlimit = 0, $hidenavigation = 0, $pagenavastextinput = 0, $morehtmlrightbeforearrow = '')
  3880. {
  3881. global $conf, $langs;
  3882. $savlimit = $limit;
  3883. $savtotalnboflines = $totalnboflines;
  3884. $totalnboflines = abs($totalnboflines);
  3885. if ($picto == 'setup') $picto = 'title_setup.png';
  3886. if (($conf->browser->name == 'ie') && $picto == 'generic') $picto = 'title.gif';
  3887. if ($limit < 0) $limit = $conf->liste_limit;
  3888. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  3889. {
  3890. $nextpage = 1;
  3891. } else {
  3892. $nextpage = 0;
  3893. }
  3894. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  3895. print "\n";
  3896. print "<!-- Begin title '".$titre."' -->\n";
  3897. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  3898. // Left
  3899. if ($picto && $titre) print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  3900. print '<td class="nobordernopadding valignmiddle col-title">';
  3901. print '<div class="titre inline-block">'.$titre;
  3902. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  3903. print '</div></td>';
  3904. // Center
  3905. if ($morehtmlcenter)
  3906. {
  3907. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3908. }
  3909. // Right
  3910. print '<td class="nobordernopadding valignmiddle right">';
  3911. if ($sortfield) $options .= "&sortfield=".urlencode($sortfield);
  3912. if ($sortorder) $options .= "&sortorder=".urlencode($sortorder);
  3913. // Show navigation bar
  3914. $pagelist = '';
  3915. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  3916. {
  3917. if ($totalnboflines) // If we know total nb of lines
  3918. {
  3919. // Define nb of extra page links before and after selected page + ... + first or last
  3920. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  3921. if ($limit > 0) $nbpages = ceil($totalnboflines / $limit);
  3922. else $nbpages = 1;
  3923. $cpt = ($page - $maxnbofpage);
  3924. if ($cpt < 0) { $cpt = 0; }
  3925. if ($cpt >= 1)
  3926. {
  3927. if (empty($pagenavastextinput)) {
  3928. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  3929. if ($cpt > 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  3930. elseif ($cpt == 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  3931. }
  3932. }
  3933. do {
  3934. if ($pagenavastextinput) {
  3935. if ($cpt == $page)
  3936. {
  3937. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  3938. $pagelist .= '/';
  3939. //if (($cpt + 1) < $nbpages) $pagelist .= '/';
  3940. }
  3941. } else {
  3942. if ($cpt == $page)
  3943. {
  3944. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  3945. } else {
  3946. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  3947. }
  3948. }
  3949. $cpt++;
  3950. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  3951. if (empty($pagenavastextinput)) {
  3952. if ($cpt < $nbpages)
  3953. {
  3954. if ($cpt < $nbpages - 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  3955. elseif ($cpt == $nbpages - 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  3956. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  3957. }
  3958. } else {
  3959. //var_dump($page.' '.$cpt.' '.$nbpages);
  3960. //if (($page + 1) < $nbpages) {
  3961. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  3962. //}
  3963. }
  3964. } else {
  3965. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  3966. }
  3967. }
  3968. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  3969. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow); // output the div and ul for previous/last completed with page numbers into $pagelist
  3970. }
  3971. // js to autoselect page field on focus
  3972. if ($pagenavastextinput) {
  3973. print ajax_autoselect('.pageplusone');
  3974. }
  3975. print '</td>';
  3976. print '</tr></table>'."\n";
  3977. print "<!-- End title -->\n\n";
  3978. }
  3979. /**
  3980. * Function to show navigation arrows into lists
  3981. *
  3982. * @param int $page Number of page
  3983. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  3984. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  3985. * @param integer $nextpage Do we show a next page button
  3986. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  3987. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  3988. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  3989. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  3990. * @param int $hideselectlimit Force to hide select limit
  3991. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  3992. * @return void
  3993. */
  3994. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  3995. {
  3996. global $conf, $langs;
  3997. print '<div class="pagination"><ul>';
  3998. if ($beforearrows)
  3999. {
  4000. print '<li class="paginationbeforearrows">';
  4001. print $beforearrows;
  4002. print '</li>';
  4003. }
  4004. if ((int) $limit > 0 && empty($hideselectlimit))
  4005. {
  4006. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  4007. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4008. //$pagesizechoices.=',2:2';
  4009. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4010. print '<li class="pagination">';
  4011. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4012. $tmpchoice = explode(',', $pagesizechoices);
  4013. $tmpkey = $limit.':'.$limit;
  4014. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4015. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4016. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4017. asort($tmpchoice, SORT_NUMERIC);
  4018. foreach ($tmpchoice as $val)
  4019. {
  4020. $selected = '';
  4021. $tmp = explode(':', $val);
  4022. $key = $tmp[0];
  4023. $val = $tmp[1];
  4024. if ($key != '' && $val != '')
  4025. {
  4026. if ((int) $key == (int) $limit)
  4027. {
  4028. $selected = ' selected="selected"';
  4029. }
  4030. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4031. }
  4032. }
  4033. print '</select>';
  4034. if ($conf->use_javascript_ajax)
  4035. {
  4036. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4037. <script>
  4038. jQuery(document).ready(function () {
  4039. jQuery(".selectlimit").change(function() {
  4040. console.log("Change limit. Send submit");
  4041. $(this).parents(\'form:first\').submit();
  4042. });
  4043. });
  4044. </script>
  4045. ';
  4046. }
  4047. print '</li>';
  4048. }
  4049. if ($page > 0)
  4050. {
  4051. print '<li class="pagination paginationpage paginationpageleft"><a class="paginationprevious" href="'.$file.'?page='.($page - 1).$options.'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag($langs->trans("Previous")).'"></i></a></li>';
  4052. }
  4053. if ($betweenarrows)
  4054. {
  4055. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4056. print $betweenarrows;
  4057. print '<!--</div>-->';
  4058. }
  4059. if ($nextpage > 0)
  4060. {
  4061. print '<li class="pagination paginationpage paginationpageright"><a class="paginationnext" href="'.$file.'?page='.($page + 1).$options.'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag($langs->trans("Next")).'"></i></a></li>';
  4062. }
  4063. if ($afterarrows)
  4064. {
  4065. print '<li class="paginationafterarrows">';
  4066. print $afterarrows;
  4067. print '</li>';
  4068. }
  4069. print '</ul></div>'."\n";
  4070. }
  4071. /**
  4072. * Return a string with VAT rate label formated for view output
  4073. * Used into pdf and HTML pages
  4074. *
  4075. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4076. * @param boolean $addpercent Add a percent % sign in output
  4077. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4078. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4079. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4080. */
  4081. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4082. {
  4083. $morelabel = '';
  4084. if (preg_match('/%/', $rate))
  4085. {
  4086. $rate = str_replace('%', '', $rate);
  4087. $addpercent = true;
  4088. }
  4089. if (preg_match('/\((.*)\)/', $rate, $reg))
  4090. {
  4091. $morelabel = ' ('.$reg[1].')';
  4092. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4093. }
  4094. if (preg_match('/\*/', $rate))
  4095. {
  4096. $rate = str_replace('*', '', $rate);
  4097. $info_bits |= 1;
  4098. }
  4099. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4100. if (!preg_match('/\//', $rate)) $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4101. else {
  4102. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4103. $ret = $rate.($addpercent ? '%' : '');
  4104. }
  4105. if (($info_bits & 1) && $usestarfornpr >= 0) $ret .= ' *';
  4106. $ret .= $morelabel;
  4107. return $ret;
  4108. }
  4109. /**
  4110. * Function to format a value into an amount for visual output
  4111. * Function used into PDF and HTML pages
  4112. *
  4113. * @param float $amount Amount to format
  4114. * @param integer $form Type of format, HTML or not (not by default)
  4115. * @param Translate $outlangs Object langs for output
  4116. * @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.
  4117. * @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)
  4118. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4119. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4120. * @return string Chaine avec montant formate
  4121. *
  4122. * @see price2num() Revert function of price
  4123. */
  4124. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4125. {
  4126. global $langs, $conf;
  4127. // Clean parameters
  4128. if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = ''
  4129. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4130. if ($rounding < 0) $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4131. $nbdecimal = $rounding;
  4132. // Output separators by default (french)
  4133. $dec = ','; $thousand = ' ';
  4134. // If $outlangs not forced, we use use language
  4135. if (!is_object($outlangs)) $outlangs = $langs;
  4136. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4137. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4138. if ($thousand == 'None') $thousand = '';
  4139. elseif ($thousand == 'Space') $thousand = ' ';
  4140. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4141. //print "amount=".$amount."-";
  4142. $amount = str_replace(',', '.', $amount); // should be useless
  4143. //print $amount."-";
  4144. $datas = explode('.', $amount);
  4145. $decpart = isset($datas[1]) ? $datas[1] : '';
  4146. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4147. //print "decpart=".$decpart."<br>";
  4148. $end = '';
  4149. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4150. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal = dol_strlen($decpart);
  4151. // Si on depasse max
  4152. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  4153. {
  4154. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4155. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN))
  4156. {
  4157. // Si un affichage est tronque, on montre des ...
  4158. $end = '...';
  4159. }
  4160. }
  4161. // If force rounding
  4162. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  4163. // Format number
  4164. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4165. if ($form)
  4166. {
  4167. $output = preg_replace('/\s/', '&nbsp;', $output);
  4168. $output = preg_replace('/\'/', '&#039;', $output);
  4169. }
  4170. // Add symbol of currency if requested
  4171. $cursymbolbefore = $cursymbolafter = '';
  4172. if ($currency_code)
  4173. {
  4174. if ($currency_code == 'auto') $currency_code = $conf->currency;
  4175. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4176. $listoflanguagesbefore = array('nl_NL');
  4177. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore))
  4178. {
  4179. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4180. } else {
  4181. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4182. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4183. }
  4184. }
  4185. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4186. return $output;
  4187. }
  4188. /**
  4189. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4190. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4191. * should be roundtext2num().
  4192. *
  4193. * @param float $amount Amount to convert/clean or round
  4194. * @param string $rounding ''=No rounding
  4195. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4196. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4197. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4198. * 'CR'=Currency rate
  4199. * Numeric = Nb of digits for rounding
  4200. * @param int $alreadysqlnb Put 1 if you know that content is already universal format number
  4201. * @return string Amount with universal numeric format (Example: '99.99999').
  4202. * If conversion fails, it return text unchanged if $rounding = '' or '0' if $rounding is defined.
  4203. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined..
  4204. *
  4205. * @see price() Opposite function of price2num
  4206. */
  4207. function price2num($amount, $rounding = '', $alreadysqlnb = 0)
  4208. {
  4209. global $langs, $conf;
  4210. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4211. // Numbers must be '1234.56'
  4212. // Decimal delimiter for PHP and database SQL requests must be '.'
  4213. $dec = ','; $thousand = ' ';
  4214. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4215. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4216. if ($thousand == 'None') $thousand = '';
  4217. elseif ($thousand == 'Space') $thousand = ' ';
  4218. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4219. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4220. if ($alreadysqlnb != 1) // If not a PHP number or unknown, we change format
  4221. {
  4222. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4223. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4224. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4225. if (is_numeric($amount))
  4226. {
  4227. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4228. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4229. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4230. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4231. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4232. }
  4233. //print "QQ".$amount.'<br>';
  4234. // Now make replace (the main goal of function)
  4235. if ($thousand != ',' && $thousand != '.') $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4236. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4237. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4238. $amount = str_replace($dec, '.', $amount);
  4239. }
  4240. // Now, make a rounding if required
  4241. if ($rounding)
  4242. {
  4243. $nbofdectoround = '';
  4244. if ($rounding == 'MU') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4245. elseif ($rounding == 'MT') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4246. elseif ($rounding == 'MS') $nbofdectoround = empty($conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : $conf->global->MAIN_MAX_DECIMALS_STOCK;
  4247. elseif ($rounding == 'CR') $nbofdectoround = 8;
  4248. elseif (is_numeric($rounding)) $nbofdectoround = $rounding;
  4249. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  4250. if (dol_strlen($nbofdectoround)) $amount = round($amount, $nbofdectoround); // $nbofdectoround can be 0.
  4251. else return 'ErrorBadParameterProvidedToFunction';
  4252. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4253. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4254. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4255. if (is_numeric($amount))
  4256. {
  4257. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4258. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4259. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4260. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4261. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4262. }
  4263. //print "TT".$amount.'<br>';
  4264. // Always make replace because each math function (like round) replace
  4265. // with local values and we want a number that has a SQL string format x.y
  4266. if ($thousand != ',' && $thousand != '.') $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4267. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4268. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4269. $amount = str_replace($dec, '.', $amount);
  4270. }
  4271. return $amount;
  4272. }
  4273. /**
  4274. * Output a dimension with best unit
  4275. *
  4276. * @param float $dimension Dimension
  4277. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4278. * @param string $type 'weight', 'volume', ...
  4279. * @param Translate $outputlangs Translate language object
  4280. * @param int $round -1 = non rounding, x = number of decimal
  4281. * @param string $forceunitoutput 'no' or numeric (-3, -6, ...) compared to $unit (In most case, this value is value defined into $conf->global->MAIN_WEIGHT_DEFAULT_UNIT)
  4282. * @return string String to show dimensions
  4283. */
  4284. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
  4285. {
  4286. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4287. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  4288. {
  4289. $dimension = $dimension * 1000000;
  4290. $unit = $unit - 6;
  4291. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  4292. {
  4293. $dimension = $dimension * 1000;
  4294. $unit = $unit - 3;
  4295. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  4296. {
  4297. $dimension = $dimension / 1000000;
  4298. $unit = $unit + 6;
  4299. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  4300. {
  4301. $dimension = $dimension / 1000;
  4302. $unit = $unit + 3;
  4303. }
  4304. // Special case when we want output unit into pound or ounce
  4305. /* TODO
  4306. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4307. {
  4308. $dimension = // convert dimension from standard unit into ounce or pound
  4309. $unit = $forceunitoutput;
  4310. }
  4311. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4312. {
  4313. $dimension = // convert dimension from standard unit into ounce or pound
  4314. $unit = $forceunitoutput;
  4315. }*/
  4316. $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuringUnitString(0, $type, $unit);
  4317. return $ret;
  4318. }
  4319. /**
  4320. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4321. * Note: This function applies same rules than get_default_tva
  4322. *
  4323. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4324. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4325. * @param Societe $thirdparty_buyer Object of buying third party
  4326. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4327. * @param int $vatnpr If vat rate is NPR or not
  4328. * @return mixed 0 if not found, localtax rate if found
  4329. * @see get_default_tva()
  4330. */
  4331. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  4332. {
  4333. global $db, $conf, $mysoc;
  4334. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) $thirdparty_seller = $mysoc;
  4335. 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);
  4336. $vatratecleaned = $vatrate;
  4337. $reg = array();
  4338. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4339. {
  4340. $vatratecleaned = trim($reg[1]);
  4341. $vatratecode = $reg[2];
  4342. }
  4343. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4344. {
  4345. return 0;
  4346. }*/
  4347. // Some test to guess with no need to make database access
  4348. if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4349. {
  4350. if ($local == 1)
  4351. {
  4352. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  4353. if ($thirdparty_seller->id == $mysoc->id)
  4354. {
  4355. if (!$thirdparty_buyer->localtax1_assuj) return 0;
  4356. } else {
  4357. if (!$thirdparty_seller->localtax1_assuj) return 0;
  4358. }
  4359. }
  4360. if ($local == 2)
  4361. {
  4362. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4363. if (!$mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0.
  4364. if ($thirdparty_seller->id == $mysoc->id)
  4365. {
  4366. if (!$thirdparty_buyer->localtax2_assuj) return 0;
  4367. } else {
  4368. if (!$thirdparty_seller->localtax2_assuj) return 0;
  4369. }
  4370. }
  4371. } else {
  4372. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) return 0;
  4373. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) return 0;
  4374. }
  4375. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4376. if (in_array($mysoc->country_code, array('ES')))
  4377. {
  4378. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4379. }
  4380. // Search local taxes
  4381. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  4382. {
  4383. if ($local == 1)
  4384. {
  4385. if ($thirdparty_seller != $mysoc)
  4386. {
  4387. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4388. {
  4389. return $thirdparty_seller->localtax1_value;
  4390. }
  4391. } else // i am the seller
  4392. {
  4393. if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4394. {
  4395. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4396. }
  4397. }
  4398. }
  4399. if ($local == 2)
  4400. {
  4401. if ($thirdparty_seller != $mysoc)
  4402. {
  4403. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4404. // TODO We should also return value defined on thirdparty only if defined
  4405. {
  4406. return $thirdparty_seller->localtax2_value;
  4407. }
  4408. } else // i am the seller
  4409. {
  4410. if (in_array($mysoc->country_code, array('ES')))
  4411. {
  4412. return $thirdparty_buyer->localtax2_value;
  4413. } else {
  4414. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4415. }
  4416. }
  4417. }
  4418. }
  4419. // By default, search value of local tax on line of common tax
  4420. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4421. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4422. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  4423. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4424. if ($vatratecode) $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  4425. else $sql .= " AND t.recuperableonly ='".$db->escape($vatnpr)."'";
  4426. dol_syslog("get_localtax", LOG_DEBUG);
  4427. $resql = $db->query($sql);
  4428. if ($resql)
  4429. {
  4430. $obj = $db->fetch_object($resql);
  4431. if ($local == 1) return $obj->localtax1;
  4432. elseif ($local == 2) return $obj->localtax2;
  4433. }
  4434. return 0;
  4435. }
  4436. /**
  4437. * Return true if LocalTax (1 or 2) is unique.
  4438. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  4439. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  4440. *
  4441. * @param int $local Local tax to test (1 or 2)
  4442. * @return boolean True if LocalTax have multiple values, False if not
  4443. */
  4444. function isOnlyOneLocalTax($local)
  4445. {
  4446. $tax = get_localtax_by_third($local);
  4447. $valors = explode(":", $tax);
  4448. if (count($valors) > 1)
  4449. {
  4450. return false;
  4451. } else {
  4452. return true;
  4453. }
  4454. }
  4455. /**
  4456. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  4457. *
  4458. * @param int $local LocalTax to get
  4459. * @return number Values of localtax
  4460. */
  4461. function get_localtax_by_third($local)
  4462. {
  4463. global $db, $mysoc;
  4464. $sql = "SELECT t.localtax1, t.localtax2 ";
  4465. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  4466. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  4467. $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";
  4468. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  4469. $sql .= " )";
  4470. $resql = $db->query($sql);
  4471. if ($resql)
  4472. {
  4473. $obj = $db->fetch_object($resql);
  4474. if ($local == 1) return $obj->localtax1;
  4475. elseif ($local == 2) return $obj->localtax2;
  4476. }
  4477. return 0;
  4478. }
  4479. /**
  4480. * Get vat main information from Id.
  4481. * You can call getLocalTaxesFromRate after to get other fields.
  4482. *
  4483. * @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.
  4484. * @param Societe $buyer Company object
  4485. * @param Societe $seller Company object
  4486. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  4487. * @return array array('rowid'=> , 'code'=> ...)
  4488. * @see getLocalTaxesFromRate()
  4489. */
  4490. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  4491. {
  4492. global $db, $mysoc;
  4493. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  4494. // Search local taxes
  4495. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
  4496. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4497. if ($firstparamisid) $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4498. else {
  4499. $vatratecleaned = $vatrate;
  4500. $vatratecode = '';
  4501. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4502. {
  4503. $vatratecleaned = $reg[1];
  4504. $vatratecode = $reg[2];
  4505. }
  4506. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4507. /*if ($mysoc->country_code == 'ES') $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // vat in spain use the buyer country ??
  4508. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  4509. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  4510. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4511. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4512. }
  4513. $resql = $db->query($sql);
  4514. if ($resql)
  4515. {
  4516. $obj = $db->fetch_object($resql);
  4517. 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);
  4518. else return array();
  4519. } else dol_print_error($db);
  4520. return array();
  4521. }
  4522. /**
  4523. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  4524. * This does not take into account the seller setup if subject to vat or not, only country.
  4525. * TODO
  4526. * This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  4527. * Instead this function must be called when adding a line to get the array of localtax and type, and then
  4528. * provide it to the function calcul_price_total.
  4529. *
  4530. * @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.
  4531. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  4532. * @param Societe $buyer Company object
  4533. * @param Societe $seller Company object
  4534. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  4535. * @return array array(localtax_type1(1-6/0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  4536. * @see getTaxesFromId()
  4537. */
  4538. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  4539. {
  4540. global $db, $mysoc;
  4541. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  4542. // Search local taxes
  4543. $sql = "SELECT t.taux as rate, t.code, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
  4544. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4545. if ($firstparamisid) $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4546. else {
  4547. $vatratecleaned = $vatrate;
  4548. $vatratecode = '';
  4549. $reg = array();
  4550. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "x.x (yy)"
  4551. {
  4552. $vatratecleaned = $reg[1];
  4553. $vatratecode = $reg[2];
  4554. }
  4555. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4556. if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  4557. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  4558. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4559. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4560. }
  4561. $resql = $db->query($sql);
  4562. if ($resql)
  4563. {
  4564. $obj = $db->fetch_object($resql);
  4565. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  4566. if ($local == 1)
  4567. {
  4568. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4569. } elseif ($local == 2)
  4570. {
  4571. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4572. } else {
  4573. return array($obj->localtax1_type, get_localtax($vateratestring, 1, $buyer, $seller), $obj->localtax2_type, get_localtax($vateratestring, 2, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4574. }
  4575. }
  4576. return 0;
  4577. }
  4578. /**
  4579. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  4580. * Function called by get_default_tva
  4581. *
  4582. * @param int $idprod Id of product or 0 if not a predefined product
  4583. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4584. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  4585. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  4586. * @see get_product_localtax_for_country()
  4587. */
  4588. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice = 0)
  4589. {
  4590. global $db, $conf, $mysoc;
  4591. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  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. if ($idprodfournprice > 0) // We want vat for product for a "supplier" object
  4602. {
  4603. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  4604. $ret = $product->vatrate_supplier;
  4605. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4606. } else {
  4607. $ret = $product->tva_tx; // Default vat of product we defined
  4608. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4609. }
  4610. $found = 1;
  4611. } else {
  4612. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  4613. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  4614. }
  4615. }
  4616. if (!$found)
  4617. {
  4618. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  4619. {
  4620. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  4621. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  4622. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4623. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4624. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  4625. $sql .= $db->plimit(1);
  4626. $resql = $db->query($sql);
  4627. if ($resql)
  4628. {
  4629. $obj = $db->fetch_object($resql);
  4630. if ($obj)
  4631. {
  4632. $ret = $obj->vat_rate;
  4633. if ($obj->default_vat_code) $ret .= ' ('.$obj->default_vat_code.')';
  4634. }
  4635. $db->free($sql);
  4636. } else dol_print_error($db);
  4637. } else $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  4638. }
  4639. dol_syslog("get_product_vat_for_country: ret=".$ret);
  4640. return $ret;
  4641. }
  4642. /**
  4643. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  4644. *
  4645. * @param int $idprod Id of product
  4646. * @param int $local 1 for localtax1, 2 for localtax 2
  4647. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4648. * @return int <0 if KO, Vat rate if OK
  4649. * @see get_product_vat_for_country()
  4650. */
  4651. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  4652. {
  4653. global $db, $mysoc;
  4654. if (!class_exists('Product')) {
  4655. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4656. }
  4657. $ret = 0;
  4658. $found = 0;
  4659. if ($idprod > 0)
  4660. {
  4661. // Load product
  4662. $product = new Product($db);
  4663. $result = $product->fetch($idprod);
  4664. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4665. {
  4666. /* Not defined yet, so we don't use this
  4667. if ($local==1) $ret=$product->localtax1_tx;
  4668. elseif ($local==2) $ret=$product->localtax2_tx;
  4669. $found=1;
  4670. */
  4671. } else {
  4672. // TODO Read default product vat according to countrycode and product
  4673. }
  4674. }
  4675. if (!$found)
  4676. {
  4677. // If vat of product for the country not found or not defined, we return higher vat of country.
  4678. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  4679. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4680. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4681. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  4682. $sql .= $db->plimit(1);
  4683. $resql = $db->query($sql);
  4684. if ($resql)
  4685. {
  4686. $obj = $db->fetch_object($resql);
  4687. if ($obj)
  4688. {
  4689. if ($local == 1) $ret = $obj->localtax1;
  4690. elseif ($local == 2) $ret = $obj->localtax2;
  4691. }
  4692. } else dol_print_error($db);
  4693. }
  4694. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  4695. return $ret;
  4696. }
  4697. /**
  4698. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  4699. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4700. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4701. * 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.
  4702. * 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
  4703. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  4704. * Sinon TVA proposee par defaut=0. Fin de regle.
  4705. *
  4706. * @param Societe $thirdparty_seller Objet societe vendeuse
  4707. * @param Societe $thirdparty_buyer Objet societe acheteuse
  4708. * @param int $idprod Id product
  4709. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  4710. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  4711. * @see get_default_npr(), get_default_localtax()
  4712. */
  4713. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4714. {
  4715. global $conf;
  4716. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4717. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  4718. $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;
  4719. $seller_country_code = $thirdparty_seller->country_code;
  4720. $seller_in_cee = isInEEC($thirdparty_seller);
  4721. $buyer_country_code = $thirdparty_buyer->country_code;
  4722. $buyer_in_cee = isInEEC($thirdparty_buyer);
  4723. dol_syslog("get_default_tva: seller use vat=".$seller_use_vat.", seller country=".$seller_country_code.", seller in cee=".$seller_in_cee.", buyer vat number=".$thirdparty_buyer->tva_intra." buyer country=".$buyer_country_code.", buyer in cee=".$buyer_in_cee.", idprod=".$idprod.", idprodfournprice=".$idprodfournprice.", SERVICE_ARE_ECOMMERCE_200238EC=".(!empty($conf->global->SERVICES_ARE_ECOMMERCE_200238EC) ? $conf->global->SERVICES_ARE_ECOMMERCE_200238EC : ''));
  4724. // 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)
  4725. // we use the buyer VAT.
  4726. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  4727. {
  4728. if ($seller_in_cee && $buyer_in_cee && !$thirdparty_buyer->isACompany())
  4729. {
  4730. //print 'VATRULE 0';
  4731. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  4732. }
  4733. }
  4734. // If seller does not use VAT
  4735. if (!$seller_use_vat)
  4736. {
  4737. //print 'VATRULE 1';
  4738. return 0;
  4739. }
  4740. // 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.
  4741. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4742. if (($seller_country_code == $buyer_country_code)
  4743. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) // Warning ->country_code not always defined
  4744. {
  4745. //print 'VATRULE 2';
  4746. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4747. }
  4748. // 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.
  4749. // Not supported
  4750. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  4751. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4752. if (($seller_in_cee && $buyer_in_cee))
  4753. {
  4754. $isacompany = $thirdparty_buyer->isACompany();
  4755. if ($isacompany)
  4756. {
  4757. //print 'VATRULE 3';
  4758. return 0;
  4759. } else {
  4760. //print 'VATRULE 4';
  4761. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4762. }
  4763. }
  4764. // Si (vendeur en France et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4765. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee) && !$thirdparty_buyer->isACompany()) {
  4766. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4767. }
  4768. // Sinon la TVA proposee par defaut=0. Fin de regle.
  4769. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  4770. //print 'VATRULE 5';
  4771. return 0;
  4772. }
  4773. /**
  4774. * Fonction qui renvoie si tva doit etre tva percue recuperable
  4775. *
  4776. * @param Societe $thirdparty_seller Thirdparty seller
  4777. * @param Societe $thirdparty_buyer Thirdparty buyer
  4778. * @param int $idprod Id product
  4779. * @param int $idprodfournprice Id supplier price for product
  4780. * @return float 0 or 1
  4781. * @see get_default_tva(), get_default_localtax()
  4782. */
  4783. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4784. {
  4785. global $db;
  4786. if ($idprodfournprice > 0)
  4787. {
  4788. if (!class_exists('ProductFournisseur')) {
  4789. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  4790. }
  4791. $prodprice = new ProductFournisseur($db);
  4792. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  4793. return $prodprice->fourn_tva_npr;
  4794. } elseif ($idprod > 0)
  4795. {
  4796. if (!class_exists('Product')) {
  4797. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4798. }
  4799. $prod = new Product($db);
  4800. $prod->fetch($idprod);
  4801. return $prod->tva_npr;
  4802. }
  4803. return 0;
  4804. }
  4805. /**
  4806. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4807. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4808. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4809. * Sinon TVA proposee par defaut=0. Fin de regle.
  4810. *
  4811. * @param Societe $thirdparty_seller Thirdparty seller
  4812. * @param Societe $thirdparty_buyer Thirdparty buyer
  4813. * @param int $local Localtax to process (1 or 2)
  4814. * @param int $idprod Id product
  4815. * @return integer localtax, -1 si ne peut etre determine
  4816. * @see get_default_tva(), get_default_npr()
  4817. */
  4818. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  4819. {
  4820. global $mysoc;
  4821. if (!is_object($thirdparty_seller)) return -1;
  4822. if (!is_object($thirdparty_buyer)) return -1;
  4823. if ($local == 1) // Localtax 1
  4824. {
  4825. if ($mysoc->country_code == 'ES')
  4826. {
  4827. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) return 0;
  4828. } else {
  4829. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  4830. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) return 0;
  4831. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') return 0;
  4832. }
  4833. } elseif ($local == 2) //I Localtax 2
  4834. {
  4835. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  4836. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) return 0;
  4837. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') return 0;
  4838. }
  4839. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  4840. {
  4841. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  4842. }
  4843. return 0;
  4844. }
  4845. /**
  4846. * Return yes or no in current language
  4847. *
  4848. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  4849. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  4850. * @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.
  4851. * @return string HTML string
  4852. */
  4853. function yn($yesno, $case = 1, $color = 0)
  4854. {
  4855. global $langs;
  4856. $result = 'unknown'; $classname = '';
  4857. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  4858. {
  4859. $result = $langs->trans('yes');
  4860. if ($case == 1 || $case == 3) $result = $langs->trans("Yes");
  4861. if ($case == 2) $result = '<input type="checkbox" value="1" checked disabled>';
  4862. if ($case == 3) $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  4863. $classname = 'ok';
  4864. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  4865. {
  4866. $result = $langs->trans("no");
  4867. if ($case == 1 || $case == 3) $result = $langs->trans("No");
  4868. if ($case == 2) $result = '<input type="checkbox" value="0" disabled>';
  4869. if ($case == 3) $result = '<input type="checkbox" value="0" disabled> '.$result;
  4870. if ($color == 2) $classname = 'ok';
  4871. else $classname = 'error';
  4872. }
  4873. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  4874. return $result;
  4875. }
  4876. /**
  4877. * Return a path to have a the directory according to object where files are stored.
  4878. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart)
  4879. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, $modulepart) if multidir_output not defined.
  4880. * Example our with new usage: $object is invoice -> 'INYYMM-ABCD'
  4881. * 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/"
  4882. *
  4883. * @param string $num Id of object (deprecated, $object will be used in future)
  4884. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  4885. * @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)
  4886. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  4887. * @param Object $object Object
  4888. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...')
  4889. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  4890. */
  4891. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
  4892. {
  4893. global $conf;
  4894. $path = '';
  4895. $arrayforoldpath = array('cheque', 'user', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  4896. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[] = 'product';
  4897. if (!empty($level) && in_array($modulepart, $arrayforoldpath))
  4898. {
  4899. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  4900. if (empty($alpha)) $num = preg_replace('/([^0-9])/i', '', $num);
  4901. else $num = preg_replace('/^.*\-/i', '', $num);
  4902. $num = substr("000".$num, -$level);
  4903. if ($level == 1) $path = substr($num, 0, 1);
  4904. if ($level == 2) $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  4905. if ($level == 3) $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  4906. } else {
  4907. // TODO
  4908. // We will enhance here a common way of forging path for document storage
  4909. // Here, object->id, object->ref and modulepart are required.
  4910. //var_dump($modulepart);
  4911. if (in_array($modulepart, array('thirdparty', 'contact', 'member', 'propal', 'proposal', 'commande', 'order', 'facture', 'invoice',
  4912. 'supplier_order', 'supplier_proposal', 'shipment', 'contract', 'expensereport', 'ficheinter')))
  4913. {
  4914. $path = ($object->ref ? $object->ref : $object->id);
  4915. }
  4916. }
  4917. if (empty($withoutslash) && !empty($path)) $path .= '/';
  4918. return $path;
  4919. }
  4920. /**
  4921. * Creation of a directory (this can create recursive subdir)
  4922. *
  4923. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  4924. * @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)
  4925. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  4926. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  4927. */
  4928. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  4929. {
  4930. global $conf;
  4931. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  4932. $dir_osencoded = dol_osencode($dir);
  4933. if (@is_dir($dir_osencoded)) return 0;
  4934. $nberr = 0;
  4935. $nbcreated = 0;
  4936. $ccdir = '';
  4937. if (!empty($dataroot)) {
  4938. // Remove data root from loop
  4939. $dir = str_replace($dataroot.'/', '', $dir);
  4940. $ccdir = $dataroot.'/';
  4941. }
  4942. $cdir = explode("/", $dir);
  4943. $num = count($cdir);
  4944. for ($i = 0; $i < $num; $i++)
  4945. {
  4946. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  4947. else $ccdir .= $cdir[$i];
  4948. if (preg_match("/^.:$/", $ccdir, $regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  4949. // Attention, le is_dir() peut echouer bien que le rep existe.
  4950. // (ex selon config de open_basedir)
  4951. if ($ccdir)
  4952. {
  4953. $ccdir_osencoded = dol_osencode($ccdir);
  4954. if (!@is_dir($ccdir_osencoded))
  4955. {
  4956. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  4957. umask(0);
  4958. $dirmaskdec = octdec($newmask);
  4959. if (empty($newmask)) {
  4960. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  4961. }
  4962. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  4963. if (!@mkdir($ccdir_osencoded, $dirmaskdec))
  4964. {
  4965. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  4966. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  4967. $nberr++;
  4968. } else {
  4969. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  4970. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  4971. $nbcreated++;
  4972. }
  4973. } else {
  4974. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  4975. }
  4976. }
  4977. }
  4978. return ($nberr ? -$nberr : $nbcreated);
  4979. }
  4980. /**
  4981. * Return picto saying a field is required
  4982. *
  4983. * @return string Chaine avec picto obligatoire
  4984. */
  4985. function picto_required()
  4986. {
  4987. return '<span class="fieldrequired">*</span>';
  4988. }
  4989. /**
  4990. * Clean a string from all HTML tags and entities.
  4991. * This function differs from strip_tags because:
  4992. * - <br> are replaced with \n if removelinefeed=0 or 1
  4993. * - if entities are found, they are decoded BEFORE the strip
  4994. * - you can decide to convert line feed into a space
  4995. *
  4996. * @param string $stringtoclean String to clean
  4997. * @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..."
  4998. * @param string $pagecodeto Encoding of input/output string
  4999. * @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)
  5000. * @return string String cleaned
  5001. *
  5002. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5003. */
  5004. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0)
  5005. {
  5006. if ($removelinefeed == 2) $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5007. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5008. // We remove entities BEFORE stripping (in case of a separator char is encoded and not the other, the strip will fails)
  5009. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5010. if ($strip_tags) {
  5011. $temp = strip_tags($temp);
  5012. } else {
  5013. $pattern = "/<[^<>]+>/";
  5014. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5015. $temp = preg_replace($pattern, "", $temp); // pass 1
  5016. // $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5017. $temp = preg_replace($pattern, "", $temp); // pass 2
  5018. // $temp after pass 2: 0000-021
  5019. }
  5020. // Remove also CR LF
  5021. if ($removelinefeed == 1) $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5022. // and double spaces
  5023. while (strpos($temp, " "))
  5024. {
  5025. $temp = str_replace(" ", " ", $temp);
  5026. }
  5027. return trim($temp);
  5028. }
  5029. /**
  5030. * Clean a string to keep only desirable HTML tags.
  5031. *
  5032. * @param string $stringtoclean String to clean
  5033. * @param boolean $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5034. * @param boolean $removeclassattribute Remove the class attribute from tags
  5035. * @return string String cleaned
  5036. *
  5037. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5038. */
  5039. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1)
  5040. {
  5041. $allowed_tags = array(
  5042. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5043. "ol", "p", "q", "s", "section", "span", "strike", "strong", "title", "table", "tr", "th", "td", "u", "ul", "sup", "sub", "blockquote", "pre", "h1", "h2", "h3", "h4", "h5", "h6"
  5044. );
  5045. $allowed_tags_string = join("><", $allowed_tags);
  5046. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5047. if ($cleanalsosomestyles) {
  5048. $stringtoclean = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $stringtoclean); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless
  5049. }
  5050. if ($removeclassattribute) {
  5051. $stringtoclean = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $stringtoclean);
  5052. }
  5053. // TODO Remove '/href=("|\'|)javascript/' string ?
  5054. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  5055. return $temp;
  5056. }
  5057. /**
  5058. * Clean a string from some undesirable HTML tags.
  5059. * Note. Not enough secured as dol_string_onlythesehtmltags().
  5060. *
  5061. * @param string $stringtoclean String to clean
  5062. * @param array $disallowed_tags Array of tags not allowed
  5063. * @param string $cleanalsosomestyles Clean also some tags
  5064. * @return string String cleaned
  5065. *
  5066. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags()
  5067. */
  5068. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5069. {
  5070. $temp = $stringtoclean;
  5071. foreach ($disallowed_tags as $tagtoremove)
  5072. {
  5073. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5074. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5075. }
  5076. if ($cleanalsosomestyles) {
  5077. $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/', '', $temp); // Note: If hacker try to introduce css comment into string to avoid this, string should be encoded by the dol_htmlentitiesbr so be harmless
  5078. }
  5079. return $temp;
  5080. }
  5081. /**
  5082. * Return first line of text. Cut will depends if content is HTML or not.
  5083. *
  5084. * @param string $text Input text
  5085. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5086. * @param string $charset Charset of $text string (UTF-8 by default)
  5087. * @return string Output text
  5088. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5089. */
  5090. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5091. {
  5092. if ($nboflines == 1)
  5093. {
  5094. if (dol_textishtml($text))
  5095. {
  5096. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5097. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5098. } else {
  5099. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5100. }
  5101. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5102. } else {
  5103. $ishtml = 0;
  5104. if (dol_textishtml($text))
  5105. {
  5106. $text = preg_replace('/\n/', '', $text);
  5107. $ishtml = 1;
  5108. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5109. } else {
  5110. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5111. }
  5112. $text = strtr($text, $repTable);
  5113. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5114. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5115. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5116. $firstline = '';
  5117. $i = 0;
  5118. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5119. while (($i < $nba) && ($i < ($nboflines * 2)))
  5120. {
  5121. if ($i % 2 == 0) $firstline .= $a[$i];
  5122. elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) $firstline .= ($ishtml ? "<br>\n" : "\n");
  5123. $i++;
  5124. }
  5125. unset($a);
  5126. return $firstline.(($i < $nba) ? '...' : '');
  5127. }
  5128. }
  5129. /**
  5130. * Replace CRLF in string with a HTML BR tag.
  5131. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have encode the special chars of stringtoencode into HTML before.
  5132. *
  5133. * @param string $stringtoencode String to encode
  5134. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5135. * @param bool $forxml false=Use <br>, true=Use <br />
  5136. * @return string String encoded
  5137. * @see dol_nboflines(), dolGetFirstLineOfText()
  5138. */
  5139. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5140. {
  5141. if (!$nl2brmode) {
  5142. return nl2br($stringtoencode, $forxml);
  5143. } else {
  5144. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  5145. return $ret;
  5146. }
  5147. }
  5148. /**
  5149. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5150. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5151. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5152. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5153. * For PDF usage, you can show text by 2 ways:
  5154. * - writeHTMLCell -> param must be encoded into HTML.
  5155. * - MultiCell -> param must not be encoded into HTML.
  5156. * Because writeHTMLCell convert also \n into <br>, if function
  5157. * is used to build PDF, nl2brmode must be 1.
  5158. *
  5159. * @param string $stringtoencode String to encode
  5160. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5161. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5162. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5163. * @return string String encoded
  5164. */
  5165. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  5166. {
  5167. $newstring = $stringtoencode;
  5168. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  5169. {
  5170. $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.
  5171. if ($removelasteolbr) $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  5172. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  5173. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  5174. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  5175. } else {
  5176. if ($removelasteolbr) $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  5177. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  5178. }
  5179. // Other substitutions that htmlentities does not do
  5180. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5181. return $newstring;
  5182. }
  5183. /**
  5184. * This function is called to decode a HTML string (it decodes entities and br tags)
  5185. *
  5186. * @param string $stringtodecode String to decode
  5187. * @param string $pagecodeto Page code for result
  5188. * @return string String decoded
  5189. */
  5190. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  5191. {
  5192. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT, $pagecodeto);
  5193. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  5194. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  5195. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  5196. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  5197. return $ret;
  5198. }
  5199. /**
  5200. * This function remove all ending \n and br at end
  5201. *
  5202. * @param string $stringtodecode String to decode
  5203. * @return string String decoded
  5204. */
  5205. function dol_htmlcleanlastbr($stringtodecode)
  5206. {
  5207. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
  5208. return $ret;
  5209. }
  5210. /**
  5211. * Replace html_entity_decode functions to manage errors
  5212. *
  5213. * @param string $a Operand a
  5214. * @param string $b Operand b (ENT_QUOTES=convert simple and double quotes)
  5215. * @param string $c Operand c
  5216. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  5217. * @return string String decoded
  5218. */
  5219. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  5220. {
  5221. $newstring = $a;
  5222. if ($keepsomeentities) $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  5223. $newstring = html_entity_decode($newstring, $b, $c);
  5224. if ($keepsomeentities) $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  5225. return $newstring;
  5226. }
  5227. /**
  5228. * Replace htmlentities functions.
  5229. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5230. *
  5231. * @param string $string The input string to encode
  5232. * @param int $flags Flags (see PHP doc above)
  5233. * @param string $encoding Encoding page code
  5234. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5235. * @return string $ret Encoded string
  5236. */
  5237. function dol_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = false)
  5238. {
  5239. return htmlentities($string, $flags, $encoding, $double_encode);
  5240. }
  5241. /**
  5242. * Check if a string is a correct iso string
  5243. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5244. * Example, if string contains euro symbol that has ascii code 128
  5245. *
  5246. * @param string $s String to check
  5247. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  5248. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  5249. */
  5250. function dol_string_is_good_iso($s, $clean = 0)
  5251. {
  5252. $len = dol_strlen($s);
  5253. $out = '';
  5254. $ok = 1;
  5255. for ($scursor = 0; $scursor < $len; $scursor++)
  5256. {
  5257. $ordchar = ord($s[$scursor]);
  5258. //print $scursor.'-'.$ordchar.'<br>';
  5259. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok = 0; break; } elseif ($ordchar > 126 && $ordchar < 160) { $ok = 0; break; } elseif ($clean) {
  5260. $out .= $s[$scursor];
  5261. }
  5262. }
  5263. if ($clean) return $out;
  5264. return $ok;
  5265. }
  5266. /**
  5267. * Return nb of lines of a clear text
  5268. *
  5269. * @param string $s String to check
  5270. * @param int $maxchar Not yet used
  5271. * @return int Number of lines
  5272. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  5273. */
  5274. function dol_nboflines($s, $maxchar = 0)
  5275. {
  5276. if ($s == '') return 0;
  5277. $arraystring = explode("\n", $s);
  5278. $nb = count($arraystring);
  5279. return $nb;
  5280. }
  5281. /**
  5282. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  5283. *
  5284. * @param string $text Text
  5285. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  5286. * @param string $charset Give the charset used to encode the $text variable in memory.
  5287. * @return int Number of lines
  5288. * @see dol_nboflines(), dolGetFirstLineOfText()
  5289. */
  5290. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  5291. {
  5292. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5293. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5294. $text = strtr($text, $repTable);
  5295. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5296. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5297. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5298. $nblines = (int) floor((count($a) + 1) / 2);
  5299. // count possible auto line breaks
  5300. if ($maxlinesize)
  5301. {
  5302. foreach ($a as $line)
  5303. {
  5304. if (dol_strlen($line) > $maxlinesize)
  5305. {
  5306. //$line_dec = html_entity_decode(strip_tags($line));
  5307. $line_dec = html_entity_decode($line);
  5308. if (dol_strlen($line_dec) > $maxlinesize)
  5309. {
  5310. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  5311. $nblines += substr_count($line_dec, '\n');
  5312. }
  5313. }
  5314. }
  5315. }
  5316. unset($a);
  5317. return $nblines;
  5318. }
  5319. /**
  5320. * Return if a text is a html content
  5321. *
  5322. * @param string $msg Content to check
  5323. * @param int $option 0=Full detection, 1=Fast check
  5324. * @return boolean true/false
  5325. * @see dol_concatdesc()
  5326. */
  5327. function dol_textishtml($msg, $option = 0)
  5328. {
  5329. if ($option == 1)
  5330. {
  5331. if (preg_match('/<html/i', $msg)) return true;
  5332. elseif (preg_match('/<body/i', $msg)) return true;
  5333. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5334. elseif (preg_match('/<br/i', $msg)) return true;
  5335. return false;
  5336. } else {
  5337. if (preg_match('/<html/i', $msg)) return true;
  5338. elseif (preg_match('/<body/i', $msg)) return true;
  5339. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5340. elseif (preg_match('/<(b|em|i|u)>/i', $msg)) return true;
  5341. elseif (preg_match('/<br\/>/i', $msg)) return true;
  5342. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) return true;
  5343. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg)) return true;
  5344. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg)) return true;
  5345. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  5346. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  5347. elseif (preg_match('/<h[0-9]>/i', $msg)) return true;
  5348. elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  5349. elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  5350. return false;
  5351. }
  5352. }
  5353. /**
  5354. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  5355. * text1 html + text2 html => text1 + '<br>' + text2
  5356. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  5357. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  5358. * text1 txt + text2 txt => text1 + '\n' + text2
  5359. *
  5360. * @param string $text1 Text 1
  5361. * @param string $text2 Text 2
  5362. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  5363. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  5364. * @return string Text 1 + new line + Text2
  5365. * @see dol_textishtml()
  5366. */
  5367. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  5368. {
  5369. if (!empty($invert))
  5370. {
  5371. $tmp = $text1;
  5372. $text1 = $text2;
  5373. $text2 = $tmp;
  5374. }
  5375. $ret = '';
  5376. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  5377. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  5378. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  5379. return $ret;
  5380. }
  5381. /**
  5382. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  5383. *
  5384. * @param Translate $outputlangs Output language
  5385. * @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)
  5386. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  5387. * @param Object $object Object for keys on object
  5388. * @return array Array of substitutions
  5389. * @see setSubstitFromObject()
  5390. */
  5391. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  5392. {
  5393. global $db, $conf, $mysoc, $user, $extrafields;
  5394. $substitutionarray = array();
  5395. if (empty($exclude) || !in_array('user', $exclude))
  5396. {
  5397. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  5398. // this will include signature content first and then replace var found into content of signature
  5399. $signature = $user->signature;
  5400. $substitutionarray = array_merge($substitutionarray, array(
  5401. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  5402. )
  5403. );
  5404. $substitutionarray = array_merge($substitutionarray, array(
  5405. '__USER_ID__' => (string) $user->id,
  5406. '__USER_LOGIN__' => (string) $user->login,
  5407. '__USER_EMAIL__' => (string) $user->email,
  5408. '__USER_LASTNAME__' => (string) $user->lastname,
  5409. '__USER_FIRSTNAME__' => (string) $user->firstname,
  5410. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  5411. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  5412. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  5413. )
  5414. );
  5415. }
  5416. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc))
  5417. {
  5418. $substitutionarray = array_merge($substitutionarray, array(
  5419. '__MYCOMPANY_NAME__' => $mysoc->name,
  5420. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  5421. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  5422. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  5423. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  5424. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  5425. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  5426. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  5427. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  5428. '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '),
  5429. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  5430. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  5431. '__MYCOMPANY_TOWN__' => $mysoc->town,
  5432. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  5433. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  5434. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  5435. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  5436. ));
  5437. }
  5438. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)))
  5439. {
  5440. if ($onlykey)
  5441. {
  5442. $substitutionarray['__ID__'] = '__ID__';
  5443. $substitutionarray['__REF__'] = '__REF__';
  5444. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  5445. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  5446. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  5447. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  5448. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  5449. if (!empty($conf->societe->enabled)) // Most objects are concerned
  5450. {
  5451. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  5452. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  5453. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  5454. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  5455. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  5456. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  5457. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  5458. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  5459. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  5460. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  5461. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  5462. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  5463. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  5464. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  5465. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  5466. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  5467. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  5468. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  5469. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  5470. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  5471. }
  5472. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent'))
  5473. {
  5474. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  5475. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  5476. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  5477. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  5478. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  5479. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  5480. }
  5481. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature'))
  5482. {
  5483. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  5484. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  5485. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  5486. }
  5487. if (!empty($conf->projet->enabled)) // Most objects
  5488. {
  5489. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  5490. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  5491. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  5492. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  5493. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  5494. }
  5495. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract'))
  5496. {
  5497. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  5498. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  5499. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  5500. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  5501. }
  5502. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  5503. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  5504. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  5505. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  5506. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  5507. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  5508. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  5509. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  5510. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  5511. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  5512. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping'))
  5513. {
  5514. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tacking number';
  5515. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  5516. }
  5517. } else {
  5518. $substitutionarray['__ID__'] = $object->id;
  5519. $substitutionarray['__REF__'] = $object->ref;
  5520. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5521. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5522. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  5523. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  5524. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5525. // For backward compatibility
  5526. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5527. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5528. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5529. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5530. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5531. $substitutionarray['__SUPPLIER_ORDER_DELAY_DELIVERY__'] = $outputlangs->transnoentities("AvailabilityType".$object->availability_code) != ('AvailabilityType'.$object->availability_code) ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : '');
  5532. $birthday = dol_print_date($object->birth, 'day');
  5533. if (is_object($object) && $object->element == 'adherent' && $object->id > 0)
  5534. {
  5535. $substitutionarray['__MEMBER_ID__'] = $object->id;
  5536. if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  5537. $substitutionarray['__MEMBER_FIRSTNAME__'] = $object->firstname;
  5538. $substitutionarray['__MEMBER_LASTNAME__'] = $object->lastname;
  5539. if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  5540. $substitutionarray['__MEMBER_COMPANY__'] = $object->societe;
  5541. $substitutionarray['__MEMBER_ADDRESS__'] = $object->address;
  5542. $substitutionarray['__MEMBER_ZIP__'] = $object->zip;
  5543. $substitutionarray['__MEMBER_TOWN__'] = $object->town;
  5544. $substitutionarray['__MEMBER_COUNTRY__'] = $object->country;
  5545. $substitutionarray['__MEMBER_EMAIL__'] = $object->email;
  5546. $substitutionarray['__MEMBER_BIRTH__'] = $birthday;
  5547. $substitutionarray['__MEMBER_PHOTO__'] = $object->photo;
  5548. $substitutionarray['__MEMBER_LOGIN__'] = $object->login;
  5549. $substitutionarray['__MEMBER_PASSWORD__'] = $object->pass;
  5550. $substitutionarray['__MEMBER_PHONE__'] = $object->phone;
  5551. $substitutionarray['__MEMBER_PHONEPRO__'] = $object->phone_perso;
  5552. $substitutionarray['__MEMBER_PHONEMOBILE__'] = $object->phone_mobile;
  5553. $substitutionarray['__MEMBER_TYPE__'] = $object->type;
  5554. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  5555. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  5556. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  5557. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  5558. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  5559. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  5560. }
  5561. if (is_object($object) && $object->element == 'societe') {
  5562. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  5563. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  5564. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  5565. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  5566. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  5567. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  5568. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  5569. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  5570. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  5571. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  5572. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  5573. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  5574. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  5575. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  5576. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  5577. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  5578. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  5579. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  5580. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  5581. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  5582. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  5583. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  5584. } elseif (is_object($object->thirdparty)) {
  5585. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  5586. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  5587. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  5588. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  5589. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  5590. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  5591. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  5592. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  5593. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  5594. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  5595. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  5596. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  5597. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  5598. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  5599. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  5600. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  5601. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  5602. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  5603. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  5604. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  5605. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  5606. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  5607. }
  5608. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  5609. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  5610. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  5611. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  5612. }
  5613. if (is_object($object->project))
  5614. {
  5615. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  5616. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  5617. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  5618. }
  5619. if (is_object($object->projet)) // Deprecated, for backward compatibility
  5620. {
  5621. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  5622. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  5623. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  5624. }
  5625. if (is_object($object) && $object->element == 'shipping')
  5626. {
  5627. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  5628. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  5629. }
  5630. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines))
  5631. {
  5632. $dateplannedstart = '';
  5633. $datenextexpiration = '';
  5634. foreach ($object->lines as $line)
  5635. {
  5636. if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue;
  5637. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue;
  5638. }
  5639. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  5640. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  5641. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  5642. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  5643. }
  5644. // Create dynamic tags for __EXTRAFIELD_FIELD__
  5645. if ($object->table_element && $object->id > 0)
  5646. {
  5647. if (!is_object($extrafields)) $extrafields = new ExtraFields($db);
  5648. $extrafields->fetch_name_optionals_label($object->table_element, true);
  5649. if ($object->fetch_optionals() > 0)
  5650. {
  5651. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
  5652. {
  5653. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  5654. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  5655. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  5656. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  5657. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  5658. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  5659. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  5660. $datetime = $object->array_options['options_'.$key];
  5661. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  5662. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  5663. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  5664. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  5665. }
  5666. }
  5667. }
  5668. }
  5669. }
  5670. // Complete substitution array with the url to make online payment
  5671. $paymenturl = '';
  5672. if (empty($substitutionarray['__REF__']))
  5673. {
  5674. $paymenturl = '';
  5675. } else {
  5676. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  5677. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  5678. $outputlangs->loadLangs(array('paypal', 'other'));
  5679. $typeforonlinepayment = 'free';
  5680. if (is_object($object) && $object->element == 'commande') $typeforonlinepayment = 'order';
  5681. if (is_object($object) && $object->element == 'facture') $typeforonlinepayment = 'invoice';
  5682. if (is_object($object) && $object->element == 'member') $typeforonlinepayment = 'member';
  5683. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  5684. $paymenturl = $url;
  5685. }
  5686. if ($object->id > 0)
  5687. {
  5688. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  5689. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  5690. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal')
  5691. {
  5692. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  5693. } else $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  5694. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande')
  5695. {
  5696. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  5697. } else $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  5698. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture')
  5699. {
  5700. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  5701. } else $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  5702. if (is_object($object) && $object->element == 'propal') $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  5703. if (is_object($object) && $object->element == 'commande') $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  5704. if (is_object($object) && $object->element == 'facture') $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  5705. }
  5706. if (is_object($object) && $object->element == 'action')
  5707. {
  5708. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  5709. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  5710. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  5711. }
  5712. }
  5713. }
  5714. if (empty($exclude) || !in_array('objectamount', $exclude))
  5715. {
  5716. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  5717. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  5718. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  5719. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  5720. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? ($object->total_vat ? $object->total_vat : $object->total_tva) : '';
  5721. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  5722. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  5723. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5724. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5725. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? ($object->total_vat ? price($object->total_vat, 0, $outputlangs, 0, 0, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, 0, -1, $conf->currency) : null)) : '';
  5726. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5727. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5728. // TODO Add keys for foreign multicurrency
  5729. // For backward compatibility
  5730. if ($onlykey != 2)
  5731. {
  5732. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  5733. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  5734. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? ($object->total_vat ? $object->total_vat : $object->total_tva) : '';
  5735. }
  5736. }
  5737. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  5738. if (empty($exclude) || !in_array('date', $exclude))
  5739. {
  5740. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5741. $tmp = dol_getdate(dol_now(), true);
  5742. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5743. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  5744. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5745. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  5746. $substitutionarray = array_merge($substitutionarray, array(
  5747. '__DAY__' => (string) $tmp['mday'],
  5748. '__DAY_TEXT__' => $outputlangs->trans('Day'.$tmp['wday']), // Monday
  5749. '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'].'Min'), // Mon
  5750. '__DAY_TEXT_MIN__' => $outputlangs->trans('Short'.$tmp['weekday']), // M
  5751. '__MONTH__' => (string) $tmp['mon'],
  5752. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  5753. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  5754. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  5755. '__YEAR__' => (string) $tmp['year'],
  5756. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  5757. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  5758. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  5759. '__NEXT_DAY__' => (string) $tmp4['day'],
  5760. '__NEXT_MONTH__' => (string) $tmp5['month'],
  5761. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  5762. ));
  5763. }
  5764. if (!empty($conf->multicompany->enabled))
  5765. {
  5766. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  5767. }
  5768. if (empty($exclude) || !in_array('system', $exclude))
  5769. {
  5770. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  5771. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  5772. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  5773. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  5774. }
  5775. return $substitutionarray;
  5776. }
  5777. /**
  5778. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  5779. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  5780. * Example of usage:
  5781. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  5782. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  5783. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  5784. *
  5785. * @param string $text Source string in which we must do substitution
  5786. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  5787. * @param Translate $outputlangs Output language
  5788. * @return string Output string after substitutions
  5789. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  5790. */
  5791. function make_substitutions($text, $substitutionarray, $outputlangs = null)
  5792. {
  5793. global $conf, $langs;
  5794. if (!is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  5795. if (empty($outputlangs)) $outputlangs = $langs;
  5796. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  5797. if (is_object($outputlangs))
  5798. {
  5799. $reg = array();
  5800. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg))
  5801. {
  5802. $msgishtml = 0;
  5803. if (dol_textishtml($text, 1)) $msgishtml = 1;
  5804. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  5805. $tmp = explode('|', $reg[1]);
  5806. if (!empty($tmp[1])) $outputlangs->load($tmp[1]);
  5807. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
  5808. }
  5809. }
  5810. // Make substitution for constant keys.
  5811. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  5812. $reg = array();
  5813. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg))
  5814. {
  5815. $msgishtml = 0;
  5816. if (dol_textishtml($text, 1)) $msgishtml = 1;
  5817. $keyfound = $reg[1];
  5818. if (preg_match('/(_pass|_pw|password|secret|_key|key$)/i', $keyfound)) $newval = '*****forbidden*****';
  5819. else $newval = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  5820. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ?dol_htmlentitiesbr($newval) : $newval, $text);
  5821. }
  5822. // Make substitition for array $substitutionarray
  5823. foreach ($substitutionarray as $key => $value)
  5824. {
  5825. if (!isset($value)) continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  5826. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value = ''; // Protection
  5827. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  5828. }
  5829. return $text;
  5830. }
  5831. /**
  5832. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  5833. * In this case, method completesubstitutionarray provided by module is called.
  5834. *
  5835. * @param array $substitutionarray Array substitution old value => new value value
  5836. * @param Translate $outputlangs Output language
  5837. * @param Object $object Source object
  5838. * @param mixed $parameters Add more parameters (useful to pass product lines)
  5839. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  5840. * @return void
  5841. * @see make_substitutions()
  5842. */
  5843. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  5844. {
  5845. global $conf, $user;
  5846. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5847. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  5848. // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
  5849. /*if (is_object($object) && is_array($object->array_options))
  5850. {
  5851. foreach($object->array_options as $key => $val)
  5852. {
  5853. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  5854. $substitutionarray['__EXTRAFIELD_'.$keyshort.'__']=$val;
  5855. // For backward compatibiliy
  5856. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  5857. }
  5858. }*/
  5859. // Check if there is external substitution to do, requested by plugins
  5860. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  5861. foreach ($dirsubstitutions as $reldir)
  5862. {
  5863. $dir = dol_buildpath($reldir, 0);
  5864. // Check if directory exists
  5865. if (!dol_is_dir($dir)) continue;
  5866. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  5867. foreach ($substitfiles as $substitfile)
  5868. {
  5869. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg))
  5870. {
  5871. $module = $reg[1];
  5872. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  5873. // Include the user's functions file
  5874. require_once $dir.$substitfile['name'];
  5875. // Call the user's function, and only if it is defined
  5876. $function_name = $module."_".$callfunc;
  5877. if (function_exists($function_name)) $function_name($substitutionarray, $outputlangs, $object, $parameters);
  5878. }
  5879. }
  5880. }
  5881. }
  5882. /**
  5883. * Format output for start and end date
  5884. *
  5885. * @param int $date_start Start date
  5886. * @param int $date_end End date
  5887. * @param string $format Output format
  5888. * @param Translate $outputlangs Output language
  5889. * @return void
  5890. */
  5891. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  5892. {
  5893. print get_date_range($date_start, $date_end, $format, $outputlangs);
  5894. }
  5895. /**
  5896. * Format output for start and end date
  5897. *
  5898. * @param int $date_start Start date
  5899. * @param int $date_end End date
  5900. * @param string $format Output format
  5901. * @param Translate $outputlangs Output language
  5902. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  5903. * @return string String
  5904. */
  5905. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  5906. {
  5907. global $langs;
  5908. $out = '';
  5909. if (!is_object($outputlangs)) $outputlangs = $langs;
  5910. if ($date_start && $date_end)
  5911. {
  5912. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  5913. }
  5914. if ($date_start && !$date_end)
  5915. {
  5916. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  5917. }
  5918. if (!$date_start && $date_end)
  5919. {
  5920. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  5921. }
  5922. return $out;
  5923. }
  5924. /**
  5925. * Return firstname and lastname in correct order
  5926. *
  5927. * @param string $firstname Firstname
  5928. * @param string $lastname Lastname
  5929. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname
  5930. * @return string Firstname + lastname or Lastname + firstname
  5931. */
  5932. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  5933. {
  5934. global $conf;
  5935. $ret = '';
  5936. // If order not defined, we use the setup
  5937. if ($nameorder < 0) $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  5938. if ($nameorder && $nameorder != 2 && $nameorder != 3)
  5939. {
  5940. $ret .= $firstname;
  5941. if ($firstname && $lastname) $ret .= ' ';
  5942. $ret .= $lastname;
  5943. } elseif ($nameorder == 2 || $nameorder == 3)
  5944. {
  5945. $ret .= $firstname;
  5946. if (empty($ret) && $nameorder == 3)
  5947. {
  5948. $ret .= $lastname;
  5949. }
  5950. } else {
  5951. $ret .= $lastname;
  5952. if ($firstname && $lastname) $ret .= ' ';
  5953. $ret .= $firstname;
  5954. }
  5955. return $ret;
  5956. }
  5957. /**
  5958. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  5959. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5960. * Note: Prefer to use setEventMessages instead.
  5961. *
  5962. * @param mixed $mesgs Message string or array
  5963. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5964. * @return void
  5965. * @see dol_htmloutput_events()
  5966. */
  5967. function setEventMessage($mesgs, $style = 'mesgs')
  5968. {
  5969. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  5970. if (!is_array($mesgs)) // If mesgs is a string
  5971. {
  5972. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  5973. } else // If mesgs is an array
  5974. {
  5975. foreach ($mesgs as $mesg)
  5976. {
  5977. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  5978. }
  5979. }
  5980. }
  5981. /**
  5982. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  5983. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5984. *
  5985. * @param string $mesg Message string
  5986. * @param array $mesgs Message array
  5987. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5988. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  5989. * @return void
  5990. * @see dol_htmloutput_events()
  5991. */
  5992. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  5993. {
  5994. if (empty($mesg) && empty($mesgs))
  5995. {
  5996. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  5997. } else {
  5998. if ($messagekey)
  5999. {
  6000. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  6001. // TODO
  6002. $mesg .= '';
  6003. }
  6004. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey]))
  6005. {
  6006. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  6007. if (empty($mesgs)) setEventMessage($mesg, $style);
  6008. else {
  6009. if (!empty($mesg) && !in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  6010. setEventMessage($mesgs, $style);
  6011. }
  6012. }
  6013. }
  6014. }
  6015. /**
  6016. * Print formated messages to output (Used to show messages on html output).
  6017. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  6018. * no need to call it explicitely.
  6019. *
  6020. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  6021. * @return void
  6022. * @see dol_htmloutput_mesg()
  6023. */
  6024. function dol_htmloutput_events($disabledoutputofmessages = 0)
  6025. {
  6026. // Show mesgs
  6027. if (isset($_SESSION['dol_events']['mesgs'])) {
  6028. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  6029. unset($_SESSION['dol_events']['mesgs']);
  6030. }
  6031. // Show errors
  6032. if (isset($_SESSION['dol_events']['errors'])) {
  6033. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  6034. unset($_SESSION['dol_events']['errors']);
  6035. }
  6036. // Show warnings
  6037. if (isset($_SESSION['dol_events']['warnings'])) {
  6038. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  6039. unset($_SESSION['dol_events']['warnings']);
  6040. }
  6041. }
  6042. /**
  6043. * Get formated messages to output (Used to show messages on html output).
  6044. * This include also the translation of the message key.
  6045. *
  6046. * @param string $mesgstring Message string or message key
  6047. * @param string[] $mesgarray Array of message strings or message keys
  6048. * @param string $style Style of message output ('ok' or 'error')
  6049. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6050. * @return string Return html output
  6051. *
  6052. * @see dol_print_error()
  6053. * @see dol_htmloutput_errors()
  6054. * @see setEventMessages()
  6055. */
  6056. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  6057. {
  6058. global $conf, $langs;
  6059. $ret = 0; $return = '';
  6060. $out = '';
  6061. $divstart = $divend = '';
  6062. // If inline message with no format, we add it.
  6063. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out))
  6064. {
  6065. $divstart = '<div class="'.$style.' clearboth">';
  6066. $divend = '</div>';
  6067. }
  6068. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  6069. {
  6070. $langs->load("errors");
  6071. $out .= $divstart;
  6072. if (is_array($mesgarray) && count($mesgarray))
  6073. {
  6074. foreach ($mesgarray as $message)
  6075. {
  6076. $ret++;
  6077. $out .= $langs->trans($message);
  6078. if ($ret < count($mesgarray)) $out .= "<br>\n";
  6079. }
  6080. }
  6081. if ($mesgstring)
  6082. {
  6083. $langs->load("errors");
  6084. $ret++;
  6085. $out .= $langs->trans($mesgstring);
  6086. }
  6087. $out .= $divend;
  6088. }
  6089. if ($out)
  6090. {
  6091. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  6092. {
  6093. $return = '<script>
  6094. $(document).ready(function() {
  6095. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  6096. if (block) {
  6097. $.dolEventValid("","'.dol_escape_js($out).'");
  6098. } else {
  6099. /* jnotify(message, preset of message type, keepmessage) */
  6100. $.jnotify("'.dol_escape_js($out).'",
  6101. "'.($style == "ok" ? 3000 : $style).'",
  6102. '.($style == "ok" ? "false" : "true").',
  6103. { remove: function (){} } );
  6104. }
  6105. });
  6106. </script>';
  6107. } else {
  6108. $return = $out;
  6109. }
  6110. }
  6111. return $return;
  6112. }
  6113. /**
  6114. * Get formated error messages to output (Used to show messages on html output).
  6115. *
  6116. * @param string $mesgstring Error message
  6117. * @param array $mesgarray Error messages array
  6118. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6119. * @return string Return html output
  6120. *
  6121. * @see dol_print_error()
  6122. * @see dol_htmloutput_mesg()
  6123. */
  6124. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6125. {
  6126. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6127. }
  6128. /**
  6129. * Print formated messages to output (Used to show messages on html output).
  6130. *
  6131. * @param string $mesgstring Message string or message key
  6132. * @param string[] $mesgarray Array of message strings or message keys
  6133. * @param string $style Which style to use ('ok', 'warning', 'error')
  6134. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  6135. * @return void
  6136. *
  6137. * @see dol_print_error()
  6138. * @see dol_htmloutput_errors()
  6139. * @see setEventMessages()
  6140. */
  6141. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  6142. {
  6143. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) return;
  6144. $iserror = 0;
  6145. $iswarning = 0;
  6146. if (is_array($mesgarray))
  6147. {
  6148. foreach ($mesgarray as $val)
  6149. {
  6150. if ($val && preg_match('/class="error"/i', $val)) { $iserror++; break; }
  6151. if ($val && preg_match('/class="warning"/i', $val)) { $iswarning++; break; }
  6152. }
  6153. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) $iserror++;
  6154. elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) $iswarning++;
  6155. if ($style == 'error') $iserror++;
  6156. if ($style == 'warning') $iswarning++;
  6157. if ($iserror || $iswarning)
  6158. {
  6159. // Remove div from texts
  6160. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  6161. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  6162. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  6163. // Remove div from texts array
  6164. if (is_array($mesgarray))
  6165. {
  6166. $newmesgarray = array();
  6167. foreach ($mesgarray as $val)
  6168. {
  6169. if (is_string($val))
  6170. {
  6171. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  6172. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  6173. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  6174. $newmesgarray[] = $tmpmesgstring;
  6175. } else {
  6176. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  6177. }
  6178. }
  6179. $mesgarray = $newmesgarray;
  6180. }
  6181. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  6182. } else print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  6183. }
  6184. /**
  6185. * Print formated error messages to output (Used to show messages on html output).
  6186. *
  6187. * @param string $mesgstring Error message
  6188. * @param array $mesgarray Error messages array
  6189. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6190. * @return void
  6191. *
  6192. * @see dol_print_error()
  6193. * @see dol_htmloutput_mesg()
  6194. */
  6195. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6196. {
  6197. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6198. }
  6199. /**
  6200. * Advanced sort array by second index function, which produces ascending (default)
  6201. * or descending output and uses optionally natural case insensitive sorting (which
  6202. * can be optionally case sensitive as well).
  6203. *
  6204. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  6205. * @param string $index Key in array to use for sorting criteria
  6206. * @param int $order Sort order ('asc' or 'desc')
  6207. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  6208. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  6209. * @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.
  6210. * @return array Sorted array
  6211. */
  6212. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  6213. {
  6214. // Clean parameters
  6215. $order = strtolower($order);
  6216. if (is_array($array))
  6217. {
  6218. $sizearray = count($array);
  6219. if ($sizearray > 0)
  6220. {
  6221. $temp = array();
  6222. foreach (array_keys($array) as $key)
  6223. {
  6224. if (is_object($array[$key]))
  6225. {
  6226. $temp[$key] = $array[$key]->$index;
  6227. } else {
  6228. $temp[$key] = $array[$key][$index];
  6229. }
  6230. }
  6231. if (!$natsort) {
  6232. ($order == 'asc') ? asort($temp) : arsort($temp);
  6233. } else {
  6234. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  6235. if ($order != 'asc') $temp = array_reverse($temp, true);
  6236. }
  6237. $sorted = array();
  6238. foreach (array_keys($temp) as $key)
  6239. {
  6240. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  6241. }
  6242. return $sorted;
  6243. }
  6244. }
  6245. return $array;
  6246. }
  6247. /**
  6248. * Check if a string is in UTF8
  6249. *
  6250. * @param string $str String to check
  6251. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  6252. */
  6253. function utf8_check($str)
  6254. {
  6255. // We must use here a binary strlen function (so not dol_strlen)
  6256. $strLength = dol_strlen($str);
  6257. for ($i = 0; $i < $strLength; $i++)
  6258. {
  6259. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  6260. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n = 1; // 110bbbbb
  6261. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n = 2; // 1110bbbb
  6262. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n = 3; // 11110bbb
  6263. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n = 4; // 111110bb
  6264. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n = 5; // 1111110b
  6265. else return false; // Does not match any model
  6266. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  6267. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  6268. return false;
  6269. }
  6270. }
  6271. return true;
  6272. }
  6273. /**
  6274. * Check if a string is in ASCII
  6275. *
  6276. * @param string $str String to check
  6277. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  6278. */
  6279. function ascii_check($str)
  6280. {
  6281. if (function_exists('mb_check_encoding')) {
  6282. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  6283. if (!mb_check_encoding($str, 'ASCII')) return false;
  6284. } else {
  6285. if (preg_match('/[^\x00-\x7f]/', $str)) return false; // Contains a byte > 7f
  6286. }
  6287. return true;
  6288. }
  6289. /**
  6290. * Return a string encoded into OS filesystem encoding. This function is used to define
  6291. * value to pass to filesystem PHP functions.
  6292. *
  6293. * @param string $str String to encode (UTF-8)
  6294. * @return string Encoded string (UTF-8, ISO-8859-1)
  6295. */
  6296. function dol_osencode($str)
  6297. {
  6298. global $conf;
  6299. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  6300. if (empty($tmp) && !empty($_SERVER["WINDIR"])) $tmp = 'iso-8859-1'; // By default for windows
  6301. if (empty($tmp)) $tmp = 'utf-8'; // By default for other
  6302. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  6303. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  6304. return $str;
  6305. }
  6306. /**
  6307. * Return an id or code from a code or id.
  6308. * Store also Code-Id into a cache to speed up next request on same key.
  6309. *
  6310. * @param DoliDB $db Database handler
  6311. * @param string $key Code or Id to get Id or Code
  6312. * @param string $tablename Table name without prefix
  6313. * @param string $fieldkey Field to search the key into
  6314. * @param string $fieldid Field to get
  6315. * @param int $entityfilter Filter by entity
  6316. * @return int <0 if KO, Id of code if OK
  6317. * @see $langs->getLabelFromKey
  6318. */
  6319. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  6320. {
  6321. global $cache_codes;
  6322. // If key empty
  6323. if ($key == '') return '';
  6324. // Check in cache
  6325. if (isset($cache_codes[$tablename][$key][$fieldid])) // Can be defined to 0 or ''
  6326. {
  6327. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  6328. }
  6329. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  6330. $sql = "SELECT ".$fieldid." as valuetoget";
  6331. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  6332. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  6333. if (!empty($entityfilter))
  6334. $sql .= " AND entity IN (".getEntity($tablename).")";
  6335. $resql = $db->query($sql);
  6336. if ($resql)
  6337. {
  6338. $obj = $db->fetch_object($resql);
  6339. if ($obj) $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  6340. else $cache_codes[$tablename][$key][$fieldid] = '';
  6341. $db->free($resql);
  6342. return $cache_codes[$tablename][$key][$fieldid];
  6343. } else {
  6344. return -1;
  6345. }
  6346. }
  6347. /**
  6348. * Verify if condition in string is ok or not
  6349. *
  6350. * @param string $strRights String with condition to check
  6351. * @return boolean True or False. Return True if strRights is ''
  6352. */
  6353. function verifCond($strRights)
  6354. {
  6355. global $user, $conf, $langs;
  6356. global $leftmenu;
  6357. global $rights; // To export to dol_eval function
  6358. //print $strRights."<br>\n";
  6359. $rights = true;
  6360. if ($strRights != '')
  6361. {
  6362. $str = 'if(!('.$strRights.')) { $rights = false; }';
  6363. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  6364. }
  6365. return $rights;
  6366. }
  6367. /**
  6368. * Replace eval function to add more security.
  6369. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  6370. *
  6371. * @param string $s String to evaluate
  6372. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  6373. * @param int $hideerrors 1=Hide errors
  6374. * @return mixed Nothing or return result of eval
  6375. */
  6376. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  6377. {
  6378. // Only global variables can be changed by eval function and returned to caller
  6379. global $db, $langs, $user, $conf, $website, $websitepage;
  6380. global $action, $mainmenu, $leftmenu;
  6381. global $rights;
  6382. global $object;
  6383. global $mysoc;
  6384. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  6385. global $soc; // For backward compatibility
  6386. //print $s."<br>\n";
  6387. if ($returnvalue)
  6388. {
  6389. if ($hideerrors) return @eval('return '.$s.';');
  6390. else return eval('return '.$s.';');
  6391. } else {
  6392. if ($hideerrors) @eval($s);
  6393. else eval($s);
  6394. }
  6395. }
  6396. /**
  6397. * Return if var element is ok
  6398. *
  6399. * @param string $element Variable to check
  6400. * @return boolean Return true of variable is not empty
  6401. */
  6402. function dol_validElement($element)
  6403. {
  6404. return (trim($element) != '');
  6405. }
  6406. /**
  6407. * Return img flag of country for a language code or country code
  6408. *
  6409. * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR)
  6410. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  6411. * @return string HTML img string with flag.
  6412. */
  6413. function picto_from_langcode($codelang, $moreatt = '')
  6414. {
  6415. global $langs;
  6416. if (empty($codelang)) return '';
  6417. if ($codelang == 'auto')
  6418. {
  6419. return '<span class="fa fa-globe"></span>';
  6420. }
  6421. $langtocountryflag = array(
  6422. 'ar_AR' => '',
  6423. 'ca_ES' => 'catalonia',
  6424. 'da_DA' => 'dk',
  6425. 'fr_CA' => 'mq',
  6426. 'sv_SV' => 'se'
  6427. );
  6428. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  6429. else {
  6430. $tmparray = explode('_', $codelang);
  6431. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  6432. }
  6433. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  6434. }
  6435. /**
  6436. * Return default language from country code.
  6437. * Return null if not found.
  6438. *
  6439. * @param string $countrycode Country code like 'US', 'FR', 'CA', ...
  6440. * @return string Value of locale like 'en_US', 'fr_FR', ...
  6441. */
  6442. function getLanguageCodeFromCountryCode($countrycode)
  6443. {
  6444. global $mysoc;
  6445. if (empty($countrycode)) return null;
  6446. if (strtoupper($countrycode) == 'MQ') return 'fr_CA';
  6447. if (strtoupper($countrycode) == 'SE') return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  6448. if (strtoupper($countrycode) == 'CH')
  6449. {
  6450. if ($mysoc->country_code == 'FR') return 'fr_CH';
  6451. if ($mysoc->country_code == 'DE') return 'de_CH';
  6452. }
  6453. // Locale list taken from:
  6454. // http://stackoverflow.com/questions/3191664/
  6455. // list-of-all-locales-and-their-short-codes
  6456. $locales = array(
  6457. 'af-ZA',
  6458. 'am-ET',
  6459. 'ar-AE',
  6460. 'ar-BH',
  6461. 'ar-DZ',
  6462. 'ar-EG',
  6463. 'ar-IQ',
  6464. 'ar-JO',
  6465. 'ar-KW',
  6466. 'ar-LB',
  6467. 'ar-LY',
  6468. 'ar-MA',
  6469. 'ar-OM',
  6470. 'ar-QA',
  6471. 'ar-SA',
  6472. 'ar-SY',
  6473. 'ar-TN',
  6474. 'ar-YE',
  6475. 'as-IN',
  6476. 'ba-RU',
  6477. 'be-BY',
  6478. 'bg-BG',
  6479. 'bn-BD',
  6480. 'bn-IN',
  6481. 'bo-CN',
  6482. 'br-FR',
  6483. 'ca-ES',
  6484. 'co-FR',
  6485. 'cs-CZ',
  6486. 'cy-GB',
  6487. 'da-DK',
  6488. 'de-AT',
  6489. 'de-CH',
  6490. 'de-DE',
  6491. 'de-LI',
  6492. 'de-LU',
  6493. 'dv-MV',
  6494. 'el-GR',
  6495. 'en-AU',
  6496. 'en-BZ',
  6497. 'en-CA',
  6498. 'en-GB',
  6499. 'en-IE',
  6500. 'en-IN',
  6501. 'en-JM',
  6502. 'en-MY',
  6503. 'en-NZ',
  6504. 'en-PH',
  6505. 'en-SG',
  6506. 'en-TT',
  6507. 'en-US',
  6508. 'en-ZA',
  6509. 'en-ZW',
  6510. 'es-AR',
  6511. 'es-BO',
  6512. 'es-CL',
  6513. 'es-CO',
  6514. 'es-CR',
  6515. 'es-DO',
  6516. 'es-EC',
  6517. 'es-ES',
  6518. 'es-GT',
  6519. 'es-HN',
  6520. 'es-MX',
  6521. 'es-NI',
  6522. 'es-PA',
  6523. 'es-PE',
  6524. 'es-PR',
  6525. 'es-PY',
  6526. 'es-SV',
  6527. 'es-US',
  6528. 'es-UY',
  6529. 'es-VE',
  6530. 'et-EE',
  6531. 'eu-ES',
  6532. 'fa-IR',
  6533. 'fi-FI',
  6534. 'fo-FO',
  6535. 'fr-BE',
  6536. 'fr-CA',
  6537. 'fr-CH',
  6538. 'fr-FR',
  6539. 'fr-LU',
  6540. 'fr-MC',
  6541. 'fy-NL',
  6542. 'ga-IE',
  6543. 'gd-GB',
  6544. 'gl-ES',
  6545. 'gu-IN',
  6546. 'he-IL',
  6547. 'hi-IN',
  6548. 'hr-BA',
  6549. 'hr-HR',
  6550. 'hu-HU',
  6551. 'hy-AM',
  6552. 'id-ID',
  6553. 'ig-NG',
  6554. 'ii-CN',
  6555. 'is-IS',
  6556. 'it-CH',
  6557. 'it-IT',
  6558. 'ja-JP',
  6559. 'ka-GE',
  6560. 'kk-KZ',
  6561. 'kl-GL',
  6562. 'km-KH',
  6563. 'kn-IN',
  6564. 'ko-KR',
  6565. 'ky-KG',
  6566. 'lb-LU',
  6567. 'lo-LA',
  6568. 'lt-LT',
  6569. 'lv-LV',
  6570. 'mi-NZ',
  6571. 'mk-MK',
  6572. 'ml-IN',
  6573. 'mn-MN',
  6574. 'mr-IN',
  6575. 'ms-BN',
  6576. 'ms-MY',
  6577. 'mt-MT',
  6578. 'nb-NO',
  6579. 'ne-NP',
  6580. 'nl-BE',
  6581. 'nl-NL',
  6582. 'nn-NO',
  6583. 'oc-FR',
  6584. 'or-IN',
  6585. 'pa-IN',
  6586. 'pl-PL',
  6587. 'ps-AF',
  6588. 'pt-BR',
  6589. 'pt-PT',
  6590. 'rm-CH',
  6591. 'ro-RO',
  6592. 'ru-RU',
  6593. 'rw-RW',
  6594. 'sa-IN',
  6595. 'se-FI',
  6596. 'se-NO',
  6597. 'se-SE',
  6598. 'si-LK',
  6599. 'sk-SK',
  6600. 'sl-SI',
  6601. 'sq-AL',
  6602. 'sv-FI',
  6603. 'sv-SE',
  6604. 'sw-KE',
  6605. 'ta-IN',
  6606. 'te-IN',
  6607. 'th-TH',
  6608. 'tk-TM',
  6609. 'tn-ZA',
  6610. 'tr-TR',
  6611. 'tt-RU',
  6612. 'ug-CN',
  6613. 'uk-UA',
  6614. 'ur-PK',
  6615. 'vi-VN',
  6616. 'wo-SN',
  6617. 'xh-ZA',
  6618. 'yo-NG',
  6619. 'zh-CN',
  6620. 'zh-HK',
  6621. 'zh-MO',
  6622. 'zh-SG',
  6623. 'zh-TW',
  6624. 'zu-ZA',
  6625. );
  6626. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  6627. if (in_array($buildprimarykeytotest, $locales)) return strtolower($countrycode).'_'.strtoupper($countrycode);
  6628. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) // Need extension php-intl
  6629. {
  6630. foreach ($locales as $locale)
  6631. {
  6632. $locale_language = locale_get_primary_language($locale);
  6633. $locale_region = locale_get_region($locale);
  6634. if (strtoupper($countrycode) == $locale_region)
  6635. {
  6636. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  6637. return strtolower($locale_language).'_'.strtoupper($locale_region);
  6638. }
  6639. }
  6640. } else {
  6641. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  6642. }
  6643. return null;
  6644. }
  6645. /**
  6646. * Complete or removed entries into a head array (used to build tabs).
  6647. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  6648. * Or by change using hook completeTabsHead
  6649. *
  6650. * @param Conf $conf Object conf
  6651. * @param Translate $langs Object langs
  6652. * @param object|null $object Object object
  6653. * @param array $head Object head
  6654. * @param int $h New position to fill
  6655. * @param string $type Value for object where objectvalue can be
  6656. * 'thirdparty' to add a tab in third party view
  6657. * 'intervention' to add a tab in intervention view
  6658. * 'supplier_order' to add a tab in supplier order view
  6659. * 'supplier_invoice' to add a tab in supplier invoice view
  6660. * 'invoice' to add a tab in customer invoice view
  6661. * 'order' to add a tab in customer order view
  6662. * 'contract' to add a tabl in contract view
  6663. * 'product' to add a tab in product view
  6664. * 'propal' to add a tab in propal view
  6665. * 'user' to add a tab in user view
  6666. * 'group' to add a tab in group view
  6667. * 'member' to add a tab in fundation member view
  6668. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  6669. * 'ecm' to add a tab for another ecm view
  6670. * 'stock' to add a tab for warehouse view
  6671. * @param string $mode 'add' to complete head, 'remove' to remove entries
  6672. * @return void
  6673. */
  6674. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  6675. {
  6676. global $hookmanager;
  6677. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  6678. {
  6679. foreach ($conf->modules_parts['tabs'][$type] as $value)
  6680. {
  6681. $values = explode(':', $value);
  6682. if ($mode == 'add' && !preg_match('/^\-/', $values[1]))
  6683. {
  6684. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  6685. {
  6686. if ($values[0] != $type) continue;
  6687. if (verifCond($values[4]))
  6688. {
  6689. if ($values[3]) $langs->load($values[3]);
  6690. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6691. {
  6692. $substitutionarray = array();
  6693. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6694. $label = make_substitutions($reg[1], $substitutionarray);
  6695. } else $label = $langs->trans($values[2]);
  6696. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  6697. $head[$h][1] = $label;
  6698. $head[$h][2] = str_replace('+', '', $values[1]);
  6699. $h++;
  6700. }
  6701. } elseif (count($values) == 5) // deprecated
  6702. {
  6703. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  6704. if ($values[0] != $type) continue;
  6705. if ($values[3]) $langs->load($values[3]);
  6706. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6707. {
  6708. $substitutionarray = array();
  6709. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6710. $label = make_substitutions($reg[1], $substitutionarray);
  6711. } else $label = $langs->trans($values[2]);
  6712. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  6713. $head[$h][1] = $label;
  6714. $head[$h][2] = str_replace('+', '', $values[1]);
  6715. $h++;
  6716. }
  6717. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1]))
  6718. {
  6719. if ($values[0] != $type) continue;
  6720. $tabname = str_replace('-', '', $values[1]);
  6721. foreach ($head as $key => $val)
  6722. {
  6723. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  6724. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  6725. if ($head[$key][2] == $tabname && $condition)
  6726. {
  6727. unset($head[$key]);
  6728. break;
  6729. }
  6730. }
  6731. }
  6732. }
  6733. }
  6734. // No need to make a return $head. Var is modified as a reference
  6735. if (!empty($hookmanager))
  6736. {
  6737. $parameters = array('object' => $object, 'mode' => $mode, 'head' => $head);
  6738. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  6739. if ($reshook > 0)
  6740. {
  6741. $head = $hookmanager->resArray;
  6742. $h = count($head);
  6743. }
  6744. }
  6745. }
  6746. /**
  6747. * Print common footer :
  6748. * conf->global->MAIN_HTML_FOOTER
  6749. * js for switch of menu hider
  6750. * js for conf->global->MAIN_GOOGLE_AN_ID
  6751. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  6752. * js for conf->logbuffer
  6753. *
  6754. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  6755. * @return void
  6756. */
  6757. function printCommonFooter($zone = 'private')
  6758. {
  6759. global $conf, $hookmanager, $user, $debugbar;
  6760. global $action;
  6761. global $micro_start_time;
  6762. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  6763. else print "\n".'<!-- Common footer for public page -->'."\n";
  6764. // A div to store page_y POST parameter so we can read it using javascript
  6765. print "\n<!-- A div to store page_y POST parameter -->\n";
  6766. print '<div id="page_y" style="display: none;">'.$_POST['page_y'].'</div>'."\n";
  6767. $parameters = array();
  6768. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  6769. if (empty($reshook))
  6770. {
  6771. if (!empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  6772. print "\n";
  6773. if (!empty($conf->use_javascript_ajax))
  6774. {
  6775. print '<script>'."\n";
  6776. print 'jQuery(document).ready(function() {'."\n";
  6777. if ($zone == 'private' && empty($conf->dol_use_jmobile))
  6778. {
  6779. print "\n";
  6780. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  6781. print 'jQuery("li.menuhider").click(function(event) {';
  6782. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  6783. print ' console.log("We click on .menuhider");'."\n";
  6784. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  6785. print '});'."\n";
  6786. }
  6787. // Management of focus and mandatory for fields
  6788. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))))
  6789. {
  6790. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  6791. $relativepathstring = $_SERVER["PHP_SELF"];
  6792. // Clean $relativepathstring
  6793. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  6794. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  6795. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  6796. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  6797. if (!empty($user->default_values[$relativepathstring]['focus']))
  6798. {
  6799. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval)
  6800. {
  6801. $qualified = 0;
  6802. if ($defkey != '_noquery_')
  6803. {
  6804. $tmpqueryarraytohave = explode('&', $defkey);
  6805. $foundintru = 0;
  6806. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  6807. {
  6808. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  6809. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  6810. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  6811. }
  6812. if (!$foundintru) $qualified = 1;
  6813. //var_dump($defkey.'-'.$qualified);
  6814. } else $qualified = 1;
  6815. if ($qualified)
  6816. {
  6817. foreach ($defval as $paramkey => $paramval)
  6818. {
  6819. // Set focus on field
  6820. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  6821. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  6822. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  6823. }
  6824. }
  6825. }
  6826. }
  6827. if (!empty($user->default_values[$relativepathstring]['mandatory']))
  6828. {
  6829. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval)
  6830. {
  6831. $qualified = 0;
  6832. if ($defkey != '_noquery_')
  6833. {
  6834. $tmpqueryarraytohave = explode('&', $defkey);
  6835. $foundintru = 0;
  6836. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  6837. {
  6838. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  6839. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  6840. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  6841. }
  6842. if (!$foundintru) $qualified = 1;
  6843. //var_dump($defkey.'-'.$qualified);
  6844. } else $qualified = 1;
  6845. if ($qualified)
  6846. {
  6847. foreach ($defval as $paramkey => $paramval)
  6848. {
  6849. // Add property 'required' on input
  6850. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6851. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6852. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
  6853. }
  6854. }
  6855. }
  6856. }
  6857. }
  6858. print '});'."\n";
  6859. // End of tuning
  6860. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO))
  6861. {
  6862. print "\n";
  6863. print "/* JS CODE TO ENABLE to add memory info */\n";
  6864. print 'window.console && console.log("';
  6865. if (!empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  6866. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  6867. if (!empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  6868. {
  6869. $micro_end_time = microtime(true);
  6870. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  6871. }
  6872. if (function_exists("memory_get_usage")) {
  6873. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  6874. }
  6875. if (function_exists("memory_get_peak_usage")) {
  6876. print ' - Real mem peak: '.memory_get_peak_usage(true);
  6877. }
  6878. if (function_exists("zend_loader_file_encoded"))
  6879. {
  6880. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  6881. }
  6882. print '");'."\n";
  6883. }
  6884. print "\n".'</script>'."\n";
  6885. // Google Analytics
  6886. // TODO Add a hook here
  6887. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID))
  6888. {
  6889. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  6890. foreach ($tmptagarray as $tmptag) {
  6891. print "\n";
  6892. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  6893. print "
  6894. <!-- Global site tag (gtag.js) - Google Analytics -->
  6895. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  6896. <script>
  6897. window.dataLayer = window.dataLayer || [];
  6898. function gtag(){dataLayer.push(arguments);}
  6899. gtag('js', new Date());
  6900. gtag('config', '".trim($tmptag)."');
  6901. </script>";
  6902. print "\n";
  6903. }
  6904. }
  6905. }
  6906. // Add Xdebug coverage of code
  6907. if (defined('XDEBUGCOVERAGE'))
  6908. {
  6909. print_r(xdebug_get_code_coverage());
  6910. }
  6911. // Add DebugBar data
  6912. if (!empty($user->rights->debugbar->read) && is_object($debugbar))
  6913. {
  6914. $debugbar['time']->stopMeasure('pageaftermaster');
  6915. print '<!-- Output debugbar data -->'."\n";
  6916. $renderer = $debugbar->getRenderer();
  6917. print $debugbar->getRenderer()->render();
  6918. } elseif (count($conf->logbuffer)) // If there is some logs in buffer to show
  6919. {
  6920. print "\n";
  6921. print "<!-- Start of log output\n";
  6922. //print '<div class="hidden">'."\n";
  6923. foreach ($conf->logbuffer as $logline)
  6924. {
  6925. print $logline."<br>\n";
  6926. }
  6927. //print '</div>'."\n";
  6928. print "End of log output -->\n";
  6929. }
  6930. }
  6931. }
  6932. /**
  6933. * Split a string with 2 keys into key array.
  6934. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  6935. *
  6936. * @param string $string String to explode
  6937. * @param string $delimiter Delimiter between each couple of data
  6938. * @param string $kv Delimiter between key and value
  6939. * @return array Array of data exploded
  6940. */
  6941. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  6942. {
  6943. if ($a = explode($delimiter, $string))
  6944. {
  6945. $ka = array();
  6946. foreach ($a as $s) { // each part
  6947. if ($s) {
  6948. if ($pos = strpos($s, $kv)) { // key/value delimiter
  6949. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  6950. } else { // key delimiter not found
  6951. $ka[] = trim($s);
  6952. }
  6953. }
  6954. }
  6955. return $ka;
  6956. }
  6957. return array();
  6958. }
  6959. /**
  6960. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  6961. *
  6962. * @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.
  6963. * @return string HTML code to set focus
  6964. */
  6965. function dol_set_focus($selector)
  6966. {
  6967. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  6968. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  6969. }
  6970. /**
  6971. * Return getmypid() or random PID when function is disabled
  6972. * Some web hosts disable this php function for security reasons
  6973. * and sometimes we can't redeclare function
  6974. *
  6975. * @return int
  6976. */
  6977. function dol_getmypid()
  6978. {
  6979. if (!function_exists('getmypid')) {
  6980. return mt_rand(1, 32768);
  6981. } else {
  6982. return getmypid();
  6983. }
  6984. }
  6985. /**
  6986. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  6987. *
  6988. * @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")
  6989. * @param string $value The value to look for.
  6990. * If param $mode is 0, can contains several keywords separated with a space or |
  6991. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  6992. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  6993. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  6994. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  6995. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  6996. * @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')
  6997. * 3=value is list of string separated with comma (Example 'text 1,text 2'), 4=value is a list of ID separated with comma (Example '1,3,4') for search into a multiselect string ('1,2')
  6998. * @param integer $nofirstand 1=Do not output the first 'AND'
  6999. * @return string $res The statement to append to the SQL query
  7000. */
  7001. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  7002. {
  7003. global $db, $langs;
  7004. $value = trim($value);
  7005. if ($mode == 0)
  7006. {
  7007. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  7008. }
  7009. if ($mode == 1)
  7010. {
  7011. $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
  7012. }
  7013. $value = preg_replace('/\s*\|\s*/', '|', $value);
  7014. $crits = explode(' ', $value);
  7015. $res = '';
  7016. if (!is_array($fields)) $fields = array($fields);
  7017. $nboffields = count($fields);
  7018. $end2 = count($crits);
  7019. $j = 0;
  7020. foreach ($crits as $crit)
  7021. {
  7022. $i = 0; $i2 = 0;
  7023. $newres = '';
  7024. foreach ($fields as $field)
  7025. {
  7026. if ($mode == 1)
  7027. {
  7028. $operator = '=';
  7029. $newcrit = preg_replace('/([<>=]+)/', '', trim($crit));
  7030. $reg = array();
  7031. preg_match('/([<>=]+)/', trim($crit), $reg);
  7032. if ($reg[1])
  7033. {
  7034. $operator = $reg[1];
  7035. }
  7036. if ($newcrit != '')
  7037. {
  7038. $numnewcrit = price2num($newcrit);
  7039. if (is_numeric($numnewcrit))
  7040. {
  7041. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$numnewcrit;
  7042. } else {
  7043. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  7044. }
  7045. $i2++; // a criteria was added to string
  7046. }
  7047. } elseif ($mode == 2 || $mode == -2)
  7048. {
  7049. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '')."IN (".$db->escape(trim($crit)).")";
  7050. if ($mode == -2) $newres .= ' OR '.$field.' IS NULL';
  7051. $i2++; // a criteria was added to string
  7052. } elseif ($mode == 3 || $mode == -3)
  7053. {
  7054. $tmparray = explode(',', trim($crit));
  7055. if (count($tmparray))
  7056. {
  7057. $listofcodes = '';
  7058. foreach ($tmparray as $val)
  7059. {
  7060. if ($val)
  7061. {
  7062. $listofcodes .= ($listofcodes ? ',' : '');
  7063. $listofcodes .= "'".$db->escape(trim($val))."'";
  7064. }
  7065. }
  7066. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$listofcodes.")";
  7067. $i2++; // a criteria was added to string
  7068. }
  7069. if ($mode == -3) $newres .= ' OR '.$field.' IS NULL';
  7070. } elseif ($mode == 4)
  7071. {
  7072. $tmparray = explode(',', trim($crit));
  7073. if (count($tmparray))
  7074. {
  7075. $listofcodes = '';
  7076. foreach ($tmparray as $val)
  7077. {
  7078. if ($val)
  7079. {
  7080. $newres .= ($i2 > 0 ? ' OR (' : '(').$field.' LIKE \''.$db->escape(trim($val)).',%\'';
  7081. $newres .= ' OR '.$field.' = \''.$db->escape(trim($val)).'\'';
  7082. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape(trim($val)).'\'';
  7083. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape(trim($val)).',%\'';
  7084. $newres .= ')';
  7085. $i2++;
  7086. }
  7087. }
  7088. }
  7089. } else // $mode=0
  7090. {
  7091. $tmpcrits = explode('|', $crit);
  7092. $i3 = 0;
  7093. foreach ($tmpcrits as $tmpcrit)
  7094. {
  7095. if ($tmpcrit !== '0' && empty($tmpcrit)) continue;
  7096. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  7097. if (preg_match('/\.(id|rowid)$/', $field)) // Special case for rowid that is sometimes a ref so used as a search field
  7098. {
  7099. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ?trim($tmpcrit) : '0');
  7100. } else {
  7101. $newres .= $field." LIKE '";
  7102. $tmpcrit = trim($tmpcrit);
  7103. $tmpcrit2 = $tmpcrit;
  7104. $tmpbefore = '%'; $tmpafter = '%';
  7105. if (preg_match('/^[\^\$]/', $tmpcrit))
  7106. {
  7107. $tmpbefore = '';
  7108. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  7109. }
  7110. if (preg_match('/[\^\$]$/', $tmpcrit))
  7111. {
  7112. $tmpafter = '';
  7113. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  7114. }
  7115. $newres .= $tmpbefore;
  7116. $newres .= $db->escape($tmpcrit2);
  7117. $newres .= $tmpafter;
  7118. $newres .= "'";
  7119. if ($tmpcrit2 == '')
  7120. {
  7121. $newres .= ' OR '.$field." IS NULL";
  7122. }
  7123. }
  7124. $i3++;
  7125. }
  7126. $i2++; // a criteria was added to string
  7127. }
  7128. $i++;
  7129. }
  7130. if ($newres) $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  7131. $j++;
  7132. }
  7133. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  7134. //print 'xx'.$res.'yy';
  7135. return $res;
  7136. }
  7137. /**
  7138. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  7139. *
  7140. * @param Object $object Object
  7141. * @return string Url string
  7142. */
  7143. function showDirectDownloadLink($object)
  7144. {
  7145. global $conf, $langs;
  7146. $out = '';
  7147. $url = $object->getLastMainDocLink($object->element);
  7148. if ($url)
  7149. {
  7150. $out .= img_picto('', 'globe').' '.$langs->trans("DirectDownloadLink").'<br>';
  7151. $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
  7152. $out .= ajax_autoselect("directdownloadlink", 0);
  7153. }
  7154. return $out;
  7155. }
  7156. /**
  7157. * Return the filename of file to get the thumbs
  7158. *
  7159. * @param string $file Original filename (full or relative path)
  7160. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  7161. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  7162. * @return string New file name (full or relative path, including the thumbs/)
  7163. */
  7164. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  7165. {
  7166. $dirName = dirname($file);
  7167. if ($dirName == '.') $dirName = '';
  7168. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  7169. $fileName = basename($fileName);
  7170. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  7171. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  7172. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  7173. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  7174. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  7175. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  7176. if (!$extImgTarget) return $file;
  7177. $subdir = '';
  7178. if ($extName) $subdir = 'thumbs/';
  7179. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  7180. }
  7181. /**
  7182. * Return URL we can use for advanced preview links
  7183. *
  7184. * @param string $modulepart propal, facture, facture_fourn, ...
  7185. * @param string $relativepath Relative path of docs.
  7186. * @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)
  7187. * @param string $param More param on http links
  7188. * @return string|array Output string with href link or array with all components of link
  7189. */
  7190. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  7191. {
  7192. global $conf, $langs;
  7193. if (empty($conf->use_javascript_ajax)) return '';
  7194. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  7195. if ($alldata == 1)
  7196. {
  7197. if ($isAllowedForPreview) return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : ''), 'mime'=>dol_mimetype($relativepath));
  7198. else return array();
  7199. }
  7200. // old behavior, return a string
  7201. if ($isAllowedForPreview) return 'javascript:document_preview(\''.dol_escape_js(DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : '')).'\', \''.dol_mimetype($relativepath).'\', \''.dol_escape_js($langs->trans('Preview')).'\')';
  7202. else return '';
  7203. }
  7204. /**
  7205. * Make content of an input box selected when we click into input field.
  7206. *
  7207. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  7208. * @param string $addlink Add a 'link to' after
  7209. * @return string
  7210. */
  7211. function ajax_autoselect($htmlname, $addlink = '')
  7212. {
  7213. global $langs;
  7214. $out = '<script>
  7215. jQuery(document).ready(function () {
  7216. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  7217. });
  7218. </script>';
  7219. if ($addlink) $out .= ' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  7220. return $out;
  7221. }
  7222. /**
  7223. * Return if a file is qualified for preview
  7224. *
  7225. * @param string $file Filename we looking for information
  7226. * @return int 1 If allowed, 0 otherwise
  7227. * @see dol_mimetype(), image_format_supported() from images.lib.php
  7228. */
  7229. function dolIsAllowedForPreview($file)
  7230. {
  7231. global $conf;
  7232. // Check .noexe extension in filename
  7233. if (preg_match('/\.noexe$/i', $file)) return 0;
  7234. // Check mime types
  7235. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  7236. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) $mime_preview[] = 'svg+xml';
  7237. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  7238. //$mime_preview[]='archive';
  7239. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  7240. if ($num_mime !== false) return 1;
  7241. // By default, not allowed for preview
  7242. return 0;
  7243. }
  7244. /**
  7245. * Return mime type of a file
  7246. *
  7247. * @param string $file Filename we looking for MIME type
  7248. * @param string $default Default mime type if extension not found in known list
  7249. * @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
  7250. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  7251. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  7252. */
  7253. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  7254. {
  7255. $mime = $default;
  7256. $imgmime = 'other.png';
  7257. $famime = 'file-o';
  7258. $srclang = '';
  7259. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  7260. // Plain text files
  7261. if (preg_match('/\.txt$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7262. if (preg_match('/\.rtx$/i', $tmpfile)) { $mime = 'text/richtext'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7263. if (preg_match('/\.csv$/i', $tmpfile)) { $mime = 'text/csv'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7264. if (preg_match('/\.tsv$/i', $tmpfile)) { $mime = 'text/tab-separated-values'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7265. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7266. if (preg_match('/\.ini$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'ini'; $famime = 'file-text-o'; }
  7267. if (preg_match('/\.md$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'md'; $famime = 'file-text-o'; }
  7268. if (preg_match('/\.css$/i', $tmpfile)) { $mime = 'text/css'; $imgmime = 'css.png'; $srclang = 'css'; $famime = 'file-text-o'; }
  7269. if (preg_match('/\.lang$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'lang'; $famime = 'file-text-o'; }
  7270. // Certificate files
  7271. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7272. // XML based (HTML/XML/XAML)
  7273. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { $mime = 'text/html'; $imgmime = 'html.png'; $srclang = 'html'; $famime = 'file-text-o'; }
  7274. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xml'; $famime = 'file-text-o'; }
  7275. if (preg_match('/\.xaml$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xaml'; $famime = 'file-text-o'; }
  7276. // Languages
  7277. if (preg_match('/\.bas$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'bas'; $famime = 'file-code-o'; }
  7278. if (preg_match('/\.(c)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'c'; $famime = 'file-code-o'; }
  7279. if (preg_match('/\.(cpp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cpp'; $famime = 'file-code-o'; }
  7280. if (preg_match('/\.cs$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cs'; $famime = 'file-code-o'; }
  7281. if (preg_match('/\.(h)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'h'; $famime = 'file-code-o'; }
  7282. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'java'; $famime = 'file-code-o'; }
  7283. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7284. if (preg_match('/\.phtml$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7285. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'pl.png'; $srclang = 'perl'; $famime = 'file-code-o'; }
  7286. if (preg_match('/\.sql$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'sql'; $famime = 'file-code-o'; }
  7287. if (preg_match('/\.js$/i', $tmpfile)) { $mime = 'text/x-javascript'; $imgmime = 'jscript.png'; $srclang = 'js'; $famime = 'file-code-o'; }
  7288. // Open office
  7289. if (preg_match('/\.odp$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.presentation'; $imgmime = 'ooffice.png'; $famime = 'file-powerpoint-o'; }
  7290. if (preg_match('/\.ods$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.spreadsheet'; $imgmime = 'ooffice.png'; $famime = 'file-excel-o'; }
  7291. if (preg_match('/\.odt$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.text'; $imgmime = 'ooffice.png'; $famime = 'file-word-o'; }
  7292. // MS Office
  7293. if (preg_match('/\.mdb$/i', $tmpfile)) { $mime = 'application/msaccess'; $imgmime = 'mdb.png'; $famime = 'file-o'; }
  7294. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7295. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7296. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7297. if (preg_match('/\.xla(m)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7298. if (preg_match('/\.xls$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7299. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) { $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7300. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-powerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7301. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) { $mime = 'application/x-mspowerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7302. // Other
  7303. if (preg_match('/\.pdf$/i', $tmpfile)) { $mime = 'application/pdf'; $imgmime = 'pdf.png'; $famime = 'file-pdf-o'; }
  7304. // Scripts
  7305. if (preg_match('/\.bat$/i', $tmpfile)) { $mime = 'text/x-bat'; $imgmime = 'script.png'; $srclang = 'dos'; $famime = 'file-code-o'; }
  7306. if (preg_match('/\.sh$/i', $tmpfile)) { $mime = 'text/x-sh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7307. if (preg_match('/\.ksh$/i', $tmpfile)) { $mime = 'text/x-ksh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7308. if (preg_match('/\.bash$/i', $tmpfile)) { $mime = 'text/x-bash'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7309. // Images
  7310. if (preg_match('/\.ico$/i', $tmpfile)) { $mime = 'image/x-icon'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7311. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) { $mime = 'image/jpeg'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7312. if (preg_match('/\.png$/i', $tmpfile)) { $mime = 'image/png'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7313. if (preg_match('/\.gif$/i', $tmpfile)) { $mime = 'image/gif'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7314. if (preg_match('/\.bmp$/i', $tmpfile)) { $mime = 'image/bmp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7315. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) { $mime = 'image/tiff'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7316. if (preg_match('/\.svg$/i', $tmpfile)) { $mime = 'image/svg+xml'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7317. if (preg_match('/\.webp$/i', $tmpfile)) { $mime = 'image/webp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7318. // Calendar
  7319. if (preg_match('/\.vcs$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7320. if (preg_match('/\.ics$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7321. // Other
  7322. if (preg_match('/\.torrent$/i', $tmpfile)) { $mime = 'application/x-bittorrent'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7323. // Audio
  7324. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { $mime = 'audio'; $imgmime = 'audio.png'; $famime = 'file-audio-o'; }
  7325. // Video
  7326. if (preg_match('/\.ogv$/i', $tmpfile)) { $mime = 'video/ogg'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7327. if (preg_match('/\.webm$/i', $tmpfile)) { $mime = 'video/webm'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7328. if (preg_match('/\.avi$/i', $tmpfile)) { $mime = 'video/x-msvideo'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7329. if (preg_match('/\.divx$/i', $tmpfile)) { $mime = 'video/divx'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7330. if (preg_match('/\.xvid$/i', $tmpfile)) { $mime = 'video/xvid'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7331. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) { $mime = 'video'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7332. // Archive
  7333. 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, ...
  7334. // Exe
  7335. if (preg_match('/\.(exe|com)$/i', $tmpfile)) { $mime = 'application/octet-stream'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7336. // Lib
  7337. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { $mime = 'library'; $imgmime = 'library.png'; $famime = 'file-o'; }
  7338. // Err
  7339. if (preg_match('/\.err$/i', $tmpfile)) { $mime = 'error'; $imgmime = 'error.png'; $famime = 'file-text-o'; }
  7340. // Return string
  7341. if ($mode == 1)
  7342. {
  7343. $tmp = explode('/', $mime);
  7344. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  7345. }
  7346. if ($mode == 2)
  7347. {
  7348. return $imgmime;
  7349. }
  7350. if ($mode == 3)
  7351. {
  7352. return $srclang;
  7353. }
  7354. if ($mode == 4)
  7355. {
  7356. return $famime;
  7357. }
  7358. return $mime;
  7359. }
  7360. /**
  7361. * Return value from dictionary
  7362. *
  7363. * @param string $tablename name of dictionary
  7364. * @param string $field the value to return
  7365. * @param int $id id of line
  7366. * @param bool $checkentity add filter on entity
  7367. * @param string $rowidfield name of the column rowid
  7368. * @return string
  7369. */
  7370. function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  7371. {
  7372. global $dictvalues, $db, $langs;
  7373. if (!isset($dictvalues[$tablename]))
  7374. {
  7375. $dictvalues[$tablename] = array();
  7376. $sql = 'SELECT * FROM '.$tablename.' WHERE 1'; // Here select * is allowed as it is generic code and we don't have list of fields
  7377. if ($checkentity) $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  7378. $resql = $db->query($sql);
  7379. if ($resql)
  7380. {
  7381. while ($obj = $db->fetch_object($resql))
  7382. {
  7383. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  7384. }
  7385. } else {
  7386. dol_print_error($db);
  7387. }
  7388. }
  7389. if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
  7390. else // Not found
  7391. {
  7392. if ($id > 0) return $id;
  7393. return '';
  7394. }
  7395. }
  7396. /**
  7397. * Return true if the color is light
  7398. *
  7399. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  7400. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  7401. */
  7402. function colorIsLight($stringcolor)
  7403. {
  7404. $stringcolor = str_replace('#', '', $stringcolor);
  7405. $res = -1;
  7406. if (!empty($stringcolor))
  7407. {
  7408. $res = 0;
  7409. $tmp = explode(',', $stringcolor);
  7410. if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
  7411. {
  7412. $r = $tmp[0];
  7413. $g = $tmp[1];
  7414. $b = $tmp[2];
  7415. } else {
  7416. $hexr = $stringcolor[0].$stringcolor[1];
  7417. $hexg = $stringcolor[2].$stringcolor[3];
  7418. $hexb = $stringcolor[4].$stringcolor[5];
  7419. $r = hexdec($hexr);
  7420. $g = hexdec($hexg);
  7421. $b = hexdec($hexb);
  7422. }
  7423. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  7424. if ($bright > 0.6) $res = 1;
  7425. }
  7426. return $res;
  7427. }
  7428. /**
  7429. * Function to test if an entry is enabled or not
  7430. *
  7431. * @param string $type_user 0=We test for internal user, 1=We test for external user
  7432. * @param array $menuentry Array for feature entry to test
  7433. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  7434. * @return int 0=Hide, 1=Show, 2=Show gray
  7435. */
  7436. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  7437. {
  7438. global $conf;
  7439. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  7440. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  7441. if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
  7442. if ($type_user && $menuentry['module'])
  7443. {
  7444. $tmploops = explode('|', $menuentry['module']);
  7445. $found = 0;
  7446. foreach ($tmploops as $tmploop)
  7447. {
  7448. if (in_array($tmploop, $listofmodulesforexternal)) {
  7449. $found++; break;
  7450. }
  7451. }
  7452. if (!$found) return 0; // Entry is for menus all excluded to external users
  7453. }
  7454. if (!$menuentry['perms'] && $type_user) return 0; // No permissions and user is external
  7455. 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
  7456. if (!$menuentry['perms']) return 2; // No permissions and user is external
  7457. return 1;
  7458. }
  7459. /**
  7460. * Round to next multiple.
  7461. *
  7462. * @param double $n Number to round up
  7463. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  7464. * @return integer Value rounded.
  7465. */
  7466. function roundUpToNextMultiple($n, $x = 5)
  7467. {
  7468. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  7469. }
  7470. /**
  7471. * Function dolGetBadge
  7472. *
  7473. * @param string $label label of badge no html : use in alt attribute for accessibility
  7474. * @param string $html optional : label of badge with html
  7475. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  7476. * @param string $mode default '' , 'pill', 'dot'
  7477. * @param string $url the url for link
  7478. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  7479. * @return string Html badge
  7480. */
  7481. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  7482. {
  7483. $attr = array(
  7484. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  7485. );
  7486. if (empty($html)) {
  7487. $html = $label;
  7488. }
  7489. if (!empty($url)) {
  7490. $attr['href'] = $url;
  7491. }
  7492. if ($mode === 'dot') {
  7493. $attr['class'] .= ' classfortooltip';
  7494. $attr['title'] = $html;
  7495. $attr['aria-label'] = $label;
  7496. $html = '';
  7497. }
  7498. // Override attr
  7499. if (!empty($params['attr']) && is_array($params['attr'])) {
  7500. foreach ($params['attr']as $key => $value) {
  7501. if ($key == 'class') {
  7502. $attr['class'] .= ' '.$value;
  7503. } elseif ($key == 'classOverride') {
  7504. $attr['class'] = $value;
  7505. } else {
  7506. $attr[$key] = $value;
  7507. }
  7508. }
  7509. }
  7510. // TODO: add hook
  7511. // escape all attribute
  7512. $attr = array_map('dol_escape_htmltag', $attr);
  7513. $TCompiledAttr = array();
  7514. foreach ($attr as $key => $value) {
  7515. $TCompiledAttr[] = $key.'="'.$value.'"';
  7516. }
  7517. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7518. $tag = !empty($url) ? 'a' : 'span';
  7519. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  7520. }
  7521. /**
  7522. * Function dolGetStatus
  7523. *
  7524. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  7525. * @param string $statusLabelShort Short label of badge no html
  7526. * @param string $html Optional : label of badge with html
  7527. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  7528. * @param int $displayMode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
  7529. * @param string $url The url for link
  7530. * @param array $params Various params for future : recommended rather than adding more function arguments
  7531. * @return string Html status string
  7532. */
  7533. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  7534. {
  7535. global $conf;
  7536. $return = '';
  7537. $dolGetBadgeParams = array();
  7538. if (!empty($params['badgeParams'])) {
  7539. $dolGetBadgeParams = $params['badgeParams'];
  7540. }
  7541. // TODO : add a hook
  7542. if ($displayMode == 0) {
  7543. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  7544. } elseif ($displayMode == 1) {
  7545. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7546. } // Use status with images (for backward compatibility)
  7547. elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  7548. $return = '';
  7549. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  7550. $htmlLabelShort = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : (!empty($statusLabelShort) ? $statusLabelShort : $statusLabel)).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  7551. // For small screen, we always use the short label instead of long label.
  7552. if (!empty($conf->dol_optimize_smallscreen))
  7553. {
  7554. if ($displayMode == 0) $displayMode = 1;
  7555. elseif ($displayMode == 4) $displayMode = 2;
  7556. elseif ($displayMode == 6) $displayMode = 5;
  7557. }
  7558. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  7559. $statusImg = array(
  7560. 'status0' => 'statut0',
  7561. 'status1' => 'statut1',
  7562. 'status2' => 'statut2',
  7563. 'status3' => 'statut3',
  7564. 'status4' => 'statut4',
  7565. 'status5' => 'statut5',
  7566. 'status6' => 'statut6',
  7567. 'status7' => 'statut7',
  7568. 'status8' => 'statut8',
  7569. 'status9' => 'statut9'
  7570. );
  7571. if (!empty($statusImg[$statusType])) {
  7572. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  7573. } else {
  7574. $htmlImg = img_picto($statusLabel, $statusType);
  7575. }
  7576. if ($displayMode === 2) {
  7577. $return = $htmlImg.' '.$htmlLabelShort;
  7578. } elseif ($displayMode === 3) {
  7579. $return = $htmlImg;
  7580. } elseif ($displayMode === 4) {
  7581. $return = $htmlImg.' '.$htmlLabel;
  7582. } elseif ($displayMode === 5) {
  7583. $return = $htmlLabelShort.' '.$htmlImg;
  7584. } else { // $displayMode >= 6
  7585. $return = $htmlLabel.' '.$htmlImg;
  7586. }
  7587. } // Use new badge
  7588. elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  7589. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7590. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  7591. $dolGetBadgeParams['attr']['title'] = $statusLabel;
  7592. if ($displayMode == 3) {
  7593. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  7594. } elseif ($displayMode === 5) {
  7595. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  7596. } else {
  7597. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  7598. }
  7599. }
  7600. return $return;
  7601. }
  7602. /**
  7603. * Function dolGetButtonAction
  7604. *
  7605. * @param string $label label of button no html : use in alt attribute for accessibility $html is not empty
  7606. * @param string $html optional : content with html
  7607. * @param string $actionType default, delete, danger
  7608. * @param string $url the url for link
  7609. * @param string $id attribute id of button
  7610. * @param int $userRight user action right
  7611. * @param array $params various params for future : recommended rather than adding more function arguments
  7612. * @return string html button
  7613. */
  7614. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  7615. {
  7616. $class = 'butAction';
  7617. if ($actionType == 'danger' || $actionType == 'delete') {
  7618. $class = 'butActionDelete';
  7619. }
  7620. $attr = array(
  7621. 'class' => $class
  7622. ,'href' => empty($url) ? '' : $url
  7623. );
  7624. if (empty($html)) {
  7625. $html = $label;
  7626. } else {
  7627. $attr['aria-label'] = $label;
  7628. }
  7629. if (empty($userRight)) {
  7630. $attr['class'] = 'butActionRefused';
  7631. $attr['href'] = '';
  7632. }
  7633. if (!empty($id)) {
  7634. $attr['id'] = $id;
  7635. }
  7636. // Override attr
  7637. if (!empty($params['attr']) && is_array($params['attr'])) {
  7638. foreach ($params['attr'] as $key => $value) {
  7639. if ($key == 'class') {
  7640. $attr['class'] .= ' '.$value;
  7641. } elseif ($key == 'classOverride') {
  7642. $attr['class'] = $value;
  7643. } else {
  7644. $attr[$key] = $value;
  7645. }
  7646. }
  7647. }
  7648. if (isset($attr['href']) && empty($attr['href'])) {
  7649. unset($attr['href']);
  7650. }
  7651. // TODO : add a hook
  7652. // escape all attribute
  7653. $attr = array_map('dol_escape_htmltag', $attr);
  7654. $TCompiledAttr = array();
  7655. foreach ($attr as $key => $value) {
  7656. $TCompiledAttr[] = $key.'="'.$value.'"';
  7657. }
  7658. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7659. $tag = !empty($attr['href']) ? 'a' : 'span';
  7660. return '<div class="inline-block divButAction"><'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'></div>';
  7661. }
  7662. /**
  7663. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  7664. *
  7665. * @param string $label label of button
  7666. * @param string $helpText optional : content for help tooltip
  7667. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  7668. * @param string $url the url for link
  7669. * @param string $id attribute id of button
  7670. * @param int $status 0 no user rights, 1 active, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  7671. * @param array $params various params for future : recommended rather than adding more function arguments
  7672. * @return string html button
  7673. */
  7674. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  7675. {
  7676. global $langs, $conf, $user;
  7677. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  7678. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  7679. return '';
  7680. }
  7681. $class = 'btnTitle';
  7682. if ($iconClass == 'fa fa-plus-circle') $class .= ' btnTitlePlus';
  7683. $useclassfortooltip = 1;
  7684. if (!empty($params['morecss'])) $class .= ' '.$params['morecss'];
  7685. $attr = array(
  7686. 'class' => $class,
  7687. 'href' => empty($url) ? '' : $url
  7688. );
  7689. if (!empty($helpText)) {
  7690. $attr['title'] = dol_escape_htmltag($helpText);
  7691. } elseif (empty($attr['title']) && $label) {
  7692. $attr['title'] = $label;
  7693. $useclassfortooltip = 0;
  7694. }
  7695. if ($status <= 0) {
  7696. $attr['class'] .= ' refused';
  7697. $attr['href'] = '';
  7698. if ($status == -1) { // disable
  7699. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  7700. } elseif ($status == 0) { // Not enough permissions
  7701. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  7702. }
  7703. }
  7704. if (!empty($attr['title']) && $useclassfortooltip) {
  7705. $attr['class'] .= ' classfortooltip';
  7706. }
  7707. if (!empty($id)) {
  7708. $attr['id'] = $id;
  7709. }
  7710. // Override attr
  7711. if (!empty($params['attr']) && is_array($params['attr'])) {
  7712. foreach ($params['attr'] as $key => $value) {
  7713. if ($key == 'class') {
  7714. $attr['class'] .= ' '.$value;
  7715. } elseif ($key == 'classOverride') {
  7716. $attr['class'] = $value;
  7717. } else {
  7718. $attr[$key] = $value;
  7719. }
  7720. }
  7721. }
  7722. if (isset($attr['href']) && empty($attr['href'])) {
  7723. unset($attr['href']);
  7724. }
  7725. // TODO : add a hook
  7726. // escape all attribute
  7727. $attr = array_map('dol_escape_htmltag', $attr);
  7728. $TCompiledAttr = array();
  7729. foreach ($attr as $key => $value) {
  7730. $TCompiledAttr[] = $key.'="'.$value.'"';
  7731. }
  7732. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  7733. $tag = (empty($attr['href']) ? 'span' : 'a');
  7734. $button = '<'.$tag.' '.$compiledAttributes.'>';
  7735. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  7736. if (!empty($params['forcenohideoftext'])) {
  7737. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  7738. }
  7739. $button .= '</'.$tag.'>';
  7740. return $button;
  7741. }
  7742. /**
  7743. * Get an array with properties of an element.
  7744. * Called by fetchObjectByElement.
  7745. *
  7746. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  7747. * @return array (module, classpath, element, subelement, classfile, classname)
  7748. */
  7749. function getElementProperties($element_type)
  7750. {
  7751. $regs = array();
  7752. $classfile = $classname = $classpath = '';
  7753. // Parse element/subelement (ex: project_task)
  7754. $module = $element_type;
  7755. $element = $element_type;
  7756. $subelement = $element_type;
  7757. // If we ask an resource form external module (instead of default path)
  7758. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  7759. $element = $subelement = $regs[1];
  7760. $module = $regs[2];
  7761. }
  7762. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  7763. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  7764. $module = $element = $regs[1];
  7765. $subelement = $regs[2];
  7766. }
  7767. // For compat
  7768. if ($element_type == "action") {
  7769. $classpath = 'comm/action/class';
  7770. $subelement = 'Actioncomm';
  7771. $module = 'agenda';
  7772. }
  7773. // To work with non standard path
  7774. if ($element_type == 'facture' || $element_type == 'invoice') {
  7775. $classpath = 'compta/facture/class';
  7776. $module = 'facture';
  7777. $subelement = 'facture';
  7778. }
  7779. if ($element_type == 'commande' || $element_type == 'order') {
  7780. $classpath = 'commande/class';
  7781. $module = 'commande';
  7782. $subelement = 'commande';
  7783. }
  7784. if ($element_type == 'propal') {
  7785. $classpath = 'comm/propal/class';
  7786. }
  7787. if ($element_type == 'supplier_proposal') {
  7788. $classpath = 'supplier_proposal/class';
  7789. }
  7790. if ($element_type == 'shipping') {
  7791. $classpath = 'expedition/class';
  7792. $subelement = 'expedition';
  7793. $module = 'expedition_bon';
  7794. }
  7795. if ($element_type == 'delivery') {
  7796. $classpath = 'livraison/class';
  7797. $subelement = 'livraison';
  7798. $module = 'livraison_bon';
  7799. }
  7800. if ($element_type == 'contract') {
  7801. $classpath = 'contrat/class';
  7802. $module = 'contrat';
  7803. $subelement = 'contrat';
  7804. }
  7805. if ($element_type == 'member') {
  7806. $classpath = 'adherents/class';
  7807. $module = 'adherent';
  7808. $subelement = 'adherent';
  7809. }
  7810. if ($element_type == 'cabinetmed_cons') {
  7811. $classpath = 'cabinetmed/class';
  7812. $module = 'cabinetmed';
  7813. $subelement = 'cabinetmedcons';
  7814. }
  7815. if ($element_type == 'fichinter') {
  7816. $classpath = 'fichinter/class';
  7817. $module = 'ficheinter';
  7818. $subelement = 'fichinter';
  7819. }
  7820. if ($element_type == 'dolresource' || $element_type == 'resource') {
  7821. $classpath = 'resource/class';
  7822. $module = 'resource';
  7823. $subelement = 'dolresource';
  7824. }
  7825. if ($element_type == 'propaldet') {
  7826. $classpath = 'comm/propal/class';
  7827. $module = 'propal';
  7828. $subelement = 'propaleligne';
  7829. }
  7830. if ($element_type == 'order_supplier') {
  7831. $classpath = 'fourn/class';
  7832. $module = 'fournisseur';
  7833. $subelement = 'commandefournisseur';
  7834. $classfile = 'fournisseur.commande';
  7835. }
  7836. if ($element_type == 'invoice_supplier') {
  7837. $classpath = 'fourn/class';
  7838. $module = 'fournisseur';
  7839. $subelement = 'facturefournisseur';
  7840. $classfile = 'fournisseur.facture';
  7841. }
  7842. if ($element_type == "service") {
  7843. $classpath = 'product/class';
  7844. $subelement = 'product';
  7845. }
  7846. if (empty($classfile)) $classfile = strtolower($subelement);
  7847. if (empty($classname)) $classname = ucfirst($subelement);
  7848. if (empty($classpath)) $classpath = $module.'/class';
  7849. $element_properties = array(
  7850. 'module' => $module,
  7851. 'classpath' => $classpath,
  7852. 'element' => $element,
  7853. 'subelement' => $subelement,
  7854. 'classfile' => $classfile,
  7855. 'classname' => $classname
  7856. );
  7857. return $element_properties;
  7858. }
  7859. /**
  7860. * Fetch an object from its id and element_type
  7861. * Inclusion of classes is automatic
  7862. *
  7863. * @param int $element_id Element id
  7864. * @param string $element_type Element type
  7865. * @param string $element_ref Element ref (Use this or element_id but not both)
  7866. * @return int|object object || 0 || -1 if error
  7867. */
  7868. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  7869. {
  7870. global $conf, $db;
  7871. $element_prop = getElementProperties($element_type);
  7872. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
  7873. {
  7874. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  7875. $objecttmp = new $element_prop['classname']($db);
  7876. $ret = $objecttmp->fetch($element_id, $element_ref);
  7877. if ($ret >= 0)
  7878. {
  7879. return $objecttmp;
  7880. }
  7881. }
  7882. return 0;
  7883. }
  7884. /**
  7885. * Return if a file can contains executable content
  7886. *
  7887. * @param string $filename File name to test
  7888. * @return boolean True if yes, False if no
  7889. */
  7890. function isAFileWithExecutableContent($filename)
  7891. {
  7892. if (preg_match('/\.(htm|html|js|phar|php|php\d+|phtml|pht|pl|py|cgi|ksh|sh|shtml|bash|bat|cmd|wpk|exe|dmg)$/i', $filename))
  7893. {
  7894. return true;
  7895. }
  7896. return false;
  7897. }
  7898. /**
  7899. * Return the value of token currently saved into session with name 'newtoken'.
  7900. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  7901. *
  7902. * @return string
  7903. */
  7904. function newToken()
  7905. {
  7906. return $_SESSION['newtoken'];
  7907. }
  7908. /**
  7909. * Return the value of token currently saved into session with name 'token'.
  7910. *
  7911. * @return string
  7912. */
  7913. function currentToken()
  7914. {
  7915. return $_SESSION['token'];
  7916. }
  7917. /**
  7918. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  7919. *
  7920. * @param string $header The first left header of the table (automatic translated)
  7921. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  7922. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  7923. * @param integer $emptyRows (optional) The count of empty rows after the first header
  7924. * @param integer $number (optional) The number that is shown right after the first header, when not set the link is shown on the right side of the header as "FullList"
  7925. * @return void
  7926. *
  7927. * @see finishSimpleTable()
  7928. */
  7929. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  7930. {
  7931. global $langs;
  7932. print '<div class="div-table-responsive-no-min">';
  7933. print '<table class="noborder centpercent">';
  7934. print '<tr class="liste_titre">';
  7935. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  7936. print $langs->trans($header);
  7937. // extra space between the first header and the number
  7938. if ($number > -1) {
  7939. print ' ';
  7940. }
  7941. if (!empty($link)) {
  7942. if (!empty($arguments)) {
  7943. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  7944. } else {
  7945. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  7946. }
  7947. }
  7948. if ($number > -1) {
  7949. print '<span class="badge">'.$number.'</span>';
  7950. }
  7951. if (!empty($link)) {
  7952. print '</a>';
  7953. }
  7954. print '</th>';
  7955. if ($number < 0 && !empty($link)) {
  7956. print '<th class="right">';
  7957. if (!empty($arguments)) {
  7958. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  7959. } else {
  7960. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  7961. }
  7962. print $langs->trans("FullList");
  7963. print '</a>';
  7964. print '</th>';
  7965. }
  7966. print '</tr>';
  7967. }
  7968. /**
  7969. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  7970. *
  7971. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  7972. * @return void
  7973. *
  7974. * @see startSimpleTable()
  7975. */
  7976. function finishSimpleTable($addLineBreak = false)
  7977. {
  7978. print '</table>';
  7979. print '</div>';
  7980. if ($addLineBreak) {
  7981. print '<br>';
  7982. }
  7983. }
  7984. /**
  7985. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  7986. *
  7987. * @param integer $tableColumnCount The complete count columns of the table
  7988. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  7989. * @param integer $nbofloop (optional) The maximum count of rows thaht the table show (when it is zero (0) no summary line will show, expect "$noneWord" when $num === 0)
  7990. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  7991. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  7992. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  7993. * @return void
  7994. */
  7995. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  7996. {
  7997. global $langs;
  7998. if ($num === 0) {
  7999. print '<tr class="oddeven">';
  8000. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  8001. print '</tr>';
  8002. return;
  8003. }
  8004. if ($nbofloop === 0)
  8005. {
  8006. // don't show a summary line
  8007. return;
  8008. }
  8009. if ($num === 0) {
  8010. $colspan = $tableColumnCount;
  8011. }
  8012. elseif ($num > $nbofloop) {
  8013. $colspan = $tableColumnCount;
  8014. } else {
  8015. $colspan = $tableColumnCount - 1;
  8016. }
  8017. if ($extraRightColumn) {
  8018. $colspan--;
  8019. }
  8020. print '<tr class="liste_total">';
  8021. if ($nbofloop > 0 && $num > $nbofloop) {
  8022. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  8023. } else {
  8024. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  8025. print '<td class="right" width="100">'.price($total).'</td>';
  8026. }
  8027. if ($extraRightColumn) {
  8028. print '<td></td>';
  8029. }
  8030. print '</tr>';
  8031. }