functions.lib.php 555 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561
  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-2022 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019-2023 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
  21. * Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
  22. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  23. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. * or see https://www.gnu.org/
  38. */
  39. /**
  40. * \file htdocs/core/lib/functions.lib.php
  41. * \brief A set of functions for Dolibarr
  42. * This file contains all frequently used functions.
  43. */
  44. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  45. // Function for better PHP x compatibility
  46. if (!function_exists('utf8_encode')) {
  47. /**
  48. * Implement utf8_encode for PHP that does not support it.
  49. *
  50. * @param mixed $elements PHP Object to json encode
  51. * @return string Json encoded string
  52. */
  53. function utf8_encode($elements)
  54. {
  55. return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
  56. }
  57. }
  58. if (!function_exists('utf8_decode')) {
  59. /**
  60. * Implement utf8_decode for PHP that does not support it.
  61. *
  62. * @param mixed $elements PHP Object to json encode
  63. * @return string Json encoded string
  64. */
  65. function utf8_decode($elements)
  66. {
  67. return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
  68. }
  69. }
  70. if (!function_exists('str_starts_with')) {
  71. /**
  72. * str_starts_with
  73. *
  74. * @param string $haystack haystack
  75. * @param string $needle needle
  76. * @return boolean
  77. */
  78. function str_starts_with($haystack, $needle)
  79. {
  80. return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
  81. }
  82. }
  83. if (!function_exists('str_ends_with')) {
  84. /**
  85. * str_ends_with
  86. *
  87. * @param string $haystack haystack
  88. * @param string $needle needle
  89. * @return boolean
  90. */
  91. function str_ends_with($haystack, $needle)
  92. {
  93. return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
  94. }
  95. }
  96. if (!function_exists('str_contains')) {
  97. /**
  98. * str_contains
  99. *
  100. * @param string $haystack haystack
  101. * @param string $needle needle
  102. * @return boolean
  103. */
  104. function str_contains($haystack, $needle)
  105. {
  106. return $needle !== '' && mb_strpos($haystack, $needle) !== false;
  107. }
  108. }
  109. /**
  110. * Return the full path of the directory where a module (or an object of a module) stores its files. Path may depends on the entity if a multicompany module is enabled.
  111. *
  112. * @param CommonObject $object Dolibarr common object
  113. * @param string $module Override object element, for example to use 'mycompany' instead of 'societe'
  114. * @return string|void The path of the relative directory of the module
  115. * @since Dolibarr V18
  116. */
  117. function getMultidirOutput($object, $module = '')
  118. {
  119. global $conf;
  120. if (!is_object($object) && empty($module)) {
  121. return null;
  122. }
  123. if (empty($module) && !empty($object->element)) {
  124. $module = $object->element;
  125. }
  126. // Special case for backward compatibility
  127. if ($module == 'fichinter') {
  128. $module = 'ficheinter';
  129. }
  130. if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
  131. return $conf->$module->multidir_output[(empty($object->entity) ? $conf->entity : $object->entity)];
  132. } else {
  133. return 'error-diroutput-not-defined-for-this-object='.$module;
  134. }
  135. }
  136. /**
  137. * Return dolibarr global constant string value
  138. *
  139. * @param string $key key to return value, return '' if not set
  140. * @param string $default value to return
  141. * @return string
  142. */
  143. function getDolGlobalString($key, $default = '')
  144. {
  145. global $conf;
  146. return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
  147. }
  148. /**
  149. * Return a Dolibarr global constant int value.
  150. * The constants $conf->global->xxx are loaded by the script master.inc.php included at begin of any PHP page.
  151. *
  152. * @param string $key key to return value, return 0 if not set
  153. * @param int $default value to return
  154. * @return int
  155. */
  156. function getDolGlobalInt($key, $default = 0)
  157. {
  158. global $conf;
  159. return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
  160. }
  161. /**
  162. * Return Dolibarr user constant string value
  163. *
  164. * @param string $key key to return value, return '' if not set
  165. * @param string $default value to return
  166. * @param User $tmpuser To get another user than current user
  167. * @return string
  168. */
  169. function getDolUserString($key, $default = '', $tmpuser = null)
  170. {
  171. if (empty($tmpuser)) {
  172. global $user;
  173. $tmpuser = $user;
  174. }
  175. return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  176. }
  177. /**
  178. * Return Dolibarr user constant int value
  179. *
  180. * @param string $key key to return value, return 0 if not set
  181. * @param int $default value to return
  182. * @param User $tmpuser To get another user than current user
  183. * @return int
  184. */
  185. function getDolUserInt($key, $default = 0, $tmpuser = null)
  186. {
  187. if (empty($tmpuser)) {
  188. global $user;
  189. $tmpuser = $user;
  190. }
  191. return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  192. }
  193. /**
  194. * Is Dolibarr module enabled
  195. *
  196. * @param string $module Module name to check
  197. * @return boolean True if module is enabled
  198. */
  199. function isModEnabled($module)
  200. {
  201. global $conf;
  202. // Fix special cases
  203. $arrayconv = array(
  204. 'bank' => 'banque',
  205. 'category' => 'categorie',
  206. 'contract' => 'contrat',
  207. 'project' => 'projet',
  208. 'delivery_note' => 'expedition'
  209. );
  210. if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
  211. $arrayconv['supplier_order'] = 'fournisseur';
  212. $arrayconv['supplier_invoice'] = 'fournisseur';
  213. }
  214. if (!empty($arrayconv[$module])) {
  215. $module = $arrayconv[$module];
  216. }
  217. return !empty($conf->modules[$module]);
  218. //return !empty($conf->$module->enabled);
  219. }
  220. /**
  221. * Return a DoliDB instance (database handler).
  222. *
  223. * @param string $type Type of database (mysql, pgsql...)
  224. * @param string $host Address of database server
  225. * @param string $user Authorized username
  226. * @param string $pass Password
  227. * @param string $name Name of database
  228. * @param int $port Port of database server
  229. * @return DoliDB A DoliDB instance
  230. */
  231. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  232. {
  233. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  234. $class = 'DoliDB'.ucfirst($type);
  235. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  236. return $dolidb;
  237. }
  238. /**
  239. * Get list of entity id to use.
  240. *
  241. * @param string $element Current element
  242. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  243. * 'product', 'productprice', 'stock', 'bom', 'mo',
  244. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  245. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  246. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  247. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  248. * 'email_template', 'event', 'donation'
  249. * 'c_paiement', 'c_payment_term', ...
  250. * @param int $shared 0=Return id of current entity only,
  251. * 1=Return id of current entity + shared entities (default)
  252. * @param object $currentobject Current object if needed
  253. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  254. */
  255. function getEntity($element, $shared = 1, $currentobject = null)
  256. {
  257. global $conf, $mc, $hookmanager, $object, $action, $db;
  258. if (!is_object($hookmanager)) {
  259. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  260. $hookmanager = new HookManager($db);
  261. }
  262. // fix different element names (France to English)
  263. switch ($element) {
  264. case 'projet':
  265. $element = 'project';
  266. break;
  267. case 'contrat':
  268. $element = 'contract';
  269. break; // "/contrat/class/contrat.class.php"
  270. case 'order_supplier':
  271. $element = 'supplier_order';
  272. break; // "/fourn/class/fournisseur.commande.class.php"
  273. case 'invoice_supplier':
  274. $element = 'supplier_invoice';
  275. break; // "/fourn/class/fournisseur.facture.class.php"
  276. }
  277. if (is_object($mc)) {
  278. $out = $mc->getEntity($element, $shared, $currentobject);
  279. } else {
  280. $out = '';
  281. $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans');
  282. if (in_array($element, $addzero)) {
  283. $out .= '0,';
  284. }
  285. $out .= ((int) $conf->entity);
  286. }
  287. // Manipulate entities to query on the fly
  288. $parameters = array(
  289. 'element' => $element,
  290. 'shared' => $shared,
  291. 'object' => $object,
  292. 'currentobject' => $currentobject,
  293. 'out' => $out
  294. );
  295. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  296. if (is_numeric($reshook)) {
  297. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  298. $out .= ','.$hookmanager->resPrint; // add
  299. } elseif ($reshook == 1) {
  300. $out = $hookmanager->resPrint; // replace
  301. }
  302. }
  303. return $out;
  304. }
  305. /**
  306. * Set entity id to use when to create an object
  307. *
  308. * @param object $currentobject Current object
  309. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  310. */
  311. function setEntity($currentobject)
  312. {
  313. global $conf, $mc;
  314. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  315. return $mc->setEntity($currentobject);
  316. } else {
  317. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  318. }
  319. }
  320. /**
  321. * Return if string has a name dedicated to store a secret
  322. *
  323. * @param string $keyname Name of key to test
  324. * @return boolean True if key is used to store a secret
  325. */
  326. function isASecretKey($keyname)
  327. {
  328. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  329. }
  330. /**
  331. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  332. *
  333. * @param int|string $n Numeric value
  334. * @return string Column in Excel format
  335. */
  336. function num2Alpha($n)
  337. {
  338. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
  339. $r = chr($n % 26 + 0x41) . $r;
  340. }
  341. return $r;
  342. }
  343. /**
  344. * Return information about user browser
  345. *
  346. * Returns array with the following format:
  347. * array(
  348. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  349. * 'browserversion' => Browser version. Empty if unknown
  350. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  351. * 'layout' => (tablet|phone|classic)
  352. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  353. * 'tablet' => true/false
  354. * )
  355. *
  356. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  357. * @return array Check function documentation
  358. */
  359. function getBrowserInfo($user_agent)
  360. {
  361. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  362. $name = 'unknown';
  363. $version = '';
  364. $os = 'unknown';
  365. $phone = '';
  366. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  367. $detectmobile = new Mobile_Detect(null, $user_agent);
  368. $tablet = $detectmobile->isTablet();
  369. if ($detectmobile->isMobile()) {
  370. $phone = 'unknown';
  371. // If phone/smartphone, we set phone os name.
  372. if ($detectmobile->is('AndroidOS')) {
  373. $os = $phone = 'android';
  374. } elseif ($detectmobile->is('BlackBerryOS')) {
  375. $os = $phone = 'blackberry';
  376. } elseif ($detectmobile->is('iOS')) {
  377. $os = 'ios';
  378. $phone = 'iphone';
  379. } elseif ($detectmobile->is('PalmOS')) {
  380. $os = $phone = 'palm';
  381. } elseif ($detectmobile->is('SymbianOS')) {
  382. $os = 'symbian';
  383. } elseif ($detectmobile->is('webOS')) {
  384. $os = 'webos';
  385. } elseif ($detectmobile->is('MaemoOS')) {
  386. $os = 'maemo';
  387. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  388. $os = 'windows';
  389. }
  390. }
  391. // OS
  392. if (preg_match('/linux/i', $user_agent)) {
  393. $os = 'linux';
  394. } elseif (preg_match('/macintosh/i', $user_agent)) {
  395. $os = 'macintosh';
  396. } elseif (preg_match('/windows/i', $user_agent)) {
  397. $os = 'windows';
  398. }
  399. // Name
  400. $reg = array();
  401. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  402. $name = 'firefox';
  403. $version = empty($reg[2]) ? '' : $reg[2];
  404. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  405. $name = 'edge';
  406. $version = empty($reg[2]) ? '' : $reg[2];
  407. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  408. $name = 'chrome';
  409. $version = empty($reg[2]) ? '' : $reg[2];
  410. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  411. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  412. $name = 'chrome';
  413. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  414. $name = 'iceweasel';
  415. } elseif (preg_match('/epiphany/i', $user_agent)) {
  416. $name = 'epiphany';
  417. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  418. $name = 'safari';
  419. $version = empty($reg[2]) ? '' : $reg[2];
  420. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  421. // Safari is often present in string for mobile but its not.
  422. $name = 'opera';
  423. $version = empty($reg[2]) ? '' : $reg[2];
  424. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  425. $name = 'ie';
  426. $version = end($reg);
  427. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  428. // MS products at end
  429. $name = 'ie';
  430. $version = end($reg);
  431. } elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  432. // MS products at end
  433. $name = 'lynxlinks';
  434. $version = empty($reg[3]) ? '' : $reg[3];
  435. }
  436. if ($tablet) {
  437. $layout = 'tablet';
  438. } elseif ($phone) {
  439. $layout = 'phone';
  440. } else {
  441. $layout = 'classic';
  442. }
  443. return array(
  444. 'browsername' => $name,
  445. 'browserversion' => $version,
  446. 'browseros' => $os,
  447. 'browserua' => $user_agent,
  448. 'layout' => $layout, // tablet, phone, classic
  449. 'phone' => $phone, // deprecated
  450. 'tablet' => $tablet // deprecated
  451. );
  452. }
  453. /**
  454. * Function called at end of web php process
  455. *
  456. * @return void
  457. */
  458. function dol_shutdown()
  459. {
  460. global $db;
  461. $disconnectdone = false;
  462. $depth = 0;
  463. if (is_object($db) && !empty($db->connected)) {
  464. $depth = $db->transaction_opened;
  465. $disconnectdone = $db->close();
  466. }
  467. dol_syslog("--- End access to ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]).(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
  468. }
  469. /**
  470. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  471. * Warning:
  472. * For action=add, use: $var = GETPOST('var'); // No GETPOSTISSET, so GETPOST always called and default value is retreived if not a form POST, and value of form is retreived if it is a form POST.
  473. * For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var;
  474. *
  475. * @param string $paramname Name or parameter to test
  476. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  477. */
  478. function GETPOSTISSET($paramname)
  479. {
  480. $isset = false;
  481. $relativepathstring = $_SERVER["PHP_SELF"];
  482. // Clean $relativepathstring
  483. if (constant('DOL_URL_ROOT')) {
  484. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  485. }
  486. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  487. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  488. //var_dump($relativepathstring);
  489. //var_dump($user->default_values);
  490. // Code for search criteria persistence.
  491. // Retrieve values if restore_lastsearch_values
  492. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  493. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  494. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  495. if (is_array($tmp)) {
  496. foreach ($tmp as $key => $val) {
  497. if ($key == $paramname) { // We are on the requested parameter
  498. $isset = true;
  499. break;
  500. }
  501. }
  502. }
  503. }
  504. // If there is saved contextpage, limit, page or mode
  505. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  506. $isset = true;
  507. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  508. $isset = true;
  509. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  510. $isset = true;
  511. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  512. $isset = true;
  513. }
  514. } else {
  515. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  516. }
  517. return $isset;
  518. }
  519. /**
  520. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  521. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  522. *
  523. * @param string $paramname Name or parameter to test
  524. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  525. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  526. */
  527. function GETPOSTISARRAY($paramname, $method = 0)
  528. {
  529. // for $method test need return the same $val as GETPOST
  530. if (empty($method)) {
  531. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  532. } elseif ($method == 1) {
  533. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  534. } elseif ($method == 2) {
  535. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  536. } elseif ($method == 3) {
  537. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  538. } else {
  539. $val = 'BadFirstParameterForGETPOST';
  540. }
  541. return is_array($val);
  542. }
  543. /**
  544. * Return value of a param into GET or POST supervariable.
  545. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  546. * Note: The property $user->default_values is loaded by main.php when loading the user.
  547. *
  548. * @param string $paramname Name of parameter to found
  549. * @param string $check Type of check
  550. * ''=no check (deprecated)
  551. * 'none'=no check (only for param that should have very rich content like passwords)
  552. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  553. * 'int'=check it's numeric (integer or float)
  554. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  555. * 'alpha'=Same than alphanohtml since v13
  556. * 'alphawithlgt'=alpha with lgt
  557. * 'alphanohtml'=check there is no html content and no " and no ../
  558. * 'aZ'=check it's a-z only
  559. * 'aZ09'=check it's simple alpha string (recommended for keys)
  560. * 'aZ09arobase'=check it's a string for an element type
  561. * 'aZ09comma'=check it's a string for a sortfield or sortorder
  562. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  563. * 'nohtml'=check there is no html content
  564. * 'restricthtml'=check html content is restricted to some tags only
  565. * 'custom'= custom filter specify $filter and $options)
  566. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  567. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  568. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  569. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  570. * @return string|array Value found (string or array), or '' if check fails
  571. */
  572. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  573. {
  574. global $mysoc, $user, $conf;
  575. if (empty($paramname)) {
  576. return 'BadFirstParameterForGETPOST';
  577. }
  578. if (empty($check)) {
  579. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and a 2nd param that is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  580. // Enable this line to know who call the GETPOST with '' $check parameter.
  581. //var_dump(debug_backtrace()[0]);
  582. }
  583. if (empty($method)) {
  584. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  585. } elseif ($method == 1) {
  586. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  587. } elseif ($method == 2) {
  588. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  589. } elseif ($method == 3) {
  590. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  591. } else {
  592. return 'BadThirdParameterForGETPOST';
  593. }
  594. if (empty($method) || $method == 3 || $method == 4) {
  595. $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
  596. // Clean $relativepathstring
  597. if (constant('DOL_URL_ROOT')) {
  598. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  599. }
  600. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  601. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  602. //var_dump($relativepathstring);
  603. //var_dump($user->default_values);
  604. // Code for search criteria persistence.
  605. // Retrieve saved values if restore_lastsearch_values is set
  606. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  607. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  608. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  609. if (is_array($tmp)) {
  610. foreach ($tmp as $key => $val) {
  611. if ($key == $paramname) { // We are on the requested parameter
  612. $out = $val;
  613. break;
  614. }
  615. }
  616. }
  617. }
  618. // If there is saved contextpage, page or limit
  619. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  620. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  621. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  622. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  623. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  624. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  625. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  626. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  627. }
  628. } elseif (!isset($_GET['sortfield'])) {
  629. // Else, retrieve default values if we are not doing a sort
  630. // 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
  631. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  632. // Search default value from $object->field
  633. global $object;
  634. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  635. $out = $object->fields[$paramname]['default'];
  636. }
  637. }
  638. if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
  639. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  640. // Now search in setup to overwrite default values
  641. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  642. if (isset($user->default_values[$relativepathstring]['createform'])) {
  643. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  644. $qualified = 0;
  645. if ($defkey != '_noquery_') {
  646. $tmpqueryarraytohave = explode('&', $defkey);
  647. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  648. $foundintru = 0;
  649. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  650. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  651. $foundintru = 1;
  652. }
  653. }
  654. if (!$foundintru) {
  655. $qualified = 1;
  656. }
  657. //var_dump($defkey.'-'.$qualified);
  658. } else {
  659. $qualified = 1;
  660. }
  661. if ($qualified) {
  662. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  663. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  664. break;
  665. }
  666. }
  667. }
  668. }
  669. }
  670. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  671. // Management of default search_filters and sort order
  672. if (!empty($user->default_values)) {
  673. // $user->default_values defined from menu 'Setup - Default values'
  674. //var_dump($user->default_values[$relativepathstring]);
  675. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  676. // Sorted on which fields ? ASC or DESC ?
  677. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  678. // Even if paramname is sortfield, data are stored into ['sortorder...']
  679. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  680. $qualified = 0;
  681. if ($defkey != '_noquery_') {
  682. $tmpqueryarraytohave = explode('&', $defkey);
  683. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  684. $foundintru = 0;
  685. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  686. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  687. $foundintru = 1;
  688. }
  689. }
  690. if (!$foundintru) {
  691. $qualified = 1;
  692. }
  693. //var_dump($defkey.'-'.$qualified);
  694. } else {
  695. $qualified = 1;
  696. }
  697. if ($qualified) {
  698. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  699. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  700. if ($out) {
  701. $out .= ', ';
  702. }
  703. if ($paramname == 'sortfield') {
  704. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  705. }
  706. if ($paramname == 'sortorder') {
  707. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  708. }
  709. }
  710. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  711. }
  712. }
  713. }
  714. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  715. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  716. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  717. continue;
  718. }
  719. $qualified = 0;
  720. if ($defkey != '_noquery_') {
  721. $tmpqueryarraytohave = explode('&', $defkey);
  722. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  723. $foundintru = 0;
  724. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  725. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  726. $foundintru = 1;
  727. }
  728. }
  729. if (!$foundintru) {
  730. $qualified = 1;
  731. }
  732. //var_dump($defkey.'-'.$qualified);
  733. } else {
  734. $qualified = 1;
  735. }
  736. if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
  737. // We must keep $_POST and $_GET here
  738. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  739. // We made a search from quick search menu, do we still use default filter ?
  740. if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
  741. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  742. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  743. }
  744. } else {
  745. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  746. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  747. }
  748. break;
  749. }
  750. }
  751. }
  752. }
  753. }
  754. }
  755. }
  756. }
  757. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value, when using variable parameters __XXX__ in the GET URL)
  758. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  759. // 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.
  760. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  761. $reg = array();
  762. $maxloop = 20;
  763. $loopnb = 0; // Protection against infinite loop
  764. 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.
  765. $loopnb++;
  766. $newout = '';
  767. if ($reg[1] == 'DAY') {
  768. $tmp = dol_getdate(dol_now(), true);
  769. $newout = $tmp['mday'];
  770. } elseif ($reg[1] == 'MONTH') {
  771. $tmp = dol_getdate(dol_now(), true);
  772. $newout = $tmp['mon'];
  773. } elseif ($reg[1] == 'YEAR') {
  774. $tmp = dol_getdate(dol_now(), true);
  775. $newout = $tmp['year'];
  776. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  777. $tmp = dol_getdate(dol_now(), true);
  778. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  779. $newout = $tmp2['day'];
  780. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  781. $tmp = dol_getdate(dol_now(), true);
  782. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  783. $newout = $tmp2['month'];
  784. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  785. $tmp = dol_getdate(dol_now(), true);
  786. $newout = ($tmp['year'] - 1);
  787. } elseif ($reg[1] == 'NEXT_DAY') {
  788. $tmp = dol_getdate(dol_now(), true);
  789. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  790. $newout = $tmp2['day'];
  791. } elseif ($reg[1] == 'NEXT_MONTH') {
  792. $tmp = dol_getdate(dol_now(), true);
  793. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  794. $newout = $tmp2['month'];
  795. } elseif ($reg[1] == 'NEXT_YEAR') {
  796. $tmp = dol_getdate(dol_now(), true);
  797. $newout = ($tmp['year'] + 1);
  798. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  799. $newout = $mysoc->country_id;
  800. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  801. $newout = $user->id;
  802. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  803. $newout = $user->fk_user;
  804. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  805. $newout = $conf->entity;
  806. } else {
  807. $newout = ''; // Key not found, we replace with empty string
  808. }
  809. //var_dump('__'.$reg[1].'__ -> '.$newout);
  810. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  811. }
  812. }
  813. // Check type of variable and make sanitization according to this
  814. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  815. if (!is_array($out) || empty($out)) {
  816. $out = array();
  817. } else {
  818. $tmparray = explode(':', $check);
  819. if (!empty($tmparray[1])) {
  820. $tmpcheck = $tmparray[1];
  821. } else {
  822. $tmpcheck = 'alphanohtml';
  823. }
  824. foreach ($out as $outkey => $outval) {
  825. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  826. }
  827. }
  828. } else {
  829. // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
  830. // we use the < or > to make a search on a numeric value to do higher or lower so we can add a space to break html tags
  831. if (strpos($paramname, 'search_') === 0) {
  832. $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
  833. }
  834. $out = sanitizeVal($out, $check, $filter, $options);
  835. }
  836. // Sanitizing for special parameters.
  837. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  838. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  839. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  840. $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
  841. do {
  842. $oldstringtoclean = $out;
  843. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  844. $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
  845. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  846. } while ($oldstringtoclean != $out);
  847. }
  848. // Code for search criteria persistence.
  849. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  850. if (empty($method) || $method == 3 || $method == 4) {
  851. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  852. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  853. // We save search key only if $out not empty that means:
  854. // - posted value not empty, or
  855. // - 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).
  856. if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
  857. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  858. }
  859. }
  860. }
  861. return $out;
  862. }
  863. /**
  864. * Return value of a param into GET or POST supervariable.
  865. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  866. * Note: The property $user->default_values is loaded by main.php when loading the user.
  867. *
  868. * @param string $paramname Name of parameter to found
  869. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  870. * @return int Value found (int)
  871. */
  872. function GETPOSTINT($paramname, $method = 0)
  873. {
  874. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  875. }
  876. /**
  877. * Return a sanitized or empty value after checking value against a rule.
  878. *
  879. * @deprecated
  880. * @param string|array $out Value to check/clear.
  881. * @param string $check Type of check/sanitizing
  882. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  883. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  884. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  885. */
  886. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  887. {
  888. return sanitizeVal($out, $check, $filter, $options);
  889. }
  890. /**
  891. * Return a sanitized or empty value after checking value against a rule.
  892. *
  893. * @param string|array $out Value to check/clear.
  894. * @param string $check Type of check/sanitizing
  895. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  896. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  897. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  898. */
  899. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  900. {
  901. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  902. // Check is done after replacement
  903. switch ($check) {
  904. case 'none':
  905. break;
  906. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  907. if (!is_numeric($out)) {
  908. $out = '';
  909. }
  910. break;
  911. case 'intcomma':
  912. if (is_array($out)) {
  913. $out = implode(',', $out);
  914. }
  915. if (preg_match('/[^0-9,-]+/i', $out)) {
  916. $out = '';
  917. }
  918. break;
  919. case 'san_alpha':
  920. $out = filter_var($out, FILTER_SANITIZE_STRING);
  921. break;
  922. case 'email':
  923. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  924. break;
  925. case 'aZ':
  926. if (!is_array($out)) {
  927. $out = trim($out);
  928. if (preg_match('/[^a-z]+/i', $out)) {
  929. $out = '';
  930. }
  931. }
  932. break;
  933. case 'aZ09':
  934. if (!is_array($out)) {
  935. $out = trim($out);
  936. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  937. $out = '';
  938. }
  939. }
  940. break;
  941. case 'aZ09arobase': // great to sanitize $objecttype parameter
  942. if (!is_array($out)) {
  943. $out = trim($out);
  944. if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
  945. $out = '';
  946. }
  947. }
  948. break;
  949. case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
  950. if (!is_array($out)) {
  951. $out = trim($out);
  952. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  953. $out = '';
  954. }
  955. }
  956. break;
  957. case 'alpha': // No html and no ../ and "
  958. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  959. if (!is_array($out)) {
  960. $out = trim($out);
  961. do {
  962. $oldstringtoclean = $out;
  963. // Remove html tags
  964. $out = dol_string_nohtmltag($out, 0);
  965. // Remove also other dangerous string sequences
  966. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  967. // '../' or '..\' is dangerous because it allows dir transversals
  968. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  969. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  970. } while ($oldstringtoclean != $out);
  971. // keep lines feed
  972. }
  973. break;
  974. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
  975. if (!is_array($out)) {
  976. $out = trim($out);
  977. do {
  978. $oldstringtoclean = $out;
  979. // Remove html tags
  980. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  981. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  982. // '../' or '..\' is dangerous because it allows dir transversals
  983. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  984. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  985. } while ($oldstringtoclean != $out);
  986. }
  987. break;
  988. case 'nohtml': // No html
  989. $out = dol_string_nohtmltag($out, 0);
  990. break;
  991. case 'restricthtmlnolink':
  992. case 'restricthtml': // Recommended for most html textarea
  993. case 'restricthtmlallowclass':
  994. case 'restricthtmlallowunvalid':
  995. $out = dol_htmlwithnojs($out, 1, $check);
  996. break;
  997. case 'custom':
  998. if (!empty($out)) {
  999. if (empty($filter)) {
  1000. return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
  1001. }
  1002. /*if (empty($options)) {
  1003. return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
  1004. }*/
  1005. $out = filter_var($out, $filter, $options);
  1006. }
  1007. break;
  1008. default:
  1009. dol_syslog("Error, you call sanitizeVal() with a bad value for the check type. Data can't be sanitized.", LOG_ERR);
  1010. break;
  1011. }
  1012. return $out;
  1013. }
  1014. if (!function_exists('dol_getprefix')) {
  1015. /**
  1016. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  1017. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  1018. * or two instances in same virtual servers.
  1019. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  1020. *
  1021. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  1022. * @return string A calculated prefix
  1023. */
  1024. function dol_getprefix($mode = '')
  1025. {
  1026. // If prefix is for email (we need to have $conf already loaded for this case)
  1027. if ($mode == 'email') {
  1028. global $conf;
  1029. if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID')) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  1030. if (getDolGlobalString('MAIL_PREFIX_FOR_EMAIL_ID') != 'SERVER_NAME') {
  1031. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  1032. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  1033. return $_SERVER["SERVER_NAME"];
  1034. }
  1035. }
  1036. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  1037. if (!empty($conf->file->instance_unique_id)) {
  1038. return sha1('dolibarr'.$conf->file->instance_unique_id);
  1039. }
  1040. // For backward compatibility when instance_unique_id is not set
  1041. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1042. }
  1043. // If prefix is for session (no need to have $conf loaded)
  1044. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  1045. $tmp_instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance
  1046. // The recommended value (may be not defined for old versions)
  1047. if (!empty($tmp_instance_unique_id)) {
  1048. return sha1('dolibarr'.$tmp_instance_unique_id);
  1049. }
  1050. // For backward compatibility when instance_unique_id is not set
  1051. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  1052. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1053. } else {
  1054. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  1055. }
  1056. }
  1057. }
  1058. /**
  1059. * Make an include_once using default root and alternate root if it fails.
  1060. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  1061. * To link to a module file from a module file, use include './mymodulefile';
  1062. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  1063. *
  1064. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  1065. * @param string $classname Class name (deprecated)
  1066. * @return bool True if load is a success, False if it fails
  1067. */
  1068. function dol_include_once($relpath, $classname = '')
  1069. {
  1070. global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retrieved with $GLOBALS['var']
  1071. $fullpath = dol_buildpath($relpath);
  1072. if (!file_exists($fullpath)) {
  1073. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  1074. return false;
  1075. }
  1076. if (!empty($classname) && !class_exists($classname)) {
  1077. return include $fullpath;
  1078. } else {
  1079. return include_once $fullpath;
  1080. }
  1081. }
  1082. /**
  1083. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  1084. *
  1085. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  1086. * @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)
  1087. * @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)
  1088. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  1089. * 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
  1090. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  1091. */
  1092. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  1093. {
  1094. global $conf;
  1095. $path = preg_replace('/^\//', '', $path);
  1096. if (empty($type)) { // For a filesystem path
  1097. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  1098. if (is_array($conf->file->dol_document_root)) {
  1099. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  1100. if ($key == 'main') {
  1101. continue;
  1102. }
  1103. // if (@file_exists($dirroot.'/'.$path)) {
  1104. if (@file_exists($dirroot.'/'.$path)) { // avoid [php:warn]
  1105. $res = $dirroot.'/'.$path;
  1106. return $res;
  1107. }
  1108. }
  1109. }
  1110. if ($returnemptyifnotfound) {
  1111. // Not found into alternate dir
  1112. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  1113. return '';
  1114. }
  1115. }
  1116. } else {
  1117. // For an url path
  1118. // We try to get local path of file on filesystem from url
  1119. // Note that trying to know if a file on disk exist by forging path on disk from url
  1120. // works only for some web server and some setup. This is bugged when
  1121. // using proxy, rewriting, virtual path, etc...
  1122. $res = '';
  1123. if ($type == 1) {
  1124. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  1125. }
  1126. if ($type == 2) {
  1127. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  1128. }
  1129. if ($type == 3) {
  1130. $res = DOL_URL_ROOT.'/'.$path;
  1131. }
  1132. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  1133. if ($key == 'main') {
  1134. if ($type == 3) {
  1135. /*global $dolibarr_main_url_root;*/
  1136. // Define $urlwithroot
  1137. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
  1138. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1139. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1140. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  1141. }
  1142. continue;
  1143. }
  1144. $regs = array();
  1145. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  1146. if (!empty($regs[1])) {
  1147. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1148. //if (file_exists($dirroot.'/'.$regs[1])) {
  1149. if (@file_exists($dirroot.'/'.$regs[1])) { // avoid [php:warn]
  1150. if ($type == 1) {
  1151. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1152. }
  1153. if ($type == 2) {
  1154. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1155. }
  1156. if ($type == 3) {
  1157. /*global $dolibarr_main_url_root;*/
  1158. // Define $urlwithroot
  1159. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($conf->file->dol_main_url_root));
  1160. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1161. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1162. $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
  1163. }
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. }
  1169. return $res;
  1170. }
  1171. /**
  1172. * Create a clone of instance of object (new instance with same value for each properties)
  1173. * With native = 0: Property that are reference are different memory area in the new object (full isolation clone). This means $this->db of new object may not be valid.
  1174. * 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.
  1175. * With native = 2: Property that are reference are different memory area in the new object (full isolation clone). Only scalar and array values are cloned. This means method are not availables and $this->db of new object is not valid.
  1176. *
  1177. * @param object $object Object to clone
  1178. * @param int $native 0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended)
  1179. * @return object Clone object
  1180. * @see https://php.net/manual/language.oop5.cloning.php
  1181. */
  1182. function dol_clone($object, $native = 0)
  1183. {
  1184. if ($native == 0) {
  1185. // deprecated method, use the method with native = 2 instead
  1186. $tmpsavdb = null;
  1187. if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
  1188. $tmpsavdb = $object->db;
  1189. unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
  1190. }
  1191. $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
  1192. if (!empty($tmpsavdb)) {
  1193. $object->db = $tmpsavdb;
  1194. }
  1195. } elseif ($native == 2) {
  1196. // recommended method to have a full isolated cloned object
  1197. $myclone = new stdClass();
  1198. $tmparray = get_object_vars($object); // return only public properties
  1199. if (is_array($tmparray)) {
  1200. foreach ($tmparray as $propertykey => $propertyval) {
  1201. if (is_scalar($propertyval) || is_array($propertyval)) {
  1202. $myclone->$propertykey = $propertyval;
  1203. }
  1204. }
  1205. }
  1206. } else {
  1207. $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep the reference (refering to the same target/variable)
  1208. }
  1209. return $myclone;
  1210. }
  1211. /**
  1212. * Optimize a size for some browsers (phone, smarphone, ...)
  1213. *
  1214. * @param int $size Size we want
  1215. * @param string $type Type of optimizing:
  1216. * '' = function used to define a size for truncation
  1217. * 'width' = function is used to define a width
  1218. * @return int New size after optimizing
  1219. */
  1220. function dol_size($size, $type = '')
  1221. {
  1222. global $conf;
  1223. if (empty($conf->dol_optimize_smallscreen)) {
  1224. return $size;
  1225. }
  1226. if ($type == 'width' && $size > 250) {
  1227. return 250;
  1228. } else {
  1229. return 10;
  1230. }
  1231. }
  1232. /**
  1233. * Clean a string to use it as a file name.
  1234. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1235. *
  1236. * @param string $str String to clean
  1237. * @param string $newstr String to replace bad chars with.
  1238. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1239. * @return string String cleaned (a-zA-Z_)
  1240. *
  1241. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1242. */
  1243. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1244. {
  1245. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1246. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1247. // Char '/' and '\' are file delimiters.
  1248. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1249. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';', '`');
  1250. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1251. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1252. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1253. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1254. $tmp = str_replace('..', '', $tmp);
  1255. return $tmp;
  1256. }
  1257. /**
  1258. * Clean a string to use it as a path name. Similare to dol_sanitizeFileName but accept / and \ chars.
  1259. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1260. *
  1261. * @param string $str String to clean
  1262. * @param string $newstr String to replace bad chars with
  1263. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1264. * @return string String cleaned (a-zA-Z_)
  1265. *
  1266. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1267. */
  1268. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1269. {
  1270. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1271. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1272. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1273. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';', '`');
  1274. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1275. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1276. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1277. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1278. $tmp = str_replace('..', '', $tmp);
  1279. return $tmp;
  1280. }
  1281. /**
  1282. * Clean a string to use it as an URL (into a href or src attribute)
  1283. *
  1284. * @param string $stringtoclean String to clean
  1285. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1286. * @return string Escaped string.
  1287. */
  1288. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1289. {
  1290. // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char)
  1291. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1292. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1293. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1294. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1295. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1296. if ($type == 1) {
  1297. // removing : should disable links to external url like http:aaa)
  1298. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1299. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1300. }
  1301. do {
  1302. $oldstringtoclean = $stringtoclean;
  1303. // removing '&colon' should disable links to external url like http:aaa)
  1304. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1305. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1306. } while ($oldstringtoclean != $stringtoclean);
  1307. if ($type == 1) {
  1308. // removing '//' should disable links to external url like //aaa or http//)
  1309. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1310. }
  1311. return $stringtoclean;
  1312. }
  1313. /**
  1314. * Clean a string to use it as an Email.
  1315. *
  1316. * @param string $stringtoclean String to clean. Example 'abc@mycompany.com <My name>'
  1317. * @return string Escaped string.
  1318. */
  1319. function dol_sanitizeEmail($stringtoclean)
  1320. {
  1321. do {
  1322. $oldstringtoclean = $stringtoclean;
  1323. $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
  1324. } while ($oldstringtoclean != $stringtoclean);
  1325. return $stringtoclean;
  1326. }
  1327. /**
  1328. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1329. *
  1330. * @param string $str String to clean
  1331. * @return string Cleaned string
  1332. *
  1333. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1334. */
  1335. function dol_string_unaccent($str)
  1336. {
  1337. global $conf;
  1338. if (is_null($str)) {
  1339. return '';
  1340. }
  1341. if (utf8_check($str)) {
  1342. if (extension_loaded('intl') && getDolGlobalString('MAIN_UNACCENT_USE_TRANSLITERATOR')) {
  1343. $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
  1344. return $transliterator->transliterate($str);
  1345. }
  1346. // See http://www.utf8-chartable.de/
  1347. $string = rawurlencode($str);
  1348. $replacements = array(
  1349. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1350. '%C3%87' => 'C',
  1351. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1352. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1353. '%C3%91' => 'N',
  1354. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1355. '%C5%A0' => 'S',
  1356. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1357. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1358. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1359. '%C3%A7' => 'c',
  1360. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1361. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1362. '%C3%B1' => 'n',
  1363. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1364. '%C5%A1' => 's',
  1365. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1366. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1367. );
  1368. $string = strtr($string, $replacements);
  1369. return rawurldecode($string);
  1370. } else {
  1371. // See http://www.ascii-code.com/
  1372. $string = strtr(
  1373. $str,
  1374. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1375. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1376. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1377. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1378. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1379. \xF9\xFA\xFB\xFC\xFD\xFF",
  1380. "AAAAAAC
  1381. EEEEIIIIDN
  1382. OOOOOUUUY
  1383. aaaaaaceeee
  1384. iiiidnooooo
  1385. uuuuyy"
  1386. );
  1387. $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"));
  1388. return $string;
  1389. }
  1390. }
  1391. /**
  1392. * Clean a string from all punctuation characters to use it as a ref or login.
  1393. * This is a more complete function than dol_sanitizeFileName().
  1394. *
  1395. * @param string $str String to clean
  1396. * @param string $newstr String to replace forbidden chars with
  1397. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1398. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1399. * @param int $keepspaces 1=Do not treat space as a special char to replace or remove
  1400. * @return string Cleaned string
  1401. *
  1402. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1403. */
  1404. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
  1405. {
  1406. $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
  1407. if (empty($keepspaces)) {
  1408. $forbidden_chars_to_replace[] = " ";
  1409. }
  1410. $forbidden_chars_to_remove = array();
  1411. //$forbidden_chars_to_remove=array("(",")");
  1412. if (is_array($badcharstoreplace)) {
  1413. $forbidden_chars_to_replace = $badcharstoreplace;
  1414. }
  1415. if (is_array($badcharstoremove)) {
  1416. $forbidden_chars_to_remove = $badcharstoremove;
  1417. }
  1418. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1419. }
  1420. /**
  1421. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1422. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1423. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1424. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1425. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1426. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1427. * @param string $str String to clean
  1428. * @param int $removetabcrlf Remove also CR-LF
  1429. * @return string Cleaned string
  1430. *
  1431. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1432. */
  1433. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1434. {
  1435. if ($removetabcrlf) {
  1436. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1437. } else {
  1438. return preg_replace('/[\x00-\x08\x11-\x12\x14-\x1F\x7F]/u', '', $str); // /u operator should make UTF8 valid characters being ignored so are not included into the replace
  1439. }
  1440. }
  1441. /**
  1442. * Returns text escaped for inclusion into javascript code
  1443. *
  1444. * @param string $stringtoescape String to escape
  1445. * @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 \
  1446. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1447. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1448. */
  1449. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1450. {
  1451. if (is_null($stringtoescape)) {
  1452. return '';
  1453. }
  1454. // escape quotes and backslashes, newlines, etc.
  1455. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1456. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1457. if (empty($noescapebackslashn)) {
  1458. $substitjs["\n"] = '\\n';
  1459. $substitjs['\\'] = '\\\\';
  1460. }
  1461. if (empty($mode)) {
  1462. $substitjs["'"] = "\\'";
  1463. $substitjs['"'] = "\\'";
  1464. } elseif ($mode == 1) {
  1465. $substitjs["'"] = "\\'";
  1466. } elseif ($mode == 2) {
  1467. $substitjs['"'] = '\\"';
  1468. } elseif ($mode == 3) {
  1469. $substitjs["'"] = "\\'";
  1470. $substitjs['"'] = "\\\"";
  1471. }
  1472. return strtr($stringtoescape, $substitjs);
  1473. }
  1474. /**
  1475. * Returns text escaped for inclusion into javascript code
  1476. *
  1477. * @param string $stringtoescape String to escape
  1478. * @return string Escaped string for JSON content.
  1479. */
  1480. function dol_escape_json($stringtoescape)
  1481. {
  1482. return str_replace('"', '\"', $stringtoescape);
  1483. }
  1484. /**
  1485. * Returns text escaped for inclusion into a php string, build with double quotes " or '
  1486. *
  1487. * @param string $stringtoescape String to escape
  1488. * @param int<1,2> $stringforquotes 2=String for doublequotes, 1=String for simple quotes
  1489. * @return string Escaped string for PHP content.
  1490. */
  1491. function dol_escape_php($stringtoescape, $stringforquotes = 2)
  1492. {
  1493. if (is_null($stringtoescape)) {
  1494. return '';
  1495. }
  1496. if ($stringforquotes == 2) {
  1497. return str_replace('"', "'", $stringtoescape);
  1498. }
  1499. if ($stringforquotes == 1) {
  1500. return str_replace("'", "\'", str_replace('"', "'", $stringtoescape));
  1501. }
  1502. return 'Bad parameter for stringforquotes in dol_escape_php';
  1503. }
  1504. /**
  1505. * Returns text escaped for inclusion into a XML string
  1506. *
  1507. * @param string $stringtoescape String to escape
  1508. * @return string Escaped string for XML content.
  1509. */
  1510. function dol_escape_xml($stringtoescape)
  1511. {
  1512. return $stringtoescape;
  1513. }
  1514. /**
  1515. * Return a string label (so on 1 line only and that should not contains any HTML) ready to be output on HTML page
  1516. * To use text that is not HTML content inside an attribute, use can simply only dol_escape_htmltag(). In doubt, use dolPrintHTMLForAttribute().
  1517. *
  1518. * @param string $s String to print
  1519. * @return string String ready for HTML output
  1520. */
  1521. function dolPrintLabel($s)
  1522. {
  1523. return dol_escape_htmltag(dol_htmlentitiesbr($s));
  1524. }
  1525. /**
  1526. * Return a string ready to be output on HTML page
  1527. * To use text inside an attribute, you can simply use dolPrintHTMLForAttribute() or dol_escape_htmltag()
  1528. *
  1529. * @param string $s String to print
  1530. * @param int $allowiframe Allow iframe tags
  1531. * @return string String ready for HTML output
  1532. */
  1533. function dolPrintHTML($s, $allowiframe = 0)
  1534. {
  1535. return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, 'common', 0, 1);
  1536. }
  1537. /**
  1538. * Return a string ready to be output on an HTML attribute (alt, title, data-html, ...)
  1539. *
  1540. * @param string $s String to print
  1541. * @return string String ready for HTML output
  1542. */
  1543. function dolPrintHTMLForAttribute($s)
  1544. {
  1545. // The dol_htmlentitiesbr will convert simple text into html
  1546. // The dol_escape_htmltag will escape html chars.
  1547. return dol_escape_htmltag(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 0, 0, 0, array('br', 'b', 'font', 'span')), 1, -1, '', 0, 1);
  1548. }
  1549. /**
  1550. * Return a string ready to be output on input textarea
  1551. * To use text inside an attribute, use can use only dol_escape_htmltag()
  1552. *
  1553. * @param string $s String to print
  1554. * @param int $allowiframe Allow iframe tags
  1555. * @return string String ready for HTML output into a textarea
  1556. */
  1557. function dolPrintHTMLForTextArea($s, $allowiframe = 0)
  1558. {
  1559. return dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($s), 1, 1, 1, $allowiframe)), 1, 1, '', 0, 1);
  1560. }
  1561. /**
  1562. * Return a string ready to be output on an HTML attribute (alt, title, ...)
  1563. *
  1564. * @param string $s String to print
  1565. * @return string String ready for HTML output
  1566. */
  1567. function dolPrintPassword($s)
  1568. {
  1569. return htmlspecialchars($s, ENT_COMPAT, 'UTF-8');
  1570. }
  1571. /**
  1572. * Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields.
  1573. * When we need to output strings on pages, we should use:
  1574. * - dolPrintHTML... that is dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1)), 1, 1) for notes or descriptions into textarea, add 'common' if into a html content
  1575. * - dolPrintLabel... that is dol_escape_htmltag(dol_htmlentitiesbr()) for simple labels.
  1576. * - dolPrintPassword that is abelhtmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords.
  1577. *
  1578. * @param string $stringtoescape String to escape
  1579. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1580. * @param int $keepn 1=Preserve \r\n strings, 0=Replace them with escaped value, -1=Remove them. Set to 1 when escaping for a <textarea>.
  1581. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes into tag.
  1582. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1583. * @param int $cleanalsojavascript Clean also javascript. @TODO switch this option to 1 by default.
  1584. * @return string Escaped string
  1585. * @see dol_string_nohtmltag(), dol_string_onlythesehtmltags(), dol_string_nospecial(), dol_string_unaccent(), dol_htmlentitiesbr()
  1586. */
  1587. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0, $cleanalsojavascript = 0)
  1588. {
  1589. if ($noescapetags == 'common') {
  1590. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody,h1,h2,h3,h4,h5,h6,h7,h8,h9';
  1591. // Add also html5 tags
  1592. $noescapetags .= ',header,footer,nav,section,menu,menuitem';
  1593. }
  1594. if ($cleanalsojavascript) {
  1595. $stringtoescape = dol_string_onlythesehtmltags($stringtoescape, 0, 0, $cleanalsojavascript, 0, array(), 0);
  1596. }
  1597. // escape quotes and backslashes, newlines, etc.
  1598. if ($escapeonlyhtmltags) {
  1599. $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
  1600. } else {
  1601. $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
  1602. }
  1603. if (!$keepb) {
  1604. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>'', '<strong>'=>'', '</strong>'=>''));
  1605. }
  1606. if (!$keepn) {
  1607. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1608. } elseif ($keepn == -1) {
  1609. $tmp = strtr($tmp, array("\r"=>'', "\n"=>''));
  1610. }
  1611. if ($escapeonlyhtmltags) {
  1612. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1613. } else {
  1614. // Escape tags to keep
  1615. $tmparrayoftags = array();
  1616. if ($noescapetags) {
  1617. $tmparrayoftags = explode(',', $noescapetags);
  1618. }
  1619. if (count($tmparrayoftags)) {
  1620. // TODO Does not works yet when there is attributes into tag
  1621. foreach ($tmparrayoftags as $tagtoreplace) {
  1622. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1623. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1624. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1625. }
  1626. }
  1627. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1628. if (count($tmparrayoftags)) {
  1629. foreach ($tmparrayoftags as $tagtoreplace) {
  1630. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1631. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1632. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1633. }
  1634. }
  1635. return $result;
  1636. }
  1637. }
  1638. /**
  1639. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1640. *
  1641. * @param string $string String to encode
  1642. * @param string $encoding Character set encoding
  1643. * @return string String converted
  1644. */
  1645. function dol_strtolower($string, $encoding = "UTF-8")
  1646. {
  1647. if (function_exists('mb_strtolower')) {
  1648. return mb_strtolower($string, $encoding);
  1649. } else {
  1650. return strtolower($string);
  1651. }
  1652. }
  1653. /**
  1654. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1655. *
  1656. * @param string $string String to encode
  1657. * @param string $encoding Character set encoding
  1658. * @return string String converted
  1659. * @see dol_ucfirst(), dol_ucwords()
  1660. */
  1661. function dol_strtoupper($string, $encoding = "UTF-8")
  1662. {
  1663. if (function_exists('mb_strtoupper')) {
  1664. return mb_strtoupper($string, $encoding);
  1665. } else {
  1666. return strtoupper($string);
  1667. }
  1668. }
  1669. /**
  1670. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1671. *
  1672. * @param string $string String to encode
  1673. * @param string $encoding Character set encodign
  1674. * @return string String converted
  1675. * @see dol_strtoupper(), dol_ucwords()
  1676. */
  1677. function dol_ucfirst($string, $encoding = "UTF-8")
  1678. {
  1679. if (function_exists('mb_substr')) {
  1680. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1681. } else {
  1682. return ucfirst($string);
  1683. }
  1684. }
  1685. /**
  1686. * Convert first character of all the words of a string to upper.
  1687. *
  1688. * @param string $string String to encode
  1689. * @param string $encoding Character set encodign
  1690. * @return string String converted
  1691. * @see dol_strtoupper(), dol_ucfirst()
  1692. */
  1693. function dol_ucwords($string, $encoding = "UTF-8")
  1694. {
  1695. if (function_exists('mb_convert_case')) {
  1696. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1697. } else {
  1698. return ucwords($string);
  1699. }
  1700. }
  1701. /**
  1702. * Write log message into outputs. Possible outputs can be:
  1703. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1704. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1705. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1706. * this, use logging to files instead of syslog (see setup of module).
  1707. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1708. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1709. * This function works only if syslog module is enabled.
  1710. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1711. *
  1712. * @param string $message Line to log. ''=Show nothing
  1713. * @param int $level Log level
  1714. * 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
  1715. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1716. * @param int $ident 1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log)
  1717. * @param string $suffixinfilename When output is a file, append this suffix into default log filename. Example '_stripe', '_mail'
  1718. * @param string $restricttologhandler Force output of log only to this log handler
  1719. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1720. * @return void
  1721. */
  1722. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1723. {
  1724. global $conf, $user, $debugbar;
  1725. // If syslog module enabled
  1726. if (!isModEnabled('syslog')) {
  1727. return;
  1728. }
  1729. // Check if we are into execution of code of a website
  1730. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1731. global $website, $websitekey;
  1732. if (is_object($website) && !empty($website->ref)) {
  1733. $suffixinfilename .= '_website_'.$website->ref;
  1734. } elseif (!empty($websitekey)) {
  1735. $suffixinfilename .= '_website_'.$websitekey;
  1736. }
  1737. }
  1738. // Check if we have a forced suffix
  1739. if (defined('USESUFFIXINLOG')) {
  1740. $suffixinfilename .= constant('USESUFFIXINLOG');
  1741. }
  1742. if ($ident < 0) {
  1743. foreach ($conf->loghandlers as $loghandlerinstance) {
  1744. $loghandlerinstance->setIdent($ident);
  1745. }
  1746. }
  1747. if (!empty($message)) {
  1748. // Test log level
  1749. $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');
  1750. if (!array_key_exists($level, $logLevels)) {
  1751. throw new Exception('Incorrect log level');
  1752. }
  1753. if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
  1754. return;
  1755. }
  1756. if (!getDolGlobalString('MAIN_SHOW_PASSWORD_INTO_LOG')) {
  1757. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1758. }
  1759. // If adding log inside HTML page is required
  1760. if ((!empty($_REQUEST['logtohtml']) && getDolGlobalString('MAIN_ENABLE_LOG_TO_HTML'))
  1761. || (is_object($user) && $user->hasRight('debugbar', 'read') && is_object($debugbar))) {
  1762. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1763. }
  1764. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1765. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1766. if (getDolGlobalString('MAIN_ENABLE_LOG_INLINE_HTML') && !empty($_GET["log"])) {
  1767. print "\n\n<!-- Log start\n";
  1768. print dol_escape_htmltag($message)."\n";
  1769. print "Log end -->\n";
  1770. }
  1771. $data = array(
  1772. 'message' => $message,
  1773. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1774. 'level' => $level,
  1775. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1776. 'ip' => false
  1777. );
  1778. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1779. if (!empty($remoteip)) {
  1780. $data['ip'] = $remoteip;
  1781. // This is when server run behind a reverse proxy
  1782. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1783. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1784. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1785. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1786. }
  1787. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1788. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1789. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1790. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1791. // 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).
  1792. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1793. } elseif (!empty($_SERVER['LOGNAME'])) {
  1794. // 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).
  1795. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1796. }
  1797. // Loop on each log handler and send output
  1798. foreach ($conf->loghandlers as $loghandlerinstance) {
  1799. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1800. continue;
  1801. }
  1802. $loghandlerinstance->export($data, $suffixinfilename);
  1803. }
  1804. unset($data);
  1805. }
  1806. if ($ident > 0) {
  1807. foreach ($conf->loghandlers as $loghandlerinstance) {
  1808. $loghandlerinstance->setIdent($ident);
  1809. }
  1810. }
  1811. }
  1812. /**
  1813. * Return HTML code to output a button to open a dialog popup box.
  1814. * Such buttons must be included inside a HTML form.
  1815. *
  1816. * @param string $name A name for the html component
  1817. * @param string $label Label shown in Popup title top bar
  1818. * @param string $buttonstring button string (HTML text we can click on)
  1819. * @param string $url Relative Url to open. For example '/project/card.php'
  1820. * @param string $disabled Disabled text
  1821. * @param string $morecss More CSS
  1822. * @param string $jsonopen Some JS code to execute on click/open of popup
  1823. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1824. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1825. * @param string $accesskey A key to use shortcut
  1826. * @return string HTML component with button
  1827. */
  1828. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
  1829. {
  1830. global $conf;
  1831. if (strpos($url, '?') > 0) {
  1832. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1833. } else {
  1834. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1835. }
  1836. $out = '';
  1837. $backtopagejsfieldsid = '';
  1838. $backtopagejsfieldslabel = '';
  1839. if ($backtopagejsfields) {
  1840. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1841. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1842. $backtopagejsfields = $name.":".$backtopagejsfields;
  1843. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1844. } else {
  1845. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1846. }
  1847. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1848. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1849. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1850. }
  1851. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1852. $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
  1853. $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
  1854. if (empty($conf->use_javascript_ajax)) {
  1855. $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
  1856. } elseif ($jsonopen) {
  1857. $out .= ' href="#" onclick="'.$jsonopen.'"';
  1858. } else {
  1859. $out .= ' href="#"';
  1860. }
  1861. $out .= '>'.$buttonstring.'</a>';
  1862. if (!empty($conf->use_javascript_ajax)) {
  1863. // Add code to open url using the popup. Add also hidden field to retreive the returned variables
  1864. $out .= '<!-- code to open popup and variables to retreive returned variables -->';
  1865. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1866. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1867. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1868. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1869. $out .= '<script nonce="'.getNonce().'" type="text/javascript">
  1870. jQuery(document).ready(function () {
  1871. jQuery(".button_'.$name.'").click(function () {
  1872. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1873. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1874. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1875. $tmpdialog.dialog({
  1876. autoOpen: false,
  1877. modal: true,
  1878. height: (window.innerHeight - 150),
  1879. width: \'80%\',
  1880. title: \''.dol_escape_js($label).'\',
  1881. open: function (event, ui) {
  1882. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1883. },
  1884. close: function (event, ui) {
  1885. var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1886. var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1887. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1888. if (returnedid != "" && returnedid != "div for returned id") {
  1889. jQuery("#'.(empty($backtopagejsfieldsid) ? "none" : $backtopagejsfieldsid).'").val(returnedid);
  1890. }
  1891. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1892. jQuery("#'.(empty($backtopagejsfieldslabel) ? "none" : $backtopagejsfieldslabel).'").val(returnedlabel);
  1893. }
  1894. }
  1895. });
  1896. $tmpdialog.dialog(\'open\');
  1897. return false;
  1898. });
  1899. });
  1900. </script>';
  1901. }
  1902. return $out;
  1903. }
  1904. /**
  1905. * Show tab header of a card
  1906. *
  1907. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1908. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1909. * @param string $title Title
  1910. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no sepaaration under tab (to start a tab just after), -3=Add tab header but no footer separation
  1911. * @param string $picto Add a picto on tab title
  1912. * @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.
  1913. * @param string $morehtmlright Add more html content on right of tabs title
  1914. * @param string $morecss More Css
  1915. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1916. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1917. * @return void
  1918. * @deprecated Use print dol_get_fiche_head() instead
  1919. */
  1920. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1921. {
  1922. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1923. }
  1924. /**
  1925. * Show tabs of a record
  1926. *
  1927. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1928. * @param string $active Active tab name
  1929. * @param string $title Title
  1930. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after), -3=-2+'noborderbottom'
  1931. * @param string $picto Add a picto on tab title
  1932. * @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.
  1933. * @param string $morehtmlright Add more html content on right of tabs title
  1934. * @param string $morecss More CSS on the link <a>
  1935. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1936. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1937. * @param int $dragdropfile 0 (default) or 1. 1 enable a drop zone for file to be upload, 0 disable it
  1938. * @return string
  1939. */
  1940. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
  1941. {
  1942. global $conf, $langs, $hookmanager;
  1943. // Show title
  1944. $showtitle = 1;
  1945. if (!empty($conf->dol_optimize_smallscreen)) {
  1946. $showtitle = 0;
  1947. }
  1948. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1949. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1950. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1951. }
  1952. // Show right part
  1953. if ($morehtmlright) {
  1954. $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.
  1955. }
  1956. // Show title
  1957. if (!empty($title) && $showtitle && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  1958. $limittitle = 30;
  1959. $out .= '<a class="tabTitle">';
  1960. if ($picto) {
  1961. $noprefix = $pictoisfullpath;
  1962. if (strpos($picto, 'fontawesome_') !== false) {
  1963. $noprefix = 1;
  1964. }
  1965. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1966. }
  1967. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1968. $out .= '</a>';
  1969. }
  1970. // Show tabs
  1971. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1972. $maxkey = -1;
  1973. if (is_array($links) && !empty($links)) {
  1974. $keys = array_keys($links);
  1975. if (count($keys)) {
  1976. $maxkey = max($keys);
  1977. }
  1978. }
  1979. // Show tabs
  1980. // if =0 we don't use the feature
  1981. if (empty($limittoshow)) {
  1982. $limittoshow = (!getDolGlobalString('MAIN_MAXTABS_IN_CARD') ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1983. }
  1984. if (!empty($conf->dol_optimize_smallscreen)) {
  1985. $limittoshow = 2;
  1986. }
  1987. $displaytab = 0;
  1988. $nbintab = 0;
  1989. $popuptab = 0;
  1990. $outmore = '';
  1991. for ($i = 0; $i <= $maxkey; $i++) {
  1992. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1993. // If active tab is already present
  1994. if ($i >= $limittoshow) {
  1995. $limittoshow--;
  1996. }
  1997. }
  1998. }
  1999. for ($i = 0; $i <= $maxkey; $i++) {
  2000. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  2001. $isactive = true;
  2002. } else {
  2003. $isactive = false;
  2004. }
  2005. if ($i < $limittoshow || $isactive) {
  2006. // Output entry with a visible tab
  2007. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && getDolGlobalString('MAIN_HIDE_INACTIVETAB_ON_PRINT')) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
  2008. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  2009. if (!empty($links[$i][0])) {
  2010. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  2011. } else {
  2012. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  2013. }
  2014. } elseif (!empty($links[$i][1])) {
  2015. //print "x $i $active ".$links[$i][2]." z";
  2016. $out .= '<div class="tab tab'.($isactive ? 'active' : 'unactive').'" style="margin: 0 !important">';
  2017. if (!empty($links[$i][0])) {
  2018. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  2019. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').(!empty($links[$i][5]) ? ' '.$links[$i][5] : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  2020. }
  2021. $out .= $links[$i][1];
  2022. if (!empty($links[$i][0])) {
  2023. $out .= '</a>'."\n";
  2024. }
  2025. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  2026. $out .= '</div>';
  2027. }
  2028. $out .= '</div>';
  2029. } else {
  2030. // Add entry into the combo popup with the other tabs
  2031. if (!$popuptab) {
  2032. $popuptab = 1;
  2033. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  2034. }
  2035. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  2036. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  2037. if (!empty($links[$i][0])) {
  2038. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  2039. } else {
  2040. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  2041. }
  2042. } elseif (!empty($links[$i][1])) {
  2043. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  2044. $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.
  2045. $outmore .= '</a>'."\n";
  2046. }
  2047. $outmore .= '</div>';
  2048. $nbintab++;
  2049. }
  2050. $displaytab = $i;
  2051. }
  2052. if ($popuptab) {
  2053. $outmore .= '</div>';
  2054. }
  2055. if ($popuptab) { // If there is some tabs not shown
  2056. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  2057. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  2058. $widthofpopup = 200;
  2059. $tabsname = $moretabssuffix;
  2060. if (empty($tabsname)) {
  2061. $tabsname = str_replace("@", "", $picto);
  2062. }
  2063. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  2064. $out .= '<div class="tab valignmiddle"><a href="#" class="tab moretab inline-block tabunactive valignmiddle"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
  2065. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  2066. $out .= $outmore;
  2067. $out .= '</div>';
  2068. $out .= '<div></div>';
  2069. $out .= "</div>\n";
  2070. $out .= '<script nonce="'.getNonce().'">';
  2071. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  2072. var x = this.offsetLeft, y = this.offsetTop;
  2073. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  2074. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  2075. $('#moretabsList".$tabsname."').css('".$right."','8px');
  2076. }
  2077. $('#moretabsList".$tabsname."').css('".$left."','auto');
  2078. });
  2079. ";
  2080. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  2081. $out .= "</script>";
  2082. }
  2083. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  2084. $out .= "</div>\n";
  2085. }
  2086. if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
  2087. $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
  2088. }
  2089. if (!empty($dragdropfile)) {
  2090. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2091. $out .= dragAndDropFileUpload("dragDropAreaTabBar");
  2092. }
  2093. $parameters = array('tabname' => $active, 'out' => $out);
  2094. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  2095. if ($reshook > 0) {
  2096. $out = $hookmanager->resPrint;
  2097. }
  2098. return $out;
  2099. }
  2100. /**
  2101. * Show tab footer of a card
  2102. *
  2103. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  2104. * @return void
  2105. * @deprecated Use print dol_get_fiche_end() instead
  2106. */
  2107. function dol_fiche_end($notab = 0)
  2108. {
  2109. print dol_get_fiche_end($notab);
  2110. }
  2111. /**
  2112. * Return tab footer of a card
  2113. *
  2114. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  2115. * @return string
  2116. */
  2117. function dol_get_fiche_end($notab = 0)
  2118. {
  2119. if (!$notab || $notab == -1) {
  2120. return "\n</div>\n";
  2121. } else {
  2122. return '';
  2123. }
  2124. }
  2125. /**
  2126. * Show tab footer of a card.
  2127. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  2128. *
  2129. * @param Object $object Object to show
  2130. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  2131. * @param string $morehtml More html content to output just before the nav bar
  2132. * @param int $shownav Show Condition (navigation is shown if value is 1)
  2133. * @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.
  2134. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  2135. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  2136. * @param string $moreparam More param to add in nav link url.
  2137. * @param int $nodbprefix Do not include DB prefix to forge table name
  2138. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  2139. * @param string $morehtmlstatus More html code to show under navigation arrows
  2140. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  2141. * @param string $morehtmlright More html code to show before navigation arrows
  2142. * @return void
  2143. */
  2144. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  2145. {
  2146. global $conf, $form, $user, $langs, $hookmanager, $action;
  2147. $error = 0;
  2148. $maxvisiblephotos = 1;
  2149. $showimage = 1;
  2150. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  2151. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  2152. if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
  2153. $showbarcode = 0;
  2154. }
  2155. $modulepart = 'unknown';
  2156. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  2157. $modulepart = $object->element;
  2158. } elseif ($object->element == 'member') {
  2159. $modulepart = 'memberphoto';
  2160. } elseif ($object->element == 'user') {
  2161. $modulepart = 'userphoto';
  2162. }
  2163. if (class_exists("Imagick")) {
  2164. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  2165. $modulepart = $object->element;
  2166. } elseif ($object->element == 'fichinter') {
  2167. $modulepart = 'ficheinter';
  2168. } elseif ($object->element == 'contrat') {
  2169. $modulepart = 'contract';
  2170. } elseif ($object->element == 'order_supplier') {
  2171. $modulepart = 'supplier_order';
  2172. } elseif ($object->element == 'invoice_supplier') {
  2173. $modulepart = 'supplier_invoice';
  2174. }
  2175. }
  2176. if ($object->element == 'product') {
  2177. $width = 80;
  2178. $cssclass = 'photowithmargin photoref';
  2179. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  2180. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  2181. if ($conf->browser->layout == 'phone') {
  2182. $maxvisiblephotos = 1;
  2183. }
  2184. if ($showimage) {
  2185. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
  2186. } else {
  2187. if (getDolGlobalString('PRODUCT_NODISPLAYIFNOPHOTO')) {
  2188. $nophoto = '';
  2189. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2190. } else { // Show no photo link
  2191. $nophoto = '/public/theme/common/nophoto.png';
  2192. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" title="'.dol_escape_htmltag($langs->trans("UploadAnImageToSeeAPhotoHere", $langs->transnoentitiesnoconv("Documents"))).'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  2193. }
  2194. }
  2195. } elseif ($object->element == 'ticket') {
  2196. $width = 80;
  2197. $cssclass = 'photoref';
  2198. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  2199. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  2200. if ($conf->browser->layout == 'phone') {
  2201. $maxvisiblephotos = 1;
  2202. }
  2203. if ($showimage) {
  2204. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  2205. if ($object->nbphoto > 0) {
  2206. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  2207. } else {
  2208. $showimage = 0;
  2209. }
  2210. }
  2211. if (!$showimage) {
  2212. if (getDolGlobalString('TICKET_NODISPLAYIFNOPHOTO')) {
  2213. $nophoto = '';
  2214. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2215. } else { // Show no photo link
  2216. $nophoto = img_picto('No photo', 'object_ticket');
  2217. $morehtmlleft .= '<!-- No photo to show -->';
  2218. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2219. $morehtmlleft .= $nophoto;
  2220. $morehtmlleft .= '</div></div>';
  2221. }
  2222. }
  2223. } else {
  2224. if ($showimage) {
  2225. if ($modulepart != 'unknown') {
  2226. $phototoshow = '';
  2227. // Check if a preview file is available
  2228. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  2229. $objectref = dol_sanitizeFileName($object->ref);
  2230. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  2231. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  2232. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  2233. $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
  2234. } else {
  2235. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  2236. }
  2237. if (empty($subdir)) {
  2238. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  2239. }
  2240. $filepath = $dir_output.$subdir."/";
  2241. $filepdf = $filepath.$objectref.".pdf";
  2242. $relativepath = $subdir.'/'.$objectref.'.pdf';
  2243. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  2244. $fileimage = $filepdf.'_preview.png';
  2245. $relativepathimage = $relativepath.'_preview.png';
  2246. $pdfexists = file_exists($filepdf);
  2247. // If PDF file exists
  2248. if ($pdfexists) {
  2249. // Conversion du PDF en image png si fichier png non existant
  2250. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  2251. if (!getDolGlobalString('MAIN_DISABLE_PDF_THUMBS')) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  2252. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2253. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  2254. if ($ret < 0) {
  2255. $error++;
  2256. }
  2257. }
  2258. }
  2259. }
  2260. if ($pdfexists && !$error) {
  2261. $heightforphotref = 80;
  2262. if (!empty($conf->dol_optimize_smallscreen)) {
  2263. $heightforphotref = 60;
  2264. }
  2265. // If the preview file is found
  2266. if (file_exists($fileimage)) {
  2267. $phototoshow = '<div class="photoref">';
  2268. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  2269. $phototoshow .= '</div>';
  2270. }
  2271. }
  2272. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  2273. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  2274. }
  2275. if ($phototoshow) {
  2276. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  2277. $morehtmlleft .= $phototoshow;
  2278. $morehtmlleft .= '</div>';
  2279. }
  2280. }
  2281. if (empty($phototoshow)) { // Show No photo link (picto of object)
  2282. if ($object->element == 'action') {
  2283. $width = 80;
  2284. $cssclass = 'photorefcenter';
  2285. $nophoto = img_picto('No photo', 'title_agenda');
  2286. } else {
  2287. $width = 14;
  2288. $cssclass = 'photorefcenter';
  2289. $picto = $object->picto;
  2290. $prefix = 'object_';
  2291. if ($object->element == 'project' && !$object->public) {
  2292. $picto = 'project'; // instead of projectpub
  2293. }
  2294. if (strpos($picto, 'fontawesome_') !== false) {
  2295. $prefix = '';
  2296. }
  2297. $nophoto = img_picto('No photo', $prefix.$picto);
  2298. }
  2299. $morehtmlleft .= '<!-- No photo to show -->';
  2300. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2301. $morehtmlleft .= $nophoto;
  2302. $morehtmlleft .= '</div></div>';
  2303. }
  2304. }
  2305. }
  2306. // Show barcode
  2307. if ($showbarcode) {
  2308. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
  2309. }
  2310. if ($object->element == 'societe') {
  2311. if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
  2312. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  2313. } else {
  2314. $morehtmlstatus .= $object->getLibStatut(6);
  2315. }
  2316. } elseif ($object->element == 'product') {
  2317. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  2318. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
  2319. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  2320. } else {
  2321. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  2322. }
  2323. $morehtmlstatus .= ' &nbsp; ';
  2324. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2325. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && getDolGlobalString('MAIN_DIRECT_STATUS_UPDATE')) {
  2326. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2327. } else {
  2328. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2329. }
  2330. } elseif (in_array($object->element, array('salary'))) {
  2331. $tmptxt = $object->getLibStatut(6, $object->alreadypaid);
  2332. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2333. $tmptxt = $object->getLibStatut(5, $object->alreadypaid);
  2334. }
  2335. $morehtmlstatus .= $tmptxt;
  2336. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva'))) { // TODO Move this to use ->alreadypaid
  2337. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2338. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2339. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2340. }
  2341. $morehtmlstatus .= $tmptxt;
  2342. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2343. if ($object->statut == 0) {
  2344. $morehtmlstatus .= $object->getLibStatut(5);
  2345. } else {
  2346. $morehtmlstatus .= $object->getLibStatut(4);
  2347. }
  2348. } elseif ($object->element == 'facturerec') {
  2349. if ($object->frequency == 0) {
  2350. $morehtmlstatus .= $object->getLibStatut(2);
  2351. } else {
  2352. $morehtmlstatus .= $object->getLibStatut(5);
  2353. }
  2354. } elseif ($object->element == 'project_task') {
  2355. $object->fk_statut = 1;
  2356. if ($object->progress > 0) {
  2357. $object->fk_statut = 2;
  2358. }
  2359. if ($object->progress >= 100) {
  2360. $object->fk_statut = 3;
  2361. }
  2362. $tmptxt = $object->getLibStatut(5);
  2363. $morehtmlstatus .= $tmptxt; // No status on task
  2364. } elseif (method_exists($object, 'getLibStatut')) { // Generic case for status
  2365. $tmptxt = $object->getLibStatut(6);
  2366. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2367. $tmptxt = $object->getLibStatut(5);
  2368. }
  2369. $morehtmlstatus .= $tmptxt;
  2370. }
  2371. // Add if object was dispatched "into accountancy"
  2372. if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2373. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2374. if (method_exists($object, 'getVentilExportCompta')) {
  2375. $accounted = $object->getVentilExportCompta();
  2376. $langs->load("accountancy");
  2377. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2378. }
  2379. }
  2380. // Add alias for thirdparty
  2381. if (!empty($object->name_alias)) {
  2382. $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
  2383. }
  2384. // Add label
  2385. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2386. if (!empty($object->label)) {
  2387. $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
  2388. }
  2389. }
  2390. // Show address and email
  2391. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2392. $moreaddress = $object->getBannerAddress('refaddress', $object); // address, email, url, social networks
  2393. if ($moreaddress) {
  2394. $morehtmlref .= '<div class="refidno refaddress">';
  2395. $morehtmlref .= $moreaddress;
  2396. $morehtmlref .= '</div>';
  2397. }
  2398. }
  2399. if (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && (getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) {
  2400. $morehtmlref .= '<div style="clear: both;"></div>';
  2401. $morehtmlref .= '<div class="refidno opacitymedium">';
  2402. $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
  2403. $morehtmlref .= '</div>';
  2404. }
  2405. $parameters=array('morehtmlref'=>$morehtmlref);
  2406. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2407. if ($reshook < 0) {
  2408. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2409. } elseif (empty($reshook)) {
  2410. $morehtmlref .= $hookmanager->resPrint;
  2411. } elseif ($reshook > 0) {
  2412. $morehtmlref = $hookmanager->resPrint;
  2413. }
  2414. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2415. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2416. print '</div>';
  2417. print '<div class="underrefbanner clearboth"></div>';
  2418. }
  2419. /**
  2420. * Show a string with the label tag dedicated to the HTML edit field.
  2421. *
  2422. * @param string $langkey Translation key
  2423. * @param string $fieldkey Key of the html select field the text refers to
  2424. * @param int $fieldrequired 1=Field is mandatory
  2425. * @return string
  2426. * @deprecated Form::editfieldkey
  2427. */
  2428. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2429. {
  2430. global $langs;
  2431. $ret = '';
  2432. if ($fieldrequired) {
  2433. $ret .= '<span class="fieldrequired">';
  2434. }
  2435. $ret .= '<label for="'.$fieldkey.'">';
  2436. $ret .= $langs->trans($langkey);
  2437. $ret .= '</label>';
  2438. if ($fieldrequired) {
  2439. $ret .= '</span>';
  2440. }
  2441. return $ret;
  2442. }
  2443. /**
  2444. * Return string to add class property on html element with pair/impair.
  2445. *
  2446. * @param string $var 0 or 1
  2447. * @param string $moreclass More class to add
  2448. * @return string String to add class onto HTML element
  2449. */
  2450. function dol_bc($var, $moreclass = '')
  2451. {
  2452. global $bc;
  2453. $ret = ' '.$bc[$var];
  2454. if ($moreclass) {
  2455. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2456. }
  2457. return $ret;
  2458. }
  2459. /**
  2460. * Return a formated address (part address/zip/town/state) according to country rules.
  2461. * See https://en.wikipedia.org/wiki/Address
  2462. *
  2463. * @param Object $object A company or contact object
  2464. * @param int $withcountry 1=Add country into address string
  2465. * @param string $sep Separator to use to separate info when building string
  2466. * @param Translate $outputlangs Object lang that contains language for text translation.
  2467. * @param int $mode 0=Standard output, 1=Remove address
  2468. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2469. * @return string Formated string
  2470. * @see dol_print_address()
  2471. */
  2472. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2473. {
  2474. global $conf, $langs, $hookmanager;
  2475. $ret = '';
  2476. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2477. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2478. // Address
  2479. if (empty($mode)) {
  2480. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : preg_replace('/(\r\n|\r|\n)+/', $sep, $object->address)));
  2481. }
  2482. // Zip/Town/State
  2483. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || getDolGlobalString('MAIN_FORCE_STATE_INTO_ADDRESS')) {
  2484. // US: title firstname name \n address lines \n town, state, zip \n country
  2485. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2486. $ret .= (($ret && $town) ? $sep : '').$town;
  2487. if (!empty($object->state)) {
  2488. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2489. }
  2490. if (!empty($object->zip)) {
  2491. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2492. }
  2493. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2494. // UK: title firstname name \n address lines \n town state \n zip \n country
  2495. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2496. $ret .= ($ret ? $sep : '').$town;
  2497. if (!empty($object->state)) {
  2498. $ret .= ($ret ? ", " : '').$object->state;
  2499. }
  2500. if (!empty($object->zip)) {
  2501. $ret .= ($ret ? $sep : '').$object->zip;
  2502. }
  2503. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2504. // ES: title firstname name \n address lines \n zip town \n state \n country
  2505. $ret .= ($ret ? $sep : '').$object->zip;
  2506. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2507. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2508. if (!empty($object->state)) {
  2509. $ret .= $sep.$object->state;
  2510. }
  2511. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2512. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2513. // See https://www.sljfaq.org/afaq/addresses.html
  2514. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2515. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2516. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2517. // IT: title firstname name\n address lines \n zip town state_code \n country
  2518. $ret .= ($ret ? $sep : '').$object->zip;
  2519. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2520. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2521. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2522. } else {
  2523. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2524. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2525. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2526. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2527. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2528. $ret .= ($ret ? ", " : '').$object->state;
  2529. }
  2530. }
  2531. if (!is_object($outputlangs)) {
  2532. $outputlangs = $langs;
  2533. }
  2534. if ($withcountry) {
  2535. $langs->load("dict");
  2536. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2537. }
  2538. if ($hookmanager) {
  2539. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2540. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2541. if ($reshook > 0) {
  2542. $ret = '';
  2543. }
  2544. $ret .= $hookmanager->resPrint;
  2545. }
  2546. return $ret;
  2547. }
  2548. /**
  2549. * Format a string.
  2550. *
  2551. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2552. * @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)
  2553. * @param int $is_gmt See comment of timestamp parameter
  2554. * @return string A formatted string
  2555. */
  2556. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2557. {
  2558. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2559. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2560. } else {
  2561. return 'Error date into a not supported range';
  2562. }
  2563. }
  2564. /**
  2565. * Output date in a string format according to outputlangs (or langs if not defined).
  2566. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2567. *
  2568. * @param int $time GM Timestamps date
  2569. * @param string $format Output date format (tag of strftime function)
  2570. * "%d %b %Y",
  2571. * "%d/%m/%Y %H:%M",
  2572. * "%d/%m/%Y %H:%M:%S",
  2573. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2574. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2575. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2576. * false or 'tzserver' => output string is for local PHP server TZ usage
  2577. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2578. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2579. * @param Translate $outputlangs Object lang that contains language for text translation.
  2580. * @param boolean $encodetooutput false=no convert into output pagecode
  2581. * @return string Formated date or '' if time is null
  2582. *
  2583. * @see dol_mktime(), dol_stringtotime(), dol_getdate(), selectDate()
  2584. */
  2585. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2586. {
  2587. global $conf, $langs;
  2588. // If date undefined or "", we return ""
  2589. if (dol_strlen($time) == 0) {
  2590. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2591. }
  2592. if ($tzoutput === 'auto') {
  2593. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2594. }
  2595. // Clean parameters
  2596. $to_gmt = false;
  2597. $offsettz = $offsetdst = 0;
  2598. if ($tzoutput) {
  2599. $to_gmt = true; // For backward compatibility
  2600. if (is_string($tzoutput)) {
  2601. if ($tzoutput == 'tzserver') {
  2602. $to_gmt = false;
  2603. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2604. $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
  2605. $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
  2606. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2607. $to_gmt = true;
  2608. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2609. if (class_exists('DateTimeZone')) {
  2610. $user_date_tz = new DateTimeZone($offsettzstring);
  2611. $user_dt = new DateTime();
  2612. $user_dt->setTimezone($user_date_tz);
  2613. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2614. $offsettz = $user_dt->getOffset(); // should include dst ?
  2615. } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
  2616. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2617. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2618. }
  2619. }
  2620. }
  2621. }
  2622. if (!is_object($outputlangs)) {
  2623. $outputlangs = $langs;
  2624. }
  2625. if (!$format) {
  2626. $format = 'daytextshort';
  2627. }
  2628. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2629. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2630. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour', 'dayhoursec'))) ? 1 : 0; // Test on original $format param.
  2631. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2632. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2633. if ($formatwithoutreduce != $format) {
  2634. $format = $formatwithoutreduce;
  2635. $reduceformat = 1;
  2636. } // so format 'dayreduceformat' is processed like day
  2637. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2638. // TODO Add format daysmallyear and dayhoursmallyear
  2639. if ($format == 'day') {
  2640. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2641. } elseif ($format == 'hour') {
  2642. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2643. } elseif ($format == 'hourduration') {
  2644. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2645. } elseif ($format == 'daytext') {
  2646. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2647. } elseif ($format == 'daytextshort') {
  2648. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2649. } elseif ($format == 'dayhour') {
  2650. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2651. } elseif ($format == 'dayhoursec') {
  2652. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2653. } elseif ($format == 'dayhourtext') {
  2654. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2655. } elseif ($format == 'dayhourtextshort') {
  2656. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2657. } elseif ($format == 'dayhourlog') {
  2658. // Format not sensitive to language
  2659. $format = '%Y%m%d%H%M%S';
  2660. } elseif ($format == 'dayhourlogsmall') {
  2661. // Format not sensitive to language
  2662. $format = '%y%m%d%H%M';
  2663. } elseif ($format == 'dayhourldap') {
  2664. $format = '%Y%m%d%H%M%SZ';
  2665. } elseif ($format == 'dayhourxcard') {
  2666. $format = '%Y%m%dT%H%M%SZ';
  2667. } elseif ($format == 'dayxcard') {
  2668. $format = '%Y%m%d';
  2669. } elseif ($format == 'dayrfc') {
  2670. $format = '%Y-%m-%d'; // DATE_RFC3339
  2671. } elseif ($format == 'dayhourrfc') {
  2672. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2673. } elseif ($format == 'standard') {
  2674. $format = '%Y-%m-%d %H:%M:%S';
  2675. }
  2676. if ($reduceformat) {
  2677. $format = str_replace('%Y', '%y', $format);
  2678. $format = str_replace('yyyy', 'yy', $format);
  2679. }
  2680. // Clean format
  2681. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2682. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2683. $format = str_replace('%b', '__b__', $format);
  2684. $format = str_replace('%B', '__B__', $format);
  2685. }
  2686. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2687. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2688. $format = str_replace('%a', '__a__', $format);
  2689. $format = str_replace('%A', '__A__', $format);
  2690. }
  2691. // Analyze date
  2692. $reg = array();
  2693. 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
  2694. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]));
  2695. return '';
  2696. } 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
  2697. // This part of code should not be used anymore.
  2698. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]), LOG_WARNING);
  2699. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2700. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2701. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2702. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2703. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2704. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2705. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2706. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2707. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2708. if ($to_gmt) {
  2709. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2710. } else {
  2711. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2712. }
  2713. $dtts = new DateTime();
  2714. $dtts->setTimestamp($time);
  2715. $dtts->setTimezone($tzo);
  2716. $newformat = str_replace(
  2717. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2718. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2719. $format
  2720. );
  2721. $ret = $dtts->format($newformat);
  2722. $ret = str_replace(
  2723. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2724. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2725. $ret
  2726. );
  2727. } else {
  2728. // Date is a timestamps
  2729. if ($time < 100000000000) { // Protection against bad date values
  2730. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2731. if ($to_gmt) {
  2732. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2733. } else {
  2734. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2735. }
  2736. $dtts = new DateTime();
  2737. $dtts->setTimestamp($timetouse);
  2738. $dtts->setTimezone($tzo);
  2739. $newformat = str_replace(
  2740. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2741. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2742. $format
  2743. );
  2744. $ret = $dtts->format($newformat);
  2745. $ret = str_replace(
  2746. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2747. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2748. $ret
  2749. );
  2750. //var_dump($ret);exit;
  2751. } else {
  2752. $ret = 'Bad value '.$time.' for date';
  2753. }
  2754. }
  2755. if (preg_match('/__b__/i', $format)) {
  2756. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2757. if ($to_gmt) {
  2758. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2759. } else {
  2760. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2761. }
  2762. $dtts = new DateTime();
  2763. $dtts->setTimestamp($timetouse);
  2764. $dtts->setTimezone($tzo);
  2765. $month = $dtts->format("m");
  2766. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2767. if ($encodetooutput) {
  2768. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2769. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2770. } else {
  2771. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2772. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2773. }
  2774. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2775. $ret = str_replace('__b__', $monthtextshort, $ret);
  2776. $ret = str_replace('__B__', $monthtext, $ret);
  2777. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2778. //return $ret;
  2779. }
  2780. if (preg_match('/__a__/i', $format)) {
  2781. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2782. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2783. if ($to_gmt) {
  2784. $tzo = new DateTimeZone('UTC');
  2785. } else {
  2786. $tzo = new DateTimeZone(date_default_timezone_get());
  2787. }
  2788. $dtts = new DateTime();
  2789. $dtts->setTimestamp($timetouse);
  2790. $dtts->setTimezone($tzo);
  2791. $w = $dtts->format("w");
  2792. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2793. $ret = str_replace('__A__', $dayweek, $ret);
  2794. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2795. }
  2796. return $ret;
  2797. }
  2798. /**
  2799. * Return an array with locale date info.
  2800. * WARNING: This function use PHP server timezone by default to return locale informations.
  2801. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2802. *
  2803. * @param int $timestamp Timestamp
  2804. * @param boolean $fast Fast mode. deprecated.
  2805. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2806. * @return array Array of informations
  2807. * 'seconds' => $secs,
  2808. * 'minutes' => $min,
  2809. * 'hours' => $hour,
  2810. * 'mday' => $day,
  2811. * 'wday' => $dow, 0=sunday, 6=saturday
  2812. * 'mon' => $month,
  2813. * 'year' => $year,
  2814. * 'yday' => floor($secsInYear/$_day_power)
  2815. * '0' => original timestamp
  2816. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2817. */
  2818. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2819. {
  2820. if ($timestamp === '') {
  2821. return array();
  2822. }
  2823. $datetimeobj = new DateTime();
  2824. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2825. if ($forcetimezone) {
  2826. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2827. }
  2828. $arrayinfo = array(
  2829. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2830. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2831. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2832. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2833. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2834. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2835. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2836. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2837. '0'=>$timestamp
  2838. );
  2839. return $arrayinfo;
  2840. }
  2841. /**
  2842. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2843. * Replace function mktime not available under Windows if year < 1970
  2844. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2845. *
  2846. * @param int $hour Hour (can be -1 for undefined)
  2847. * @param int $minute Minute (can be -1 for undefined)
  2848. * @param int $second Second (can be -1 for undefined)
  2849. * @param int $month Month (1 to 12)
  2850. * @param int $day Day (1 to 31)
  2851. * @param int $year Year
  2852. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2853. * False or 0 or 'tzserver' = local to server TZ
  2854. * 'auto'
  2855. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2856. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user into a GMT date.
  2857. * 'tz,TimeZone' = use specified timezone
  2858. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2859. * @return int|string Date as a timestamp, '' or false if error
  2860. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2861. */
  2862. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2863. {
  2864. global $conf;
  2865. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2866. if ($gm === 'auto') {
  2867. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2868. }
  2869. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2870. // Clean parameters
  2871. if ($hour == -1 || empty($hour)) {
  2872. $hour = 0;
  2873. }
  2874. if ($minute == -1 || empty($minute)) {
  2875. $minute = 0;
  2876. }
  2877. if ($second == -1 || empty($second)) {
  2878. $second = 0;
  2879. }
  2880. // Check parameters
  2881. if ($check) {
  2882. if (!$month || !$day) {
  2883. return '';
  2884. }
  2885. if ($day > 31) {
  2886. return '';
  2887. }
  2888. if ($month > 12) {
  2889. return '';
  2890. }
  2891. if ($hour < 0 || $hour > 24) {
  2892. return '';
  2893. }
  2894. if ($minute < 0 || $minute > 60) {
  2895. return '';
  2896. }
  2897. if ($second < 0 || $second > 60) {
  2898. return '';
  2899. }
  2900. }
  2901. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2902. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2903. $localtz = new DateTimeZone($default_timezone);
  2904. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2905. // We use dol_tz_string first because it is more reliable.
  2906. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2907. try {
  2908. $localtz = new DateTimeZone($default_timezone);
  2909. } catch (Exception $e) {
  2910. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2911. $default_timezone = @date_default_timezone_get();
  2912. }
  2913. } elseif (strrpos($gm, "tz,") !== false) {
  2914. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2915. try {
  2916. $localtz = new DateTimeZone($timezone);
  2917. } catch (Exception $e) {
  2918. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2919. }
  2920. }
  2921. if (empty($localtz)) {
  2922. $localtz = new DateTimeZone('UTC');
  2923. }
  2924. //var_dump($localtz);
  2925. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2926. $dt = new DateTime('now', $localtz);
  2927. $dt->setDate((int) $year, (int) $month, (int) $day);
  2928. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2929. $date = $dt->getTimestamp(); // should include daylight saving time
  2930. //var_dump($date);
  2931. return $date;
  2932. }
  2933. /**
  2934. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2935. *
  2936. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2937. * 'gmt' => we return GMT timestamp,
  2938. * 'tzserver' => we add the PHP server timezone
  2939. * 'tzref' => we add the company timezone. Not implemented.
  2940. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2941. * @return int $date Timestamp
  2942. */
  2943. function dol_now($mode = 'auto')
  2944. {
  2945. $ret = 0;
  2946. if ($mode === 'auto') {
  2947. $mode = 'gmt';
  2948. }
  2949. if ($mode == 'gmt') {
  2950. $ret = time(); // Time for now at greenwich.
  2951. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2952. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2953. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2954. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2955. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2956. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2957. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2958. // $ret=dol_now('gmt')+($tzsecond*3600);
  2959. //}
  2960. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2961. // Time for now with user timezone added
  2962. //print 'time: '.time();
  2963. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2964. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2965. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2966. }
  2967. return $ret;
  2968. }
  2969. /**
  2970. * Return string with formated size
  2971. *
  2972. * @param int $size Size to print
  2973. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2974. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2975. * @return string Link
  2976. */
  2977. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2978. {
  2979. global $conf, $langs;
  2980. $level = 1024;
  2981. if (!empty($conf->dol_optimize_smallscreen)) {
  2982. $shortunit = 1;
  2983. }
  2984. // Set value text
  2985. if (empty($shortvalue) || $size < ($level * 10)) {
  2986. $ret = $size;
  2987. $textunitshort = $langs->trans("b");
  2988. $textunitlong = $langs->trans("Bytes");
  2989. } else {
  2990. $ret = round($size / $level, 0);
  2991. $textunitshort = $langs->trans("Kb");
  2992. $textunitlong = $langs->trans("KiloBytes");
  2993. }
  2994. // Use long or short text unit
  2995. if (empty($shortunit)) {
  2996. $ret .= ' '.$textunitlong;
  2997. } else {
  2998. $ret .= ' '.$textunitshort;
  2999. }
  3000. return $ret;
  3001. }
  3002. /**
  3003. * Show Url link
  3004. *
  3005. * @param string $url Url to show
  3006. * @param string $target Target for link
  3007. * @param int $max Max number of characters to show
  3008. * @param int $withpicto With picto
  3009. * @param string $morecss More CSS
  3010. * @return string HTML Link
  3011. */
  3012. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = '')
  3013. {
  3014. global $langs;
  3015. if (empty($url)) {
  3016. return '';
  3017. }
  3018. $linkstart = '<a href="';
  3019. if (!preg_match('/^http/i', $url)) {
  3020. $linkstart .= 'http://';
  3021. }
  3022. $linkstart .= $url;
  3023. $linkstart .= '"';
  3024. if ($target) {
  3025. $linkstart .= ' target="'.$target.'"';
  3026. }
  3027. $linkstart .= ' title="'.$langs->trans("URL").': '.$url.'"';
  3028. $linkstart .= '>';
  3029. $link = '';
  3030. if (!preg_match('/^http/i', $url)) {
  3031. $link .= 'http://';
  3032. }
  3033. $link .= dol_trunc($url, $max);
  3034. $linkend = '</a>';
  3035. if ($morecss == 'float') { // deprecated
  3036. return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto($langs->trans("Url"), 'globe', 'class="paddingrightonly"') : '').$link.'</div>';
  3037. } else {
  3038. return $linkstart.'<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ? img_picto('', 'globe', 'class="paddingrightonly"') : '').$link.'</span>'.$linkend;
  3039. }
  3040. }
  3041. /**
  3042. * Show EMail link formatted for HTML output.
  3043. *
  3044. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  3045. * @param int $cid Id of contact if known
  3046. * @param int $socid Id of third party if known
  3047. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  3048. * @param int $max Max number of characters to show
  3049. * @param int $showinvalid 1=Show warning if syntax email is wrong
  3050. * @param int|string $withpicto Show picto
  3051. * @return string HTML Link
  3052. */
  3053. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  3054. {
  3055. global $user, $langs, $hookmanager;
  3056. //global $conf; $conf->global->AGENDA_ADDACTIONFOREMAIL = 1;
  3057. //$showinvalid = 1; $email = 'rrrrr';
  3058. $newemail = dol_escape_htmltag($email);
  3059. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
  3060. $withpicto = 0;
  3061. }
  3062. if (empty($email)) {
  3063. return '&nbsp;';
  3064. }
  3065. if (!empty($addlink)) {
  3066. $newemail = '<a class="paddingrightonly" style="text-overflow: ellipsis;" href="';
  3067. if (!preg_match('/^mailto:/i', $email)) {
  3068. $newemail .= 'mailto:';
  3069. }
  3070. $newemail .= $email;
  3071. $newemail .= '">';
  3072. $newemail .= ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '');
  3073. $newemail .= dol_trunc($email, $max);
  3074. $newemail .= '</a>';
  3075. if ($showinvalid && !isValidEmail($email)) {
  3076. $langs->load("errors");
  3077. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email), '', 'paddingrightonly');
  3078. }
  3079. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3080. $type = 'AC_EMAIL';
  3081. $linktoaddaction = '';
  3082. if (getDolGlobalString('AGENDA_ADDACTIONFOREMAIL')) {
  3083. $linktoaddaction = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.urlencode($type).'&amp;contactid='.((int) $cid).'&amp;socid='.((int) $socid).'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  3084. }
  3085. if ($linktoaddaction) {
  3086. $newemail = '<div>'.$newemail.' '.$linktoaddaction.'</div>';
  3087. }
  3088. }
  3089. } else {
  3090. $newemail = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
  3091. if ($showinvalid && !isValidEmail($email)) {
  3092. $langs->load("errors");
  3093. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  3094. }
  3095. }
  3096. //$rep = '<div class="nospan" style="margin-right: 10px">';
  3097. //$rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto), 'class="paddingrightonly"') : '').$newemail;
  3098. //$rep .= '</div>';
  3099. $rep = $newemail;
  3100. if ($hookmanager) {
  3101. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  3102. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  3103. if ($reshook > 0) {
  3104. $rep = '';
  3105. }
  3106. $rep .= $hookmanager->resPrint;
  3107. }
  3108. return $rep;
  3109. }
  3110. /**
  3111. * Get array of social network dictionary
  3112. *
  3113. * @return array Array of Social Networks Dictionary
  3114. */
  3115. function getArrayOfSocialNetworks()
  3116. {
  3117. global $conf, $db;
  3118. $socialnetworks = array();
  3119. // Enable caching of array
  3120. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  3121. $cachekey = 'socialnetworks_' . $conf->entity;
  3122. $dataretrieved = dol_getcache($cachekey);
  3123. if (!is_null($dataretrieved)) {
  3124. $socialnetworks = $dataretrieved;
  3125. } else {
  3126. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  3127. $sql .= " WHERE entity=".$conf->entity;
  3128. $resql = $db->query($sql);
  3129. if ($resql) {
  3130. while ($obj = $db->fetch_object($resql)) {
  3131. $socialnetworks[$obj->code] = array(
  3132. 'rowid' => $obj->rowid,
  3133. 'label' => $obj->label,
  3134. 'url' => $obj->url,
  3135. 'icon' => $obj->icon,
  3136. 'active' => $obj->active,
  3137. );
  3138. }
  3139. }
  3140. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  3141. }
  3142. return $socialnetworks;
  3143. }
  3144. /**
  3145. * Show social network link
  3146. *
  3147. * @param string $value Social network ID to show (only skype, without 'Name of recipient' before)
  3148. * @param int $cid Id of contact if known
  3149. * @param int $socid Id of third party if known
  3150. * @param string $type 'skype','facebook',...
  3151. * @param array $dictsocialnetworks List of socialnetworks availables
  3152. * @return string HTML Link
  3153. */
  3154. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  3155. {
  3156. global $conf, $user, $langs;
  3157. $htmllink = $value;
  3158. if (empty($value)) {
  3159. return '&nbsp;';
  3160. }
  3161. if (!empty($type)) {
  3162. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  3163. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  3164. $htmllink .= '<span class="fab pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  3165. if ($type == 'skype') {
  3166. $htmllink .= dol_escape_htmltag($value);
  3167. $htmllink .= '&nbsp; <a href="skype:';
  3168. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3169. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  3170. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  3171. $htmllink .= '</a><a href="skype:';
  3172. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  3173. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  3174. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  3175. $htmllink .= '</a>';
  3176. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create')) {
  3177. $addlink = 'AC_SKYPE';
  3178. $link = '';
  3179. if (getDolGlobalString('AGENDA_ADDACTIONFORSKYPE')) {
  3180. $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>';
  3181. }
  3182. $htmllink .= ($link ? ' '.$link : '');
  3183. }
  3184. } else {
  3185. $networkconstname = 'MAIN_INFO_SOCIETE_'.strtoupper($type).'_URL';
  3186. if (getDolGlobalString($networkconstname)) {
  3187. $link = str_replace('{socialid}', $value, getDolGlobalString($networkconstname));
  3188. if (preg_match('/^https?:\/\//i', $link)) {
  3189. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3190. } else {
  3191. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3192. }
  3193. } elseif (!empty($dictsocialnetworks[$type]['url'])) {
  3194. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  3195. if ($tmpvirginurl) {
  3196. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3197. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3198. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  3199. if ($tmpvirginurl3) {
  3200. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3201. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3202. }
  3203. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  3204. if ($tmpvirginurl2) {
  3205. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3206. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3207. }
  3208. }
  3209. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  3210. if (preg_match('/^https?:\/\//i', $link)) {
  3211. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3212. } else {
  3213. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3214. }
  3215. } else {
  3216. $htmllink .= dol_escape_htmltag($value);
  3217. }
  3218. }
  3219. $htmllink .= '</div>';
  3220. } else {
  3221. $langs->load("errors");
  3222. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  3223. }
  3224. return $htmllink;
  3225. }
  3226. /**
  3227. * Format professional IDs according to their country
  3228. *
  3229. * @param string $profID Value of profID to format
  3230. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  3231. * @param string $countrycode Country code to use for formatting
  3232. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  3233. * @return string Formated profID
  3234. */
  3235. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1)
  3236. {
  3237. global $mysoc;
  3238. if (empty($profID) || empty($profIDtype)) {
  3239. return '';
  3240. }
  3241. if (empty($countrycode)) {
  3242. $countrycode = $mysoc->country_code;
  3243. }
  3244. $newProfID = $profID;
  3245. $id = substr($profIDtype, -1);
  3246. $ret = '';
  3247. if (strtoupper($countrycode) == 'FR') {
  3248. // France
  3249. // (see https://www.economie.gouv.fr/entreprises/numeros-identification-entreprise)
  3250. if ($id == 1 && dol_strlen($newProfID) == 9) {
  3251. // SIREN (ex: 123 123 123)
  3252. $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3);
  3253. }
  3254. if ($id == 2 && dol_strlen($newProfID) == 14) {
  3255. // SIRET (ex: 123 123 123 12345)
  3256. $newProfID = substr($newProfID, 0, 3).' '.substr($newProfID, 3, 3).' '.substr($newProfID, 6, 3).' '.substr($newProfID, 9, 5);
  3257. }
  3258. if ($id == 3 && dol_strlen($newProfID) == 5) {
  3259. // NAF/APE (ex: 69.20Z)
  3260. $newProfID = substr($newProfID, 0, 2).'.'.substr($newProfID, 2, 3);
  3261. }
  3262. if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) {
  3263. // TVA intracommunautaire (ex: FR12 123 123 123)
  3264. $newProfID = substr($newProfID, 0, 4).' '.substr($newProfID, 4, 3).' '.substr($newProfID, 7, 3).' '.substr($newProfID, 10, 3);
  3265. }
  3266. }
  3267. if (!empty($addcpButton)) {
  3268. $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  3269. } else {
  3270. $ret = $newProfID;
  3271. }
  3272. return $ret;
  3273. }
  3274. /**
  3275. * Format phone numbers according to country
  3276. *
  3277. * @param string $phone Phone number to format
  3278. * @param string $countrycode Country code to use for formatting
  3279. * @param int $cid Id of contact if known
  3280. * @param int $socid Id of third party if known
  3281. * @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), 'tel'=Force "tel:..." link
  3282. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx. You can also use 'hidenum' to hide the number, keep only the picto.
  3283. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  3284. * @param string $titlealt Text to show on alt
  3285. * @param int $adddivfloat Add div float around phone.
  3286. * @return string Formated phone number
  3287. */
  3288. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  3289. {
  3290. global $conf, $user, $langs, $mysoc, $hookmanager;
  3291. // Clean phone parameter
  3292. $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
  3293. if (empty($phone)) {
  3294. return '';
  3295. }
  3296. if (getDolGlobalString('MAIN_PHONE_SEPAR')) {
  3297. $separ = $conf->global->MAIN_PHONE_SEPAR;
  3298. }
  3299. if (empty($countrycode) && is_object($mysoc)) {
  3300. $countrycode = $mysoc->country_code;
  3301. }
  3302. // Short format for small screens
  3303. if ($conf->dol_optimize_smallscreen) {
  3304. $separ = '';
  3305. }
  3306. $newphone = $phone;
  3307. if (strtoupper($countrycode) == "FR") {
  3308. // France
  3309. if (dol_strlen($phone) == 10) {
  3310. $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);
  3311. } elseif (dol_strlen($phone) == 7) {
  3312. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  3313. } elseif (dol_strlen($phone) == 9) {
  3314. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  3315. } elseif (dol_strlen($phone) == 11) {
  3316. $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);
  3317. } elseif (dol_strlen($phone) == 12) {
  3318. $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);
  3319. } elseif (dol_strlen($phone) == 13) {
  3320. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  3321. }
  3322. } elseif (strtoupper($countrycode) == "CA") {
  3323. if (dol_strlen($phone) == 10) {
  3324. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  3325. }
  3326. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  3327. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  3328. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3329. }
  3330. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  3331. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  3332. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  3333. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  3334. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  3335. }
  3336. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  3337. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  3338. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  3339. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  3340. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  3341. }
  3342. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  3343. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  3344. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3345. }
  3346. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  3347. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  3348. $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);
  3349. }
  3350. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  3351. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  3352. $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);
  3353. }
  3354. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  3355. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  3356. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3357. }
  3358. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  3359. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  3360. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3361. }
  3362. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  3363. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  3364. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3365. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  3366. $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);
  3367. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  3368. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3369. }
  3370. } elseif (strtoupper($countrycode) == "ML") {//Mali
  3371. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  3372. $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);
  3373. }
  3374. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  3375. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  3376. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3377. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  3378. $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);
  3379. }
  3380. } elseif (strtoupper($countrycode) == "MU") {
  3381. //Maurice
  3382. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  3383. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  3384. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  3385. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  3386. }
  3387. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  3388. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  3389. $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);
  3390. }
  3391. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  3392. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  3393. $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);
  3394. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  3395. $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);
  3396. }
  3397. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  3398. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  3399. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3400. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  3401. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3402. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  3403. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  3404. }
  3405. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  3406. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  3407. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3408. }
  3409. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  3410. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  3411. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3412. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  3413. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3414. }
  3415. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  3416. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  3417. $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);
  3418. }
  3419. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  3420. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  3421. $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);
  3422. }
  3423. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3424. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3425. $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);
  3426. }
  3427. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3428. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3429. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3430. }
  3431. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3432. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
  3433. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  3434. }
  3435. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3436. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3437. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3438. }
  3439. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3440. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3441. $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);
  3442. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3443. $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);
  3444. }
  3445. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3446. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3447. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3448. }
  3449. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3450. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3451. $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);
  3452. }
  3453. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3454. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3455. $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);
  3456. }
  3457. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3458. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3459. $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);
  3460. }
  3461. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3462. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3463. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3464. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3465. $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);
  3466. }
  3467. } elseif (strtoupper($countrycode) == "AU") {
  3468. //Australie
  3469. if (dol_strlen($phone) == 12) {
  3470. //ex: +61_A_BCDE_FGHI
  3471. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3472. }
  3473. } elseif (strtoupper($countrycode) == "LU") {
  3474. // Luxembourg
  3475. if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
  3476. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
  3477. } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
  3478. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 1);
  3479. } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
  3480. $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);
  3481. } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
  3482. $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);
  3483. }
  3484. }
  3485. $newphoneastart = $newphoneaend = '';
  3486. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3487. if ($addlink == 'tel' || $conf->browser->layout == 'phone' || (isModEnabled('clicktodial') && getDolGlobalString('CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS'))) { // If phone or option for, we use link of phone
  3488. $newphoneastart = '<a href="tel:'.$phone.'">';
  3489. $newphoneaend .= '</a>';
  3490. } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3491. if (empty($user->clicktodial_loaded)) {
  3492. $user->fetch_clicktodial();
  3493. }
  3494. // Define urlmask
  3495. $urlmask = getDolGlobalString('CLICKTODIAL_URL', 'ErrorClickToDialModuleNotConfigured');
  3496. if (!empty($user->clicktodial_url)) {
  3497. $urlmask = $user->clicktodial_url;
  3498. }
  3499. $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
  3500. $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
  3501. $clicktodial_password = (!empty($user->clicktodial_password) ? urlencode($user->clicktodial_password) : '');
  3502. // This line is for backward compatibility
  3503. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3504. // Thoose lines are for substitution
  3505. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3506. '__PHONETO__'=>urlencode($phone),
  3507. '__LOGIN__'=>$clicktodial_login,
  3508. '__PASS__'=>$clicktodial_password);
  3509. $url = make_substitutions($url, $substitarray);
  3510. if (!getDolGlobalString('CLICKTODIAL_DO_NOT_USE_AJAX_CALL')) {
  3511. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3512. $newphoneastart = '<a href="'.$url.'" class="cssforclicktodial">'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3513. $newphoneaend = '</a>';
  3514. } else {
  3515. // Old method
  3516. $newphoneastart = '<a href="'.$url.'"';
  3517. if (getDolGlobalString('CLICKTODIAL_FORCENEWTARGET')) {
  3518. $newphoneastart .= ' target="_blank" rel="noopener noreferrer"';
  3519. }
  3520. $newphoneastart .= '>';
  3521. $newphoneaend .= '</a>';
  3522. }
  3523. }
  3524. //if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight('agenda', 'myactions', 'create'))
  3525. if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3526. $type = 'AC_TEL';
  3527. $addlinktoagenda = '';
  3528. if ($addlink == 'AC_FAX') {
  3529. $type = 'AC_FAX';
  3530. }
  3531. if (getDolGlobalString('AGENDA_ADDACTIONFORPHONE')) {
  3532. $addlinktoagenda = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage='. urlencode($_SERVER['REQUEST_URI']) .'&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  3533. }
  3534. if ($addlinktoagenda) {
  3535. $newphone = '<span>'.$newphone.' '.$addlinktoagenda.'</span>';
  3536. }
  3537. }
  3538. }
  3539. if (empty($titlealt)) {
  3540. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3541. }
  3542. $rep = '';
  3543. if ($hookmanager) {
  3544. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3545. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3546. $rep .= $hookmanager->resPrint;
  3547. }
  3548. if (empty($reshook)) {
  3549. $picto = '';
  3550. if ($withpicto) {
  3551. if ($withpicto == 'fax') {
  3552. $picto = 'phoning_fax';
  3553. } elseif ($withpicto == 'phone') {
  3554. $picto = 'phoning';
  3555. } elseif ($withpicto == 'mobile') {
  3556. $picto = 'phoning_mobile';
  3557. } else {
  3558. $picto = '';
  3559. }
  3560. }
  3561. if ($adddivfloat == 1) {
  3562. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3563. } elseif (empty($adddivfloat)) {
  3564. $rep .= '<span style="margin-right: 10px;">';
  3565. }
  3566. $rep .= $newphoneastart;
  3567. $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png') : '');
  3568. if ($separ != 'hidenum') {
  3569. $rep .= ($withpicto ? ' ' : '').$newphone;
  3570. }
  3571. $rep .= $newphoneaend;
  3572. if ($adddivfloat == 1) {
  3573. $rep .= '</div>';
  3574. } elseif (empty($adddivfloat)) {
  3575. $rep .= '</span>';
  3576. }
  3577. }
  3578. return $rep;
  3579. }
  3580. /**
  3581. * Return an IP formated to be shown on screen
  3582. *
  3583. * @param string $ip IP
  3584. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3585. * @return string Formated IP, with country if GeoIP module is enabled
  3586. */
  3587. function dol_print_ip($ip, $mode = 0)
  3588. {
  3589. global $langs;
  3590. $ret = '';
  3591. if (empty($mode)) {
  3592. $ret .= $ip;
  3593. }
  3594. if ($mode != 2) {
  3595. $countrycode = dolGetCountryCodeFromIp($ip);
  3596. if ($countrycode) { // If success, countrycode is us, fr, ...
  3597. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3598. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3599. } else {
  3600. $ret .= ' ('.$countrycode.')';
  3601. }
  3602. } else {
  3603. // Nothing
  3604. }
  3605. }
  3606. return $ret;
  3607. }
  3608. /**
  3609. * Return the IP of remote user.
  3610. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3611. * Then HTTP_CLIENT_IP if defined (rare)
  3612. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3613. *
  3614. * @return string Ip of remote user.
  3615. */
  3616. function getUserRemoteIP()
  3617. {
  3618. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3619. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3620. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3621. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3622. } else {
  3623. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3624. }
  3625. } else {
  3626. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3627. }
  3628. } else {
  3629. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3630. }
  3631. return $ip;
  3632. }
  3633. /**
  3634. * Return if we are using a HTTPS connexion
  3635. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3636. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3637. * Then HTTP_X_FORWARDED_SSL
  3638. *
  3639. * @return boolean True if user is using HTTPS
  3640. */
  3641. function isHTTPS()
  3642. {
  3643. $isSecure = false;
  3644. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3645. $isSecure = true;
  3646. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
  3647. $isSecure = true;
  3648. }
  3649. return $isSecure;
  3650. }
  3651. /**
  3652. * Return a country code from IP. Empty string if not found.
  3653. *
  3654. * @param string $ip IP
  3655. * @return string Country code ('us', 'fr', ...)
  3656. */
  3657. function dolGetCountryCodeFromIp($ip)
  3658. {
  3659. global $conf;
  3660. $countrycode = '';
  3661. if (!empty($conf->geoipmaxmind->enabled)) {
  3662. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3663. //$ip='24.24.24.24';
  3664. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3665. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3666. $geoip = new DolGeoIP('country', $datafile);
  3667. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3668. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3669. }
  3670. return $countrycode;
  3671. }
  3672. /**
  3673. * Return country code for current user.
  3674. * If software is used inside a local network, detection may fails (we need a public ip)
  3675. *
  3676. * @return string Country code (fr, es, it, us, ...)
  3677. */
  3678. function dol_user_country()
  3679. {
  3680. global $conf, $langs, $user;
  3681. //$ret=$user->xxx;
  3682. $ret = '';
  3683. if (!empty($conf->geoipmaxmind->enabled)) {
  3684. $ip = getUserRemoteIP();
  3685. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3686. //$ip='24.24.24.24';
  3687. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3688. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3689. $geoip = new DolGeoIP('country', $datafile);
  3690. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3691. $ret = $countrycode;
  3692. }
  3693. return $ret;
  3694. }
  3695. /**
  3696. * Format address string
  3697. *
  3698. * @param string $address Address string, already formatted with dol_format_address()
  3699. * @param int $htmlid Html ID (for example 'gmap')
  3700. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3701. * @param int $id Id of object
  3702. * @param int $noprint No output. Result is the function return
  3703. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3704. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3705. * @see dol_format_address()
  3706. */
  3707. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3708. {
  3709. global $conf, $user, $langs, $hookmanager;
  3710. $out = '';
  3711. if ($address) {
  3712. if ($hookmanager) {
  3713. $parameters = array('element' => $element, 'id' => $id);
  3714. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3715. $out .= $hookmanager->resPrint;
  3716. }
  3717. if (empty($reshook)) {
  3718. if (empty($charfornl)) {
  3719. $out .= nl2br($address);
  3720. } else {
  3721. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3722. }
  3723. // TODO Remove this block, we can add this using the hook now
  3724. $showgmap = $showomap = 0;
  3725. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS')) {
  3726. $showgmap = 1;
  3727. }
  3728. if ($element == 'contact' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_CONTACTS')) {
  3729. $showgmap = 1;
  3730. }
  3731. if ($element == 'member' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_MEMBERS')) {
  3732. $showgmap = 1;
  3733. }
  3734. if ($element == 'user' && isModEnabled('google') && getDolGlobalString('GOOGLE_ENABLE_GMAPS_USERS')) {
  3735. $showgmap = 1;
  3736. }
  3737. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS')) {
  3738. $showomap = 1;
  3739. }
  3740. if ($element == 'contact' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_CONTACTS')) {
  3741. $showomap = 1;
  3742. }
  3743. if ($element == 'member' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_MEMBERS')) {
  3744. $showomap = 1;
  3745. }
  3746. if ($element == 'user' && isModEnabled('openstreetmap') && getDolGlobalString('OPENSTREETMAP_ENABLE_MAPS_USERS')) {
  3747. $showomap = 1;
  3748. }
  3749. if ($showgmap) {
  3750. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3751. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3752. }
  3753. if ($showomap) {
  3754. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3755. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3756. }
  3757. }
  3758. }
  3759. if ($noprint) {
  3760. return $out;
  3761. } else {
  3762. print $out;
  3763. }
  3764. }
  3765. /**
  3766. * Return true if email syntax is ok.
  3767. *
  3768. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3769. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3770. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3771. * @return boolean true if email syntax is OK, false if KO or empty string
  3772. * @see isValidMXRecord()
  3773. */
  3774. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3775. {
  3776. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3777. return true;
  3778. }
  3779. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3780. return true;
  3781. }
  3782. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3783. return true;
  3784. }
  3785. return false;
  3786. }
  3787. /**
  3788. * Return if the domain name has a valid MX record.
  3789. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3790. *
  3791. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3792. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3793. * @see isValidEmail()
  3794. */
  3795. function isValidMXRecord($domain)
  3796. {
  3797. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3798. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3799. return 0;
  3800. }
  3801. if (function_exists('getmxrr')) {
  3802. $mxhosts = array();
  3803. $weight = array();
  3804. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3805. if (count($mxhosts) > 1) {
  3806. return 1;
  3807. }
  3808. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3809. return 1;
  3810. }
  3811. return 0;
  3812. }
  3813. }
  3814. // function idn_to_ascii or checkdnsrr or getmxrr does not exists
  3815. return -1;
  3816. }
  3817. /**
  3818. * Return true if phone number syntax is ok
  3819. * TODO Decide what to do with this
  3820. *
  3821. * @param string $phone phone (Ex: "0601010101")
  3822. * @return boolean true if phone syntax is OK, false if KO or empty string
  3823. */
  3824. function isValidPhone($phone)
  3825. {
  3826. return true;
  3827. }
  3828. /**
  3829. * Return first letters of a strings.
  3830. * Example with nbofchar=1: 'ghi' will return 'g' but 'abc def' will return 'ad'
  3831. * Example with nbofchar=2: 'ghi' will return 'gh' but 'abc def' will return 'abde'
  3832. *
  3833. * @param string $s String to truncate
  3834. * @param int $nbofchar Nb of characters to keep
  3835. * @return string Return first chars.
  3836. */
  3837. function dolGetFirstLetters($s, $nbofchar = 1)
  3838. {
  3839. $ret = '';
  3840. $tmparray = explode(' ', $s);
  3841. foreach ($tmparray as $tmps) {
  3842. $ret .= dol_substr($tmps, 0, $nbofchar);
  3843. }
  3844. return $ret;
  3845. }
  3846. /**
  3847. * Make a strlen call. Works even if mbstring module not enabled
  3848. *
  3849. * @param string $string String to calculate length
  3850. * @param string $stringencoding Encoding of string
  3851. * @return int Length of string
  3852. */
  3853. function dol_strlen($string, $stringencoding = 'UTF-8')
  3854. {
  3855. if (is_null($string)) {
  3856. return 0;
  3857. }
  3858. if (function_exists('mb_strlen')) {
  3859. return mb_strlen($string, $stringencoding);
  3860. } else {
  3861. return strlen($string);
  3862. }
  3863. }
  3864. /**
  3865. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3866. *
  3867. * @param string $string String to scan
  3868. * @param string $start Start position
  3869. * @param int|null $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3870. * @param string $stringencoding Page code used for input string encoding
  3871. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3872. * @return string substring
  3873. */
  3874. function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
  3875. {
  3876. global $langs;
  3877. if (empty($stringencoding)) {
  3878. $stringencoding = $langs->charset_output;
  3879. }
  3880. $ret = '';
  3881. if (empty($trunconbytes)) {
  3882. if (function_exists('mb_substr')) {
  3883. $ret = mb_substr($string, $start, $length, $stringencoding);
  3884. } else {
  3885. $ret = substr($string, $start, $length);
  3886. }
  3887. } else {
  3888. if (function_exists('mb_strcut')) {
  3889. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3890. } else {
  3891. $ret = substr($string, $start, $length);
  3892. }
  3893. }
  3894. return $ret;
  3895. }
  3896. /**
  3897. * Truncate a string to a particular length adding '…' if string larger than length.
  3898. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3899. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3900. *
  3901. * @param string $string String to truncate
  3902. * @param int $size Max string size visible (excluding …). 0 for no limit. WARNING: Final string size can have 3 more chars (if we added …, or if size was max+1 so it does not worse to replace with ...)
  3903. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3904. * @param string $stringencoding Tell what is source string encoding
  3905. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3906. * @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)
  3907. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3908. */
  3909. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3910. {
  3911. global $conf;
  3912. if (empty($size) || getDolGlobalString('MAIN_DISABLE_TRUNC')) {
  3913. return $string;
  3914. }
  3915. if (empty($stringencoding)) {
  3916. $stringencoding = 'UTF-8';
  3917. }
  3918. // reduce for small screen
  3919. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3920. $size = round($size / 3);
  3921. }
  3922. // We go always here
  3923. if ($trunc == 'right') {
  3924. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3925. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3926. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3927. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3928. } else {
  3929. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3930. return $string;
  3931. }
  3932. } elseif ($trunc == 'middle') {
  3933. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3934. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3935. $size1 = round($size / 2);
  3936. $size2 = round($size / 2);
  3937. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3938. } else {
  3939. return $string;
  3940. }
  3941. } elseif ($trunc == 'left') {
  3942. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3943. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3944. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3945. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3946. } else {
  3947. return $string;
  3948. }
  3949. } elseif ($trunc == 'wrap') {
  3950. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3951. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3952. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3953. } else {
  3954. return $string;
  3955. }
  3956. } else {
  3957. return 'BadParam3CallingDolTrunc';
  3958. }
  3959. }
  3960. /**
  3961. * Return the picto for a data type
  3962. *
  3963. * @param string $key Key
  3964. * @return string Pïcto for the key
  3965. */
  3966. function getPictoForType($key)
  3967. {
  3968. // Set array with type -> picto
  3969. $type2picto = array(
  3970. 'varchar'=>'font',
  3971. 'text'=>'font',
  3972. 'html'=>'code',
  3973. 'int'=>'sort-numeric-down',
  3974. 'double'=>'sort-numeric-down',
  3975. 'price'=>'currency',
  3976. 'pricecy'=>'multicurrency',
  3977. 'password' => 'key',
  3978. 'boolean'=>'check-square',
  3979. 'date'=>'calendar',
  3980. 'datetime'=>'calendar',
  3981. 'phone'=> 'phone',
  3982. 'mail'=> 'email',
  3983. 'url'=> 'url',
  3984. 'ip'=> 'country',
  3985. 'select' => 'list',
  3986. 'sellist' => 'list',
  3987. 'radio' => 'check-circle',
  3988. 'checkbox' => 'check-square',
  3989. 'chkbxlst' => 'check-square',
  3990. 'link' => 'link',
  3991. 'separate'=> 'minus'
  3992. );
  3993. if (!empty($type2picto[$key])) {
  3994. return img_picto('', $type2picto[$key], 'class="pictofixedwidth"');
  3995. }
  3996. return img_picto('', 'generic', 'class="pictofixedwidth"');
  3997. }
  3998. /**
  3999. * Show picto whatever it's its name (generic function)
  4000. *
  4001. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  4002. * @param string $picto Name of image file to show ('filenew', ...).
  4003. * For font awesome icon (example 'user'), you can use picto_nocolor to not have the color of picto forced.
  4004. * If no extension provided and it is not a font awesome icon, we use '.png'. Image must be stored into theme/xxx/img directory.
  4005. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4006. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4007. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4008. * Example: fontawesome_envelope-open-text_fas_red_1em if you want to use fontaweseome icons: fontawesome_<icon-name>_<style>_<color>_<size> (only icon-name is mandatory)
  4009. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  4010. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  4011. * @param int $srconly Return only content of the src attribute of img.
  4012. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4013. * @param string $alt Force alt for bind people
  4014. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  4015. * @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.
  4016. * @return string Return img tag
  4017. * @see img_object(), img_picto_common()
  4018. */
  4019. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  4020. {
  4021. global $conf, $langs;
  4022. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  4023. $url = DOL_URL_ROOT;
  4024. $theme = isset($conf->theme) ? $conf->theme : null;
  4025. $path = 'theme/'.$theme;
  4026. if (empty($picto)) {
  4027. $picto = 'generic';
  4028. }
  4029. // Define fullpathpicto to use into src
  4030. if ($pictoisfullpath) {
  4031. // Clean parameters
  4032. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  4033. $picto .= '.png';
  4034. }
  4035. $fullpathpicto = $picto;
  4036. $reg = array();
  4037. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4038. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4039. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4040. }
  4041. } else {
  4042. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', (is_null($picto) ? '' : $picto));
  4043. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  4044. $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
  4045. if (strpos($pictowithouttext, 'fontawesome_') === 0 || strpos($pictowithouttext, 'fa-') === 0) {
  4046. // This is a font awesome image 'fontawesome_xxx' or 'fa-xxx'
  4047. $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
  4048. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  4049. // Compatibility with old fontawesome versions
  4050. if ($pictowithouttext == 'file-o') {
  4051. $pictowithouttext = 'file';
  4052. }
  4053. $pictowithouttextarray = explode('_', $pictowithouttext);
  4054. $marginleftonlyshort = 0;
  4055. if (!empty($pictowithouttextarray[1])) {
  4056. // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
  4057. $fakey = 'fa-'.$pictowithouttextarray[0];
  4058. $faprefix = empty($pictowithouttextarray[1]) ? 'fas' : $pictowithouttextarray[1];
  4059. $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
  4060. $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  4061. } else {
  4062. $fakey = 'fa-'.$pictowithouttext;
  4063. $faprefix = 'fas';
  4064. $facolor = '';
  4065. $fasize = '';
  4066. }
  4067. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  4068. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  4069. $morestyle = '';
  4070. $reg = array();
  4071. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4072. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4073. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4074. }
  4075. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  4076. $morestyle = $reg[1];
  4077. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  4078. }
  4079. $moreatt = trim($moreatt);
  4080. $enabledisablehtml = '<span class="'.$faprefix.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  4081. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  4082. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4083. $enabledisablehtml .= $titlealt;
  4084. }*/
  4085. $enabledisablehtml .= '</span>';
  4086. return $enabledisablehtml;
  4087. }
  4088. if (empty($srconly) && in_array($pictowithouttext, array(
  4089. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  4090. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  4091. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  4092. 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  4093. 'cash-register', 'category', 'chart', 'check', 'clock', 'clone', 'close_title', 'code', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
  4094. 'check-circle', 'check-square', 'currency', 'multicurrency',
  4095. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  4096. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  4097. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
  4098. 'filter', 'file', 'file-o', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus', 'font',
  4099. 'gears', 'generate', 'generic', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  4100. 'hands-helping', 'help', 'holiday',
  4101. 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
  4102. 'key', 'knowledgemanagement',
  4103. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
  4104. 'margin', 'map-marker-alt', 'member', 'meeting', 'minus', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  4105. 'off', 'on', 'order',
  4106. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
  4107. 'stock', 'resize', 'service', 'stats',
  4108. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_warning', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
  4109. 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  4110. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  4111. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  4112. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  4113. 'technic', 'ticket',
  4114. 'error', 'warning',
  4115. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
  4116. 'shapes', 'skill', 'square', 'sort-numeric-down', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  4117. 'tick', 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  4118. 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
  4119. 'conferenceorbooth', 'eventorganization',
  4120. 'stamp', 'signature'
  4121. ))) {
  4122. $fakey = $pictowithouttext;
  4123. $facolor = '';
  4124. $fasize = '';
  4125. $fa = getDolGlobalString('MAIN_FONTAWESOME_ICON_STYLE', 'fas');
  4126. if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'file', 'file-o', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  4127. $fa = 'far';
  4128. }
  4129. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  4130. $fa = 'fab';
  4131. }
  4132. $arrayconvpictotofa = array(
  4133. 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  4134. 'bank_account'=>'university',
  4135. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  4136. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  4137. 'bom'=>'shapes',
  4138. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time', 'cross'=>'times',
  4139. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  4140. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  4141. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  4142. 'file-o'=>'file', 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  4143. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  4144. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  4145. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  4146. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  4147. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'jobprofile'=>'cogs',
  4148. 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  4149. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  4150. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  4151. 'sign-out'=>'sign-out-alt',
  4152. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_warning'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  4153. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  4154. 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  4155. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'order'=>'file-invoice',
  4156. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  4157. 'other'=>'square',
  4158. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'proposal'=>'file-signature',
  4159. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'pictoconfirm'=>'check-square', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
  4160. 'recent' => 'check-square', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  4161. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  4162. 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
  4163. 'service'=>'concierge-bell',
  4164. 'skill'=>'shapes', 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  4165. 'supplier'=>'building', 'technic'=>'cogs',
  4166. 'timespent'=>'clock', 'tick' => 'check', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  4167. 'title_agenda'=>'calendar-alt',
  4168. 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'arrow-alt-circle-down',
  4169. 'jabber'=>'comment-o',
  4170. 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
  4171. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  4172. );
  4173. if ($conf->currency == 'EUR') {
  4174. $arrayconvpictotofa['currency'] = 'euro-sign';
  4175. $arrayconvpictotofa['multicurrency'] = 'dollar-sign';
  4176. } else {
  4177. $arrayconvpictotofa['currency'] = 'dollar-sign';
  4178. $arrayconvpictotofa['multicurrency'] = 'euro-sign';
  4179. }
  4180. if ($pictowithouttext == 'off') {
  4181. $fakey = 'fa-square';
  4182. $fasize = '1.3em';
  4183. } elseif ($pictowithouttext == 'on') {
  4184. $fakey = 'fa-check-square';
  4185. $fasize = '1.3em';
  4186. } elseif ($pictowithouttext == 'listlight') {
  4187. $fakey = 'fa-download';
  4188. $marginleftonlyshort = 1;
  4189. } elseif ($pictowithouttext == 'printer') {
  4190. $fakey = 'fa-print';
  4191. $fasize = '1.2em';
  4192. } elseif ($pictowithouttext == 'note') {
  4193. $fakey = 'fa-sticky-note';
  4194. $marginleftonlyshort = 1;
  4195. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  4196. $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');
  4197. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  4198. if (preg_match('/selected/', $pictowithouttext)) {
  4199. $facolor = '#888';
  4200. }
  4201. $marginleftonlyshort = 1;
  4202. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  4203. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  4204. } else {
  4205. $fakey = 'fa-'.$pictowithouttext;
  4206. }
  4207. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  4208. $morecss .= ' em092';
  4209. }
  4210. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  4211. $morecss .= ' em088';
  4212. }
  4213. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  4214. $morecss .= ' em080';
  4215. }
  4216. // Define $marginleftonlyshort
  4217. $arrayconvpictotomarginleftonly = array(
  4218. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  4219. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  4220. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  4221. );
  4222. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  4223. $marginleftonlyshort = 0;
  4224. }
  4225. // Add CSS
  4226. $arrayconvpictotomorcess = array(
  4227. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  4228. 'bank_account'=>'infobox-bank_account',
  4229. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  4230. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  4231. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  4232. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  4233. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  4234. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  4235. 'incoterm'=>'infobox-supplier_proposal',
  4236. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  4237. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  4238. 'order'=>'infobox-commande',
  4239. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  4240. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_warning'=>'font-status4 warning', 'switch_on_red'=>'font-status8',
  4241. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  4242. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  4243. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  4244. 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
  4245. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  4246. 'resource'=>'infobox-action',
  4247. 'salary'=>'infobox-bank_account', 'shapes'=>'infobox-adherent', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  4248. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  4249. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  4250. 'vat'=>'infobox-bank_account',
  4251. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  4252. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  4253. );
  4254. if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4255. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  4256. }
  4257. // Define $color
  4258. $arrayconvpictotocolor = array(
  4259. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  4260. 'clone'=>'#999', 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  4261. 'dynamicprice'=>'#a69944',
  4262. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  4263. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  4264. 'lock'=>'#ddd', 'lot'=>'#a69944',
  4265. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  4266. 'other'=>'#ddd', 'world'=>'#986c6a',
  4267. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  4268. //'shipment'=>'#a69944',
  4269. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999',
  4270. 'technic' => '#999', 'tick' => '#282', 'timespent' => '#555',
  4271. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  4272. 'website'=>'#304', 'workstation'=>'#a69944'
  4273. );
  4274. if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4275. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  4276. }
  4277. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  4278. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  4279. $morestyle = '';
  4280. $reg = array();
  4281. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4282. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4283. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4284. }
  4285. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  4286. $morestyle = $reg[1];
  4287. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  4288. }
  4289. $moreatt = trim($moreatt);
  4290. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  4291. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  4292. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4293. $enabledisablehtml .= $titlealt;
  4294. }*/
  4295. $enabledisablehtml .= '</span>';
  4296. return $enabledisablehtml;
  4297. }
  4298. if (getDolGlobalString('MAIN_OVERWRITE_THEME_PATH')) {
  4299. $path = getDolGlobalString('MAIN_OVERWRITE_THEME_PATH') . '/theme/'.$theme; // If the theme does not have the same name as the module
  4300. } elseif (getDolGlobalString('MAIN_OVERWRITE_THEME_RES')) {
  4301. $path = getDolGlobalString('MAIN_OVERWRITE_THEME_RES') . '/theme/' . getDolGlobalString('MAIN_OVERWRITE_THEME_RES'); // To allow an external module to overwrite image resources whatever is activated theme
  4302. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  4303. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  4304. }
  4305. // If we ask an image into $url/$mymodule/img (instead of default path)
  4306. $regs = array();
  4307. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  4308. $picto = $regs[1];
  4309. $path = $regs[2]; // $path is $mymodule
  4310. }
  4311. // Clean parameters
  4312. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  4313. $picto .= '.png';
  4314. }
  4315. // If alt path are defined, define url where img file is, according to physical path
  4316. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  4317. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  4318. if ($type == 'main') {
  4319. continue;
  4320. }
  4321. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  4322. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  4323. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  4324. break;
  4325. }
  4326. }
  4327. // $url is '' or '/custom', $path is current theme or
  4328. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  4329. }
  4330. if ($srconly) {
  4331. return $fullpathpicto;
  4332. }
  4333. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  4334. return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dol_escape_htmltag($alt).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
  4335. }
  4336. /**
  4337. * Show a picto called object_picto (generic function)
  4338. *
  4339. * @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.
  4340. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  4341. * For external modules use imagename@mymodule to search into directory "img" of module.
  4342. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  4343. * @param int $pictoisfullpath If 1, image path is a full path
  4344. * @param int $srconly Return only content of the src attribute of img.
  4345. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4346. * @return string Return img tag
  4347. * @see img_picto(), img_picto_common()
  4348. */
  4349. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  4350. {
  4351. if (strpos($picto, '^') === 0) {
  4352. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  4353. } else {
  4354. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  4355. }
  4356. }
  4357. /**
  4358. * Show weather picto
  4359. *
  4360. * @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.
  4361. * @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).
  4362. * @param string $moreatt Add more attribute on img tag
  4363. * @param int $pictoisfullpath If 1, image path is a full path
  4364. * @param string $morecss More CSS
  4365. * @return string Return img tag
  4366. * @see img_object(), img_picto()
  4367. */
  4368. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  4369. {
  4370. global $conf;
  4371. if (is_numeric($picto)) {
  4372. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  4373. //$picto = $leveltopicto[$picto];
  4374. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  4375. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4376. $picto .= '.png';
  4377. }
  4378. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  4379. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  4380. }
  4381. /**
  4382. * Show picto (generic function)
  4383. *
  4384. * @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.
  4385. * @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.
  4386. * @param string $moreatt Add more attribute on img tag
  4387. * @param int $pictoisfullpath If 1, image path is a full path
  4388. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4389. * @return string Return img tag
  4390. * @see img_object(), img_picto()
  4391. */
  4392. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  4393. {
  4394. global $conf;
  4395. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4396. $picto .= '.png';
  4397. }
  4398. if ($pictoisfullpath) {
  4399. $path = $picto;
  4400. } else {
  4401. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  4402. if (getDolGlobalInt('MAIN_MODULE_CAN_OVERWRITE_COMMONICONS')) {
  4403. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  4404. if (file_exists($themepath)) {
  4405. $path = $themepath;
  4406. }
  4407. }
  4408. }
  4409. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  4410. }
  4411. /**
  4412. * Show logo action
  4413. *
  4414. * @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.
  4415. * @param string $numaction Action id or code to show
  4416. * @param string $picto Name of image file to show ('filenew', ...)
  4417. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  4418. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4419. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4420. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4421. * @param string $moreatt More attributes
  4422. * @return string Return an img tag
  4423. */
  4424. function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
  4425. {
  4426. global $langs;
  4427. if (empty($titlealt) || $titlealt == 'default') {
  4428. if ($numaction == '-1' || $numaction == 'ST_NO') {
  4429. $numaction = -1;
  4430. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  4431. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  4432. $numaction = 0;
  4433. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  4434. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  4435. $numaction = 1;
  4436. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  4437. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  4438. $numaction = 2;
  4439. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  4440. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  4441. $numaction = 3;
  4442. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  4443. } else {
  4444. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  4445. $numaction = 0;
  4446. }
  4447. }
  4448. if (!is_numeric($numaction)) {
  4449. $numaction = 0;
  4450. }
  4451. return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
  4452. }
  4453. /**
  4454. * Show pdf logo
  4455. *
  4456. * @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.
  4457. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  4458. * @return string Retourne tag img
  4459. */
  4460. function img_pdf($titlealt = 'default', $size = 3)
  4461. {
  4462. global $langs;
  4463. if ($titlealt == 'default') {
  4464. $titlealt = $langs->trans('Show');
  4465. }
  4466. return img_picto($titlealt, 'pdf'.$size.'.png');
  4467. }
  4468. /**
  4469. * Show logo +
  4470. *
  4471. * @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.
  4472. * @param string $other Add more attributes on img
  4473. * @return string Return tag img
  4474. */
  4475. function img_edit_add($titlealt = 'default', $other = '')
  4476. {
  4477. global $langs;
  4478. if ($titlealt == 'default') {
  4479. $titlealt = $langs->trans('Add');
  4480. }
  4481. return img_picto($titlealt, 'edit_add.png', $other);
  4482. }
  4483. /**
  4484. * Show logo -
  4485. *
  4486. * @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.
  4487. * @param string $other Add more attributes on img
  4488. * @return string Return tag img
  4489. */
  4490. function img_edit_remove($titlealt = 'default', $other = '')
  4491. {
  4492. global $langs;
  4493. if ($titlealt == 'default') {
  4494. $titlealt = $langs->trans('Remove');
  4495. }
  4496. return img_picto($titlealt, 'edit_remove.png', $other);
  4497. }
  4498. /**
  4499. * Show logo editer/modifier fiche
  4500. *
  4501. * @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.
  4502. * @param integer $float If you have to put the style "float: right"
  4503. * @param string $other Add more attributes on img
  4504. * @return string Return tag img
  4505. */
  4506. function img_edit($titlealt = 'default', $float = 0, $other = '')
  4507. {
  4508. global $langs;
  4509. if ($titlealt == 'default') {
  4510. $titlealt = $langs->trans('Modify');
  4511. }
  4512. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  4513. }
  4514. /**
  4515. * Show logo view card
  4516. *
  4517. * @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.
  4518. * @param integer $float If you have to put the style "float: right"
  4519. * @param string $other Add more attributes on img
  4520. * @return string Return tag img
  4521. */
  4522. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  4523. {
  4524. global $langs;
  4525. if ($titlealt == 'default') {
  4526. $titlealt = $langs->trans('View');
  4527. }
  4528. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4529. return img_picto($titlealt, 'eye', $moreatt);
  4530. }
  4531. /**
  4532. * Show delete logo
  4533. *
  4534. * @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.
  4535. * @param string $other Add more attributes on img
  4536. * @param string $morecss More CSS
  4537. * @return string Retourne tag img
  4538. */
  4539. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4540. {
  4541. global $langs;
  4542. if ($titlealt == 'default') {
  4543. $titlealt = $langs->trans('Delete');
  4544. }
  4545. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4546. }
  4547. /**
  4548. * Show printer logo
  4549. *
  4550. * @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.
  4551. * @param string $other Add more attributes on img
  4552. * @return string Retourne tag img
  4553. */
  4554. function img_printer($titlealt = "default", $other = '')
  4555. {
  4556. global $langs;
  4557. if ($titlealt == "default") {
  4558. $titlealt = $langs->trans("Print");
  4559. }
  4560. return img_picto($titlealt, 'printer.png', $other);
  4561. }
  4562. /**
  4563. * Show split logo
  4564. *
  4565. * @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.
  4566. * @param string $other Add more attributes on img
  4567. * @return string Retourne tag img
  4568. */
  4569. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4570. {
  4571. global $langs;
  4572. if ($titlealt == 'default') {
  4573. $titlealt = $langs->trans('Split');
  4574. }
  4575. return img_picto($titlealt, 'split.png', $other);
  4576. }
  4577. /**
  4578. * Show help logo with cursor "?"
  4579. *
  4580. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4581. * @param int|string $usealttitle Text to use as alt title
  4582. * @return string Return tag img
  4583. */
  4584. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4585. {
  4586. global $langs;
  4587. if ($usealttitle) {
  4588. if (is_string($usealttitle)) {
  4589. $usealttitle = dol_escape_htmltag($usealttitle);
  4590. } else {
  4591. $usealttitle = $langs->trans('Info');
  4592. }
  4593. }
  4594. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4595. }
  4596. /**
  4597. * Show info logo
  4598. *
  4599. * @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.
  4600. * @return string Return img tag
  4601. */
  4602. function img_info($titlealt = 'default')
  4603. {
  4604. global $langs;
  4605. if ($titlealt == 'default') {
  4606. $titlealt = $langs->trans('Informations');
  4607. }
  4608. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4609. }
  4610. /**
  4611. * Show warning logo
  4612. *
  4613. * @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.
  4614. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4615. * @param string $morecss Add more CSS
  4616. * @return string Return img tag
  4617. */
  4618. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4619. {
  4620. global $langs;
  4621. if ($titlealt == 'default') {
  4622. $titlealt = $langs->trans('Warning');
  4623. }
  4624. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4625. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4626. }
  4627. /**
  4628. * Show error logo
  4629. *
  4630. * @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.
  4631. * @return string Return img tag
  4632. */
  4633. function img_error($titlealt = 'default')
  4634. {
  4635. global $langs;
  4636. if ($titlealt == 'default') {
  4637. $titlealt = $langs->trans('Error');
  4638. }
  4639. return img_picto($titlealt, 'error.png');
  4640. }
  4641. /**
  4642. * Show next logo
  4643. *
  4644. * @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.
  4645. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4646. * @return string Return img tag
  4647. */
  4648. function img_next($titlealt = 'default', $moreatt = '')
  4649. {
  4650. global $langs;
  4651. if ($titlealt == 'default') {
  4652. $titlealt = $langs->trans('Next');
  4653. }
  4654. //return img_picto($titlealt, 'next.png', $moreatt);
  4655. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4656. }
  4657. /**
  4658. * Show previous logo
  4659. *
  4660. * @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.
  4661. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4662. * @return string Return img tag
  4663. */
  4664. function img_previous($titlealt = 'default', $moreatt = '')
  4665. {
  4666. global $langs;
  4667. if ($titlealt == 'default') {
  4668. $titlealt = $langs->trans('Previous');
  4669. }
  4670. //return img_picto($titlealt, 'previous.png', $moreatt);
  4671. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4672. }
  4673. /**
  4674. * Show down arrow logo
  4675. *
  4676. * @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.
  4677. * @param int $selected Selected
  4678. * @param string $moreclass Add more CSS classes
  4679. * @return string Return img tag
  4680. */
  4681. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4682. {
  4683. global $langs;
  4684. if ($titlealt == 'default') {
  4685. $titlealt = $langs->trans('Down');
  4686. }
  4687. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4688. }
  4689. /**
  4690. * Show top arrow logo
  4691. *
  4692. * @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.
  4693. * @param int $selected Selected
  4694. * @param string $moreclass Add more CSS classes
  4695. * @return string Return img tag
  4696. */
  4697. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4698. {
  4699. global $langs;
  4700. if ($titlealt == 'default') {
  4701. $titlealt = $langs->trans('Up');
  4702. }
  4703. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4704. }
  4705. /**
  4706. * Show left arrow logo
  4707. *
  4708. * @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.
  4709. * @param int $selected Selected
  4710. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4711. * @return string Return img tag
  4712. */
  4713. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4714. {
  4715. global $langs;
  4716. if ($titlealt == 'default') {
  4717. $titlealt = $langs->trans('Left');
  4718. }
  4719. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4720. }
  4721. /**
  4722. * Show right arrow logo
  4723. *
  4724. * @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.
  4725. * @param int $selected Selected
  4726. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4727. * @return string Return img tag
  4728. */
  4729. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4730. {
  4731. global $langs;
  4732. if ($titlealt == 'default') {
  4733. $titlealt = $langs->trans('Right');
  4734. }
  4735. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4736. }
  4737. /**
  4738. * Show tick logo if allowed
  4739. *
  4740. * @param string $allow Allow
  4741. * @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.
  4742. * @return string Return img tag
  4743. */
  4744. function img_allow($allow, $titlealt = 'default')
  4745. {
  4746. global $langs;
  4747. if ($titlealt == 'default') {
  4748. $titlealt = $langs->trans('Active');
  4749. }
  4750. if ($allow == 1) {
  4751. return img_picto($titlealt, 'tick.png');
  4752. }
  4753. return '-';
  4754. }
  4755. /**
  4756. * Return image of a credit card according to its brand name
  4757. *
  4758. * @param string $brand Brand name of credit card
  4759. * @param string $morecss More CSS
  4760. * @return string Return img tag
  4761. */
  4762. function img_credit_card($brand, $morecss = null)
  4763. {
  4764. if (is_null($morecss)) {
  4765. $morecss = 'fa-2x';
  4766. }
  4767. if ($brand == 'visa' || $brand == 'Visa') {
  4768. $brand = 'cc-visa';
  4769. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4770. $brand = 'cc-mastercard';
  4771. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4772. $brand = 'cc-amex';
  4773. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4774. $brand = 'cc-discover';
  4775. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4776. $brand = 'cc-jcb';
  4777. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4778. $brand = 'cc-diners-club';
  4779. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4780. $brand = 'credit-card';
  4781. }
  4782. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4783. }
  4784. /**
  4785. * Show MIME img of a file
  4786. *
  4787. * @param string $file Filename
  4788. * @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.
  4789. * @param string $morecss More css
  4790. * @return string Return img tag
  4791. */
  4792. function img_mime($file, $titlealt = '', $morecss = '')
  4793. {
  4794. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4795. $mimetype = dol_mimetype($file, '', 1);
  4796. $mimeimg = dol_mimetype($file, '', 2);
  4797. $mimefa = dol_mimetype($file, '', 4);
  4798. if (empty($titlealt)) {
  4799. $titlealt = 'Mime type: '.$mimetype;
  4800. }
  4801. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4802. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4803. }
  4804. /**
  4805. * Show search logo
  4806. *
  4807. * @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.
  4808. * @param string $other Add more attributes on img
  4809. * @return string Retourne tag img
  4810. */
  4811. function img_search($titlealt = 'default', $other = '')
  4812. {
  4813. global $conf, $langs;
  4814. if ($titlealt == 'default') {
  4815. $titlealt = $langs->trans('Search');
  4816. }
  4817. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4818. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4819. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4820. return $input;
  4821. }
  4822. /**
  4823. * Show search logo
  4824. *
  4825. * @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.
  4826. * @param string $other Add more attributes on img
  4827. * @return string Retourne tag img
  4828. */
  4829. function img_searchclear($titlealt = 'default', $other = '')
  4830. {
  4831. global $conf, $langs;
  4832. if ($titlealt == 'default') {
  4833. $titlealt = $langs->trans('Search');
  4834. }
  4835. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4836. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4837. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4838. return $input;
  4839. }
  4840. /**
  4841. * Show information for admin users or standard users
  4842. *
  4843. * @param string $text Text info
  4844. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4845. * @param int $nodiv No div
  4846. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4847. * @param string $morecss More CSS ('', 'warning', 'error')
  4848. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4849. * @return string String with info text
  4850. */
  4851. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4852. {
  4853. global $conf, $langs;
  4854. if ($infoonimgalt) {
  4855. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4856. } else {
  4857. if (empty($conf->use_javascript_ajax)) {
  4858. $textfordropdown = '';
  4859. }
  4860. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4861. $result = ($nodiv ? '' : '<div class="'.$class.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  4862. if ($textfordropdown) {
  4863. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4864. $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
  4865. jQuery(document).ready(function() {
  4866. jQuery(".'.$class.'text").click(function() {
  4867. console.log("toggle text");
  4868. jQuery(".'.$class.'").toggle();
  4869. });
  4870. });
  4871. </script>';
  4872. $result = $tmpresult.$result;
  4873. }
  4874. }
  4875. return $result;
  4876. }
  4877. /**
  4878. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4879. * This function must be called when a blocking technical error is encountered.
  4880. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4881. *
  4882. * @param DoliDB|string $db Database handler
  4883. * @param string|string[] $error String or array of errors strings to show
  4884. * @param array $errors Array of errors
  4885. * @return void
  4886. * @see dol_htmloutput_errors()
  4887. */
  4888. function dol_print_error($db = '', $error = '', $errors = null)
  4889. {
  4890. global $conf, $langs, $argv;
  4891. global $dolibarr_main_prod;
  4892. $out = '';
  4893. $syslog = '';
  4894. // If error occurs before the $lang object was loaded
  4895. if (!$langs) {
  4896. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4897. $langs = new Translate('', $conf);
  4898. $langs->load("main");
  4899. }
  4900. // Load translation files required by the error messages
  4901. $langs->loadLangs(array('main', 'errors'));
  4902. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4903. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4904. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4905. $out .= "You use an experimental or develop level of features, so please do NOT report any bugs or vulnerability, except if problem is confirmed after moving option MAIN_FEATURES_LEVEL back to 0.<br>\n";
  4906. }
  4907. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4908. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4909. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4910. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4911. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4912. }
  4913. if (function_exists("phpversion")) {
  4914. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4915. }
  4916. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4917. if (function_exists("php_uname")) {
  4918. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4919. }
  4920. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4921. $out .= "<br>\n";
  4922. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4923. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4924. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4925. $out .= "<br>\n";
  4926. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4927. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4928. } else { // Mode CLI
  4929. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4930. $syslog .= "pid=".dol_getmypid();
  4931. }
  4932. if (!empty($conf->modules)) {
  4933. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4934. }
  4935. if (is_object($db)) {
  4936. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4937. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4938. $lastqueryerror = $db->lastqueryerror();
  4939. if (!utf8_check($lastqueryerror)) {
  4940. $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
  4941. }
  4942. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4943. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4944. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4945. $out .= "<br>\n";
  4946. } else { // Mode CLI
  4947. // No dol_escape_htmltag for output, we are in CLI mode
  4948. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4949. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4950. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4951. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4952. }
  4953. $syslog .= ", sql=".$db->lastquery();
  4954. $syslog .= ", db_error=".$db->lasterror();
  4955. }
  4956. if ($error || $errors) {
  4957. $langs->load("errors");
  4958. // Merge all into $errors array
  4959. if (is_array($error) && is_array($errors)) {
  4960. $errors = array_merge($error, $errors);
  4961. } elseif (is_array($error)) {
  4962. $errors = $error;
  4963. } elseif (is_array($errors)) {
  4964. $errors = array_merge(array($error), $errors);
  4965. } else {
  4966. $errors = array_merge(array($error), array($errors));
  4967. }
  4968. foreach ($errors as $msg) {
  4969. if (empty($msg)) {
  4970. continue;
  4971. }
  4972. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4973. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4974. } else { // Mode CLI
  4975. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4976. }
  4977. $syslog .= ", msg=".$msg;
  4978. }
  4979. }
  4980. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4981. xdebug_print_function_stack();
  4982. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4983. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4984. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4985. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4986. $out .= "<br>\n";
  4987. }
  4988. // Return a http header with error code if possible
  4989. if (!headers_sent()) {
  4990. if (function_exists('top_httphead')) { // In CLI context, the method does not exists
  4991. top_httphead();
  4992. }
  4993. //http_response_code(500); // If we use 500, message is not ouput with some command line tools
  4994. http_response_code(202); // If we use 202, this is not really an error message, but this allow to ouput message on command line tools
  4995. }
  4996. if (empty($dolibarr_main_prod)) {
  4997. print $out;
  4998. } else {
  4999. if (empty($langs->defaultlang)) {
  5000. $langs->setDefaultLang();
  5001. }
  5002. $langs->loadLangs(array("main", "errors")); // Reload main because language may have been set only on previous line so we have to reload files we need.
  5003. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  5004. print 'This website or feature is currently temporarly not available or failed after a technical error.<br><br>This may be due to a maintenance operation. Current status of operation ('.dol_print_date(dol_now(), 'dayhourrfc').') are on next line...<br><br>'."\n";
  5005. print $langs->trans("DolibarrHasDetectedError").'. ';
  5006. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  5007. if (!defined("MAIN_CORE_ERROR")) {
  5008. define("MAIN_CORE_ERROR", 1);
  5009. }
  5010. }
  5011. dol_syslog("Error ".$syslog, LOG_ERR);
  5012. }
  5013. /**
  5014. * Show a public email and error code to contact if technical error
  5015. *
  5016. * @param string $prefixcode Prefix of public error code
  5017. * @param string $errormessage Complete error message
  5018. * @param array $errormessages Array of error messages
  5019. * @param string $morecss More css
  5020. * @param string $email Email
  5021. * @return void
  5022. */
  5023. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  5024. {
  5025. global $langs, $conf;
  5026. if (empty($email)) {
  5027. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  5028. }
  5029. $langs->load("errors");
  5030. $now = dol_now();
  5031. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  5032. print $langs->trans("ErrorContactEMail", $email, $prefixcode.'-'.dol_print_date($now, '%Y%m%d%H%M%S'));
  5033. if ($errormessage) {
  5034. print '<br><br>'.$errormessage;
  5035. }
  5036. if (is_array($errormessages) && count($errormessages)) {
  5037. foreach ($errormessages as $mesgtoshow) {
  5038. print '<br><br>'.$mesgtoshow;
  5039. }
  5040. }
  5041. print '</div></div>';
  5042. }
  5043. /**
  5044. * Show title line of an array
  5045. *
  5046. * @param string $name Label of field
  5047. * @param string $file Url used when we click on sort picto
  5048. * @param string $field Field to use for new sorting
  5049. * @param string $begin ("" by defaut)
  5050. * @param string $moreparam Add more parameters on sort url links ("" by default)
  5051. * @param string $moreattrib Options of attribute td ("" by defaut)
  5052. * @param string $sortfield Current field used to sort
  5053. * @param string $sortorder Current sort order
  5054. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  5055. * @param string $tooltip Tooltip
  5056. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  5057. * @return void
  5058. */
  5059. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  5060. {
  5061. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  5062. }
  5063. /**
  5064. * Get title line of an array
  5065. *
  5066. * @param string $name Translation key of field to show or complete HTML string to show
  5067. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  5068. * @param string $file Url used when we click on sort picto
  5069. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  5070. * @param string $begin ("" by defaut)
  5071. * @param string $moreparam Add more parameters on sort url links ("" by default)
  5072. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  5073. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  5074. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  5075. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  5076. * @param string $disablesortlink 1=Disable sort link
  5077. * @param string $tooltip Tooltip
  5078. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  5079. * @return string
  5080. */
  5081. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  5082. {
  5083. global $conf, $langs, $form;
  5084. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  5085. if ($moreattrib == 'class="right"') {
  5086. $prefix .= 'right '; // For backward compatibility
  5087. }
  5088. $sortorder = strtoupper($sortorder);
  5089. $out = '';
  5090. $sortimg = '';
  5091. $tag = 'th';
  5092. if ($thead == 2) {
  5093. $tag = 'div';
  5094. }
  5095. $tmpsortfield = explode(',', $sortfield);
  5096. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  5097. $tmpfield = explode(',', $field);
  5098. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  5099. if (!getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle)) {
  5100. $prefix = 'wrapcolumntitle '.$prefix;
  5101. }
  5102. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  5103. // If field is used as sort criteria we use a specific css class liste_titre_sel
  5104. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  5105. $liste_titre = 'liste_titre';
  5106. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  5107. $liste_titre = 'liste_titre_sel';
  5108. }
  5109. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  5110. //$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)).'"' : '');
  5111. $tagstart .= ($name && !getDolGlobalString('MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE') && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  5112. $tagstart .= '>';
  5113. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  5114. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  5115. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  5116. $options = preg_replace('/&+/i', '&', $options);
  5117. if (!preg_match('/^&/', $options)) {
  5118. $options = '&'.$options;
  5119. }
  5120. $sortordertouseinlink = '';
  5121. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  5122. if (preg_match('/^DESC/i', $sortorder)) {
  5123. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  5124. } else { // We reverse the var $sortordertouseinlink
  5125. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  5126. }
  5127. } else { // We are on field that is the first current sorting criteria
  5128. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  5129. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  5130. } else {
  5131. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  5132. }
  5133. }
  5134. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  5135. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  5136. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  5137. $out .= '>';
  5138. }
  5139. if ($tooltip) {
  5140. // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
  5141. if (preg_match('/:\w+$/', $tooltip)) {
  5142. $tmptooltip = explode(':', $tooltip);
  5143. } else {
  5144. $tmptooltip = array($tooltip);
  5145. }
  5146. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  5147. } else {
  5148. $out .= $langs->trans($name);
  5149. }
  5150. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  5151. $out .= '</a>';
  5152. }
  5153. if (empty($thead) && $field) { // If this is a sort field
  5154. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  5155. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  5156. $options = preg_replace('/&+/i', '&', $options);
  5157. if (!preg_match('/^&/', $options)) {
  5158. $options = '&'.$options;
  5159. }
  5160. if (!$sortorder || ($field1 != $sortfield1)) {
  5161. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  5162. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  5163. } else {
  5164. if (preg_match('/^DESC/', $sortorder)) {
  5165. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  5166. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  5167. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  5168. }
  5169. if (preg_match('/^ASC/', $sortorder)) {
  5170. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  5171. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  5172. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  5173. }
  5174. }
  5175. }
  5176. $tagend = '</'.$tag.'>';
  5177. $out = $tagstart.$sortimg.$out.$tagend;
  5178. return $out;
  5179. }
  5180. /**
  5181. * Show a title.
  5182. *
  5183. * @param string $title Title to show
  5184. * @return void
  5185. * @deprecated Use load_fiche_titre instead
  5186. * @see load_fiche_titre()
  5187. */
  5188. function print_titre($title)
  5189. {
  5190. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  5191. print '<div class="titre">'.$title.'</div>';
  5192. }
  5193. /**
  5194. * Show a title with picto
  5195. *
  5196. * @param string $title Title to show
  5197. * @param string $mesg Added message to show on right
  5198. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5199. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5200. * @param int $id To force an id on html objects
  5201. * @return void
  5202. * @deprecated Use print load_fiche_titre instead
  5203. */
  5204. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  5205. {
  5206. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  5207. }
  5208. /**
  5209. * Load a title with picto
  5210. *
  5211. * @param string $titre Title to show
  5212. * @param string $morehtmlright Added message to show on right
  5213. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5214. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5215. * @param string $id To force an id on html objects
  5216. * @param string $morecssontable More css on table
  5217. * @param string $morehtmlcenter Added message to show on center
  5218. * @return string
  5219. * @see print_barre_liste()
  5220. */
  5221. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  5222. {
  5223. global $conf;
  5224. $return = '';
  5225. if ($picto == 'setup') {
  5226. $picto = 'generic';
  5227. }
  5228. $return .= "\n";
  5229. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  5230. $return .= '<tr class="titre">';
  5231. if ($picto) {
  5232. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  5233. }
  5234. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  5235. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  5236. $return .= '</td>';
  5237. if (dol_strlen($morehtmlcenter)) {
  5238. $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5239. }
  5240. if (dol_strlen($morehtmlright)) {
  5241. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
  5242. }
  5243. $return .= '</tr></table>'."\n";
  5244. return $return;
  5245. }
  5246. /**
  5247. * Print a title with navigation controls for pagination
  5248. *
  5249. * @param string $titre Title to show (required)
  5250. * @param int|null $page Numero of page to show in navigation links (required)
  5251. * @param string $file Url of page (required)
  5252. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  5253. * @param string $sortfield Field to sort on ('' by default)
  5254. * @param string $sortorder Order to sort ('' by default)
  5255. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  5256. * @param int $num Number of records found by select with limit+1
  5257. * @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.
  5258. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  5259. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  5260. * @param string $morehtmlright More html to show (after arrows)
  5261. * @param string $morecss More css to the table
  5262. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  5263. * @param int $hideselectlimit Force to hide select limit
  5264. * @param int $hidenavigation Force to hide the arrows and page for navigation
  5265. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  5266. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  5267. * @return void
  5268. */
  5269. 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 = '')
  5270. {
  5271. global $conf;
  5272. $savlimit = $limit;
  5273. $savtotalnboflines = $totalnboflines;
  5274. $totalnboflines = abs((int) $totalnboflines);
  5275. $page = (int) $page;
  5276. if ($picto == 'setup') {
  5277. $picto = 'title_setup.png';
  5278. }
  5279. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  5280. $picto = 'title.gif';
  5281. }
  5282. if ($limit < 0) {
  5283. $limit = $conf->liste_limit;
  5284. }
  5285. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  5286. $nextpage = 1;
  5287. } else {
  5288. $nextpage = 0;
  5289. }
  5290. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
  5291. print "\n";
  5292. print "<!-- Begin title -->\n";
  5293. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  5294. // Left
  5295. if ($picto && $titre) {
  5296. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  5297. }
  5298. print '<td class="nobordernopadding valignmiddle col-title">';
  5299. print '<div class="titre inline-block">'.$titre;
  5300. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  5301. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  5302. }
  5303. print '</div></td>';
  5304. // Center
  5305. if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
  5306. print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5307. }
  5308. // Right
  5309. print '<td class="nobordernopadding valignmiddle right col-right">';
  5310. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  5311. if ($sortfield) {
  5312. $options .= "&sortfield=".urlencode($sortfield);
  5313. }
  5314. if ($sortorder) {
  5315. $options .= "&sortorder=".urlencode($sortorder);
  5316. }
  5317. // Show navigation bar
  5318. $pagelist = '';
  5319. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  5320. if ($totalnboflines) { // If we know total nb of lines
  5321. // Define nb of extra page links before and after selected page + ... + first or last
  5322. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  5323. if ($limit > 0) {
  5324. $nbpages = ceil($totalnboflines / $limit);
  5325. } else {
  5326. $nbpages = 1;
  5327. }
  5328. $cpt = ($page - $maxnbofpage);
  5329. if ($cpt < 0) {
  5330. $cpt = 0;
  5331. }
  5332. if ($cpt >= 1) {
  5333. if (empty($pagenavastextinput)) {
  5334. $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page=0'.$options.'">1</a></li>';
  5335. if ($cpt > 2) {
  5336. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5337. } elseif ($cpt == 2) {
  5338. $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page=1'.$options.'">2</a></li>';
  5339. }
  5340. }
  5341. }
  5342. do {
  5343. if ($pagenavastextinput) {
  5344. if ($cpt == $page) {
  5345. $pagelist .= '<li class="pagination"><input type="text" class="'.($totalnboflines > 100 ? 'width40' : 'width25').' center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  5346. $pagelist .= '/';
  5347. }
  5348. } else {
  5349. if ($cpt == $page) {
  5350. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  5351. } else {
  5352. $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  5353. }
  5354. }
  5355. $cpt++;
  5356. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  5357. if (empty($pagenavastextinput)) {
  5358. if ($cpt < $nbpages) {
  5359. if ($cpt < $nbpages - 2) {
  5360. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5361. } elseif ($cpt == $nbpages - 2) {
  5362. $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  5363. }
  5364. $pagelist .= '<li class="pagination"><a class="reposition" href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5365. }
  5366. } else {
  5367. //var_dump($page.' '.$cpt.' '.$nbpages);
  5368. $pagelist .= '<li class="pagination paginationlastpage"><a class="reposition" href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5369. }
  5370. } else {
  5371. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  5372. }
  5373. }
  5374. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  5375. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow, $hidenavigation); // output the div and ul for previous/last completed with page numbers into $pagelist
  5376. }
  5377. // js to autoselect page field on focus
  5378. if ($pagenavastextinput) {
  5379. print ajax_autoselect('.pageplusone');
  5380. }
  5381. print '</td>';
  5382. print '</tr>';
  5383. print '</table>'."\n";
  5384. // Center
  5385. if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
  5386. print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
  5387. }
  5388. print "<!-- End title -->\n\n";
  5389. }
  5390. /**
  5391. * Function to show navigation arrows into lists
  5392. *
  5393. * @param int $page Number of page
  5394. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  5395. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  5396. * @param integer $nextpage Do we show a next page button
  5397. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  5398. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  5399. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  5400. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  5401. * @param int $hideselectlimit Force to hide select limit
  5402. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  5403. * @param int $hidenavigation Force to hide the switch mode view and the navigation tool (hide limit section, html in $betweenarrows and $afterarrows but not $beforearrows)
  5404. * @return void
  5405. */
  5406. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '', $hidenavigation = 0)
  5407. {
  5408. global $conf, $langs;
  5409. print '<div class="pagination"><ul>';
  5410. if ($beforearrows) {
  5411. print '<li class="paginationbeforearrows">';
  5412. print $beforearrows;
  5413. print '</li>';
  5414. }
  5415. if (empty($hidenavigation)) {
  5416. if ((int) $limit > 0 && empty($hideselectlimit)) {
  5417. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
  5418. $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
  5419. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  5420. //$pagesizechoices.=',2:2';
  5421. if (getDolGlobalString('MAIN_PAGESIZE_CHOICES')) {
  5422. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  5423. }
  5424. print '<li class="pagination">';
  5425. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  5426. $tmpchoice = explode(',', $pagesizechoices);
  5427. $tmpkey = $limit.':'.$limit;
  5428. if (!in_array($tmpkey, $tmpchoice)) {
  5429. $tmpchoice[] = $tmpkey;
  5430. }
  5431. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  5432. if (!in_array($tmpkey, $tmpchoice)) {
  5433. $tmpchoice[] = $tmpkey;
  5434. }
  5435. asort($tmpchoice, SORT_NUMERIC);
  5436. foreach ($tmpchoice as $val) {
  5437. $selected = '';
  5438. $tmp = explode(':', $val);
  5439. $key = $tmp[0];
  5440. $val = $tmp[1];
  5441. if ($key != '' && $val != '') {
  5442. if ((int) $key == (int) $limit) {
  5443. $selected = ' selected="selected"';
  5444. }
  5445. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  5446. }
  5447. }
  5448. print '</select>';
  5449. if ($conf->use_javascript_ajax) {
  5450. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  5451. <script>
  5452. jQuery(document).ready(function () {
  5453. jQuery(".selectlimit").change(function() {
  5454. console.log("Change limit. Send submit");
  5455. $(this).parents(\'form:first\').submit();
  5456. });
  5457. });
  5458. </script>
  5459. ';
  5460. }
  5461. print '</li>';
  5462. }
  5463. if ($page > 0) {
  5464. print '<li class="pagination paginationpage paginationpageleft"><a class="paginationprevious reposition" href="'.$file.'?page='.($page - 1).$options.'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag($langs->trans("Previous")).'"></i></a></li>';
  5465. }
  5466. if ($betweenarrows) {
  5467. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  5468. print $betweenarrows;
  5469. print '<!--</div>-->';
  5470. }
  5471. if ($nextpage > 0) {
  5472. print '<li class="pagination paginationpage paginationpageright"><a class="paginationnext reposition" href="'.$file.'?page='.($page + 1).$options.'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag($langs->trans("Next")).'"></i></a></li>';
  5473. }
  5474. if ($afterarrows) {
  5475. print '<li class="paginationafterarrows">';
  5476. print $afterarrows;
  5477. print '</li>';
  5478. }
  5479. }
  5480. print '</ul></div>'."\n";
  5481. }
  5482. /**
  5483. * Return a string with VAT rate label formated for view output
  5484. * Used into pdf and HTML pages
  5485. *
  5486. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  5487. * @param boolean $addpercent Add a percent % sign in output
  5488. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  5489. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  5490. * @param int $html Used for html output
  5491. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  5492. */
  5493. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
  5494. {
  5495. $morelabel = '';
  5496. if (preg_match('/%/', $rate)) {
  5497. $rate = str_replace('%', '', $rate);
  5498. $addpercent = true;
  5499. }
  5500. $reg = array();
  5501. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  5502. $morelabel = ' ('.$reg[1].')';
  5503. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  5504. $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
  5505. }
  5506. if (preg_match('/\*/', $rate)) {
  5507. $rate = str_replace('*', '', $rate);
  5508. $info_bits |= 1;
  5509. }
  5510. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  5511. if (!preg_match('/\//', $rate)) {
  5512. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  5513. } else {
  5514. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  5515. $ret = $rate.($addpercent ? '%' : '');
  5516. }
  5517. if (($info_bits & 1) && $usestarfornpr >= 0) {
  5518. $ret .= ' *';
  5519. }
  5520. $ret .= $morelabel;
  5521. return $ret;
  5522. }
  5523. /**
  5524. * Function to format a value into an amount for visual output
  5525. * Function used into PDF and HTML pages
  5526. *
  5527. * @param float $amount Amount to format
  5528. * @param integer $form Type of format, HTML or not (not by default)
  5529. * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators.
  5530. * @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.
  5531. * @param int $rounding MINIMUM number of decimal to show: 0=no change, -1=we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  5532. * @param int|string $forcerounding MAXIMUM number of decimal to forcerounding decimal: -1=no change, 'MU' or 'MT' or numeric to round to MU or MT or to a given number of decimal
  5533. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  5534. * @return string String with formated amount
  5535. *
  5536. * @see price2num() Revert function of price
  5537. */
  5538. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  5539. {
  5540. global $langs, $conf;
  5541. // Clean parameters
  5542. if (empty($amount)) {
  5543. $amount = 0; // To have a numeric value if amount not defined or = ''
  5544. }
  5545. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  5546. if ($rounding == -1) {
  5547. $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT'));
  5548. }
  5549. $nbdecimal = $rounding;
  5550. if ($outlangs === 'none') {
  5551. // Use international separators
  5552. $dec = '.';
  5553. $thousand = '';
  5554. } else {
  5555. // Output separators by default (french)
  5556. $dec = ',';
  5557. $thousand = ' ';
  5558. // If $outlangs not forced, we use use language
  5559. if (!is_object($outlangs)) {
  5560. $outlangs = $langs;
  5561. }
  5562. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5563. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5564. }
  5565. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5566. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5567. }
  5568. if ($thousand == 'None') {
  5569. $thousand = '';
  5570. } elseif ($thousand == 'Space') {
  5571. $thousand = ' ';
  5572. }
  5573. }
  5574. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5575. //print "amount=".$amount."-";
  5576. $amount = str_replace(',', '.', $amount); // should be useless
  5577. //print $amount."-";
  5578. $datas = explode('.', $amount);
  5579. $decpart = isset($datas[1]) ? $datas[1] : '';
  5580. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5581. //print "decpart=".$decpart."<br>";
  5582. $end = '';
  5583. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5584. if (dol_strlen($decpart) > $nbdecimal) {
  5585. $nbdecimal = dol_strlen($decpart);
  5586. }
  5587. // Si on depasse max
  5588. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5589. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5590. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5591. // Si un affichage est tronque, on montre des ...
  5592. $end = '...';
  5593. }
  5594. }
  5595. // If force rounding
  5596. if ((string) $forcerounding != '-1') {
  5597. if ($forcerounding === 'MU') {
  5598. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5599. } elseif ($forcerounding === 'MT') {
  5600. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5601. } elseif ($forcerounding >= 0) {
  5602. $nbdecimal = $forcerounding;
  5603. }
  5604. }
  5605. // Format number
  5606. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5607. if ($form) {
  5608. $output = preg_replace('/\s/', '&nbsp;', $output);
  5609. $output = preg_replace('/\'/', '&#039;', $output);
  5610. }
  5611. // Add symbol of currency if requested
  5612. $cursymbolbefore = $cursymbolafter = '';
  5613. if ($currency_code && is_object($outlangs)) {
  5614. if ($currency_code == 'auto') {
  5615. $currency_code = $conf->currency;
  5616. }
  5617. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC', 'ZAR');
  5618. $listoflanguagesbefore = array('nl_NL');
  5619. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5620. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5621. } else {
  5622. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5623. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5624. }
  5625. }
  5626. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5627. return $output;
  5628. }
  5629. /**
  5630. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5631. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5632. * should be roundtext2num().
  5633. *
  5634. * @param string|float $amount Amount to convert/clean or round
  5635. * @param string|int $rounding ''=No rounding
  5636. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5637. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5638. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5639. * 'CU'=Round to Max unit price of foreign currency accuracy
  5640. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5641. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5642. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5643. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5644. * @return string Amount with universal numeric format (Example: '99.99999').
  5645. * If conversion fails to return a numeric, it returns:
  5646. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5647. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5648. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5649. * If amount is null or '', it returns '' if $rounding = '', it returns '0' if $rounding is defined.
  5650. *
  5651. * @see price() Opposite function of price2num
  5652. */
  5653. function price2num($amount, $rounding = '', $option = 0)
  5654. {
  5655. global $langs, $conf;
  5656. // Clean parameters
  5657. if (is_null($amount)) {
  5658. $amount = '';
  5659. }
  5660. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5661. // Numbers must be '1234.56'
  5662. // Decimal delimiter for PHP and database SQL requests must be '.'
  5663. $dec = ',';
  5664. $thousand = ' ';
  5665. if (is_null($langs)) { // $langs is not defined, we use english values.
  5666. $dec = '.';
  5667. $thousand = ',';
  5668. } else {
  5669. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5670. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5671. }
  5672. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5673. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5674. }
  5675. }
  5676. if ($thousand == 'None') {
  5677. $thousand = '';
  5678. } elseif ($thousand == 'Space') {
  5679. $thousand = ' ';
  5680. }
  5681. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5682. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5683. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5684. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5685. if (!is_numeric($amount)) {
  5686. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5687. }
  5688. if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come from input data, so 1.123 is 1123
  5689. $amount = str_replace($thousand, '', $amount);
  5690. }
  5691. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5692. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5693. // So if number was already a good number, it is converted into local Dolibarr setup.
  5694. if (is_numeric($amount)) {
  5695. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5696. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5697. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5698. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5699. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5700. }
  5701. //print "QQ".$amount."<br>\n";
  5702. // Now make replace (the main goal of function)
  5703. if ($thousand != ',' && $thousand != '.') {
  5704. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5705. }
  5706. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5707. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5708. $amount = str_replace($dec, '.', $amount);
  5709. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5710. }
  5711. //print ' XX'.$amount.' '.$rounding;
  5712. // Now, $amount is a real PHP float number. We make a rounding if required.
  5713. if ($rounding) {
  5714. $nbofdectoround = '';
  5715. if ($rounding == 'MU') {
  5716. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5717. } elseif ($rounding == 'MT') {
  5718. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5719. } elseif ($rounding == 'MS') {
  5720. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5721. } elseif ($rounding == 'CU') {
  5722. $nbofdectoround = max(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), 8); // TODO Use param of currency
  5723. } elseif ($rounding == 'CT') {
  5724. $nbofdectoround = max(getDolGlobalString('MAIN_MAX_DECIMALS_TOT'), 8); // TODO Use param of currency
  5725. } elseif (is_numeric($rounding)) {
  5726. $nbofdectoround = (int) $rounding;
  5727. }
  5728. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5729. if (dol_strlen($nbofdectoround)) {
  5730. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5731. } else {
  5732. return 'ErrorBadParameterProvidedToFunction';
  5733. }
  5734. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5735. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5736. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5737. if (is_numeric($amount)) {
  5738. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5739. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5740. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5741. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5742. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5743. }
  5744. //print "TT".$amount.'<br>';
  5745. // Always make replace because each math function (like round) replace
  5746. // with local values and we want a number that has a SQL string format x.y
  5747. if ($thousand != ',' && $thousand != '.') {
  5748. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5749. }
  5750. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5751. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5752. $amount = str_replace($dec, '.', $amount);
  5753. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5754. }
  5755. return $amount;
  5756. }
  5757. /**
  5758. * Output a dimension with best unit
  5759. *
  5760. * @param float $dimension Dimension
  5761. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5762. * @param string $type 'weight', 'volume', ...
  5763. * @param Translate $outputlangs Translate language object
  5764. * @param int $round -1 = non rounding, x = number of decimal
  5765. * @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)
  5766. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5767. * @return string String to show dimensions
  5768. */
  5769. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5770. {
  5771. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5772. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5773. $dimension = $dimension * 1000000;
  5774. $unit = $unit - 6;
  5775. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5776. $dimension = $dimension * 1000;
  5777. $unit = $unit - 3;
  5778. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5779. $dimension = $dimension / 1000000;
  5780. $unit = $unit + 6;
  5781. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5782. $dimension = $dimension / 1000;
  5783. $unit = $unit + 3;
  5784. }
  5785. // Special case when we want output unit into pound or ounce
  5786. /* TODO
  5787. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5788. {
  5789. $dimension = // convert dimension from standard unit into ounce or pound
  5790. $unit = $forceunitoutput;
  5791. }
  5792. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5793. {
  5794. $dimension = // convert dimension from standard unit into ounce or pound
  5795. $unit = $forceunitoutput;
  5796. }*/
  5797. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5798. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5799. return $ret;
  5800. }
  5801. /**
  5802. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5803. * Note: This function applies same rules than get_default_tva
  5804. *
  5805. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5806. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5807. * @param Societe $thirdparty_buyer Object of buying third party
  5808. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5809. * @param int $vatnpr If vat rate is NPR or not
  5810. * @return mixed 0 if not found, localtax rate if found
  5811. * @see get_default_tva()
  5812. */
  5813. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5814. {
  5815. global $db, $conf, $mysoc;
  5816. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5817. $thirdparty_seller = $mysoc;
  5818. }
  5819. 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);
  5820. $vatratecleaned = $vatrate;
  5821. $reg = array();
  5822. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5823. $vatratecleaned = trim($reg[1]);
  5824. $vatratecode = $reg[2];
  5825. }
  5826. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5827. {
  5828. return 0;
  5829. }*/
  5830. // Some test to guess with no need to make database access
  5831. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5832. if ($local == 1) {
  5833. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5834. return 0;
  5835. }
  5836. if ($thirdparty_seller->id == $mysoc->id) {
  5837. if (!$thirdparty_buyer->localtax1_assuj) {
  5838. return 0;
  5839. }
  5840. } else {
  5841. if (!$thirdparty_seller->localtax1_assuj) {
  5842. return 0;
  5843. }
  5844. }
  5845. }
  5846. if ($local == 2) {
  5847. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5848. if (!$mysoc->localtax2_assuj) {
  5849. return 0; // If main vat is 0, IRPF may be different than 0.
  5850. }
  5851. if ($thirdparty_seller->id == $mysoc->id) {
  5852. if (!$thirdparty_buyer->localtax2_assuj) {
  5853. return 0;
  5854. }
  5855. } else {
  5856. if (!$thirdparty_seller->localtax2_assuj) {
  5857. return 0;
  5858. }
  5859. }
  5860. }
  5861. } else {
  5862. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5863. return 0;
  5864. }
  5865. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5866. return 0;
  5867. }
  5868. }
  5869. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5870. if (in_array($mysoc->country_code, array('ES'))) {
  5871. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5872. }
  5873. // Search local taxes
  5874. if (getDolGlobalString('MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY')) {
  5875. if ($local == 1) {
  5876. if ($thirdparty_seller != $mysoc) {
  5877. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5878. return $thirdparty_seller->localtax1_value;
  5879. }
  5880. } else { // i am the seller
  5881. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5882. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5883. }
  5884. }
  5885. }
  5886. if ($local == 2) {
  5887. if ($thirdparty_seller != $mysoc) {
  5888. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5889. // TODO We should also return value defined on thirdparty only if defined
  5890. return $thirdparty_seller->localtax2_value;
  5891. }
  5892. } else { // i am the seller
  5893. if (in_array($mysoc->country_code, array('ES'))) {
  5894. return $thirdparty_buyer->localtax2_value;
  5895. } else {
  5896. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5897. }
  5898. }
  5899. }
  5900. }
  5901. // By default, search value of local tax on line of common tax
  5902. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5903. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5904. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5905. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5906. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5907. if (!empty($vatratecode)) {
  5908. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5909. } else {
  5910. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5911. }
  5912. $resql = $db->query($sql);
  5913. if ($resql) {
  5914. $obj = $db->fetch_object($resql);
  5915. if ($obj) {
  5916. if ($local == 1) {
  5917. return $obj->localtax1;
  5918. } elseif ($local == 2) {
  5919. return $obj->localtax2;
  5920. }
  5921. }
  5922. }
  5923. return 0;
  5924. }
  5925. /**
  5926. * Return true if LocalTax (1 or 2) is unique.
  5927. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5928. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5929. *
  5930. * @param int $local Local tax to test (1 or 2)
  5931. * @return boolean True if LocalTax have multiple values, False if not
  5932. */
  5933. function isOnlyOneLocalTax($local)
  5934. {
  5935. $tax = get_localtax_by_third($local);
  5936. $valors = explode(":", $tax);
  5937. if (count($valors) > 1) {
  5938. return false;
  5939. } else {
  5940. return true;
  5941. }
  5942. }
  5943. /**
  5944. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5945. *
  5946. * @param int $local LocalTax to get
  5947. * @return string Values of localtax (Can be '20', '-19:-15:-9') or 'Error'
  5948. */
  5949. function get_localtax_by_third($local)
  5950. {
  5951. global $db, $mysoc;
  5952. $sql = " SELECT t.localtax".$local." as localtax";
  5953. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
  5954. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.entity IN (".getEntity('c_tva').") AND t.taux = (";
  5955. $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";
  5956. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.entity IN (".getEntity('c_tva').") AND tt.active = 1)";
  5957. $sql .= " AND t.localtax".$local."_type <> '0'";
  5958. $sql .= " ORDER BY t.rowid DESC";
  5959. $resql = $db->query($sql);
  5960. if ($resql) {
  5961. $obj = $db->fetch_object($resql);
  5962. if ($obj) {
  5963. return $obj->localtax;
  5964. } else {
  5965. return '0';
  5966. }
  5967. }
  5968. return 'Error';
  5969. }
  5970. /**
  5971. * Get tax (VAT) main information from Id.
  5972. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5973. *
  5974. * @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.
  5975. * @param Societe $buyer Company object
  5976. * @param Societe $seller Company object
  5977. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5978. * @return array array('rowid'=> , 'code'=> ...)
  5979. * @see getLocalTaxesFromRate()
  5980. */
  5981. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5982. {
  5983. global $db, $mysoc;
  5984. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5985. // Search local taxes
  5986. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5987. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5988. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5989. if ($firstparamisid) {
  5990. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5991. } else {
  5992. $vatratecleaned = $vatrate;
  5993. $vatratecode = '';
  5994. $reg = array();
  5995. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5996. $vatratecleaned = $reg[1];
  5997. $vatratecode = $reg[2];
  5998. }
  5999. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  6000. /*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 ??
  6001. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  6002. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  6003. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  6004. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  6005. if ($vatratecode) {
  6006. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  6007. }
  6008. }
  6009. $resql = $db->query($sql);
  6010. if ($resql) {
  6011. $obj = $db->fetch_object($resql);
  6012. if ($obj) {
  6013. return array(
  6014. 'rowid'=>$obj->rowid,
  6015. 'code'=>$obj->code,
  6016. 'rate'=>$obj->rate,
  6017. 'localtax1'=>$obj->localtax1,
  6018. 'localtax1_type'=>$obj->localtax1_type,
  6019. 'localtax2'=>$obj->localtax2,
  6020. 'localtax2_type'=>$obj->localtax2_type,
  6021. 'npr'=>$obj->npr,
  6022. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  6023. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  6024. );
  6025. } else {
  6026. return array();
  6027. }
  6028. } else {
  6029. dol_print_error($db);
  6030. }
  6031. return array();
  6032. }
  6033. /**
  6034. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  6035. * This does not take into account the seller setup if subject to vat or not, only country.
  6036. *
  6037. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  6038. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  6039. * provide the selected value to the function calcul_price_total.
  6040. *
  6041. * @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.
  6042. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  6043. * @param Societe $buyer Company object
  6044. * @param Societe $seller Company object
  6045. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  6046. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  6047. * @see getTaxesFromId()
  6048. */
  6049. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  6050. {
  6051. global $db, $mysoc;
  6052. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  6053. // Search local taxes
  6054. $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";
  6055. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  6056. if ($firstparamisid) {
  6057. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  6058. } else {
  6059. $vatratecleaned = $vatrate;
  6060. $vatratecode = '';
  6061. $reg = array();
  6062. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  6063. $vatratecleaned = $reg[1];
  6064. $vatratecode = $reg[2];
  6065. }
  6066. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  6067. if (!empty($mysoc) && $mysoc->country_code == 'ES') {
  6068. $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
  6069. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'"; // local tax in spain use the buyer country ??
  6070. } else {
  6071. $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
  6072. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'";
  6073. }
  6074. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  6075. if ($vatratecode) {
  6076. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  6077. }
  6078. }
  6079. $resql = $db->query($sql);
  6080. if ($resql) {
  6081. $obj = $db->fetch_object($resql);
  6082. if ($obj) {
  6083. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  6084. if ($local == 1) {
  6085. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  6086. } elseif ($local == 2) {
  6087. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  6088. } else {
  6089. 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);
  6090. }
  6091. }
  6092. }
  6093. return array();
  6094. }
  6095. /**
  6096. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  6097. * Function called by get_default_tva().
  6098. *
  6099. * @param int $idprod Id of product or 0 if not a predefined product
  6100. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  6101. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  6102. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  6103. * @see get_product_localtax_for_country()
  6104. */
  6105. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  6106. {
  6107. global $db, $conf, $mysoc;
  6108. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6109. $ret = 0;
  6110. $found = 0;
  6111. if ($idprod > 0) {
  6112. // Load product
  6113. $product = new Product($db);
  6114. $product->fetch($idprod);
  6115. if ($mysoc->country_code == $thirdpartytouse->country_code) {
  6116. // If country to consider is ours
  6117. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  6118. $result = $product->get_buyprice($idprodfournprice, 0, 0, 0);
  6119. if ($result > 0) {
  6120. $ret = $product->vatrate_supplier;
  6121. if ($product->default_vat_code_supplier) {
  6122. $ret .= ' ('.$product->default_vat_code_supplier.')';
  6123. }
  6124. $found = 1;
  6125. }
  6126. }
  6127. if (!$found) {
  6128. $ret = $product->tva_tx; // Default sales vat of product
  6129. if ($product->default_vat_code) {
  6130. $ret .= ' ('.$product->default_vat_code.')';
  6131. }
  6132. $found = 1;
  6133. }
  6134. } else {
  6135. // TODO Read default product vat according to product and an other countrycode.
  6136. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  6137. }
  6138. }
  6139. if (!$found) {
  6140. if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
  6141. // If vat of product for the country not found or not defined, we return the first rate found (sorting on use_default, then on higher vat of country).
  6142. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  6143. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  6144. $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
  6145. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  6146. $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
  6147. $sql .= $db->plimit(1);
  6148. $resql = $db->query($sql);
  6149. if ($resql) {
  6150. $obj = $db->fetch_object($resql);
  6151. if ($obj) {
  6152. $ret = $obj->vat_rate;
  6153. if ($obj->default_vat_code) {
  6154. $ret .= ' ('.$obj->default_vat_code.')';
  6155. }
  6156. }
  6157. $db->free($resql);
  6158. } else {
  6159. dol_print_error($db);
  6160. }
  6161. } else {
  6162. // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
  6163. // '1.23'
  6164. // or '1.23 (CODE)'
  6165. $defaulttx = '';
  6166. if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
  6167. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  6168. }
  6169. /*if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  6170. $defaultcode = $reg[1];
  6171. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  6172. }*/
  6173. $ret = $defaulttx;
  6174. }
  6175. }
  6176. dol_syslog("get_product_vat_for_country: ret=".$ret);
  6177. return $ret;
  6178. }
  6179. /**
  6180. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  6181. *
  6182. * @param int $idprod Id of product
  6183. * @param int $local 1 for localtax1, 2 for localtax 2
  6184. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  6185. * @return int Return integer <0 if KO, Vat rate if OK
  6186. * @see get_product_vat_for_country()
  6187. */
  6188. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  6189. {
  6190. global $db, $mysoc;
  6191. if (!class_exists('Product')) {
  6192. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6193. }
  6194. $ret = 0;
  6195. $found = 0;
  6196. if ($idprod > 0) {
  6197. // Load product
  6198. $product = new Product($db);
  6199. $result = $product->fetch($idprod);
  6200. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  6201. /* Not defined yet, so we don't use this
  6202. if ($local==1) $ret=$product->localtax1_tx;
  6203. elseif ($local==2) $ret=$product->localtax2_tx;
  6204. $found=1;
  6205. */
  6206. } else {
  6207. // TODO Read default product vat according to product and another countrycode.
  6208. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  6209. }
  6210. }
  6211. if (!$found) {
  6212. // If vat of product for the country not found or not defined, we return higher vat of country.
  6213. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  6214. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  6215. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  6216. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  6217. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  6218. $sql .= $db->plimit(1);
  6219. $resql = $db->query($sql);
  6220. if ($resql) {
  6221. $obj = $db->fetch_object($resql);
  6222. if ($obj) {
  6223. if ($local == 1) {
  6224. $ret = $obj->localtax1;
  6225. } elseif ($local == 2) {
  6226. $ret = $obj->localtax2;
  6227. }
  6228. }
  6229. } else {
  6230. dol_print_error($db);
  6231. }
  6232. }
  6233. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  6234. return $ret;
  6235. }
  6236. /**
  6237. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  6238. * VATRULE 1: If seller does not use VAT, default VAT is 0. End of rule.
  6239. * VATRULE 2: If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6240. * VATRULE 3: If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  6241. * VATRULE 4: If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6242. * VATRULE 5: If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6243. * VATRULE 6: Otherwise the VAT proposed by default=0. End of rule.
  6244. *
  6245. * @param Societe $thirdparty_seller Objet societe vendeuse
  6246. * @param Societe $thirdparty_buyer Objet societe acheteuse
  6247. * @param int $idprod Id product
  6248. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  6249. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  6250. * @see get_default_npr(), get_default_localtax()
  6251. */
  6252. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6253. {
  6254. global $conf;
  6255. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  6256. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  6257. $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;
  6258. $seller_country_code = $thirdparty_seller->country_code;
  6259. $seller_in_cee = isInEEC($thirdparty_seller);
  6260. $buyer_country_code = $thirdparty_buyer->country_code;
  6261. $buyer_in_cee = isInEEC($thirdparty_buyer);
  6262. 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=".(getDolGlobalString('SERVICES_ARE_ECOMMERCE_200238EC') ? $conf->global->SERVICES_ARE_ECOMMERCE_200238EC : ''));
  6263. // 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)
  6264. // we use the buyer VAT.
  6265. if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
  6266. if ($seller_in_cee && $buyer_in_cee) {
  6267. $isacompany = $thirdparty_buyer->isACompany();
  6268. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6269. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6270. if (!isValidVATID($thirdparty_buyer)) {
  6271. $isacompany = 0;
  6272. }
  6273. }
  6274. if (!$isacompany) {
  6275. //print 'VATRULE 0';
  6276. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  6277. }
  6278. }
  6279. }
  6280. // If seller does not use VAT, default VAT is 0. End of rule.
  6281. if (!$seller_use_vat) {
  6282. //print 'VATRULE 1';
  6283. return 0;
  6284. }
  6285. // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6286. if (($seller_country_code == $buyer_country_code)
  6287. || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  6288. //print 'VATRULE 2';
  6289. $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6290. if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
  6291. // Special case for india.
  6292. //print 'VATRULE 2b';
  6293. $reg = array();
  6294. if (preg_match('/C+S-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
  6295. // we must revert the C+S into I
  6296. $tmpvat = str_replace("C+S", "I", $tmpvat);
  6297. } elseif (preg_match('/I-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
  6298. // we must revert the I into C+S
  6299. $tmpvat = str_replace("I", "C+S", $tmpvat);
  6300. }
  6301. }
  6302. return $tmpvat;
  6303. }
  6304. // If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  6305. // 'VATRULE 3' - Not supported
  6306. // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6307. // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6308. if (($seller_in_cee && $buyer_in_cee)) {
  6309. $isacompany = $thirdparty_buyer->isACompany();
  6310. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6311. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6312. if (!isValidVATID($thirdparty_buyer)) {
  6313. $isacompany = 0;
  6314. }
  6315. }
  6316. if (!$isacompany) {
  6317. //print 'VATRULE 4';
  6318. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6319. } else {
  6320. //print 'VATRULE 5';
  6321. return 0;
  6322. }
  6323. }
  6324. // If (seller in the European Community and buyer outside the European Community and private buyer) then VAT by default = VAT of the product sold. End of rule
  6325. // I don't see any use case that need this rule.
  6326. if (getDolGlobalString('MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC') && empty($buyer_in_cee)) {
  6327. $isacompany = $thirdparty_buyer->isACompany();
  6328. if (!$isacompany) {
  6329. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6330. //print 'VATRULE extra';
  6331. }
  6332. }
  6333. // Otherwise the VAT proposed by default=0. End of rule.
  6334. // Rem: This means that at least one of the 2 is outside the European Community and the country differs
  6335. //print 'VATRULE 6';
  6336. return 0;
  6337. }
  6338. /**
  6339. * Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
  6340. *
  6341. * @param Societe $thirdparty_seller Thirdparty seller
  6342. * @param Societe $thirdparty_buyer Thirdparty buyer
  6343. * @param int $idprod Id product
  6344. * @param int $idprodfournprice Id supplier price for product
  6345. * @return float 0 or 1
  6346. * @see get_default_tva(), get_default_localtax()
  6347. */
  6348. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6349. {
  6350. global $db;
  6351. if ($idprodfournprice > 0) {
  6352. if (!class_exists('ProductFournisseur')) {
  6353. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6354. }
  6355. $prodprice = new ProductFournisseur($db);
  6356. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  6357. return $prodprice->fourn_tva_npr;
  6358. } elseif ($idprod > 0) {
  6359. if (!class_exists('Product')) {
  6360. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6361. }
  6362. $prod = new Product($db);
  6363. $prod->fetch($idprod);
  6364. return $prod->tva_npr;
  6365. }
  6366. return 0;
  6367. }
  6368. /**
  6369. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  6370. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  6371. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  6372. * Sinon TVA proposee par defaut=0. Fin de regle.
  6373. *
  6374. * @param Societe $thirdparty_seller Thirdparty seller
  6375. * @param Societe $thirdparty_buyer Thirdparty buyer
  6376. * @param int $local Localtax to process (1 or 2)
  6377. * @param int $idprod Id product
  6378. * @return integer localtax, -1 si ne peut etre determine
  6379. * @see get_default_tva(), get_default_npr()
  6380. */
  6381. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  6382. {
  6383. global $mysoc;
  6384. if (!is_object($thirdparty_seller)) {
  6385. return -1;
  6386. }
  6387. if (!is_object($thirdparty_buyer)) {
  6388. return -1;
  6389. }
  6390. if ($local == 1) { // Localtax 1
  6391. if ($mysoc->country_code == 'ES') {
  6392. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  6393. return 0;
  6394. }
  6395. } else {
  6396. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  6397. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  6398. return 0;
  6399. }
  6400. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  6401. return 0;
  6402. }
  6403. }
  6404. } elseif ($local == 2) { //I Localtax 2
  6405. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  6406. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  6407. return 0;
  6408. }
  6409. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  6410. return 0;
  6411. }
  6412. }
  6413. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  6414. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  6415. }
  6416. return 0;
  6417. }
  6418. /**
  6419. * Return yes or no in current language
  6420. *
  6421. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  6422. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  6423. * @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.
  6424. * @return string HTML string
  6425. */
  6426. function yn($yesno, $case = 1, $color = 0)
  6427. {
  6428. global $langs;
  6429. $result = 'unknown';
  6430. $classname = '';
  6431. if ($yesno == 1 || (isset($yesno) && (strtolower($yesno) == 'yes' || strtolower($yesno) == 'true'))) { // A mettre avant test sur no a cause du == 0
  6432. $result = $langs->trans('yes');
  6433. if ($case == 1 || $case == 3) {
  6434. $result = $langs->trans("Yes");
  6435. }
  6436. if ($case == 2) {
  6437. $result = '<input type="checkbox" value="1" checked disabled>';
  6438. }
  6439. if ($case == 3) {
  6440. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  6441. }
  6442. $classname = 'ok';
  6443. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  6444. $result = $langs->trans("no");
  6445. if ($case == 1 || $case == 3) {
  6446. $result = $langs->trans("No");
  6447. }
  6448. if ($case == 2) {
  6449. $result = '<input type="checkbox" value="0" disabled>';
  6450. }
  6451. if ($case == 3) {
  6452. $result = '<input type="checkbox" value="0" disabled> '.$result;
  6453. }
  6454. if ($color == 2) {
  6455. $classname = 'ok';
  6456. } else {
  6457. $classname = 'error';
  6458. }
  6459. }
  6460. if ($color) {
  6461. return '<span class="'.$classname.'">'.$result.'</span>';
  6462. }
  6463. return $result;
  6464. }
  6465. /**
  6466. * Return a path to have a the directory according to object where files are stored.
  6467. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  6468. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  6469. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  6470. * Example out with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  6471. *
  6472. * @param string|int $num Id of object (deprecated, $object will be used in future)
  6473. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  6474. * @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)
  6475. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  6476. * @param Object $object Object to use to get ref to forge the path.
  6477. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  6478. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  6479. */
  6480. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  6481. {
  6482. global $conf;
  6483. if (empty($modulepart) && !empty($object->module)) {
  6484. $modulepart = $object->module;
  6485. }
  6486. $path = '';
  6487. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  6488. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  6489. $arrayforoldpath[] = 'product';
  6490. }
  6491. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  6492. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  6493. if (empty($alpha)) {
  6494. $num = preg_replace('/([^0-9])/i', '', $num);
  6495. } else {
  6496. $num = preg_replace('/^.*\-/i', '', $num);
  6497. }
  6498. $num = substr("000".$num, -$level);
  6499. if ($level == 1) {
  6500. $path = substr($num, 0, 1);
  6501. }
  6502. if ($level == 2) {
  6503. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  6504. }
  6505. if ($level == 3) {
  6506. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  6507. }
  6508. } else {
  6509. // We will enhance here a common way of forging path for document storage.
  6510. // In a future, we may distribute directories on several levels depending on setup and object.
  6511. // Here, $object->id, $object->ref and $modulepart are required.
  6512. //var_dump($modulepart);
  6513. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  6514. }
  6515. if (empty($withoutslash) && !empty($path)) {
  6516. $path .= '/';
  6517. }
  6518. return $path;
  6519. }
  6520. /**
  6521. * Creation of a directory (this can create recursive subdir)
  6522. *
  6523. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  6524. * @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, saying PHP has no permission when open_basedir is used)
  6525. * @param string $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  6526. * @return int Return integer < 0 if KO, 0 = already exists, > 0 if OK
  6527. */
  6528. function dol_mkdir($dir, $dataroot = '', $newmask = '')
  6529. {
  6530. global $conf;
  6531. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  6532. $dir_osencoded = dol_osencode($dir);
  6533. if (@is_dir($dir_osencoded)) {
  6534. return 0;
  6535. }
  6536. $nberr = 0;
  6537. $nbcreated = 0;
  6538. $ccdir = '';
  6539. if (!empty($dataroot)) {
  6540. // Remove data root from loop
  6541. $dir = str_replace($dataroot.'/', '', $dir);
  6542. $ccdir = $dataroot.'/';
  6543. }
  6544. $cdir = explode("/", $dir);
  6545. $num = count($cdir);
  6546. for ($i = 0; $i < $num; $i++) {
  6547. if ($i > 0) {
  6548. $ccdir .= '/'.$cdir[$i];
  6549. } else {
  6550. $ccdir .= $cdir[$i];
  6551. }
  6552. $regs = array();
  6553. if (preg_match("/^.:$/", $ccdir, $regs)) {
  6554. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  6555. }
  6556. // Attention, le is_dir() peut echouer bien que le rep existe.
  6557. // (ex selon config de open_basedir)
  6558. if ($ccdir) {
  6559. $ccdir_osencoded = dol_osencode($ccdir);
  6560. if (!@is_dir($ccdir_osencoded)) {
  6561. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  6562. umask(0);
  6563. $dirmaskdec = octdec((string) $newmask);
  6564. if (empty($newmask)) {
  6565. $dirmaskdec = !getDolGlobalString('MAIN_UMASK') ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  6566. }
  6567. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  6568. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  6569. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  6570. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  6571. $nberr++;
  6572. } else {
  6573. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  6574. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  6575. $nbcreated++;
  6576. }
  6577. } else {
  6578. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  6579. }
  6580. }
  6581. }
  6582. return ($nberr ? -$nberr : $nbcreated);
  6583. }
  6584. /**
  6585. * Change mod of a file
  6586. *
  6587. * @param string $filepath Full file path
  6588. * @param string $newmask Force new mask. For example '0644'
  6589. * @return void
  6590. */
  6591. function dolChmod($filepath, $newmask = '')
  6592. {
  6593. global $conf;
  6594. if (!empty($newmask)) {
  6595. @chmod($filepath, octdec($newmask));
  6596. } elseif (getDolGlobalString('MAIN_UMASK')) {
  6597. @chmod($filepath, octdec($conf->global->MAIN_UMASK));
  6598. }
  6599. }
  6600. /**
  6601. * Return picto saying a field is required
  6602. *
  6603. * @return string Chaine avec picto obligatoire
  6604. */
  6605. function picto_required()
  6606. {
  6607. return '<span class="fieldrequired">*</span>';
  6608. }
  6609. /**
  6610. * Clean a string from all HTML tags and entities.
  6611. * This function differs from strip_tags because:
  6612. * - <br> are replaced with \n if removelinefeed=0 or 1
  6613. * - if entities are found, they are decoded BEFORE the strip
  6614. * - you can decide to convert line feed into a space
  6615. *
  6616. * @param string $stringtoclean String to clean
  6617. * @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..."
  6618. * @param string $pagecodeto Encoding of input/output string
  6619. * @param integer $strip_tags 0=Use internal strip, 1=Use strip_tags() php function (bugged when text contains a < char that is not for a html tag or when tags is not closed like '<img onload=aaa')
  6620. * @param integer $removedoublespaces Replace double space into one space
  6621. * @return string String cleaned
  6622. *
  6623. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6624. */
  6625. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6626. {
  6627. if (is_null($stringtoclean)) {
  6628. return '';
  6629. }
  6630. if ($removelinefeed == 2) {
  6631. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6632. }
  6633. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6634. // We remove entities BEFORE stripping (in case of an open separator char that is entity encoded and not the closing other, the strip will fails)
  6635. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6636. $temp = str_replace('< ', '__ltspace__', $temp);
  6637. if ($strip_tags) {
  6638. $temp = strip_tags($temp);
  6639. } else {
  6640. // Remove '<' into remainging, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
  6641. $pattern = "/<[^<>]+>/";
  6642. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6643. // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6644. // pass 2 - $temp after pass 2: 0000-021
  6645. $tempbis = $temp;
  6646. do {
  6647. $temp = $tempbis;
  6648. $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6649. $tempbis = preg_replace($pattern, '', $tempbis);
  6650. //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
  6651. } while ($tempbis != $temp);
  6652. $temp = $tempbis;
  6653. // Remove '<' into remaining, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
  6654. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6655. }
  6656. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6657. // Remove also carriage returns
  6658. if ($removelinefeed == 1) {
  6659. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6660. }
  6661. // And double quotes
  6662. if ($removedoublespaces) {
  6663. while (strpos($temp, " ")) {
  6664. $temp = str_replace(" ", " ", $temp);
  6665. }
  6666. }
  6667. $temp = str_replace('__ltspace__', '< ', $temp);
  6668. return trim($temp);
  6669. }
  6670. /**
  6671. * Clean a string to keep only desirable HTML tags.
  6672. * WARNING: This also clean HTML comments (because they can be used to obfuscate tag name).
  6673. *
  6674. * @param string $stringtoclean String to clean
  6675. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6676. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6677. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6678. * @param int $allowiframe Allow iframe tags.
  6679. * @param array $allowed_tags List of allowed tags to replace the default list
  6680. * @param int $allowlink Allow "link" tags.
  6681. * @return string String cleaned
  6682. *
  6683. * @see dol_htmlwithnojs() dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6684. */
  6685. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array(), $allowlink = 0)
  6686. {
  6687. if (empty($allowed_tags)) {
  6688. $allowed_tags = array(
  6689. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li",
  6690. "ol", "p", "q", "s", "span", "strike", "strong", "title", "table", "tr", "th", "td", "u", "ul", "sup", "sub", "blockquote", "pre", "h1", "h2", "h3", "h4", "h5", "h6",
  6691. "header", "footer", "nav", "section", "menu", "menuitem" // html5 tags
  6692. );
  6693. }
  6694. $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6695. if ($allowiframe) {
  6696. if (!in_array('iframe', $allowed_tags)) {
  6697. $allowed_tags[] = "iframe";
  6698. }
  6699. }
  6700. if ($allowlink) {
  6701. if (!in_array('link', $allowed_tags)) {
  6702. $allowed_tags[] = "link";
  6703. }
  6704. }
  6705. $allowed_tags_string = join("><", $allowed_tags);
  6706. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6707. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6708. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6709. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6710. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6711. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6712. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6713. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </>, so may changes string obfuscated with </> that pass the injection detection into a harmfull string
  6714. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6715. $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $temp); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless
  6716. }
  6717. if ($removeclassattribute) { // Clean for remaining html tags
  6718. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6719. }
  6720. // Remove 'javascript:' that we should not find into a text with
  6721. // Warning: This is not reliable to fight against obfuscated javascript, there is a lot of other solution to include js into a common html tag (only filtered by a GETPOST(.., powerfullfilter)).
  6722. if ($cleanalsojavascript) {
  6723. $temp = preg_replace('/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t\s*:/i', '', $temp);
  6724. }
  6725. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6726. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6727. return $temp;
  6728. }
  6729. /**
  6730. * Clean a string from some undesirable HTML tags.
  6731. * Note: Complementary to dol_string_onlythesehtmltags().
  6732. * This method is used for example by dol_htmlwithnojs() when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6733. *
  6734. * @param string $stringtoclean String to clean
  6735. * @param array $allowed_attributes Array of tags not allowed
  6736. * @return string String cleaned
  6737. *
  6738. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6739. */
  6740. function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = null)
  6741. {
  6742. if (is_null($allowed_attributes)) {
  6743. $allowed_attributes = array(
  6744. "allow", "allowfullscreen", "alt", "class", "contenteditable", "data-html", "frameborder", "height", "href", "id", "name", "src", "style", "target", "title", "width",
  6745. // HTML5
  6746. "header", "footer", "nav", "section", "menu", "menuitem"
  6747. );
  6748. }
  6749. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6750. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6751. // Warning: loadHTML does not support HTML5 on old libxml versions.
  6752. $dom = new DOMDocument(null, 'UTF-8');
  6753. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6754. if (is_object($dom)) {
  6755. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6756. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6757. //var_dump($attrs->item($ii));
  6758. if (!empty($attrs->item($ii)->name)) {
  6759. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6760. // Delete attribute if not into allowed_attributes
  6761. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6762. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6763. // If attribute is 'style'
  6764. $valuetoclean = $attrs->item($ii)->value;
  6765. if (isset($valuetoclean)) {
  6766. do {
  6767. $oldvaluetoclean = $valuetoclean;
  6768. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6769. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6770. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6771. $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
  6772. $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
  6773. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
  6774. }
  6775. // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
  6776. $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
  6777. $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
  6778. } while ($oldvaluetoclean != $valuetoclean);
  6779. }
  6780. $attrs->item($ii)->value = $valuetoclean;
  6781. }
  6782. }
  6783. }
  6784. }
  6785. }
  6786. $return = $dom->saveHTML(); // This may add a LF at end of lines, so we will trim later
  6787. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6788. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6789. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6790. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6791. return trim($return);
  6792. } else {
  6793. return $stringtoclean;
  6794. }
  6795. }
  6796. /**
  6797. * Clean a string from some undesirable HTML tags.
  6798. * Note: You should use instead dol_string_onlythesehtmltags() that is more secured if you can.
  6799. *
  6800. * @param string $stringtoclean String to clean
  6801. * @param array $disallowed_tags Array of tags not allowed
  6802. * @param string $cleanalsosomestyles Clean also some tags
  6803. * @return string String cleaned
  6804. *
  6805. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6806. */
  6807. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6808. {
  6809. $temp = $stringtoclean;
  6810. foreach ($disallowed_tags as $tagtoremove) {
  6811. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6812. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6813. }
  6814. if ($cleanalsosomestyles) {
  6815. $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
  6816. }
  6817. return $temp;
  6818. }
  6819. /**
  6820. * Return first line of text. Cut will depends if content is HTML or not.
  6821. *
  6822. * @param string $text Input text
  6823. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6824. * @param string $charset Charset of $text string (UTF-8 by default)
  6825. * @return string Output text
  6826. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6827. */
  6828. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6829. {
  6830. if ($nboflines == 1) {
  6831. if (dol_textishtml($text)) {
  6832. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6833. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6834. } else {
  6835. if (isset($text)) {
  6836. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6837. } else {
  6838. $firstline = '';
  6839. }
  6840. }
  6841. return $firstline.(isset($firstline) && isset($text) && (strlen($firstline) != strlen($text)) ? '...' : '');
  6842. } else {
  6843. $ishtml = 0;
  6844. if (dol_textishtml($text)) {
  6845. $text = preg_replace('/\n/', '', $text);
  6846. $ishtml = 1;
  6847. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6848. } else {
  6849. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6850. }
  6851. $text = strtr($text, $repTable);
  6852. if ($charset == 'UTF-8') {
  6853. $pattern = '/(<br[^>]*>)/Uu';
  6854. } else {
  6855. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6856. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6857. }
  6858. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6859. $firstline = '';
  6860. $i = 0;
  6861. $countline = 0;
  6862. $lastaddediscontent = 1;
  6863. while ($countline < $nboflines && isset($a[$i])) {
  6864. if (preg_match('/<br[^>]*>/', $a[$i])) {
  6865. if (array_key_exists($i+1, $a) && !empty($a[$i+1])) {
  6866. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6867. // Is it a br for a new line of after a printed line ?
  6868. if (!$lastaddediscontent) {
  6869. $countline++;
  6870. }
  6871. $lastaddediscontent = 0;
  6872. }
  6873. } else {
  6874. $firstline .= $a[$i];
  6875. $lastaddediscontent = 1;
  6876. $countline++;
  6877. }
  6878. $i++;
  6879. }
  6880. $adddots = (isset($a[$i]) && (!preg_match('/<br[^>]*>/', $a[$i]) || (array_key_exists($i+1, $a) && !empty($a[$i+1]))));
  6881. //unset($a);
  6882. $ret = $firstline.($adddots ? '...' : '');
  6883. //exit;
  6884. return $ret;
  6885. }
  6886. }
  6887. /**
  6888. * Replace CRLF in string with a HTML BR tag.
  6889. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have
  6890. * encoded the special chars of stringtoencode into HTML before with dol_htmlentitiesbr().
  6891. *
  6892. * @param string $stringtoencode String to encode
  6893. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6894. * @param bool $forxml false=Use <br>, true=Use <br />
  6895. * @return string String encoded
  6896. * @see dol_htmlentitiesbr(), dol_nboflines(), dolGetFirstLineOfText()
  6897. */
  6898. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6899. {
  6900. if (is_null($stringtoencode)) {
  6901. return '';
  6902. }
  6903. if (!$nl2brmode) {
  6904. return nl2br($stringtoencode, $forxml);
  6905. } else {
  6906. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6907. return $ret;
  6908. }
  6909. }
  6910. /**
  6911. * Sanitize a HTML to remove js, dangerous content and external link.
  6912. * This function is used by dolPrintHTML... function for example.
  6913. *
  6914. * @param string $stringtoencode String to encode
  6915. * @param int $nouseofiframesandbox 0=Default, 1=Allow use of option MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS for html sanitizing (not yet working)
  6916. * @param string $check 'restricthtmlnolink' or 'restricthtml' or 'restricthtmlallowclass' or 'restricthtmlallowunvalid'
  6917. * @return string HTML sanitized
  6918. */
  6919. function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
  6920. {
  6921. if (empty($nouseofiframesandbox) && getDolGlobalString('MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS')) {
  6922. // TODO using sandbox on inline html content is not possible yet with current browsers
  6923. //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
  6924. //$s .= $stringtoencode;
  6925. //$s .= '</body></html></iframe>';
  6926. return $stringtoencode;
  6927. } else {
  6928. $out = $stringtoencode;
  6929. do {
  6930. $oldstringtoclean = $out;
  6931. if (!empty($out) && getDolGlobalString('MAIN_RESTRICTHTML_ONLY_VALID_HTML') && $check != 'restricthtmlallowunvalid') {
  6932. try {
  6933. libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
  6934. if (LIBXML_VERSION < 20900) {
  6935. // Avoid load of external entities (security problem).
  6936. // Required only if LIBXML_VERSION < 20900
  6937. libxml_disable_entity_loader(true);
  6938. }
  6939. $dom = new DOMDocument();
  6940. // Add a trick to solve pb with text without parent tag
  6941. // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
  6942. // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
  6943. if (dol_textishtml($out)) {
  6944. $out = '<?xml encoding="UTF-8"><div class="tricktoremove">'.$out.'</div>';
  6945. } else {
  6946. $out = '<?xml encoding="UTF-8"><div class="tricktoremove">'.dol_nl2br($out).'</div>';
  6947. }
  6948. $dom->loadHTML($out, LIBXML_HTML_NODEFDTD | LIBXML_ERR_NONE | LIBXML_HTML_NOIMPLIED | LIBXML_NONET | LIBXML_NOWARNING | LIBXML_NOERROR | LIBXML_NOXMLDECL);
  6949. $out = trim($dom->saveHTML());
  6950. // Remove the trick added to solve pb with text without parent tag
  6951. $out = preg_replace('/^<\?xml encoding="UTF-8"><div class="tricktoremove">/', '', $out);
  6952. $out = preg_replace('/<\/div>$/', '', $out);
  6953. } catch (Exception $e) {
  6954. // If error, invalid HTML string with no way to clean it
  6955. //print $e->getMessage();
  6956. $out = 'InvalidHTMLStringCantBeCleaned '.$e->getMessage();
  6957. }
  6958. }
  6959. if (!empty($out) && getDolGlobalString('MAIN_RESTRICTHTML_ONLY_VALID_HTML_TIDY') && $check != 'restricthtmlallowunvalid') {
  6960. try {
  6961. // Try cleaning using tidy
  6962. if (extension_loaded('tidy') && class_exists("tidy")) {
  6963. //print "aaa".$out."\n";
  6964. // See options at https://tidy.sourceforge.net/docs/quickref.html
  6965. $config = array(
  6966. 'clean' => false,
  6967. 'quote-marks' => false, // do not replace " that are used for real text content (not a string symbol for html attribute) into &quot;
  6968. 'doctype' => 'strict',
  6969. 'show-body-only' => true,
  6970. "indent-attributes" => false,
  6971. "vertical-space" => false,
  6972. 'ident' => false,
  6973. "wrap" => 0
  6974. // HTML5 tags
  6975. //'new-blocklevel-tags' => 'article aside audio bdi canvas details dialog figcaption figure footer header hgroup main menu menuitem nav section source summary template track video',
  6976. //'new-blocklevel-tags' => 'footer header section menu menuitem'
  6977. //'new-empty-tags' => 'command embed keygen source track wbr',
  6978. //'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
  6979. );
  6980. // Tidy
  6981. $tidy = new tidy();
  6982. $out = $tidy->repairString($out, $config, 'utf8');
  6983. //print "xxx".$out;exit;
  6984. }
  6985. } catch (Exception $e) {
  6986. // If error, invalid HTML string with no way to clean it
  6987. //print $e->getMessage();
  6988. $out = 'InvalidHTMLStringCantBeCleaned '.$e->getMessage();
  6989. }
  6990. }
  6991. // Clean some html entities that are useless so text is cleaner
  6992. $out = preg_replace('/&(tab|newline);/i', ' ', $out);
  6993. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  6994. // encoded using text entities) so we can then exclude all numeric entities.
  6995. $out = preg_replace('/&#39;/i', '&apos;', $out);
  6996. // We replace chars from a/A to z/Z encoded with numeric HTML entities with the real char so we won't loose the chars at the next step (preg_replace).
  6997. // No need to use a loop here, this step is not to sanitize (this is done at next step, this is to try to save chars, even if they are
  6998. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  6999. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  7000. return realCharForNumericEntities($m);
  7001. }, $out);
  7002. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  7003. $out = preg_replace('/&#x?[0-9]+/i', '', $out); // For example if we have j&#x61vascript with an entities without the ; to hide the 'a' of 'javascript'.
  7004. // Keep only some html tags and remove also some 'javascript:' strings
  7005. $out = dol_string_onlythesehtmltags($out, 0, ($check == 'restricthtmlallowclass' ? 0 : 1), 1);
  7006. // Keep only some html attributes and exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
  7007. if (getDolGlobalString('MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES')) {
  7008. $out = dol_string_onlythesehtmlattributes($out);
  7009. }
  7010. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  7011. $out = preg_replace('/&apos;/i', "&#39;", $out);
  7012. } while ($oldstringtoclean != $out);
  7013. // Check the limit of external links that are automatically executed in a Rich text content. We count:
  7014. // '<img' to avoid <img src="http...">, we can only accept "<img src="data:..."
  7015. // 'url(' to avoid inline style like background: url(http...
  7016. // '<link' to avoid <link href="http...">
  7017. $reg = array();
  7018. $tmpout = preg_replace('/<img src="data:/mi', '<__IMG_SRC_DATA__ src="data:', $out);
  7019. preg_match_all('/(<img|url\(|<link)/i', $tmpout, $reg);
  7020. $nblinks = count($reg[0]);
  7021. if ($nblinks > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
  7022. $out = 'ErrorTooManyLinksIntoHTMLString';
  7023. }
  7024. if (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 2 || $check == 'restricthtmlnolink') {
  7025. if ($nblinks > 0) {
  7026. $out = 'ErrorHTMLLinksNotAllowed';
  7027. }
  7028. } elseif (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 1) {
  7029. $nblinks = 0;
  7030. // Loop on each url in src= and url(
  7031. $pattern = '/src=["\']?(http[^"\']+)|url\(["\']?(http[^\)]+)/';
  7032. $matches = array();
  7033. if (preg_match_all($pattern, $out, $matches)) {
  7034. // URLs are into $matches[1]
  7035. $urls = $matches[1];
  7036. // Affiche les URLs
  7037. foreach ($urls as $url) {
  7038. $nblinks++;
  7039. echo "Found url = ".$url . "\n";
  7040. }
  7041. if ($nblinks > 0) {
  7042. $out = 'ErrorHTMLExternalLinksNotAllowed';
  7043. }
  7044. }
  7045. }
  7046. return $out;
  7047. }
  7048. }
  7049. /**
  7050. * This function is called to encode a string into a HTML string but differs from htmlentities because
  7051. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  7052. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  7053. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  7054. * For PDF usage, you can show text by 2 ways:
  7055. * - writeHTMLCell -> param must be encoded into HTML.
  7056. * - MultiCell -> param must not be encoded into HTML.
  7057. * Because writeHTMLCell convert also \n into <br>, if function is used to build PDF, nl2brmode must be 1.
  7058. * Note: When we output string on pages, we should use
  7059. * - dolPrintHTML... that is dol_escape_htmltag(dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr(), 1, 1, 1), 1, 1) for notes or descriptions,
  7060. * - dolPrintLabel... that is dol_escape_htmltag(dol_htmlentitiesbr()) for simple labels.
  7061. * - dolPrintPassword that is abelhtmlspecialchars( , ENT_COMPAT, 'UTF-8') for passwords.
  7062. *
  7063. * @param string $stringtoencode String to encode
  7064. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  7065. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  7066. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  7067. * @return string String encoded
  7068. * @see dol_escape_htmltag(), dolGetFirstLineOfText(), dol_string_onlythesehtmltags()
  7069. */
  7070. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  7071. {
  7072. if (is_null($stringtoencode)) {
  7073. return '';
  7074. }
  7075. $newstring = $stringtoencode;
  7076. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  7077. $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.
  7078. if ($removelasteolbr) {
  7079. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  7080. }
  7081. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  7082. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  7083. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  7084. } else {
  7085. if ($removelasteolbr) {
  7086. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  7087. }
  7088. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  7089. }
  7090. // Other substitutions that htmlentities does not do
  7091. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  7092. return $newstring;
  7093. }
  7094. /**
  7095. * This function is called to decode a HTML string (it decodes entities and br tags)
  7096. *
  7097. * @param string $stringtodecode String to decode
  7098. * @param string $pagecodeto Page code for result
  7099. * @return string String decoded
  7100. */
  7101. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  7102. {
  7103. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  7104. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  7105. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  7106. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  7107. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  7108. return $ret;
  7109. }
  7110. /**
  7111. * This function remove all ending \n and br at end
  7112. *
  7113. * @param string $stringtodecode String to decode
  7114. * @return string String decoded
  7115. */
  7116. function dol_htmlcleanlastbr($stringtodecode)
  7117. {
  7118. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  7119. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  7120. return $ret;
  7121. }
  7122. /**
  7123. * Replace html_entity_decode functions to manage errors
  7124. *
  7125. * @param string $a Operand a
  7126. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  7127. * @param string $c Operand c
  7128. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  7129. * @return string String decoded
  7130. */
  7131. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  7132. {
  7133. $newstring = $a;
  7134. if ($keepsomeentities) {
  7135. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  7136. }
  7137. $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
  7138. if ($keepsomeentities) {
  7139. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  7140. }
  7141. return $newstring;
  7142. }
  7143. /**
  7144. * Replace htmlentities functions.
  7145. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  7146. *
  7147. * @param string $string The input string to encode
  7148. * @param int $flags Flags (see PHP doc above)
  7149. * @param string $encoding Encoding page code
  7150. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  7151. * @return string $ret Encoded string
  7152. * @see dol_htmlentitiesbr()
  7153. */
  7154. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  7155. {
  7156. return htmlentities($string, $flags, $encoding, $double_encode);
  7157. }
  7158. /**
  7159. * Check if a string is a correct iso string
  7160. * If not, it will not be considered as HTML encoded even if it is by FPDF.
  7161. * Example, if string contains euro symbol that has ascii code 128
  7162. *
  7163. * @param string $s String to check
  7164. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  7165. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  7166. * @deprecated Duplicate of ascii_check()
  7167. * @see ascii_check()
  7168. */
  7169. function dol_string_is_good_iso($s, $clean = 0)
  7170. {
  7171. $len = dol_strlen($s);
  7172. $out = '';
  7173. $ok = 1;
  7174. for ($scursor = 0; $scursor < $len; $scursor++) {
  7175. $ordchar = ord($s[$scursor]);
  7176. //print $scursor.'-'.$ordchar.'<br>';
  7177. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  7178. $ok = 0;
  7179. break;
  7180. } elseif ($ordchar > 126 && $ordchar < 160) {
  7181. $ok = 0;
  7182. break;
  7183. } elseif ($clean) {
  7184. $out .= $s[$scursor];
  7185. }
  7186. }
  7187. if ($clean) {
  7188. return $out;
  7189. }
  7190. return $ok;
  7191. }
  7192. /**
  7193. * Return nb of lines of a clear text
  7194. *
  7195. * @param string $s String to check
  7196. * @param int $maxchar Not yet used
  7197. * @return int Number of lines
  7198. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  7199. */
  7200. function dol_nboflines($s, $maxchar = 0)
  7201. {
  7202. if ($s == '') {
  7203. return 0;
  7204. }
  7205. $arraystring = explode("\n", $s);
  7206. $nb = count($arraystring);
  7207. return $nb;
  7208. }
  7209. /**
  7210. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  7211. *
  7212. * @param string $text Text
  7213. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  7214. * @param string $charset Give the charset used to encode the $text variable in memory.
  7215. * @return int Number of lines
  7216. * @see dol_nboflines(), dolGetFirstLineOfText()
  7217. */
  7218. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  7219. {
  7220. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  7221. if (dol_textishtml($text)) {
  7222. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  7223. }
  7224. $text = strtr($text, $repTable);
  7225. if ($charset == 'UTF-8') {
  7226. $pattern = '/(<br[^>]*>)/Uu';
  7227. } else {
  7228. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  7229. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  7230. }
  7231. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  7232. $nblines = (int) floor((count($a) + 1) / 2);
  7233. // count possible auto line breaks
  7234. if ($maxlinesize) {
  7235. foreach ($a as $line) {
  7236. if (dol_strlen($line) > $maxlinesize) {
  7237. //$line_dec = html_entity_decode(strip_tags($line));
  7238. $line_dec = html_entity_decode($line);
  7239. if (dol_strlen($line_dec) > $maxlinesize) {
  7240. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  7241. $nblines += substr_count($line_dec, '\n');
  7242. }
  7243. }
  7244. }
  7245. }
  7246. unset($a);
  7247. return $nblines;
  7248. }
  7249. /**
  7250. * Return if a text is a html content
  7251. *
  7252. * @param string $msg Content to check
  7253. * @param int $option 0=Full detection, 1=Fast check
  7254. * @return boolean true/false
  7255. * @see dol_concatdesc()
  7256. */
  7257. function dol_textishtml($msg, $option = 0)
  7258. {
  7259. if (is_null($msg)) {
  7260. return false;
  7261. }
  7262. if ($option == 1) {
  7263. if (preg_match('/<html/i', $msg)) {
  7264. return true;
  7265. } elseif (preg_match('/<body/i', $msg)) {
  7266. return true;
  7267. } elseif (preg_match('/<\/textarea/i', $msg)) {
  7268. return true;
  7269. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  7270. return true;
  7271. } elseif (preg_match('/<br/i', $msg)) {
  7272. return true;
  7273. }
  7274. return false;
  7275. } else {
  7276. // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
  7277. $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
  7278. if (preg_match('/<html/i', $msg)) {
  7279. return true;
  7280. } elseif (preg_match('/<body/i', $msg)) {
  7281. return true;
  7282. } elseif (preg_match('/<\/textarea/i', $msg)) {
  7283. return true;
  7284. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  7285. return true;
  7286. } elseif (preg_match('/<(br|hr)\/>/i', $msg)) {
  7287. return true;
  7288. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)>/i', $msg)) {
  7289. return true;
  7290. } elseif (preg_match('/<(br|hr|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  7291. return true;
  7292. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  7293. return true; // must accept <img src="http://example.com/aaa.png" />
  7294. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  7295. return true; // must accept <a href="http://example.com/aaa.png" />
  7296. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  7297. return true;
  7298. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  7299. // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
  7300. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  7301. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  7302. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  7303. }
  7304. return false;
  7305. }
  7306. }
  7307. /**
  7308. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  7309. * text1 html + text2 html => text1 + '<br>' + text2
  7310. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  7311. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  7312. * text1 txt + text2 txt => text1 + '\n' + text2
  7313. *
  7314. * @param string $text1 Text 1
  7315. * @param string $text2 Text 2
  7316. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  7317. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  7318. * @return string Text 1 + new line + Text2
  7319. * @see dol_textishtml()
  7320. */
  7321. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  7322. {
  7323. if (!empty($invert)) {
  7324. $tmp = $text1;
  7325. $text1 = $text2;
  7326. $text2 = $tmp;
  7327. }
  7328. $ret = '';
  7329. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  7330. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  7331. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  7332. return $ret;
  7333. }
  7334. /**
  7335. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  7336. *
  7337. * @param Translate $outputlangs Output language
  7338. * @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)
  7339. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7340. * @param Object $object Object for keys on object
  7341. * @param array $include Array of family keys we want to include. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  7342. * @return array Array of substitutions
  7343. * @see setSubstitFromObject()
  7344. */
  7345. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
  7346. {
  7347. global $db, $conf, $mysoc, $user, $extrafields;
  7348. $substitutionarray = array();
  7349. if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include))) {
  7350. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  7351. // this will include signature content first and then replace var found into content of signature
  7352. //var_dump($onlykey);
  7353. $emailsendersignature = $user->signature; // dy default, we use the signature of current user. We must complete substitution with signature in c_email_senderprofile of array after calling getCommonSubstitutionArray()
  7354. $usersignature = $user->signature;
  7355. $substitutionarray = array_merge($substitutionarray, array(
  7356. '__SENDEREMAIL_SIGNATURE__' => (string) ((!getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
  7357. '__USER_SIGNATURE__' => (string) (($usersignature && !getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
  7358. ));
  7359. if (is_object($user)) {
  7360. $substitutionarray = array_merge($substitutionarray, array(
  7361. '__USER_ID__' => (string) $user->id,
  7362. '__USER_LOGIN__' => (string) $user->login,
  7363. '__USER_EMAIL__' => (string) $user->email,
  7364. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
  7365. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
  7366. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
  7367. '__USER_FAX__' => (string) $user->office_fax,
  7368. '__USER_LASTNAME__' => (string) $user->lastname,
  7369. '__USER_FIRSTNAME__' => (string) $user->firstname,
  7370. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  7371. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  7372. '__USER_JOB__' => (string) $user->job,
  7373. '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
  7374. '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
  7375. ));
  7376. }
  7377. }
  7378. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
  7379. $substitutionarray = array_merge($substitutionarray, array(
  7380. '__MYCOMPANY_NAME__' => $mysoc->name,
  7381. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  7382. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone, '', 0, 0, '', " ", '', '', -1),
  7383. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax, '', 0, 0, '', " ", '', '', -1),
  7384. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  7385. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  7386. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  7387. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  7388. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  7389. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  7390. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  7391. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  7392. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  7393. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  7394. '__MYCOMPANY_TOWN__' => $mysoc->town,
  7395. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  7396. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  7397. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  7398. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  7399. ));
  7400. }
  7401. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
  7402. if ($onlykey) {
  7403. $substitutionarray['__ID__'] = '__ID__';
  7404. $substitutionarray['__REF__'] = '__REF__';
  7405. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  7406. $substitutionarray['__LABEL__'] = '__LABEL__';
  7407. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  7408. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  7409. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  7410. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  7411. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  7412. if (isModEnabled("societe")) { // Most objects are concerned
  7413. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  7414. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  7415. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  7416. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  7417. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  7418. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  7419. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  7420. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  7421. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  7422. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  7423. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  7424. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  7425. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  7426. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  7427. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  7428. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  7429. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  7430. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  7431. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  7432. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  7433. }
  7434. if (isModEnabled('adherent') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
  7435. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  7436. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  7437. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  7438. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  7439. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  7440. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  7441. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  7442. }
  7443. // add variables subtitutions ticket
  7444. if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
  7445. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  7446. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  7447. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  7448. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  7449. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  7450. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  7451. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  7452. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  7453. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  7454. }
  7455. if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
  7456. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  7457. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  7458. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  7459. }
  7460. if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
  7461. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  7462. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  7463. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  7464. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  7465. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  7466. }
  7467. if (isModEnabled('contrat') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
  7468. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  7469. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  7470. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  7471. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  7472. }
  7473. if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
  7474. $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
  7475. }
  7476. if (isModEnabled("ficheinter") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
  7477. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
  7478. }
  7479. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  7480. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  7481. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  7482. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  7483. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  7484. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  7485. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  7486. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  7487. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  7488. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  7489. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  7490. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  7491. if (isModEnabled("expedition") && (!is_object($object) || $object->element == 'shipping')) {
  7492. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  7493. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  7494. $substitutionarray['__SHIPPINGMETHOD__'] = 'Shipping method';
  7495. }
  7496. if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
  7497. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  7498. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  7499. }
  7500. } else {
  7501. $substitutionarray['__ID__'] = $object->id;
  7502. $substitutionarray['__REF__'] = $object->ref;
  7503. $substitutionarray['__NEWREF__'] = $object->newref;
  7504. $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
  7505. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7506. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7507. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  7508. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  7509. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, 'day', 0, $outputlangs) : '');
  7510. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%d") : '');
  7511. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%A") : '');
  7512. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%m") : '');
  7513. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%b") : '');
  7514. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%Y") : '');
  7515. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%H") : '');
  7516. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%M") : '');
  7517. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, "%S") : '');
  7518. // For backward compatibility (deprecated)
  7519. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7520. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7521. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->delivery_date) ? dol_print_date($object->delivery_date, 'day', 0, $outputlangs) : '');
  7522. $substitutionarray['__SUPPLIER_ORDER_DELAY_DELIVERY__'] = (isset($object->availability_code) ? ($outputlangs->transnoentities("AvailabilityType".$object->availability_code) != 'AvailabilityType'.$object->availability_code ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : '')) : '');
  7523. $substitutionarray['__EXPIRATION_DATE__'] = (isset($object->fin_validite) ? dol_print_date($object->fin_validite, 'daytext') : '');
  7524. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  7525. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  7526. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  7527. if (method_exists($object, 'getCivilityLabel')) {
  7528. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  7529. }
  7530. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  7531. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  7532. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  7533. if (method_exists($object, 'getFullName')) {
  7534. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  7535. }
  7536. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  7537. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  7538. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  7539. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  7540. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  7541. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  7542. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  7543. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  7544. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  7545. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  7546. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  7547. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  7548. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  7549. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  7550. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'day');
  7551. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'day') : '');
  7552. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'day') : '');
  7553. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'day');
  7554. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'day');
  7555. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'day');
  7556. }
  7557. if (is_object($object) && $object->element == 'societe') {
  7558. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  7559. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  7560. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  7561. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  7562. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  7563. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  7564. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  7565. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  7566. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  7567. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  7568. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  7569. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  7570. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  7571. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  7572. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  7573. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  7574. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  7575. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  7576. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  7577. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  7578. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  7579. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  7580. } elseif (is_object($object->thirdparty)) {
  7581. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  7582. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  7583. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  7584. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  7585. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  7586. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  7587. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  7588. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  7589. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  7590. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  7591. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  7592. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  7593. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  7594. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  7595. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  7596. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  7597. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  7598. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  7599. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  7600. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  7601. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  7602. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  7603. }
  7604. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  7605. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  7606. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7607. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7608. }
  7609. if (is_object($object) && $object->element == 'conferenceorboothattendee') {
  7610. $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
  7611. $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7612. $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7613. }
  7614. if (is_object($object) && $object->element == 'project') {
  7615. $substitutionarray['__PROJECT_ID__'] = $object->id;
  7616. $substitutionarray['__PROJECT_REF__'] = $object->ref;
  7617. $substitutionarray['__PROJECT_NAME__'] = $object->title;
  7618. } elseif (is_object($object)) {
  7619. $project = null;
  7620. if (!empty($object->project)) {
  7621. $project = $object->project;
  7622. } elseif (!empty($object->projet)) { // Deprecated, for backward compatibility
  7623. $project = $object->projet;
  7624. }
  7625. if (!is_null($project) && is_object($project)) {
  7626. $substitutionarray['__PROJECT_ID__'] = $project->id;
  7627. $substitutionarray['__PROJECT_REF__'] = $project->ref;
  7628. $substitutionarray['__PROJECT_NAME__'] = $project->title;
  7629. } else {
  7630. // can substitute variables for project : uses lazy load in "make_substitutions" method
  7631. $project_id = 0;
  7632. if (!empty($object->fk_project) && $object->fk_project > 0) {
  7633. $project_id = $object->fk_project;
  7634. } elseif (!empty($object->fk_projet) && $object->fk_projet > 0) {
  7635. $project_id = $object->fk_project;
  7636. }
  7637. if ($project_id > 0) {
  7638. // path:class:method:id
  7639. $substitutionarray['__PROJECT_ID__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
  7640. $substitutionarray['__PROJECT_REF__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
  7641. $substitutionarray['__PROJECT_NAME__@lazyload'] = '/projet/class/project.class.php:Project:fetchAndSetSubstitution:' . $project_id;
  7642. }
  7643. }
  7644. }
  7645. if (is_object($object) && $object->element == 'shipping') {
  7646. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  7647. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  7648. $substitutionarray['__SHIPPINGMETHOD__'] = $object->shipping_method;
  7649. }
  7650. if (is_object($object) && $object->element == 'reception') {
  7651. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  7652. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  7653. }
  7654. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  7655. $dateplannedstart = '';
  7656. $datenextexpiration = '';
  7657. foreach ($object->lines as $line) {
  7658. if ($line->date_start > $dateplannedstart) {
  7659. $dateplannedstart = $line->date_start;
  7660. }
  7661. if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
  7662. $datenextexpiration = $line->date_end;
  7663. }
  7664. }
  7665. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'day');
  7666. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  7667. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'day');
  7668. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  7669. }
  7670. // add substition variable for ticket
  7671. if (is_object($object) && $object->element == 'ticket') {
  7672. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  7673. $substitutionarray['__REF__'] = $object->ref;
  7674. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  7675. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  7676. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  7677. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  7678. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  7679. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  7680. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  7681. $userstat = new User($db);
  7682. if ($object->fk_user_assign > 0) {
  7683. $userstat->fetch($object->fk_user_assign);
  7684. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7685. }
  7686. if ($object->fk_user_create > 0) {
  7687. $userstat->fetch($object->fk_user_create);
  7688. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7689. }
  7690. }
  7691. // Create dynamic tags for __EXTRAFIELD_FIELD__
  7692. if ($object->table_element && $object->id > 0) {
  7693. if (!is_object($extrafields)) {
  7694. $extrafields = new ExtraFields($db);
  7695. }
  7696. $extrafields->fetch_name_optionals_label($object->table_element, true);
  7697. if ($object->fetch_optionals() > 0) {
  7698. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  7699. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  7700. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  7701. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  7702. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  7703. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  7704. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  7705. $datetime = $object->array_options['options_'.$key];
  7706. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  7707. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  7708. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  7709. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  7710. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  7711. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  7712. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  7713. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7714. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  7715. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
  7716. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = !empty($object->array_options['options_'.$key]) ? $object->array_options['options_'.$key] : '';
  7717. }
  7718. }
  7719. }
  7720. }
  7721. }
  7722. // Complete substitution array with the url to make online payment
  7723. $paymenturl = '';
  7724. if (empty($substitutionarray['__REF__'])) {
  7725. $paymenturl = '';
  7726. } else {
  7727. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  7728. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  7729. $outputlangs->loadLangs(array('paypal', 'other'));
  7730. $amounttouse = 0;
  7731. $typeforonlinepayment = 'free';
  7732. if (is_object($object) && $object->element == 'commande') {
  7733. $typeforonlinepayment = 'order';
  7734. }
  7735. if (is_object($object) && $object->element == 'facture') {
  7736. $typeforonlinepayment = 'invoice';
  7737. }
  7738. if (is_object($object) && $object->element == 'member') {
  7739. $typeforonlinepayment = 'member';
  7740. if (!empty($object->last_subscription_amount)) {
  7741. $amounttouse = $object->last_subscription_amount;
  7742. }
  7743. }
  7744. if (is_object($object) && $object->element == 'contrat') {
  7745. $typeforonlinepayment = 'contract';
  7746. }
  7747. if (is_object($object) && $object->element == 'fichinter') {
  7748. $typeforonlinepayment = 'ficheinter';
  7749. }
  7750. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], $amounttouse);
  7751. $paymenturl = $url;
  7752. }
  7753. if ($object->id > 0) {
  7754. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ? str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  7755. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  7756. if (getDolGlobalString('PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'propal') {
  7757. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7758. } else {
  7759. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  7760. }
  7761. if (getDolGlobalString('ORDER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'commande') {
  7762. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  7763. } else {
  7764. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  7765. }
  7766. if (getDolGlobalString('INVOICE_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'facture') {
  7767. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  7768. } else {
  7769. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  7770. }
  7771. if (getDolGlobalString('CONTRACT_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'contrat') {
  7772. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  7773. } else {
  7774. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  7775. }
  7776. if (getDolGlobalString('FICHINTER_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'fichinter') {
  7777. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
  7778. } else {
  7779. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
  7780. }
  7781. if (getDolGlobalString('SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD') && is_object($object) && $object->element == 'supplier_proposal') {
  7782. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7783. } else {
  7784. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  7785. }
  7786. if (is_object($object) && $object->element == 'propal') {
  7787. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  7788. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7789. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  7790. }
  7791. if (is_object($object) && $object->element == 'commande') {
  7792. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  7793. }
  7794. if (is_object($object) && $object->element == 'facture') {
  7795. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  7796. }
  7797. if (is_object($object) && $object->element == 'contrat') {
  7798. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  7799. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7800. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', $object->ref);
  7801. }
  7802. if (is_object($object) && $object->element == 'fichinter') {
  7803. $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT."/fichinter/card.php?id=".$object->id;
  7804. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7805. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', $object->ref);
  7806. }
  7807. if (is_object($object) && $object->element == 'supplier_proposal') {
  7808. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  7809. }
  7810. if (is_object($object) && $object->element == 'shipping') {
  7811. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  7812. }
  7813. }
  7814. if (is_object($object) && $object->element == 'action') {
  7815. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  7816. $substitutionarray['__EVENT_TYPE__'] = $outputlangs->trans("Action".$object->type_code);
  7817. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, 'day', 'auto', $outputlangs);
  7818. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, 'hour', 'auto', $outputlangs);
  7819. }
  7820. }
  7821. }
  7822. if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
  7823. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  7824. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  7825. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  7826. $already_payed_all = 0;
  7827. if (is_object($object) && ($object instanceof Facture)) {
  7828. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  7829. }
  7830. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  7831. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  7832. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  7833. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  7834. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
  7835. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7836. $substitutionarray['__AMOUNT_VAT_TEXT__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, '', true) : dol_convertToWord($object->total_tva, $outputlangs, '', true)) : '';
  7837. $substitutionarray['__AMOUNT_VAT_TEXTCURRENCY__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, $conf->currency, true) : dol_convertToWord($object->total_tva, $outputlangs, $conf->currency, true)) : '';
  7838. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7839. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  7840. }
  7841. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7842. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  7843. }
  7844. // Amount keys formated in a currency
  7845. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7846. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7847. $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc - $already_payed_all, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7848. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? (isset($object->total_vat) ? price($object->total_vat, 0, $outputlangs, 0, -1, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, -1, -1, $conf->currency) : null)) : '';
  7849. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7850. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7851. }
  7852. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7853. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7854. }
  7855. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  7856. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  7857. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  7858. // TODO Add other keys for foreign multicurrency
  7859. // For backward compatibility
  7860. if ($onlykey != 2) {
  7861. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  7862. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  7863. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7864. }
  7865. }
  7866. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  7867. if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
  7868. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  7869. $now = dol_now();
  7870. $tmp = dol_getdate($now, true);
  7871. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7872. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  7873. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7874. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  7875. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  7876. $substitutionarray = array_merge($substitutionarray, array(
  7877. '__NOW_TMS__' => (string) $now, // Must be the string that represent the int
  7878. '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 'auto', $outputlangs),
  7879. '__DAY__' => (string) $tmp['mday'],
  7880. '__DAY_TEXT__' => $daytext, // Monday
  7881. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  7882. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  7883. '__MONTH__' => (string) $tmp['mon'],
  7884. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  7885. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  7886. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  7887. '__YEAR__' => (string) $tmp['year'],
  7888. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  7889. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  7890. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  7891. '__NEXT_DAY__' => (string) $tmp4['day'],
  7892. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7893. '__NEXT_MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp5['month'])),
  7894. '__NEXT_MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp5['month'])),
  7895. '__NEXT_MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp5['month'])),
  7896. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7897. ));
  7898. }
  7899. if (isModEnabled('multicompany')) {
  7900. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7901. }
  7902. if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
  7903. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7904. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7905. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7906. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7907. }
  7908. // Note: The lazyload variables are replaced only during the call by make_substitutions, and only if necessary
  7909. return $substitutionarray;
  7910. }
  7911. /**
  7912. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7913. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7914. * Example of usage:
  7915. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7916. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7917. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7918. *
  7919. * @param string $text Source string in which we must do substitution
  7920. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7921. * @param Translate $outputlangs Output language
  7922. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7923. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7924. * @return string Output string after substitutions
  7925. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7926. */
  7927. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7928. {
  7929. global $conf, $db, $langs;
  7930. if (!is_array($substitutionarray)) {
  7931. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7932. }
  7933. if (empty($outputlangs)) {
  7934. $outputlangs = $langs;
  7935. }
  7936. // Is initial text HTML or simple text ?
  7937. $msgishtml = 0;
  7938. if (dol_textishtml($text, 1)) {
  7939. $msgishtml = 1;
  7940. }
  7941. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7942. if (is_object($outputlangs)) {
  7943. $reg = array();
  7944. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7945. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7946. $tmp = explode('|', $reg[1]);
  7947. if (!empty($tmp[1])) {
  7948. $outputlangs->load($tmp[1]);
  7949. }
  7950. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7951. if (empty($converttextinhtmlifnecessary)) {
  7952. // convert $newval into HTML is necessary
  7953. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7954. } else {
  7955. if (! $msgishtml) {
  7956. $valueishtml = dol_textishtml($value, 1);
  7957. //var_dump("valueishtml=".$valueishtml);
  7958. if ($valueishtml) {
  7959. $text = dol_htmlentitiesbr($text);
  7960. $msgishtml = 1;
  7961. }
  7962. } else {
  7963. $value = dol_nl2br("$value");
  7964. }
  7965. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7966. }
  7967. }
  7968. }
  7969. // Make substitution for constant keys.
  7970. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7971. $reg = array();
  7972. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7973. $keyfound = $reg[1];
  7974. if (isASecretKey($keyfound)) {
  7975. $value = '*****forbidden*****';
  7976. } else {
  7977. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7978. }
  7979. if (empty($converttextinhtmlifnecessary)) {
  7980. // convert $newval into HTML is necessary
  7981. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7982. } else {
  7983. if (! $msgishtml) {
  7984. $valueishtml = dol_textishtml($value, 1);
  7985. if ($valueishtml) {
  7986. $text = dol_htmlentitiesbr($text);
  7987. $msgishtml = 1;
  7988. }
  7989. } else {
  7990. $value = dol_nl2br("$value");
  7991. }
  7992. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7993. }
  7994. }
  7995. // Make substitution for array $substitutionarray
  7996. foreach ($substitutionarray as $key => $value) {
  7997. if (!isset($value)) {
  7998. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7999. }
  8000. if (($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__') && (getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN'))) {
  8001. $value = ''; // Protection
  8002. }
  8003. if (empty($converttextinhtmlifnecessary)) {
  8004. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  8005. } else {
  8006. if (! $msgishtml) {
  8007. $valueishtml = dol_textishtml($value, 1);
  8008. if ($valueishtml) {
  8009. $text = dol_htmlentitiesbr($text);
  8010. $msgishtml = 1;
  8011. }
  8012. } else {
  8013. $value = dol_nl2br("$value");
  8014. }
  8015. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  8016. }
  8017. }
  8018. // TODO Implement the lazyload substitution
  8019. /*
  8020. add a loop to scan $substitutionarray:
  8021. For each key ending with '@lazyload', we extract the substitution key 'XXX' and we check inside the $text (the 1st parameter of make_substitutions), if the string XXX exists.
  8022. If no, we don't need to make replacement, so we do nothing.
  8023. If yes, we can make the substitution:
  8024. include_once $path;
  8025. $tmpobj = new $class($db);
  8026. $valuetouseforsubstitution = $tmpobj->$method($id, '__XXX__');
  8027. And make the replacement of "__XXX__@lazyload" with $valuetouseforsubstitution
  8028. */
  8029. $memory_object_list = array();
  8030. foreach ($substitutionarray as $key => $value) {
  8031. $lazy_load_arr = array();
  8032. if (preg_match('/(__[A-Z\_]+__)@lazyload$/', $key, $lazy_load_arr)) {
  8033. if (isset($lazy_load_arr[1]) && !empty($lazy_load_arr[1])) {
  8034. $key_to_substitute = $lazy_load_arr[1];
  8035. if (preg_match('/' . preg_quote($key_to_substitute, '/') . '/', $text)) {
  8036. $param_arr = explode(':', $value);
  8037. // path:class:method:id
  8038. if (count($param_arr) == 4) {
  8039. $path = $param_arr[0];
  8040. $class = $param_arr[1];
  8041. $method = $param_arr[2];
  8042. $id = (int) $param_arr[3];
  8043. // load class file and init object list in memory
  8044. if (!isset($memory_object_list[$class])) {
  8045. if (dol_is_file(DOL_DOCUMENT_ROOT . $path)) {
  8046. require_once DOL_DOCUMENT_ROOT . $path;
  8047. if (class_exists($class)) {
  8048. $memory_object_list[$class] = array(
  8049. 'list' => array(),
  8050. );
  8051. }
  8052. }
  8053. }
  8054. // fetch object and set substitution
  8055. if (isset($memory_object_list[$class]) && isset($memory_object_list[$class]['list'])) {
  8056. if (method_exists($class, $method)) {
  8057. if (!isset($memory_object_list[$class]['list'][$id])) {
  8058. $tmpobj = new $class($db);
  8059. $valuetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute);
  8060. $memory_object_list[$class]['list'][$id] = $tmpobj;
  8061. } else {
  8062. $tmpobj = $memory_object_list[$class]['list'][$id];
  8063. $valuetouseforsubstitution = $tmpobj->$method($id, $key_to_substitute, true);
  8064. }
  8065. $text = str_replace("$key_to_substitute", "$valuetouseforsubstitution", $text); // We must keep the " to work when value is 123.5 for example
  8066. }
  8067. }
  8068. }
  8069. }
  8070. }
  8071. }
  8072. }
  8073. return $text;
  8074. }
  8075. /**
  8076. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  8077. * In this case, method completesubstitutionarray provided by module is called.
  8078. *
  8079. * @param array $substitutionarray Array substitution old value => new value value
  8080. * @param Translate $outputlangs Output language
  8081. * @param Object $object Source object
  8082. * @param mixed $parameters Add more parameters (useful to pass product lines)
  8083. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  8084. * @return void
  8085. * @see make_substitutions()
  8086. */
  8087. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  8088. {
  8089. global $conf, $user;
  8090. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  8091. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  8092. // Check if there is external substitution to do, requested by plugins
  8093. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  8094. foreach ($dirsubstitutions as $reldir) {
  8095. $dir = dol_buildpath($reldir, 0);
  8096. // Check if directory exists
  8097. if (!dol_is_dir($dir)) {
  8098. continue;
  8099. }
  8100. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  8101. foreach ($substitfiles as $substitfile) {
  8102. $reg = array();
  8103. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  8104. $module = $reg[1];
  8105. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  8106. // Include the user's functions file
  8107. require_once $dir.$substitfile['name'];
  8108. // Call the user's function, and only if it is defined
  8109. $function_name = $module."_".$callfunc;
  8110. if (function_exists($function_name)) {
  8111. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  8112. }
  8113. }
  8114. }
  8115. }
  8116. if (getDolGlobalString('ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS')) {
  8117. // to list all tags in odt template
  8118. $tags = '';
  8119. foreach ($substitutionarray as $key => $value) {
  8120. $tags .= '{'.$key.'} => '.$value."\n";
  8121. }
  8122. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  8123. }
  8124. }
  8125. /**
  8126. * Format output for start and end date
  8127. *
  8128. * @param int $date_start Start date
  8129. * @param int $date_end End date
  8130. * @param string $format Output format
  8131. * @param Translate $outputlangs Output language
  8132. * @return void
  8133. */
  8134. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  8135. {
  8136. print get_date_range($date_start, $date_end, $format, $outputlangs);
  8137. }
  8138. /**
  8139. * Format output for start and end date
  8140. *
  8141. * @param int $date_start Start date
  8142. * @param int $date_end End date
  8143. * @param string $format Output date format ('day', 'dayhour', ...)
  8144. * @param Translate $outputlangs Output language
  8145. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  8146. * @return string String
  8147. */
  8148. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  8149. {
  8150. global $langs;
  8151. $out = '';
  8152. if (!is_object($outputlangs)) {
  8153. $outputlangs = $langs;
  8154. }
  8155. if ($date_start && $date_end) {
  8156. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  8157. }
  8158. if ($date_start && !$date_end) {
  8159. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  8160. }
  8161. if (!$date_start && $date_end) {
  8162. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  8163. }
  8164. return $out;
  8165. }
  8166. /**
  8167. * Return firstname and lastname in correct order
  8168. *
  8169. * @param string $firstname Firstname
  8170. * @param string $lastname Lastname
  8171. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  8172. * @return string Firstname + lastname or Lastname + firstname
  8173. */
  8174. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  8175. {
  8176. global $conf;
  8177. $ret = '';
  8178. // If order not defined, we use the setup
  8179. if ($nameorder < 0) {
  8180. $nameorder = (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION') ? 1 : 0);
  8181. }
  8182. if ($nameorder == 1) {
  8183. $ret .= $firstname;
  8184. if ($firstname && $lastname) {
  8185. $ret .= ' ';
  8186. }
  8187. $ret .= $lastname;
  8188. } elseif ($nameorder == 2 || $nameorder == 3) {
  8189. $ret .= $firstname;
  8190. if (empty($ret) && $nameorder == 3) {
  8191. $ret .= $lastname;
  8192. }
  8193. } else { // 0, 4 or 5
  8194. $ret .= $lastname;
  8195. if (empty($ret) && $nameorder == 5) {
  8196. $ret .= $firstname;
  8197. }
  8198. if ($nameorder == 0) {
  8199. if ($firstname && $lastname) {
  8200. $ret .= ' ';
  8201. }
  8202. $ret .= $firstname;
  8203. }
  8204. }
  8205. return $ret;
  8206. }
  8207. /**
  8208. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  8209. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  8210. * Note: Prefer to use setEventMessages instead.
  8211. *
  8212. * @param string|string[] $mesgs Message string or array
  8213. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  8214. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  8215. * @return void
  8216. * @see dol_htmloutput_events()
  8217. */
  8218. function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0)
  8219. {
  8220. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  8221. if (!is_array($mesgs)) {
  8222. $mesgs = trim((string) $mesgs);
  8223. // If mesgs is a not an empty string
  8224. if ($mesgs) {
  8225. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
  8226. return;
  8227. }
  8228. $_SESSION['dol_events'][$style][] = $mesgs;
  8229. }
  8230. } else {
  8231. // If mesgs is an array
  8232. foreach ($mesgs as $mesg) {
  8233. $mesg = trim((string) $mesg);
  8234. if ($mesg) {
  8235. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
  8236. return;
  8237. }
  8238. $_SESSION['dol_events'][$style][] = $mesg;
  8239. }
  8240. }
  8241. }
  8242. }
  8243. /**
  8244. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  8245. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  8246. *
  8247. * @param string $mesg Message string
  8248. * @param array|null $mesgs Message array
  8249. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  8250. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  8251. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  8252. * @return void
  8253. * @see dol_htmloutput_events()
  8254. */
  8255. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0)
  8256. {
  8257. if (empty($mesg) && empty($mesgs)) {
  8258. dol_syslog("Try to add a message in stack, but value to add is empty message", LOG_WARNING);
  8259. } else {
  8260. if ($messagekey) {
  8261. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  8262. // TODO
  8263. $mesg .= '';
  8264. }
  8265. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  8266. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  8267. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  8268. }
  8269. if (empty($mesgs)) {
  8270. setEventMessage($mesg, $style, $noduplicate);
  8271. } else {
  8272. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  8273. setEventMessage($mesg, $style, $noduplicate); // Add message string if not already into array
  8274. }
  8275. setEventMessage($mesgs, $style, $noduplicate);
  8276. }
  8277. }
  8278. }
  8279. }
  8280. /**
  8281. * Print formated messages to output (Used to show messages on html output).
  8282. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  8283. * no need to call it explicitely.
  8284. *
  8285. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  8286. * @return void
  8287. * @see dol_htmloutput_mesg()
  8288. */
  8289. function dol_htmloutput_events($disabledoutputofmessages = 0)
  8290. {
  8291. // Show mesgs
  8292. if (isset($_SESSION['dol_events']['mesgs'])) {
  8293. if (empty($disabledoutputofmessages)) {
  8294. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  8295. }
  8296. unset($_SESSION['dol_events']['mesgs']);
  8297. }
  8298. // Show errors
  8299. if (isset($_SESSION['dol_events']['errors'])) {
  8300. if (empty($disabledoutputofmessages)) {
  8301. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  8302. }
  8303. unset($_SESSION['dol_events']['errors']);
  8304. }
  8305. // Show warnings
  8306. if (isset($_SESSION['dol_events']['warnings'])) {
  8307. if (empty($disabledoutputofmessages)) {
  8308. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  8309. }
  8310. unset($_SESSION['dol_events']['warnings']);
  8311. }
  8312. }
  8313. /**
  8314. * Get formated messages to output (Used to show messages on html output).
  8315. * This include also the translation of the message key.
  8316. *
  8317. * @param string $mesgstring Message string or message key
  8318. * @param string[] $mesgarray Array of message strings or message keys
  8319. * @param string $style Style of message output ('ok' or 'error')
  8320. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8321. * @return string Return html output
  8322. *
  8323. * @see dol_print_error()
  8324. * @see dol_htmloutput_errors()
  8325. * @see setEventMessages()
  8326. */
  8327. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  8328. {
  8329. global $conf, $langs;
  8330. $ret = 0;
  8331. $return = '';
  8332. $out = '';
  8333. $divstart = $divend = '';
  8334. // If inline message with no format, we add it.
  8335. if ((empty($conf->use_javascript_ajax) || getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  8336. $divstart = '<div class="'.$style.' clearboth">';
  8337. $divend = '</div>';
  8338. }
  8339. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  8340. $langs->load("errors");
  8341. $out .= $divstart;
  8342. if (is_array($mesgarray) && count($mesgarray)) {
  8343. foreach ($mesgarray as $message) {
  8344. $ret++;
  8345. $out .= $langs->trans($message);
  8346. if ($ret < count($mesgarray)) {
  8347. $out .= "<br>\n";
  8348. }
  8349. }
  8350. }
  8351. if ($mesgstring) {
  8352. $ret++;
  8353. $out .= $langs->trans($mesgstring);
  8354. }
  8355. $out .= $divend;
  8356. }
  8357. if ($out) {
  8358. if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') && empty($keepembedded)) {
  8359. $return = '<script nonce="'.getNonce().'">
  8360. $(document).ready(function() {
  8361. var block = '.(getDolGlobalString('MAIN_USE_JQUERY_BLOCKUI') ? "true" : "false").'
  8362. if (block) {
  8363. $.dolEventValid("","'.dol_escape_js($out).'");
  8364. } else {
  8365. /* jnotify(message, preset of message type, keepmessage) */
  8366. $.jnotify("'.dol_escape_js($out).'",
  8367. "'.($style == "ok" ? 3000 : $style).'",
  8368. '.($style == "ok" ? "false" : "true").',
  8369. { remove: function (){} } );
  8370. }
  8371. });
  8372. </script>';
  8373. } else {
  8374. $return = $out;
  8375. }
  8376. }
  8377. return $return;
  8378. }
  8379. /**
  8380. * Get formated error messages to output (Used to show messages on html output).
  8381. *
  8382. * @param string $mesgstring Error message
  8383. * @param array $mesgarray Error messages array
  8384. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8385. * @return string Return html output
  8386. *
  8387. * @see dol_print_error()
  8388. * @see dol_htmloutput_mesg()
  8389. */
  8390. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8391. {
  8392. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8393. }
  8394. /**
  8395. * Print formated messages to output (Used to show messages on html output).
  8396. *
  8397. * @param string $mesgstring Message string or message key
  8398. * @param string[] $mesgarray Array of message strings or message keys
  8399. * @param string $style Which style to use ('ok', 'warning', 'error')
  8400. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  8401. * @return void
  8402. *
  8403. * @see dol_print_error()
  8404. * @see dol_htmloutput_errors()
  8405. * @see setEventMessages()
  8406. */
  8407. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  8408. {
  8409. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  8410. return;
  8411. }
  8412. $iserror = 0;
  8413. $iswarning = 0;
  8414. if (is_array($mesgarray)) {
  8415. foreach ($mesgarray as $val) {
  8416. if ($val && preg_match('/class="error"/i', $val)) {
  8417. $iserror++;
  8418. break;
  8419. }
  8420. if ($val && preg_match('/class="warning"/i', $val)) {
  8421. $iswarning++;
  8422. break;
  8423. }
  8424. }
  8425. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  8426. $iserror++;
  8427. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  8428. $iswarning++;
  8429. }
  8430. if ($style == 'error') {
  8431. $iserror++;
  8432. }
  8433. if ($style == 'warning') {
  8434. $iswarning++;
  8435. }
  8436. if ($iserror || $iswarning) {
  8437. // Remove div from texts
  8438. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  8439. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  8440. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  8441. // Remove div from texts array
  8442. if (is_array($mesgarray)) {
  8443. $newmesgarray = array();
  8444. foreach ($mesgarray as $val) {
  8445. if (is_string($val)) {
  8446. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  8447. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  8448. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  8449. $newmesgarray[] = $tmpmesgstring;
  8450. } else {
  8451. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  8452. }
  8453. }
  8454. $mesgarray = $newmesgarray;
  8455. }
  8456. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  8457. } else {
  8458. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  8459. }
  8460. }
  8461. /**
  8462. * Print formated error messages to output (Used to show messages on html output).
  8463. *
  8464. * @param string $mesgstring Error message
  8465. * @param array $mesgarray Error messages array
  8466. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8467. * @return void
  8468. *
  8469. * @see dol_print_error()
  8470. * @see dol_htmloutput_mesg()
  8471. */
  8472. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8473. {
  8474. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8475. }
  8476. /**
  8477. * Advanced sort array by second index function, which produces ascending (default)
  8478. * or descending output and uses optionally natural case insensitive sorting (which
  8479. * can be optionally case sensitive as well).
  8480. *
  8481. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  8482. * @param string $index Key in array to use for sorting criteria
  8483. * @param int $order Sort order ('asc' or 'desc')
  8484. * @param int $natsort If values are strings (I said value not type): 0=Use alphabetical order, 1=use "natural" sort (natsort)
  8485. * If values are numeric (I said value not type): 0=Use numeric order (even if type is string) so use a "natural" sort, 1=use "natural" sort too (same than 0), -1=Force alphabetical order
  8486. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  8487. * @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.
  8488. * @return array Sorted array
  8489. */
  8490. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  8491. {
  8492. // Clean parameters
  8493. $order = strtolower($order);
  8494. if (is_array($array)) {
  8495. $sizearray = count($array);
  8496. if ($sizearray > 0) {
  8497. $temp = array();
  8498. foreach (array_keys($array) as $key) {
  8499. if (is_object($array[$key])) {
  8500. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  8501. } else {
  8502. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  8503. }
  8504. if ($natsort == -1) {
  8505. $temp[$key] = '___'.$temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
  8506. }
  8507. }
  8508. if (empty($natsort) || $natsort == -1) {
  8509. if ($order == 'asc') {
  8510. asort($temp);
  8511. } else {
  8512. arsort($temp);
  8513. }
  8514. } else {
  8515. if ($case_sensitive) {
  8516. natsort($temp);
  8517. } else {
  8518. natcasesort($temp); // natecasesort is not sensible to case
  8519. }
  8520. if ($order != 'asc') {
  8521. $temp = array_reverse($temp, true);
  8522. }
  8523. }
  8524. $sorted = array();
  8525. foreach (array_keys($temp) as $key) {
  8526. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  8527. }
  8528. return $sorted;
  8529. }
  8530. }
  8531. return $array;
  8532. }
  8533. /**
  8534. * Check if a string is in UTF8. Seems similar to utf8_valid() but in pure PHP.
  8535. *
  8536. * @param string $str String to check
  8537. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special non utf8 char or Binary)
  8538. * @see utf8_valid()
  8539. */
  8540. function utf8_check($str)
  8541. {
  8542. $str = (string) $str; // Sometimes string is an int.
  8543. // We must use here a binary strlen function (so not dol_strlen)
  8544. $strLength = strlen($str);
  8545. for ($i = 0; $i < $strLength; $i++) {
  8546. if (ord($str[$i]) < 0x80) {
  8547. continue; // 0bbbbbbb
  8548. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  8549. $n = 1; // 110bbbbb
  8550. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  8551. $n = 2; // 1110bbbb
  8552. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  8553. $n = 3; // 11110bbb
  8554. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  8555. $n = 4; // 111110bb
  8556. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  8557. $n = 5; // 1111110b
  8558. } else {
  8559. return false; // Does not match any model
  8560. }
  8561. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  8562. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  8563. return false;
  8564. }
  8565. }
  8566. }
  8567. return true;
  8568. }
  8569. /**
  8570. * Check if a string is in UTF8. Seems similar to utf8_check().
  8571. *
  8572. * @param string $str String to check
  8573. * @return boolean True if string is valid UTF8 string, false if corrupted
  8574. * @see utf8_check()
  8575. */
  8576. function utf8_valid($str)
  8577. {
  8578. /* 2 other methods to test if string is utf8
  8579. $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
  8580. $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
  8581. */
  8582. return preg_match('//u', $str) ? true : false;
  8583. }
  8584. /**
  8585. * Check if a string is in ASCII
  8586. *
  8587. * @param string $str String to check
  8588. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  8589. */
  8590. function ascii_check($str)
  8591. {
  8592. if (function_exists('mb_check_encoding')) {
  8593. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  8594. if (!mb_check_encoding($str, 'ASCII')) {
  8595. return false;
  8596. }
  8597. } else {
  8598. if (preg_match('/[^\x00-\x7f]/', $str)) {
  8599. return false; // Contains a byte > 7f
  8600. }
  8601. }
  8602. return true;
  8603. }
  8604. /**
  8605. * Return a string encoded into OS filesystem encoding. This function is used to define
  8606. * value to pass to filesystem PHP functions.
  8607. *
  8608. * @param string $str String to encode (UTF-8)
  8609. * @return string Encoded string (UTF-8, ISO-8859-1)
  8610. */
  8611. function dol_osencode($str)
  8612. {
  8613. global $conf;
  8614. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  8615. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  8616. $tmp = 'iso-8859-1'; // By default for windows
  8617. }
  8618. if (empty($tmp)) {
  8619. $tmp = 'utf-8'; // By default for other
  8620. }
  8621. if (getDolGlobalString('MAIN_FILESYSTEM_ENCODING')) {
  8622. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  8623. }
  8624. if ($tmp == 'iso-8859-1') {
  8625. return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
  8626. }
  8627. return $str;
  8628. }
  8629. /**
  8630. * Return an id or code from a code or id.
  8631. * Store also Code-Id into a cache to speed up next request on same key.
  8632. *
  8633. * @param DoliDB $db Database handler
  8634. * @param string $key Code or Id to get Id or Code
  8635. * @param string $tablename Table name without prefix
  8636. * @param string $fieldkey Field to search the key into
  8637. * @param string $fieldid Field to get
  8638. * @param int $entityfilter Filter by entity
  8639. * @param string $filters Filters to add. WARNING: string must be escaped for SQL and not coming from user input.
  8640. * @return int Return integer <0 if KO, Id of code if OK
  8641. * @see $langs->getLabelFromKey
  8642. */
  8643. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '')
  8644. {
  8645. global $cache_codes;
  8646. // If key empty
  8647. if ($key == '') {
  8648. return '';
  8649. }
  8650. // Check in cache
  8651. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  8652. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  8653. }
  8654. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  8655. $sql = "SELECT ".$fieldid." as valuetoget";
  8656. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  8657. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  8658. if (!empty($entityfilter)) {
  8659. $sql .= " AND entity IN (".getEntity($tablename).")";
  8660. }
  8661. if ($filters) {
  8662. $sql .= $filters;
  8663. }
  8664. $resql = $db->query($sql);
  8665. if ($resql) {
  8666. $obj = $db->fetch_object($resql);
  8667. if ($obj) {
  8668. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  8669. } else {
  8670. $cache_codes[$tablename][$key][$fieldid] = '';
  8671. }
  8672. $db->free($resql);
  8673. return $cache_codes[$tablename][$key][$fieldid];
  8674. } else {
  8675. return -1;
  8676. }
  8677. }
  8678. /**
  8679. * Check if a variable with name $var start with $text.
  8680. * Can be used to forge dol_eval() conditions.
  8681. *
  8682. * @param $var string Variable
  8683. * @param $regextext string Text that must be a valid regex string
  8684. * @param $matchrule int 1=Test if start with, 0=Test if equal
  8685. * @return boolean|string True or False, text if bad use.
  8686. */
  8687. function isStringVarMatching($var, $regextext, $matchrule = 1)
  8688. {
  8689. if ($matchrule == 1) {
  8690. if ($var == 'mainmenu') {
  8691. global $mainmenu;
  8692. return (preg_match('/^'.$regextext.'/', $mainmenu));
  8693. } elseif ($var == 'leftmenu') {
  8694. global $leftmenu;
  8695. return (preg_match('/^'.$regextext.'/', $leftmenu));
  8696. } else {
  8697. return 'This variable is not accessible with dol_eval';
  8698. }
  8699. } else {
  8700. return 'This value for matchrule is not implemented';
  8701. }
  8702. }
  8703. /**
  8704. * Verify if condition in string is ok or not
  8705. *
  8706. * @param string $strToEvaluate String with condition to check
  8707. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  8708. */
  8709. function verifCond($strToEvaluate)
  8710. {
  8711. //print $strToEvaluate."<br>\n";
  8712. $rights = true;
  8713. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  8714. //var_dump($strToEvaluate);
  8715. //$rep = dol_eval($strToEvaluate, 1, 0, '1'); // to show the error
  8716. $rep = dol_eval($strToEvaluate, 1, 1, '1'); // The dol_eval() must contains all the "global $xxx;" for all variables $xxx found into the string condition
  8717. $rights = $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
  8718. //var_dump($rights);
  8719. }
  8720. return $rights;
  8721. }
  8722. /**
  8723. * Replace eval function to add more security.
  8724. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  8725. *
  8726. * @param string $s String to evaluate
  8727. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  8728. * @param int $hideerrors 1=Hide errors
  8729. * @param string $onlysimplestring '0' (deprecated, used for computed property of extrafields)=Accept all chars,
  8730. * '1' (most common use)=Accept only simple string with char 'a-z0-9\s^$_+-.*>&|=!?():"\',/@';',
  8731. * '2' (rarely used)=Accept also '[]'
  8732. * @return mixed Nothing or return result of eval
  8733. * @see verifCond()
  8734. */
  8735. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  8736. {
  8737. // Only this global variables can be read by eval function and returned to caller
  8738. global $conf; // Read of const is done with getDolGlobalString() but we need $conf->currency for example
  8739. global $db, $langs, $user, $website, $websitepage;
  8740. global $action, $mainmenu, $leftmenu;
  8741. global $mysoc;
  8742. global $objectoffield; // To allow the use of $objectoffield in computed fields
  8743. // Old variables used
  8744. global $object;
  8745. global $obj; // To get $obj used into list when dol_eval() is used for computed fields and $obj is not yet $object
  8746. if (!in_array($onlysimplestring, array('0', '1', '2'))) {
  8747. return "Bad call of dol_eval. Parameter onlysimplestring must be '0' (deprecated), '1' or '2'";
  8748. }
  8749. try {
  8750. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  8751. if ($onlysimplestring == '1') {
  8752. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && getDolGlobalString("MAIN_FEATURES_LEVEL")'
  8753. // We must accept: '$user->hasRight("cabinetmed", "read") && !$object->canvas=="patient@cabinetmed"'
  8754. $specialcharsallowed = '^$_+-.*>&|=!?():"\',/@';
  8755. if (getDolGlobalString('MAIN_ALLOW_UNSECURED_SPECIAL_CHARS_IN_DOL_EVAL')) {
  8756. $specialcharsallowed .= getDolGlobalString('MAIN_ALLOW_UNSECURED_SPECIAL_CHARS_IN_DOL_EVAL');
  8757. }
  8758. if (preg_match('/[^a-z0-9\s'.preg_quote($specialcharsallowed, '/').']/i', $s)) {
  8759. if ($returnvalue) {
  8760. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8761. } else {
  8762. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8763. return '';
  8764. }
  8765. }
  8766. $savescheck = '';
  8767. $scheck = $s;
  8768. while ($scheck && $savescheck != $scheck) {
  8769. $savescheck = $scheck;
  8770. $scheck = preg_replace('/->[a-zA-Z0-9_]+\(/', '->__METHOD__', $scheck); // accept parenthesis in '...->method(...'
  8771. $scheck = preg_replace('/^\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8772. $scheck = preg_replace('/\s\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '... ('. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8773. $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\(/', '__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
  8774. $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\(/', '__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
  8775. $scheck = preg_replace('/(\^|\')\(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
  8776. }
  8777. //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
  8778. if (strpos($scheck, '(') !== false) {
  8779. if ($returnvalue) {
  8780. return 'Bad string syntax to evaluate (mode 1, found call of a function or method without using the direct name of the function): '.$s;
  8781. } else {
  8782. dol_syslog('Bad string syntax to evaluate (mode 1, found call of a function or method without using the direct name of the function): '.$s);
  8783. return '';
  8784. }
  8785. }
  8786. // TODO
  8787. // We can exclude $ char that are not: $db, $langs, $leftmenu, $topmenu, $user, $langs, $objectoffield, $object...,
  8788. } elseif ($onlysimplestring == '2') {
  8789. // We must accept: (($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"
  8790. $specialcharsallowed = '^$_+-.*>&|=!?():"\',/@[]';
  8791. if (getDolGlobalString('MAIN_ALLOW_UNSECURED_SPECIAL_CHARS_IN_DOL_EVAL')) {
  8792. $specialcharsallowed .= getDolGlobalString('MAIN_ALLOW_UNSECURED_SPECIAL_CHARS_IN_DOL_EVAL');
  8793. }
  8794. if (preg_match('/[^a-z0-9\s'.preg_quote($specialcharsallowed, '/').']/i', $s)) {
  8795. if ($returnvalue) {
  8796. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8797. } else {
  8798. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8799. return '';
  8800. }
  8801. }
  8802. $savescheck = '';
  8803. $scheck = $s;
  8804. while ($scheck && $savescheck != $scheck) {
  8805. $savescheck = $scheck;
  8806. $scheck = preg_replace('/->[a-zA-Z0-9_]+\(/', '->__METHOD__', $scheck); // accept parenthesis in '...->method(...'
  8807. $scheck = preg_replace('/^\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '(...'. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8808. $scheck = preg_replace('/\s\(/', '__PARENTHESIS__ ', $scheck); // accept parenthesis in '... ('. Must replace with __PARENTHESIS__ with a space after to allow following substitutions
  8809. $scheck = preg_replace('/^!?[a-zA-Z0-9_]+\(/', '__FUNCTION__', $scheck); // accept parenthesis in 'function(' and '!function('
  8810. $scheck = preg_replace('/\s!?[a-zA-Z0-9_]+\(/', '__FUNCTION__', $scheck); // accept parenthesis in '... function(' and '... !function('
  8811. $scheck = preg_replace('/(\^|\')\(/', '__REGEXSTART__', $scheck); // To allow preg_match('/^(aaa|bbb)/'... or isStringVarMatching('leftmenu', '(aaa|bbb)')
  8812. }
  8813. //print 'scheck='.$scheck." : ".strpos($scheck, '(')."<br>\n";
  8814. if (strpos($scheck, '(') !== false) {
  8815. if ($returnvalue) {
  8816. return 'Bad string syntax to evaluate (mode 2, found call of a function or method without using the direct name of the function): '.$s;
  8817. } else {
  8818. dol_syslog('Bad string syntax to evaluate (mode 2, found call of a function or method without using the direct name of the function): '.$s);
  8819. return '';
  8820. }
  8821. }
  8822. // TODO
  8823. // We can exclude $ char that are not: $db, $leftmenu, $topmenu, $user, $langs, $object...,
  8824. }
  8825. if (is_array($s) || $s === 'Array') {
  8826. return 'Bad string syntax to evaluate (value is Array) '.var_export($s, true);
  8827. }
  8828. if (strpos($s, '::') !== false) {
  8829. if ($returnvalue) {
  8830. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  8831. } else {
  8832. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  8833. return '';
  8834. }
  8835. }
  8836. if (strpos($s, '`') !== false) {
  8837. if ($returnvalue) {
  8838. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  8839. } else {
  8840. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  8841. return '';
  8842. }
  8843. }
  8844. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  8845. if ($returnvalue) {
  8846. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  8847. } else {
  8848. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  8849. return '';
  8850. }
  8851. }
  8852. // We block use of php exec or php file functions
  8853. $forbiddenphpstrings = array('$$');
  8854. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST', 'ReflectionFunction'));
  8855. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen");
  8856. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("dol_eval", "executeCLI", "verifCond")); // native dolibarr functions
  8857. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("base64_decode", "rawurldecode", "urldecode", "str_rot13", "hex2bin")); // decode string functions used to obfuscated function name
  8858. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  8859. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("get_defined_functions", "get_defined_vars", "get_defined_constants", "get_declared_classes"));
  8860. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  8861. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("require", "include", "require_once", "include_once"));
  8862. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("eval", "create_function", "assert", "mb_ereg_replace")); // function with eval capabilities
  8863. $forbiddenphpmethods = array('invoke', 'invokeArgs'); // Method of ReflectionFunction to execute a function
  8864. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  8865. $forbiddenphpmethodsregex = '->('.implode('|', $forbiddenphpmethods).')';
  8866. do {
  8867. $oldstringtoclean = $s;
  8868. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  8869. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  8870. $s = preg_replace('/'.$forbiddenphpmethodsregex.'/i', '__forbiddenstring__', $s);
  8871. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  8872. } while ($oldstringtoclean != $s);
  8873. if (strpos($s, '__forbiddenstring__') !== false) {
  8874. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  8875. if ($returnvalue) {
  8876. return 'Bad string syntax to evaluate: '.$s;
  8877. } else {
  8878. dol_syslog('Bad string syntax to evaluate: '.$s);
  8879. return '';
  8880. }
  8881. }
  8882. //print $s."<br>\n";
  8883. if ($returnvalue) {
  8884. if ($hideerrors) {
  8885. return @eval('return '.$s.';');
  8886. } else {
  8887. return eval('return '.$s.';');
  8888. }
  8889. } else {
  8890. if ($hideerrors) {
  8891. @eval($s);
  8892. } else {
  8893. eval($s);
  8894. }
  8895. }
  8896. } catch (Error $e) {
  8897. $error = 'dol_eval try/catch error : ';
  8898. $error .= $e->getMessage();
  8899. dol_syslog($error, LOG_WARNING);
  8900. }
  8901. }
  8902. /**
  8903. * Return if var element is ok
  8904. *
  8905. * @param string $element Variable to check
  8906. * @return boolean Return true of variable is not empty
  8907. * @see getElementProperties()
  8908. */
  8909. function dol_validElement($element)
  8910. {
  8911. return (trim($element) != '');
  8912. }
  8913. /**
  8914. * Return img flag of country for a language code or country code.
  8915. *
  8916. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  8917. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  8918. * @param int $notitlealt No title alt
  8919. * @return string HTML img string with flag.
  8920. */
  8921. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  8922. {
  8923. if (empty($codelang)) {
  8924. return '';
  8925. }
  8926. if ($codelang == 'auto') {
  8927. return '<span class="fa fa-language"></span>';
  8928. }
  8929. $langtocountryflag = array(
  8930. 'ar_AR' => '',
  8931. 'ca_ES' => 'catalonia',
  8932. 'da_DA' => 'dk',
  8933. 'fr_CA' => 'mq',
  8934. 'sv_SV' => 'se',
  8935. 'sw_SW' => 'unknown',
  8936. 'AQ' => 'unknown',
  8937. 'CW' => 'unknown',
  8938. 'IM' => 'unknown',
  8939. 'JE' => 'unknown',
  8940. 'MF' => 'unknown',
  8941. 'BL' => 'unknown',
  8942. 'SX' => 'unknown'
  8943. );
  8944. if (isset($langtocountryflag[$codelang])) {
  8945. $flagImage = $langtocountryflag[$codelang];
  8946. } else {
  8947. $tmparray = explode('_', $codelang);
  8948. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  8949. }
  8950. $morecss = '';
  8951. $reg = array();
  8952. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  8953. $morecss = $reg[1];
  8954. $moreatt = "";
  8955. }
  8956. // return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  8957. return '<span class="flag-sprite '.strtolower($flagImage).($morecss ? ' '.$morecss : '').'"'.($moreatt ? ' '.$moreatt : '').(!$notitlealt ? ' title="'.$codelang.'"' : '').'></span>';
  8958. }
  8959. /**
  8960. * Return default language from country code.
  8961. * Return null if not found.
  8962. *
  8963. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  8964. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  8965. */
  8966. function getLanguageCodeFromCountryCode($countrycode)
  8967. {
  8968. global $mysoc;
  8969. if (empty($countrycode)) {
  8970. return null;
  8971. }
  8972. if (strtoupper($countrycode) == 'MQ') {
  8973. return 'fr_CA';
  8974. }
  8975. if (strtoupper($countrycode) == 'SE') {
  8976. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  8977. }
  8978. if (strtoupper($countrycode) == 'CH') {
  8979. if ($mysoc->country_code == 'FR') {
  8980. return 'fr_CH';
  8981. }
  8982. if ($mysoc->country_code == 'DE') {
  8983. return 'de_CH';
  8984. }
  8985. if ($mysoc->country_code == 'IT') {
  8986. return 'it_CH';
  8987. }
  8988. }
  8989. // Locale list taken from:
  8990. // http://stackoverflow.com/questions/3191664/
  8991. // list-of-all-locales-and-their-short-codes
  8992. $locales = array(
  8993. 'af-ZA',
  8994. 'am-ET',
  8995. 'ar-AE',
  8996. 'ar-BH',
  8997. 'ar-DZ',
  8998. 'ar-EG',
  8999. 'ar-IQ',
  9000. 'ar-JO',
  9001. 'ar-KW',
  9002. 'ar-LB',
  9003. 'ar-LY',
  9004. 'ar-MA',
  9005. 'ar-OM',
  9006. 'ar-QA',
  9007. 'ar-SA',
  9008. 'ar-SY',
  9009. 'ar-TN',
  9010. 'ar-YE',
  9011. //'as-IN', // Moved after en-IN
  9012. 'ba-RU',
  9013. 'be-BY',
  9014. 'bg-BG',
  9015. 'bn-BD',
  9016. //'bn-IN', // Moved after en-IN
  9017. 'bo-CN',
  9018. 'br-FR',
  9019. 'ca-ES',
  9020. 'co-FR',
  9021. 'cs-CZ',
  9022. 'cy-GB',
  9023. 'da-DK',
  9024. 'de-AT',
  9025. 'de-CH',
  9026. 'de-DE',
  9027. 'de-LI',
  9028. 'de-LU',
  9029. 'dv-MV',
  9030. 'el-GR',
  9031. 'en-AU',
  9032. 'en-BZ',
  9033. 'en-CA',
  9034. 'en-GB',
  9035. 'en-IE',
  9036. 'en-IN',
  9037. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  9038. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  9039. 'en-JM',
  9040. 'en-MY',
  9041. 'en-NZ',
  9042. 'en-PH',
  9043. 'en-SG',
  9044. 'en-TT',
  9045. 'en-US',
  9046. 'en-ZA',
  9047. 'en-ZW',
  9048. 'es-AR',
  9049. 'es-BO',
  9050. 'es-CL',
  9051. 'es-CO',
  9052. 'es-CR',
  9053. 'es-DO',
  9054. 'es-EC',
  9055. 'es-ES',
  9056. 'es-GT',
  9057. 'es-HN',
  9058. 'es-MX',
  9059. 'es-NI',
  9060. 'es-PA',
  9061. 'es-PE',
  9062. 'es-PR',
  9063. 'es-PY',
  9064. 'es-SV',
  9065. 'es-US',
  9066. 'es-UY',
  9067. 'es-VE',
  9068. 'et-EE',
  9069. 'eu-ES',
  9070. 'fa-IR',
  9071. 'fi-FI',
  9072. 'fo-FO',
  9073. 'fr-BE',
  9074. 'fr-CA',
  9075. 'fr-CH',
  9076. 'fr-FR',
  9077. 'fr-LU',
  9078. 'fr-MC',
  9079. 'fy-NL',
  9080. 'ga-IE',
  9081. 'gd-GB',
  9082. 'gl-ES',
  9083. 'gu-IN',
  9084. 'he-IL',
  9085. 'hi-IN',
  9086. 'hr-BA',
  9087. 'hr-HR',
  9088. 'hu-HU',
  9089. 'hy-AM',
  9090. 'id-ID',
  9091. 'ig-NG',
  9092. 'ii-CN',
  9093. 'is-IS',
  9094. 'it-CH',
  9095. 'it-IT',
  9096. 'ja-JP',
  9097. 'ka-GE',
  9098. 'kk-KZ',
  9099. 'kl-GL',
  9100. 'km-KH',
  9101. 'kn-IN',
  9102. 'ko-KR',
  9103. 'ky-KG',
  9104. 'lb-LU',
  9105. 'lo-LA',
  9106. 'lt-LT',
  9107. 'lv-LV',
  9108. 'mi-NZ',
  9109. 'mk-MK',
  9110. 'ml-IN',
  9111. 'mn-MN',
  9112. 'mr-IN',
  9113. 'ms-BN',
  9114. 'ms-MY',
  9115. 'mt-MT',
  9116. 'nb-NO',
  9117. 'ne-NP',
  9118. 'nl-BE',
  9119. 'nl-NL',
  9120. 'nn-NO',
  9121. 'oc-FR',
  9122. 'or-IN',
  9123. 'pa-IN',
  9124. 'pl-PL',
  9125. 'ps-AF',
  9126. 'pt-BR',
  9127. 'pt-PT',
  9128. 'rm-CH',
  9129. 'ro-MD',
  9130. 'ro-RO',
  9131. 'ru-RU',
  9132. 'rw-RW',
  9133. 'sa-IN',
  9134. 'se-FI',
  9135. 'se-NO',
  9136. 'se-SE',
  9137. 'si-LK',
  9138. 'sk-SK',
  9139. 'sl-SI',
  9140. 'sq-AL',
  9141. 'sv-FI',
  9142. 'sv-SE',
  9143. 'sw-KE',
  9144. 'ta-IN',
  9145. 'te-IN',
  9146. 'th-TH',
  9147. 'tk-TM',
  9148. 'tn-ZA',
  9149. 'tr-TR',
  9150. 'tt-RU',
  9151. 'ug-CN',
  9152. 'uk-UA',
  9153. 'ur-PK',
  9154. 'vi-VN',
  9155. 'wo-SN',
  9156. 'xh-ZA',
  9157. 'yo-NG',
  9158. 'zh-CN',
  9159. 'zh-HK',
  9160. 'zh-MO',
  9161. 'zh-SG',
  9162. 'zh-TW',
  9163. 'zu-ZA',
  9164. );
  9165. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  9166. if (in_array($buildprimarykeytotest, $locales)) {
  9167. return strtolower($countrycode).'_'.strtoupper($countrycode);
  9168. }
  9169. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  9170. foreach ($locales as $locale) {
  9171. $locale_language = locale_get_primary_language($locale);
  9172. $locale_region = locale_get_region($locale);
  9173. if (strtoupper($countrycode) == $locale_region) {
  9174. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  9175. return strtolower($locale_language).'_'.strtoupper($locale_region);
  9176. }
  9177. }
  9178. } else {
  9179. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  9180. }
  9181. return null;
  9182. }
  9183. /**
  9184. * Complete or removed entries into a head array (used to build tabs).
  9185. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  9186. * Or by change using hook completeTabsHead
  9187. *
  9188. * @param Conf $conf Object conf
  9189. * @param Translate $langs Object langs
  9190. * @param object|null $object Object object
  9191. * @param array $head Object head
  9192. * @param int $h New position to fill
  9193. * @param string $type Value for object where objectvalue can be
  9194. * 'thirdparty' to add a tab in third party view
  9195. * 'intervention' to add a tab in intervention view
  9196. * 'supplier_order' to add a tab in purchase order view
  9197. * 'supplier_invoice' to add a tab in purchase invoice view
  9198. * 'invoice' to add a tab in sales invoice view
  9199. * 'order' to add a tab in sales order view
  9200. * 'contract' to add a tabl in contract view
  9201. * 'product' to add a tab in product view
  9202. * 'propal' to add a tab in propal view
  9203. * 'user' to add a tab in user view
  9204. * 'group' to add a tab in group view
  9205. * 'member' to add a tab in fundation member view
  9206. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  9207. * 'ecm' to add a tab for another ecm view
  9208. * 'stock' to add a tab for warehouse view
  9209. * @param string $mode 'add' to complete head, 'remove' to remove entries
  9210. * @param string $filterorigmodule Filter on module origin: 'external' will show only external modules. 'core' only core modules. No filter (default) will add both.
  9211. * @return void
  9212. */
  9213. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
  9214. {
  9215. global $hookmanager, $db;
  9216. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  9217. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  9218. $values = explode(':', $value);
  9219. $reg = array();
  9220. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  9221. $newtab = array();
  9222. $postab = $h;
  9223. // detect if position set in $values[1] ie : +(2)mytab@mymodule (first tab is 0, second is one, ...)
  9224. $str = $values[1];
  9225. $posstart = strpos($str, '(');
  9226. if ($posstart > 0) {
  9227. $posend = strpos($str, ')');
  9228. if ($posstart > 0) {
  9229. $res1 = substr($str, $posstart + 1, $posend - $posstart -1);
  9230. if (is_numeric($res1)) {
  9231. $postab = (int) $res1;
  9232. $values[1] = '+' . substr($str, $posend + 1);
  9233. }
  9234. }
  9235. }
  9236. if (count($values) == 6) {
  9237. // new declaration with permissions:
  9238. // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  9239. // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  9240. if ($values[0] != $type) {
  9241. continue;
  9242. }
  9243. if (verifCond($values[4])) {
  9244. if ($values[3]) {
  9245. if ($filterorigmodule) { // If a filter of module origin has been requested
  9246. if (strpos($values[3], '@')) { // This is an external module
  9247. if ($filterorigmodule != 'external') {
  9248. continue;
  9249. }
  9250. } else { // This looks a core module
  9251. if ($filterorigmodule != 'core') {
  9252. continue;
  9253. }
  9254. }
  9255. }
  9256. $langs->load($values[3]);
  9257. }
  9258. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  9259. // If label is "SUBSTITUION_..."
  9260. $substitutionarray = array();
  9261. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  9262. $label = make_substitutions($reg[1], $substitutionarray);
  9263. } else {
  9264. // If label is "Label,Class,File,Method", we call the method to show content inside the badge
  9265. $labeltemp = explode(',', $values[2]);
  9266. $label = $langs->trans($labeltemp[0]);
  9267. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  9268. dol_include_once($labeltemp[2]);
  9269. $classtoload = $labeltemp[1];
  9270. if (class_exists($classtoload)) {
  9271. $obj = new $classtoload($db);
  9272. $function = $labeltemp[3];
  9273. if ($obj && $function && method_exists($obj, $function)) {
  9274. $nbrec = $obj->$function($object->id, $obj);
  9275. if (!empty($nbrec)) {
  9276. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  9277. }
  9278. }
  9279. }
  9280. }
  9281. }
  9282. $newtab[0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  9283. $newtab[1] = $label;
  9284. $newtab[2] = str_replace('+', '', $values[1]);
  9285. $h++;
  9286. } else {
  9287. continue;
  9288. }
  9289. } elseif (count($values) == 5) { // case deprecated
  9290. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  9291. if ($values[0] != $type) {
  9292. continue;
  9293. }
  9294. if ($values[3]) {
  9295. if ($filterorigmodule) { // If a filter of module origin has been requested
  9296. if (strpos($values[3], '@')) { // This is an external module
  9297. if ($filterorigmodule != 'external') {
  9298. continue;
  9299. }
  9300. } else { // This looks a core module
  9301. if ($filterorigmodule != 'core') {
  9302. continue;
  9303. }
  9304. }
  9305. }
  9306. $langs->load($values[3]);
  9307. }
  9308. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  9309. $substitutionarray = array();
  9310. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  9311. $label = make_substitutions($reg[1], $substitutionarray);
  9312. } else {
  9313. $label = $langs->trans($values[2]);
  9314. }
  9315. $newtab[0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  9316. $newtab[1] = $label;
  9317. $newtab[2] = str_replace('+', '', $values[1]);
  9318. $h++;
  9319. }
  9320. // set tab at its position
  9321. $head = array_merge(array_slice($head, 0, $postab), array($newtab), array_slice($head, $postab));
  9322. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  9323. if ($values[0] != $type) {
  9324. continue;
  9325. }
  9326. $tabname = str_replace('-', '', $values[1]);
  9327. foreach ($head as $key => $val) {
  9328. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  9329. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  9330. if ($head[$key][2] == $tabname && $condition) {
  9331. unset($head[$key]);
  9332. break;
  9333. }
  9334. }
  9335. }
  9336. }
  9337. }
  9338. // No need to make a return $head. Var is modified as a reference
  9339. if (!empty($hookmanager)) {
  9340. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
  9341. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters, $object);
  9342. if ($reshook > 0) { // Hook ask to replace completely the array
  9343. $head = $hookmanager->resArray;
  9344. } else { // Hook
  9345. $head = array_merge($head, $hookmanager->resArray);
  9346. }
  9347. $h = count($head);
  9348. }
  9349. }
  9350. /**
  9351. * Print common footer :
  9352. * conf->global->MAIN_HTML_FOOTER
  9353. * js for switch of menu hider
  9354. * js for conf->global->MAIN_GOOGLE_AN_ID
  9355. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  9356. * js for conf->logbuffer
  9357. *
  9358. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  9359. * @return void
  9360. */
  9361. function printCommonFooter($zone = 'private')
  9362. {
  9363. global $conf, $hookmanager, $user, $debugbar;
  9364. global $action;
  9365. global $micro_start_time;
  9366. if ($zone == 'private') {
  9367. print "\n".'<!-- Common footer for private page -->'."\n";
  9368. } else {
  9369. print "\n".'<!-- Common footer for public page -->'."\n";
  9370. }
  9371. // A div to store page_y POST parameter so we can read it using javascript
  9372. print "\n<!-- A div to store page_y POST parameter -->\n";
  9373. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  9374. $parameters = array();
  9375. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  9376. if (empty($reshook)) {
  9377. if (getDolGlobalString('MAIN_HTML_FOOTER')) {
  9378. print getDolGlobalString('MAIN_HTML_FOOTER') . "\n";
  9379. }
  9380. print "\n";
  9381. if (!empty($conf->use_javascript_ajax)) {
  9382. print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and madatory fields, tuning info, ... -->\n";
  9383. print '<script>'."\n";
  9384. print 'jQuery(document).ready(function() {'."\n";
  9385. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  9386. print "\n";
  9387. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  9388. print 'jQuery("li.menuhider").click(function(event) {';
  9389. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  9390. print ' console.log("We click on .menuhider");'."\n";
  9391. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  9392. print '});'."\n";
  9393. }
  9394. // Management of focus and mandatory for fields
  9395. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))) || ((empty($action) || $action == 'addline') && (preg_match('/card\.php/', $_SERVER["PHP_SELF"])))) {
  9396. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  9397. $relativepathstring = $_SERVER["PHP_SELF"];
  9398. // Clean $relativepathstring
  9399. if (constant('DOL_URL_ROOT')) {
  9400. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  9401. }
  9402. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  9403. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  9404. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  9405. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  9406. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  9407. $qualified = 0;
  9408. if ($defkey != '_noquery_') {
  9409. $tmpqueryarraytohave = explode('&', $defkey);
  9410. $foundintru = 0;
  9411. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  9412. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  9413. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  9414. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  9415. $foundintru = 1;
  9416. }
  9417. }
  9418. if (!$foundintru) {
  9419. $qualified = 1;
  9420. }
  9421. //var_dump($defkey.'-'.$qualified);
  9422. } else {
  9423. $qualified = 1;
  9424. }
  9425. if ($qualified) {
  9426. foreach ($defval as $paramkey => $paramval) {
  9427. // Set focus on field
  9428. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  9429. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  9430. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  9431. }
  9432. }
  9433. }
  9434. }
  9435. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  9436. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  9437. $qualified = 0;
  9438. if ($defkey != '_noquery_') {
  9439. $tmpqueryarraytohave = explode('&', $defkey);
  9440. $foundintru = 0;
  9441. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  9442. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  9443. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  9444. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  9445. $foundintru = 1;
  9446. }
  9447. }
  9448. if (!$foundintru) {
  9449. $qualified = 1;
  9450. }
  9451. //var_dump($defkey.'-'.$qualified);
  9452. } else {
  9453. $qualified = 1;
  9454. }
  9455. if ($qualified) {
  9456. foreach ($defval as $paramkey => $paramval) {
  9457. // Add property 'required' on input
  9458. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9459. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9460. print '// required on a select works only if key is "", so we add the required attributes but also we reset the key -1 or 0 to an empty string'."\n";
  9461. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  9462. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  9463. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  9464. // Add 'field required' class on closest td for all input elements : input, textarea and select
  9465. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  9466. }
  9467. // If we submit the cancel button we remove the required attributes
  9468. print 'jQuery("input[name=\'cancel\']").click(function() {
  9469. console.log("We click on cancel button so removed all required attribute");
  9470. jQuery("input, textarea, select").each(function(){this.removeAttribute(\'required\');});
  9471. });'."\n";
  9472. }
  9473. }
  9474. }
  9475. }
  9476. print '});'."\n";
  9477. // End of tuning
  9478. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || getDolGlobalString('MAIN_SHOW_TUNING_INFO')) {
  9479. print "\n";
  9480. print "/* JS CODE TO ENABLE to add memory info */\n";
  9481. print 'window.console && console.log("';
  9482. if (getDolGlobalString('MEMCACHED_SERVER')) {
  9483. print 'MEMCACHED_SERVER=' . getDolGlobalString('MEMCACHED_SERVER').' - ';
  9484. }
  9485. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  9486. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  9487. $micro_end_time = microtime(true);
  9488. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  9489. }
  9490. if (function_exists("memory_get_usage")) {
  9491. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  9492. }
  9493. if (function_exists("memory_get_peak_usage")) {
  9494. print ' - Real mem peak: '.memory_get_peak_usage(true);
  9495. }
  9496. if (function_exists("zend_loader_file_encoded")) {
  9497. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  9498. }
  9499. print '");'."\n";
  9500. }
  9501. print "\n".'</script>'."\n";
  9502. // Google Analytics
  9503. // TODO Add a hook here
  9504. if (isModEnabled('google') && getDolGlobalString('MAIN_GOOGLE_AN_ID')) {
  9505. $tmptagarray = explode(',', getDolGlobalString('MAIN_GOOGLE_AN_ID'));
  9506. foreach ($tmptagarray as $tmptag) {
  9507. print "\n";
  9508. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  9509. print '
  9510. <!-- Global site tag (gtag.js) - Google Analytics -->
  9511. <script nonce="'.getNonce().'" async src="https://www.googletagmanager.com/gtag/js?id='.trim($tmptag).'"></script>
  9512. <script>
  9513. window.dataLayer = window.dataLayer || [];
  9514. function gtag(){dataLayer.push(arguments);}
  9515. gtag(\'js\', new Date());
  9516. gtag(\'config\', \''.trim($tmptag).'\');
  9517. </script>';
  9518. print "\n";
  9519. }
  9520. }
  9521. }
  9522. // Add Xdebug coverage of code
  9523. if (defined('XDEBUGCOVERAGE')) {
  9524. print_r(xdebug_get_code_coverage());
  9525. }
  9526. // Add DebugBar data
  9527. if ($user->hasRight('debugbar', 'read') && is_object($debugbar)) {
  9528. $debugbar['time']->stopMeasure('pageaftermaster');
  9529. print '<!-- Output debugbar data -->'."\n";
  9530. $renderer = $debugbar->getRenderer();
  9531. print $debugbar->getRenderer()->render();
  9532. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  9533. print "\n";
  9534. print "<!-- Start of log output\n";
  9535. //print '<div class="hidden">'."\n";
  9536. foreach ($conf->logbuffer as $logline) {
  9537. print $logline."<br>\n";
  9538. }
  9539. //print '</div>'."\n";
  9540. print "End of log output -->\n";
  9541. }
  9542. }
  9543. }
  9544. /**
  9545. * Split a string with 2 keys into key array.
  9546. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  9547. *
  9548. * @param string|null $string String to explode
  9549. * @param string $delimiter Delimiter between each couple of data. Example: ';' or '[\n;]+' or '(\n\r|\r|\n|;)'
  9550. * @param string $kv Delimiter between key and value
  9551. * @return array Array of data exploded
  9552. */
  9553. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  9554. {
  9555. if (is_null($string)) {
  9556. return array();
  9557. }
  9558. if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\(.*\)$/sm', $delimiter)) {
  9559. // This is a regex string
  9560. $newdelimiter = $delimiter;
  9561. } else {
  9562. // This is a simple string
  9563. $newdelimiter = preg_quote($delimiter, '/');
  9564. }
  9565. if ($a = preg_split('/'.$newdelimiter.'/', $string)) {
  9566. $ka = array();
  9567. foreach ($a as $s) { // each part
  9568. if ($s) {
  9569. if ($pos = strpos($s, $kv)) { // key/value delimiter
  9570. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  9571. } else { // key delimiter not found
  9572. $ka[] = trim($s);
  9573. }
  9574. }
  9575. }
  9576. return $ka;
  9577. }
  9578. return array();
  9579. }
  9580. /**
  9581. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  9582. *
  9583. * @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.
  9584. * @return void
  9585. */
  9586. function dol_set_focus($selector)
  9587. {
  9588. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  9589. print '<script nonce="'.getNonce().'">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  9590. }
  9591. /**
  9592. * Return getmypid() or random PID when function is disabled
  9593. * Some web hosts disable this php function for security reasons
  9594. * and sometimes we can't redeclare function.
  9595. *
  9596. * @return int
  9597. */
  9598. function dol_getmypid()
  9599. {
  9600. if (!function_exists('getmypid')) {
  9601. return mt_rand(99900000, 99965535);
  9602. } else {
  9603. return getmypid(); // May be a number on 64 bits (depending on OS)
  9604. }
  9605. }
  9606. /**
  9607. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  9608. *
  9609. * @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")
  9610. * @param string $value The value to look for.
  9611. * If param $mode is 0, can contains several keywords separated with a space or |
  9612. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  9613. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  9614. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < -1000"
  9615. * If param $mode is 2 or -2, can contains a list of int id separated by comma like "1,3,4"
  9616. * If param $mode is 3 or -3, can contains a list of string separated by comma like "a,b,c".
  9617. * @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'), -2 is for exclude list,
  9618. * 3=value is list of string separated with comma (Example 'text 1,text 2'), -3 if for exclude list, 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
  9619. * @param integer $nofirstand 1=Do not output the first 'AND'
  9620. * @return string $res The statement to append to the SQL query
  9621. * @see dolSqlDateFilter()
  9622. */
  9623. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  9624. {
  9625. global $db, $langs;
  9626. $value = trim($value);
  9627. if ($mode == 0) {
  9628. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  9629. }
  9630. if ($mode == 1) {
  9631. $value = preg_replace('/([!<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can then explode on space to get all tests to do
  9632. }
  9633. $value = preg_replace('/\s*\|\s*/', '|', $value);
  9634. $crits = explode(' ', $value);
  9635. $res = '';
  9636. if (!is_array($fields)) {
  9637. $fields = array($fields);
  9638. }
  9639. $i1 = 0; // count the nb of and criteria added (all fields / criterias)
  9640. foreach ($crits as $crit) { // Loop on each AND criteria
  9641. $crit = trim($crit);
  9642. $i2 = 0; // count the nb of valid criteria added for this this first criteria
  9643. $newres = '';
  9644. foreach ($fields as $field) {
  9645. if ($mode == 1) {
  9646. $tmpcrits = explode('|', $crit);
  9647. $i3 = 0; // count the nb of valid criteria added for this current field
  9648. foreach ($tmpcrits as $tmpcrit) {
  9649. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9650. continue;
  9651. }
  9652. $tmpcrit = trim($tmpcrit);
  9653. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9654. $operator = '=';
  9655. $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
  9656. $reg = array();
  9657. preg_match('/([!<>=]+)/', $tmpcrit, $reg);
  9658. if (!empty($reg[1])) {
  9659. $operator = $reg[1];
  9660. }
  9661. if ($newcrit != '') {
  9662. $numnewcrit = price2num($newcrit);
  9663. if (is_numeric($numnewcrit)) {
  9664. $newres .= $field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  9665. } else {
  9666. $newres .= '1 = 2'; // force false, we received a corrupted data
  9667. }
  9668. $i3++; // a criteria was added to string
  9669. }
  9670. }
  9671. $i2++; // a criteria for 1 more field was added to string
  9672. } elseif ($mode == 2 || $mode == -2) {
  9673. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  9674. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  9675. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  9676. if ($mode == -2) {
  9677. $newres .= ' OR '.$field.' IS NULL';
  9678. }
  9679. $i2++; // a criteria for 1 more field was added to string
  9680. } elseif ($mode == 3 || $mode == -3) {
  9681. $tmparray = explode(',', $crit);
  9682. if (count($tmparray)) {
  9683. $listofcodes = '';
  9684. foreach ($tmparray as $val) {
  9685. $val = trim($val);
  9686. if ($val) {
  9687. $listofcodes .= ($listofcodes ? ',' : '');
  9688. $listofcodes .= "'".$db->escape($val)."'";
  9689. }
  9690. }
  9691. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  9692. $i2++; // a criteria for 1 more field was added to string
  9693. }
  9694. if ($mode == -3) {
  9695. $newres .= ' OR '.$field.' IS NULL';
  9696. }
  9697. } elseif ($mode == 4) {
  9698. $tmparray = explode(',', $crit);
  9699. if (count($tmparray)) {
  9700. $listofcodes = '';
  9701. foreach ($tmparray as $val) {
  9702. $val = trim($val);
  9703. if ($val) {
  9704. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  9705. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  9706. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  9707. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  9708. $newres .= ')';
  9709. $i2++; // a criteria for 1 more field was added to string (we can add several citeria for the same field as it is a multiselect search criteria)
  9710. }
  9711. }
  9712. }
  9713. } else { // $mode=0
  9714. $tmpcrits = explode('|', $crit);
  9715. $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
  9716. foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
  9717. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9718. continue;
  9719. }
  9720. $tmpcrit = trim($tmpcrit);
  9721. if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
  9722. $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
  9723. } else {
  9724. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9725. }
  9726. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  9727. $newres .= $field." = ".(is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
  9728. } else {
  9729. $tmpcrit2 = $tmpcrit;
  9730. $tmpbefore = '%';
  9731. $tmpafter = '%';
  9732. $tmps = '';
  9733. if (preg_match('/^!/', $tmpcrit)) {
  9734. $tmps .= $field." NOT LIKE "; // ! as exclude character
  9735. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  9736. } else {
  9737. $tmps .= $field." LIKE ";
  9738. }
  9739. $tmps .= "'";
  9740. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  9741. $tmpbefore = '';
  9742. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  9743. }
  9744. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  9745. $tmpafter = '';
  9746. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  9747. }
  9748. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9749. $tmps = "(".$tmps;
  9750. }
  9751. $newres .= $tmps;
  9752. $newres .= $tmpbefore;
  9753. $newres .= $db->escape($tmpcrit2);
  9754. $newres .= $tmpafter;
  9755. $newres .= "'";
  9756. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9757. $newres .= " OR ".$field." IS NULL)";
  9758. }
  9759. }
  9760. $i3++;
  9761. }
  9762. $i2++; // a criteria for 1 more field was added to string
  9763. }
  9764. }
  9765. if ($newres) {
  9766. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  9767. }
  9768. $i1++;
  9769. }
  9770. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  9771. return $res;
  9772. }
  9773. /**
  9774. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  9775. *
  9776. * @param Object $object Object
  9777. * @return string Url string
  9778. */
  9779. function showDirectDownloadLink($object)
  9780. {
  9781. global $conf, $langs;
  9782. $out = '';
  9783. $url = $object->getLastMainDocLink($object->element);
  9784. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  9785. if ($url) {
  9786. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  9787. $out .= ajax_autoselect("directdownloadlink", 0);
  9788. } else {
  9789. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  9790. }
  9791. return $out;
  9792. }
  9793. /**
  9794. * Return the filename of file to get the thumbs
  9795. *
  9796. * @param string $file Original filename (full or relative path)
  9797. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  9798. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  9799. * @return string New file name (full or relative path, including the thumbs/). May be the original path if no thumb can exists.
  9800. */
  9801. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  9802. {
  9803. $dirName = dirname($file);
  9804. if ($dirName == '.') {
  9805. $dirName = '';
  9806. }
  9807. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  9808. $fileName = basename($fileName);
  9809. if (empty($extImgTarget)) {
  9810. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  9811. }
  9812. if (empty($extImgTarget)) {
  9813. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  9814. }
  9815. if (empty($extImgTarget)) {
  9816. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  9817. }
  9818. if (empty($extImgTarget)) {
  9819. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  9820. }
  9821. if (empty($extImgTarget)) {
  9822. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  9823. }
  9824. if (empty($extImgTarget)) {
  9825. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  9826. }
  9827. if (!$extImgTarget) {
  9828. return $file;
  9829. }
  9830. $subdir = '';
  9831. if ($extName) {
  9832. $subdir = 'thumbs/';
  9833. }
  9834. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  9835. }
  9836. /**
  9837. * Return URL we can use for advanced preview links
  9838. *
  9839. * @param string $modulepart propal, facture, facture_fourn, ...
  9840. * @param string $relativepath Relative path of docs.
  9841. * @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)
  9842. * @param string $param More param on http links
  9843. * @return string|array Output string with href link or array with all components of link
  9844. */
  9845. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  9846. {
  9847. global $conf, $langs;
  9848. if (empty($conf->use_javascript_ajax)) {
  9849. return '';
  9850. }
  9851. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  9852. if ($alldata == 1) {
  9853. if ($isAllowedForPreview) {
  9854. return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart).'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : ''), 'mime'=>dol_mimetype($relativepath));
  9855. } else {
  9856. return array();
  9857. }
  9858. }
  9859. // old behavior, return a string
  9860. if ($isAllowedForPreview) {
  9861. $tmpurl = DOL_URL_ROOT.'/document.php?modulepart='.urlencode($modulepart).'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : '');
  9862. $title = $langs->trans("Preview");
  9863. //$title = '%27-alert(document.domain)-%27';
  9864. //$tmpurl = 'file='.urlencode("'-alert(document.domain)-'_small.jpg");
  9865. // We need to urlencode the parameter after the dol_escape_js($tmpurl) because $tmpurl may contain n url with param file=abc%27def if file has a ' inside.
  9866. // and when we click on href with this javascript string, a urlcode is done by browser, converted the %27 of file param
  9867. return 'javascript:document_preview(\''.urlencode(dol_escape_js($tmpurl)).'\', \''.urlencode(dol_mimetype($relativepath)).'\', \''.urlencode(dol_escape_js($title)).'\')';
  9868. } else {
  9869. return '';
  9870. }
  9871. }
  9872. /**
  9873. * Make content of an input box selected when we click into input field.
  9874. *
  9875. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  9876. * @param string $addlink Add a 'link to' after
  9877. * @param string $textonlink Text to show on link or 'image'
  9878. * @return string
  9879. */
  9880. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  9881. {
  9882. global $langs;
  9883. $out = '<script nonce="'.getNonce().'">
  9884. jQuery(document).ready(function () {
  9885. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  9886. });
  9887. </script>';
  9888. if ($addlink) {
  9889. if ($textonlink === 'image') {
  9890. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  9891. } else {
  9892. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  9893. }
  9894. }
  9895. return $out;
  9896. }
  9897. /**
  9898. * Return if a file is qualified for preview
  9899. *
  9900. * @param string $file Filename we looking for information
  9901. * @return int 1 If allowed, 0 otherwise
  9902. * @see dol_mimetype(), image_format_supported() from images.lib.php
  9903. */
  9904. function dolIsAllowedForPreview($file)
  9905. {
  9906. global $conf;
  9907. // Check .noexe extension in filename
  9908. if (preg_match('/\.noexe$/i', $file)) {
  9909. return 0;
  9910. }
  9911. // Check mime types
  9912. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  9913. if (getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_IMAGES')) {
  9914. $mime_preview[] = 'svg+xml';
  9915. }
  9916. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  9917. //$mime_preview[]='archive';
  9918. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  9919. if ($num_mime !== false) {
  9920. return 1;
  9921. }
  9922. // By default, not allowed for preview
  9923. return 0;
  9924. }
  9925. /**
  9926. * Return MIME type of a file from its name with extension.
  9927. *
  9928. * @param string $file Filename we looking for MIME type
  9929. * @param string $default Default mime type if extension not found in known list
  9930. * @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
  9931. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  9932. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  9933. */
  9934. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  9935. {
  9936. $mime = $default;
  9937. $imgmime = 'other.png';
  9938. $famime = 'file-o';
  9939. $srclang = '';
  9940. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  9941. // Plain text files
  9942. if (preg_match('/\.txt$/i', $tmpfile)) {
  9943. $mime = 'text/plain';
  9944. $imgmime = 'text.png';
  9945. $famime = 'file-alt';
  9946. } elseif (preg_match('/\.rtx$/i', $tmpfile)) {
  9947. $mime = 'text/richtext';
  9948. $imgmime = 'text.png';
  9949. $famime = 'file-alt';
  9950. } elseif (preg_match('/\.csv$/i', $tmpfile)) {
  9951. $mime = 'text/csv';
  9952. $imgmime = 'text.png';
  9953. $famime = 'file-csv';
  9954. } elseif (preg_match('/\.tsv$/i', $tmpfile)) {
  9955. $mime = 'text/tab-separated-values';
  9956. $imgmime = 'text.png';
  9957. $famime = 'file-alt';
  9958. } elseif (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  9959. $mime = 'text/plain';
  9960. $imgmime = 'text.png';
  9961. $famime = 'file-alt';
  9962. } elseif (preg_match('/\.ini$/i', $tmpfile)) {
  9963. $mime = 'text/plain';
  9964. $imgmime = 'text.png';
  9965. $srclang = 'ini';
  9966. $famime = 'file-alt';
  9967. } elseif (preg_match('/\.md$/i', $tmpfile)) {
  9968. $mime = 'text/plain';
  9969. $imgmime = 'text.png';
  9970. $srclang = 'md';
  9971. $famime = 'file-alt';
  9972. } elseif (preg_match('/\.css$/i', $tmpfile)) {
  9973. $mime = 'text/css';
  9974. $imgmime = 'css.png';
  9975. $srclang = 'css';
  9976. $famime = 'file-alt';
  9977. } elseif (preg_match('/\.lang$/i', $tmpfile)) {
  9978. $mime = 'text/plain';
  9979. $imgmime = 'text.png';
  9980. $srclang = 'lang';
  9981. $famime = 'file-alt';
  9982. } elseif (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { // Certificate files
  9983. $mime = 'text/plain';
  9984. $imgmime = 'text.png';
  9985. $famime = 'file-alt';
  9986. } elseif (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { // XML based (HTML/XML/XAML)
  9987. $mime = 'text/html';
  9988. $imgmime = 'html.png';
  9989. $srclang = 'html';
  9990. $famime = 'file-alt';
  9991. } elseif (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  9992. $mime = 'text/xml';
  9993. $imgmime = 'other.png';
  9994. $srclang = 'xml';
  9995. $famime = 'file-alt';
  9996. } elseif (preg_match('/\.xaml$/i', $tmpfile)) {
  9997. $mime = 'text/xml';
  9998. $imgmime = 'other.png';
  9999. $srclang = 'xaml';
  10000. $famime = 'file-alt';
  10001. } elseif (preg_match('/\.bas$/i', $tmpfile)) { // Languages
  10002. $mime = 'text/plain';
  10003. $imgmime = 'text.png';
  10004. $srclang = 'bas';
  10005. $famime = 'file-code';
  10006. } elseif (preg_match('/\.(c)$/i', $tmpfile)) {
  10007. $mime = 'text/plain';
  10008. $imgmime = 'text.png';
  10009. $srclang = 'c';
  10010. $famime = 'file-code';
  10011. } elseif (preg_match('/\.(cpp)$/i', $tmpfile)) {
  10012. $mime = 'text/plain';
  10013. $imgmime = 'text.png';
  10014. $srclang = 'cpp';
  10015. $famime = 'file-code';
  10016. } elseif (preg_match('/\.cs$/i', $tmpfile)) {
  10017. $mime = 'text/plain';
  10018. $imgmime = 'text.png';
  10019. $srclang = 'cs';
  10020. $famime = 'file-code';
  10021. } elseif (preg_match('/\.(h)$/i', $tmpfile)) {
  10022. $mime = 'text/plain';
  10023. $imgmime = 'text.png';
  10024. $srclang = 'h';
  10025. $famime = 'file-code';
  10026. } elseif (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  10027. $mime = 'text/plain';
  10028. $imgmime = 'text.png';
  10029. $srclang = 'java';
  10030. $famime = 'file-code';
  10031. } elseif (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  10032. $mime = 'text/plain';
  10033. $imgmime = 'php.png';
  10034. $srclang = 'php';
  10035. $famime = 'file-code';
  10036. } elseif (preg_match('/\.phtml$/i', $tmpfile)) {
  10037. $mime = 'text/plain';
  10038. $imgmime = 'php.png';
  10039. $srclang = 'php';
  10040. $famime = 'file-code';
  10041. } elseif (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  10042. $mime = 'text/plain';
  10043. $imgmime = 'pl.png';
  10044. $srclang = 'perl';
  10045. $famime = 'file-code';
  10046. } elseif (preg_match('/\.sql$/i', $tmpfile)) {
  10047. $mime = 'text/plain';
  10048. $imgmime = 'text.png';
  10049. $srclang = 'sql';
  10050. $famime = 'file-code';
  10051. } elseif (preg_match('/\.js$/i', $tmpfile)) {
  10052. $mime = 'text/x-javascript';
  10053. $imgmime = 'jscript.png';
  10054. $srclang = 'js';
  10055. $famime = 'file-code';
  10056. } elseif (preg_match('/\.odp$/i', $tmpfile)) { // Open office
  10057. $mime = 'application/vnd.oasis.opendocument.presentation';
  10058. $imgmime = 'ooffice.png';
  10059. $famime = 'file-powerpoint';
  10060. } elseif (preg_match('/\.ods$/i', $tmpfile)) {
  10061. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  10062. $imgmime = 'ooffice.png';
  10063. $famime = 'file-excel';
  10064. } elseif (preg_match('/\.odt$/i', $tmpfile)) {
  10065. $mime = 'application/vnd.oasis.opendocument.text';
  10066. $imgmime = 'ooffice.png';
  10067. $famime = 'file-word';
  10068. } elseif (preg_match('/\.mdb$/i', $tmpfile)) { // MS Office
  10069. $mime = 'application/msaccess';
  10070. $imgmime = 'mdb.png';
  10071. $famime = 'file';
  10072. } elseif (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
  10073. $mime = 'application/msword';
  10074. $imgmime = 'doc.png';
  10075. $famime = 'file-word';
  10076. } elseif (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
  10077. $mime = 'application/msword';
  10078. $imgmime = 'doc.png';
  10079. $famime = 'file-word';
  10080. } elseif (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  10081. $mime = 'application/vnd.ms-excel';
  10082. $imgmime = 'xls.png';
  10083. $famime = 'file-excel';
  10084. } elseif (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  10085. $mime = 'application/vnd.ms-excel';
  10086. $imgmime = 'xls.png';
  10087. $famime = 'file-excel';
  10088. } elseif (preg_match('/\.xls$/i', $tmpfile)) {
  10089. $mime = 'application/vnd.ms-excel';
  10090. $imgmime = 'xls.png';
  10091. $famime = 'file-excel';
  10092. } elseif (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
  10093. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  10094. $imgmime = 'xls.png';
  10095. $famime = 'file-excel';
  10096. } elseif (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
  10097. $mime = 'application/vnd.ms-powerpoint';
  10098. $imgmime = 'ppt.png';
  10099. $famime = 'file-powerpoint';
  10100. } elseif (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
  10101. $mime = 'application/x-mspowerpoint';
  10102. $imgmime = 'ppt.png';
  10103. $famime = 'file-powerpoint';
  10104. } elseif (preg_match('/\.pdf$/i', $tmpfile)) { // Other
  10105. $mime = 'application/pdf';
  10106. $imgmime = 'pdf.png';
  10107. $famime = 'file-pdf';
  10108. } elseif (preg_match('/\.bat$/i', $tmpfile)) { // Scripts
  10109. $mime = 'text/x-bat';
  10110. $imgmime = 'script.png';
  10111. $srclang = 'dos';
  10112. $famime = 'file-code';
  10113. } elseif (preg_match('/\.sh$/i', $tmpfile)) {
  10114. $mime = 'text/x-sh';
  10115. $imgmime = 'script.png';
  10116. $srclang = 'bash';
  10117. $famime = 'file-code';
  10118. } elseif (preg_match('/\.ksh$/i', $tmpfile)) {
  10119. $mime = 'text/x-ksh';
  10120. $imgmime = 'script.png';
  10121. $srclang = 'bash';
  10122. $famime = 'file-code';
  10123. } elseif (preg_match('/\.bash$/i', $tmpfile)) {
  10124. $mime = 'text/x-bash';
  10125. $imgmime = 'script.png';
  10126. $srclang = 'bash';
  10127. $famime = 'file-code';
  10128. } elseif (preg_match('/\.ico$/i', $tmpfile)) { // Images
  10129. $mime = 'image/x-icon';
  10130. $imgmime = 'image.png';
  10131. $famime = 'file-image';
  10132. } elseif (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  10133. $mime = 'image/jpeg';
  10134. $imgmime = 'image.png';
  10135. $famime = 'file-image';
  10136. } elseif (preg_match('/\.png$/i', $tmpfile)) {
  10137. $mime = 'image/png';
  10138. $imgmime = 'image.png';
  10139. $famime = 'file-image';
  10140. } elseif (preg_match('/\.gif$/i', $tmpfile)) {
  10141. $mime = 'image/gif';
  10142. $imgmime = 'image.png';
  10143. $famime = 'file-image';
  10144. } elseif (preg_match('/\.bmp$/i', $tmpfile)) {
  10145. $mime = 'image/bmp';
  10146. $imgmime = 'image.png';
  10147. $famime = 'file-image';
  10148. } elseif (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  10149. $mime = 'image/tiff';
  10150. $imgmime = 'image.png';
  10151. $famime = 'file-image';
  10152. } elseif (preg_match('/\.svg$/i', $tmpfile)) {
  10153. $mime = 'image/svg+xml';
  10154. $imgmime = 'image.png';
  10155. $famime = 'file-image';
  10156. } elseif (preg_match('/\.webp$/i', $tmpfile)) {
  10157. $mime = 'image/webp';
  10158. $imgmime = 'image.png';
  10159. $famime = 'file-image';
  10160. } elseif (preg_match('/\.vcs$/i', $tmpfile)) { // Calendar
  10161. $mime = 'text/calendar';
  10162. $imgmime = 'other.png';
  10163. $famime = 'file-alt';
  10164. } elseif (preg_match('/\.ics$/i', $tmpfile)) {
  10165. $mime = 'text/calendar';
  10166. $imgmime = 'other.png';
  10167. $famime = 'file-alt';
  10168. } elseif (preg_match('/\.torrent$/i', $tmpfile)) { // Other
  10169. $mime = 'application/x-bittorrent';
  10170. $imgmime = 'other.png';
  10171. $famime = 'file-o';
  10172. } elseif (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { // Audio
  10173. $mime = 'audio';
  10174. $imgmime = 'audio.png';
  10175. $famime = 'file-audio';
  10176. } elseif (preg_match('/\.mp4$/i', $tmpfile)) { // Video
  10177. $mime = 'video/mp4';
  10178. $imgmime = 'video.png';
  10179. $famime = 'file-video';
  10180. } elseif (preg_match('/\.ogv$/i', $tmpfile)) {
  10181. $mime = 'video/ogg';
  10182. $imgmime = 'video.png';
  10183. $famime = 'file-video';
  10184. } elseif (preg_match('/\.webm$/i', $tmpfile)) {
  10185. $mime = 'video/webm';
  10186. $imgmime = 'video.png';
  10187. $famime = 'file-video';
  10188. } elseif (preg_match('/\.avi$/i', $tmpfile)) {
  10189. $mime = 'video/x-msvideo';
  10190. $imgmime = 'video.png';
  10191. $famime = 'file-video';
  10192. } elseif (preg_match('/\.divx$/i', $tmpfile)) {
  10193. $mime = 'video/divx';
  10194. $imgmime = 'video.png';
  10195. $famime = 'file-video';
  10196. } elseif (preg_match('/\.xvid$/i', $tmpfile)) {
  10197. $mime = 'video/xvid';
  10198. $imgmime = 'video.png';
  10199. $famime = 'file-video';
  10200. } elseif (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  10201. $mime = 'video';
  10202. $imgmime = 'video.png';
  10203. $famime = 'file-video';
  10204. } elseif (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) { // Archive
  10205. // application/xxx where zzz is zip, ...
  10206. $mime = 'archive';
  10207. $imgmime = 'archive.png';
  10208. $famime = 'file-archive';
  10209. } elseif (preg_match('/\.(exe|com)$/i', $tmpfile)) { // Exe
  10210. $mime = 'application/octet-stream';
  10211. $imgmime = 'other.png';
  10212. $famime = 'file-o';
  10213. } elseif (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { // Lib
  10214. $mime = 'library';
  10215. $imgmime = 'library.png';
  10216. $famime = 'file-o';
  10217. } elseif (preg_match('/\.err$/i', $tmpfile)) { // phpcs:ignore
  10218. $mime = 'error';
  10219. $imgmime = 'error.png';
  10220. $famime = 'file-alt';
  10221. }
  10222. // Return mimetype string
  10223. switch ((int) $mode) {
  10224. case 1:
  10225. $tmp = explode('/', $mime);
  10226. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  10227. case 2:
  10228. return $imgmime;
  10229. case 3:
  10230. return $srclang;
  10231. case 4:
  10232. return $famime;
  10233. }
  10234. return $mime;
  10235. }
  10236. /**
  10237. * Return the value of a filed into a dictionary for the record $id.
  10238. * This also set all the values into a cache for a next search.
  10239. *
  10240. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  10241. * @param string $field The name of field where to find the value to return
  10242. * @param int $id Id of line record
  10243. * @param bool $checkentity Add filter on entity
  10244. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  10245. * @return string The value of field $field. This also set $dictvalues cache.
  10246. */
  10247. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  10248. {
  10249. global $conf, $db;
  10250. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  10251. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  10252. if (is_null($dictvalues)) {
  10253. $dictvalues = array();
  10254. $sql = "SELECT * FROM ".MAIN_DB_PREFIX.$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  10255. if ($checkentity) {
  10256. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  10257. }
  10258. $resql = $db->query($sql);
  10259. if ($resql) {
  10260. while ($obj = $db->fetch_object($resql)) {
  10261. $dictvalues[$obj->$rowidfield] = $obj; // $obj is stdClass
  10262. }
  10263. } else {
  10264. dol_print_error($db);
  10265. }
  10266. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  10267. }
  10268. if (!empty($dictvalues[$id])) {
  10269. // Found
  10270. $tmp = $dictvalues[$id];
  10271. return (property_exists($tmp, $field) ? $tmp->$field : '');
  10272. } else {
  10273. // Not found
  10274. return '';
  10275. }
  10276. }
  10277. /**
  10278. * Return true if the color is light
  10279. *
  10280. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  10281. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  10282. */
  10283. function colorIsLight($stringcolor)
  10284. {
  10285. $stringcolor = str_replace('#', '', $stringcolor);
  10286. $res = -1;
  10287. if (!empty($stringcolor)) {
  10288. $res = 0;
  10289. $tmp = explode(',', $stringcolor);
  10290. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  10291. $r = $tmp[0];
  10292. $g = $tmp[1];
  10293. $b = $tmp[2];
  10294. } else {
  10295. $hexr = $stringcolor[0].$stringcolor[1];
  10296. $hexg = $stringcolor[2].$stringcolor[3];
  10297. $hexb = $stringcolor[4].$stringcolor[5];
  10298. $r = hexdec($hexr);
  10299. $g = hexdec($hexg);
  10300. $b = hexdec($hexb);
  10301. }
  10302. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  10303. if ($bright > 0.6) {
  10304. $res = 1;
  10305. }
  10306. }
  10307. return $res;
  10308. }
  10309. /**
  10310. * Function to test if an entry is enabled or not
  10311. *
  10312. * @param string $type_user 0=We test for internal user, 1=We test for external user
  10313. * @param array $menuentry Array for feature entry to test
  10314. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  10315. * @return int 0=Hide, 1=Show, 2=Show gray
  10316. */
  10317. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  10318. {
  10319. global $conf;
  10320. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  10321. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  10322. if (empty($menuentry['enabled'])) {
  10323. return 0; // Entry disabled by condition
  10324. }
  10325. if ($type_user && $menuentry['module']) {
  10326. $tmploops = explode('|', $menuentry['module']);
  10327. $found = 0;
  10328. foreach ($tmploops as $tmploop) {
  10329. if (in_array($tmploop, $listofmodulesforexternal)) {
  10330. $found++;
  10331. break;
  10332. }
  10333. }
  10334. if (!$found) {
  10335. return 0; // Entry is for menus all excluded to external users
  10336. }
  10337. }
  10338. if (!$menuentry['perms'] && $type_user) {
  10339. return 0; // No permissions and user is external
  10340. }
  10341. if (!$menuentry['perms'] && getDolGlobalString('MAIN_MENU_HIDE_UNAUTHORIZED')) {
  10342. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  10343. }
  10344. if (!$menuentry['perms']) {
  10345. return 2; // No permissions and user is external
  10346. }
  10347. return 1;
  10348. }
  10349. /**
  10350. * Round to next multiple.
  10351. *
  10352. * @param double $n Number to round up
  10353. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  10354. * @return integer Value rounded.
  10355. */
  10356. function roundUpToNextMultiple($n, $x = 5)
  10357. {
  10358. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  10359. }
  10360. /**
  10361. * Function dolGetBadge
  10362. *
  10363. * @param string $label label of badge no html : use in alt attribute for accessibility
  10364. * @param string $html optional : label of badge with html
  10365. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  10366. * @param string $mode default '' , 'pill', 'dot'
  10367. * @param string $url the url for link
  10368. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  10369. * @return string Html badge
  10370. */
  10371. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  10372. {
  10373. $attr = array(
  10374. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  10375. );
  10376. if (empty($html)) {
  10377. $html = $label;
  10378. }
  10379. if (!empty($url)) {
  10380. $attr['href'] = $url;
  10381. }
  10382. if ($mode === 'dot') {
  10383. $attr['class'] .= ' classfortooltip';
  10384. $attr['title'] = $html;
  10385. $attr['aria-label'] = $label;
  10386. $html = '';
  10387. }
  10388. // Override attr
  10389. if (!empty($params['attr']) && is_array($params['attr'])) {
  10390. foreach ($params['attr'] as $key => $value) {
  10391. if ($key == 'class') {
  10392. $attr['class'] .= ' '.$value;
  10393. } elseif ($key == 'classOverride') {
  10394. $attr['class'] = $value;
  10395. } else {
  10396. $attr[$key] = $value;
  10397. }
  10398. }
  10399. }
  10400. // TODO: add hook
  10401. // escape all attribute
  10402. $attr = array_map('dol_escape_htmltag', $attr);
  10403. $TCompiledAttr = array();
  10404. foreach ($attr as $key => $value) {
  10405. $TCompiledAttr[] = $key.'="'.$value.'"';
  10406. }
  10407. $compiledAttributes = !empty($TCompiledAttr) ? implode(' ', $TCompiledAttr) : '';
  10408. $tag = !empty($url) ? 'a' : 'span';
  10409. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  10410. }
  10411. /**
  10412. * Output the badge of a status.
  10413. *
  10414. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  10415. * @param string $statusLabelShort Short label of badge no html
  10416. * @param string $html Optional : label of badge with html
  10417. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  10418. * @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
  10419. * @param string $url The url for link
  10420. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  10421. * @return string Html status string
  10422. */
  10423. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  10424. {
  10425. global $conf;
  10426. $return = '';
  10427. $dolGetBadgeParams = array();
  10428. if (!empty($params['badgeParams'])) {
  10429. $dolGetBadgeParams = $params['badgeParams'];
  10430. }
  10431. // TODO : add a hook
  10432. if ($displayMode == 0) {
  10433. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  10434. } elseif ($displayMode == 1) {
  10435. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  10436. } elseif (getDolGlobalString('MAIN_STATUS_USES_IMAGES')) {
  10437. // Use status with images (for backward compatibility)
  10438. $return = '';
  10439. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  10440. $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>' : '');
  10441. // For small screen, we always use the short label instead of long label.
  10442. if (!empty($conf->dol_optimize_smallscreen)) {
  10443. if ($displayMode == 0) {
  10444. $displayMode = 1;
  10445. } elseif ($displayMode == 4) {
  10446. $displayMode = 2;
  10447. } elseif ($displayMode == 6) {
  10448. $displayMode = 5;
  10449. }
  10450. }
  10451. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  10452. $statusImg = array(
  10453. 'status0' => 'statut0',
  10454. 'status1' => 'statut1',
  10455. 'status2' => 'statut2',
  10456. 'status3' => 'statut3',
  10457. 'status4' => 'statut4',
  10458. 'status5' => 'statut5',
  10459. 'status6' => 'statut6',
  10460. 'status7' => 'statut7',
  10461. 'status8' => 'statut8',
  10462. 'status9' => 'statut9'
  10463. );
  10464. if (!empty($statusImg[$statusType])) {
  10465. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  10466. } else {
  10467. $htmlImg = img_picto($statusLabel, $statusType);
  10468. }
  10469. if ($displayMode === 2) {
  10470. $return = $htmlImg.' '.$htmlLabelShort;
  10471. } elseif ($displayMode === 3) {
  10472. $return = $htmlImg;
  10473. } elseif ($displayMode === 4) {
  10474. $return = $htmlImg.' '.$htmlLabel;
  10475. } elseif ($displayMode === 5) {
  10476. $return = $htmlLabelShort.' '.$htmlImg;
  10477. } else { // $displayMode >= 6
  10478. $return = $htmlLabel.' '.$htmlImg;
  10479. }
  10480. } elseif (!getDolGlobalString('MAIN_STATUS_USES_IMAGES') && !empty($displayMode)) {
  10481. // Use new badge
  10482. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  10483. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  10484. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  10485. if ($displayMode == 3) {
  10486. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  10487. } elseif ($displayMode === 5) {
  10488. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  10489. } else {
  10490. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  10491. }
  10492. }
  10493. return $return;
  10494. }
  10495. /**
  10496. * Function dolGetButtonAction
  10497. *
  10498. * @param string $label Label or tooltip of button if $text is provided. Also used as tooltip in title attribute. Can be escaped HTML content or full simple text.
  10499. * @param string $text Optional : short label on button. Can be escaped HTML content or full simple text.
  10500. * @param string $actionType 'default', 'danger', 'email', 'clone', 'cancel', 'delete', ...
  10501. * @param string|array $url Url for link or array of subbutton description ('label'=>, 'url'=>, 'lang'=>, 'perm'=> )
  10502. * Example when an array is used: $arrayforbutaction = array(
  10503. * 10 => array('lang'=>'propal', 'enabled'=>isModEnabled("propal"), 'perm'=>$user->hasRight('propal', 'creer'), 'label' => 'AddProp', 'url'=>'/comm/propal/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10504. * 20 => array('lang'=>'orders', 'enabled'=>isModEnabled("commande"), 'perm'=>$user->hasRight('commande', 'creer'), 'label' => 'CreateOrder', 'url'=>'/commande/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10505. * 30 => array('lang'=>'bills', 'enabled'=>isModEnabled("facture"), 'perm'=>$user->hasRight('facture', 'creer'), 'label' => 'CreateBill', 'url'=>'/compta/facture/card.php?action=create&amp;projectid='.$object->id.'&amp;socid='.$object->socid),
  10506. * );
  10507. * @param string $id Attribute id of action button. Example 'action-delete'. This can be used for full ajax confirm if this code is reused into the ->formconfirm() method.
  10508. * @param int|boolean $userRight User action right
  10509. * // phpcs:disable
  10510. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  10511. * 'attr' => [ // to add or override button attributes
  10512. * 'xxxxx' => '', // your xxxxx attribute you want
  10513. * 'class' => 'reposition', // to add more css class to the button class attribute
  10514. * 'classOverride' => '' // to replace class attribute of the button
  10515. * ],
  10516. * 'confirm' => [
  10517. * 'url' => 'http://', // Overide Url to go when user click on action btn, if empty default url is $url.?confirm=yes, for no js compatibility use $url for fallback confirm.
  10518. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  10519. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  10520. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  10521. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  10522. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  10523. * 'isDropDrown' => false, // true|false to display dialog as a dropdown (with dark background)
  10524. * ],
  10525. * ]
  10526. * // phpcs:enable
  10527. * @return string html button
  10528. */
  10529. function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  10530. {
  10531. global $hookmanager, $action, $object, $langs;
  10532. // If $url is an array, we must build a dropdown button
  10533. if (is_array($url)) {
  10534. // Loop on $url array to remove entries of disabled modules
  10535. foreach ($url as $key => $subbutton) {
  10536. if (isset($subbutton['enabled']) && empty($subbutton['enabled'])) {
  10537. unset($url[$key]);
  10538. }
  10539. }
  10540. $out = '';
  10541. if (count($url) > 1) {
  10542. $out .= '<div class="dropdown inline-block dropdown-holder">';
  10543. $out .= '<a style="margin-right: auto;" class="dropdown-toggle classfortooltip butAction'.($userRight ? '' : 'Refused').'" title="'.dol_escape_htmltag($label).'" data-toggle="dropdown">'.($text ? $text : $label).'</a>';
  10544. $out .= '<div class="dropdown-content">';
  10545. foreach ($url as $subbutton) {
  10546. if (!empty($subbutton['lang'])) {
  10547. $langs->load($subbutton['lang']);
  10548. }
  10549. $tmpurl = DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage']));
  10550. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, '', $subbutton['perm'], array('isDropDown' => true));
  10551. }
  10552. $out .= "</div>";
  10553. $out .= "</div>";
  10554. } else {
  10555. foreach ($url as $subbutton) { // Should loop on 1 record only
  10556. if (!empty($subbutton['lang'])) {
  10557. $langs->load($subbutton['lang']);
  10558. }
  10559. $tmpurl = DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage']));
  10560. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', $tmpurl, '', $subbutton['perm']);
  10561. }
  10562. }
  10563. return $out;
  10564. }
  10565. // Here, $url is a simple link
  10566. if (!empty($params['isDropdown'])) {
  10567. $class = "dropdown-item";
  10568. } else {
  10569. $class = 'butAction';
  10570. if ($actionType == 'danger' || $actionType == 'delete') {
  10571. $class = 'butActionDelete';
  10572. if (!empty($url) && strpos($url, 'token=') === false) {
  10573. $url .= '&token='.newToken();
  10574. }
  10575. }
  10576. }
  10577. $attr = array(
  10578. 'class' => $class,
  10579. 'href' => empty($url) ? '' : $url,
  10580. 'title' => $label
  10581. );
  10582. if (empty($text)) {
  10583. $text = $label;
  10584. $attr['title'] = ''; // if html not set, leave label on title is redundant
  10585. } else {
  10586. $attr['title'] = $label;
  10587. $attr['aria-label'] = $label;
  10588. }
  10589. if (empty($userRight)) {
  10590. $attr['class'] = 'butActionRefused';
  10591. $attr['href'] = '';
  10592. $attr['title'] = (($label && $text && $label != $text) ? $label : $langs->trans('NotEnoughPermissions'));
  10593. }
  10594. if (!empty($id)) {
  10595. $attr['id'] = $id;
  10596. }
  10597. // Override attr
  10598. if (!empty($params['attr']) && is_array($params['attr'])) {
  10599. foreach ($params['attr'] as $key => $value) {
  10600. if ($key == 'class') {
  10601. $attr['class'] .= ' '.$value;
  10602. } elseif ($key == 'classOverride') {
  10603. $attr['class'] = $value;
  10604. } else {
  10605. $attr[$key] = $value;
  10606. }
  10607. }
  10608. }
  10609. // automatic add tooltip when title is detected
  10610. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  10611. $attr['class'].= ' classfortooltip';
  10612. }
  10613. // Js Confirm button
  10614. if ($userRight && !empty($params['confirm'])) {
  10615. if (!is_array($params['confirm'])) {
  10616. $params['confirm'] = array();
  10617. }
  10618. if (empty($params['confirm']['url'])) {
  10619. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  10620. }
  10621. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  10622. $attr['data-confirm-url'] = $params['confirm']['url'];
  10623. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  10624. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  10625. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  10626. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  10627. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  10628. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  10629. $attr['class'].= ' butActionConfirm';
  10630. }
  10631. if (isset($attr['href']) && empty($attr['href'])) {
  10632. unset($attr['href']);
  10633. }
  10634. // escape all attribute
  10635. $attr = array_map('dol_escape_htmltag', $attr);
  10636. $TCompiledAttr = array();
  10637. foreach ($attr as $key => $value) {
  10638. $TCompiledAttr[] = $key.'= "'.$value.'"';
  10639. }
  10640. $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
  10641. $tag = !empty($attr['href']) ? 'a' : 'span';
  10642. $parameters = array(
  10643. 'TCompiledAttr' => $TCompiledAttr, // array
  10644. 'compiledAttributes' => $compiledAttributes, // string
  10645. 'attr' => $attr,
  10646. 'tag' => $tag,
  10647. 'label' => $label,
  10648. 'html' => $text,
  10649. 'actionType' => $actionType,
  10650. 'url' => $url,
  10651. 'id' => $id,
  10652. 'userRight' => $userRight,
  10653. 'params' => $params
  10654. );
  10655. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  10656. if ($reshook < 0) {
  10657. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  10658. }
  10659. if (empty($reshook)) {
  10660. if (dol_textishtml($text)) { // If content already HTML encoded
  10661. return '<' . $tag . ' ' . $compiledAttributes . '>' . $text . '</' . $tag . '>';
  10662. } else {
  10663. return '<' . $tag . ' ' . $compiledAttributes . '>' . dol_escape_htmltag($text) . '</' . $tag . '>';
  10664. }
  10665. } else {
  10666. return $hookmanager->resPrint;
  10667. }
  10668. }
  10669. /**
  10670. * Add space between dolGetButtonTitle
  10671. *
  10672. * @param string $moreClass more css class label
  10673. * @return string html of title separator
  10674. */
  10675. function dolGetButtonTitleSeparator($moreClass = "")
  10676. {
  10677. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  10678. }
  10679. /**
  10680. * get field error icon
  10681. *
  10682. * @param string $fieldValidationErrorMsg message to add in tooltip
  10683. * @return string html output
  10684. */
  10685. function getFieldErrorIcon($fieldValidationErrorMsg)
  10686. {
  10687. $out = '';
  10688. if (!empty($fieldValidationErrorMsg)) {
  10689. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  10690. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  10691. $out.= '</span>';
  10692. }
  10693. return $out;
  10694. }
  10695. /**
  10696. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  10697. *
  10698. * @param string $label label of button
  10699. * @param string $helpText optional : content for help tooltip
  10700. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  10701. * @param string $url the url for link
  10702. * @param string $id attribute id of button
  10703. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use param $helpText as tooltip help
  10704. * @param array $params various params for future : recommended rather than adding more function arguments
  10705. * @return string html button
  10706. */
  10707. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  10708. {
  10709. global $langs, $conf, $user;
  10710. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  10711. if (getDolGlobalString('MAIN_BUTTON_HIDE_UNAUTHORIZED') && (!$user->admin) && $status <= 0) {
  10712. return '';
  10713. }
  10714. $class = 'btnTitle';
  10715. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
  10716. $class .= ' btnTitlePlus';
  10717. }
  10718. $useclassfortooltip = 1;
  10719. if (!empty($params['morecss'])) {
  10720. $class .= ' '.$params['morecss'];
  10721. }
  10722. $attr = array(
  10723. 'class' => $class,
  10724. 'href' => empty($url) ? '' : $url
  10725. );
  10726. if (!empty($helpText)) {
  10727. $attr['title'] = dol_escape_htmltag($helpText);
  10728. } elseif (empty($attr['title']) && $label) {
  10729. $attr['title'] = $label;
  10730. $useclassfortooltip = 0;
  10731. }
  10732. if ($status == 2) {
  10733. $attr['class'] .= ' btnTitleSelected';
  10734. } elseif ($status <= 0) {
  10735. $attr['class'] .= ' refused';
  10736. $attr['href'] = '';
  10737. if ($status == -1) { // disable
  10738. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  10739. } elseif ($status == 0) { // Not enough permissions
  10740. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  10741. }
  10742. }
  10743. if (!empty($attr['title']) && $useclassfortooltip) {
  10744. $attr['class'] .= ' classfortooltip';
  10745. }
  10746. if (!empty($id)) {
  10747. $attr['id'] = $id;
  10748. }
  10749. // Override attr
  10750. if (!empty($params['attr']) && is_array($params['attr'])) {
  10751. foreach ($params['attr'] as $key => $value) {
  10752. if ($key == 'class') {
  10753. $attr['class'] .= ' '.$value;
  10754. } elseif ($key == 'classOverride') {
  10755. $attr['class'] = $value;
  10756. } else {
  10757. $attr[$key] = $value;
  10758. }
  10759. }
  10760. }
  10761. if (isset($attr['href']) && empty($attr['href'])) {
  10762. unset($attr['href']);
  10763. }
  10764. // TODO : add a hook
  10765. // escape all attribute
  10766. $attr = array_map('dol_escape_htmltag', $attr);
  10767. $TCompiledAttr = array();
  10768. foreach ($attr as $key => $value) {
  10769. $TCompiledAttr[] = $key.'="'.$value.'"';
  10770. }
  10771. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  10772. $tag = (empty($attr['href']) ? 'span' : 'a');
  10773. $button = '<'.$tag.' '.$compiledAttributes.'>';
  10774. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  10775. if (!empty($params['forcenohideoftext'])) {
  10776. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  10777. }
  10778. $button .= '</'.$tag.'>';
  10779. return $button;
  10780. }
  10781. /**
  10782. * Get an array with properties of an element.
  10783. *
  10784. * @param string $element_type Element type (Value of $object->element). Example:
  10785. * 'action', 'facture', 'project', 'project_task' or
  10786. * 'myobject@mymodule' or
  10787. * 'myobject_mysubobject' (where mymodule = myobject, like 'project_task')
  10788. * @return array array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>)
  10789. * @see fetchObjectByElement()
  10790. */
  10791. function getElementProperties($element_type)
  10792. {
  10793. global $conf;
  10794. $regs = array();
  10795. //$element_type='facture';
  10796. $classfile = $classname = $classpath = $subdir = $dir_output = '';
  10797. // Parse element/subelement
  10798. $module = $element_type;
  10799. $element = $element_type;
  10800. $subelement = $element_type;
  10801. $table_element = $element_type;
  10802. // If we ask a resource form external module (instead of default path)
  10803. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) { // 'myobject@mymodule'
  10804. $element = $subelement = $regs[1];
  10805. $module = $regs[2];
  10806. }
  10807. // If we ask a resource for a string with an element and a subelement
  10808. // Example 'project_task'
  10809. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
  10810. $module = $element = $regs[1];
  10811. $subelement = $regs[2];
  10812. }
  10813. // For compatibility and to work with non standard path
  10814. if ($element_type == "action" || $element_type == "actioncomm") {
  10815. $classpath = 'comm/action/class';
  10816. $subelement = 'Actioncomm';
  10817. $module = 'agenda';
  10818. $table_element = 'actioncomm';
  10819. } elseif ($element_type == 'cronjob') {
  10820. $classpath = 'cron/class';
  10821. $module = 'cron';
  10822. $table_element = 'cron';
  10823. } elseif ($element_type == 'adherent_type') {
  10824. $classpath = 'adherents/class';
  10825. $classfile = 'adherent_type';
  10826. $module = 'adherent';
  10827. $subelement = 'adherent_type';
  10828. $classname = 'AdherentType';
  10829. $table_element = 'adherent_type';
  10830. } elseif ($element_type == 'bank_account') {
  10831. $classpath = 'compta/bank/class';
  10832. $module = 'bank'; // We need $conf->bank->dir_output and not $conf->banque->dir_output
  10833. $classfile = 'account';
  10834. $classname = 'Account';
  10835. } elseif ($element_type == 'category') {
  10836. $classpath = 'categories/class';
  10837. $module = 'categorie';
  10838. $subelement = 'categorie';
  10839. $table_element = 'categorie';
  10840. } elseif ($element_type == 'contact') {
  10841. $classpath = 'contact/class';
  10842. $classfile = 'contact';
  10843. $module = 'societe';
  10844. $subelement = 'contact';
  10845. $table_element = 'socpeople';
  10846. } elseif ($element_type == 'inventory') {
  10847. $module = 'product';
  10848. $classpath = 'product/inventory/class';
  10849. } elseif ($element_type == 'stock' || $element_type == 'entrepot') {
  10850. $module = 'stock';
  10851. $classpath = 'product/stock/class';
  10852. $classfile = 'entrepot';
  10853. $classname = 'Entrepot';
  10854. $table_element = 'entrepot';
  10855. } elseif ($element_type == 'project') {
  10856. $classpath = 'projet/class';
  10857. $module = 'projet';
  10858. $table_element = 'projet';
  10859. } elseif ($element_type == 'project_task') {
  10860. $classpath = 'projet/class';
  10861. $module = 'projet';
  10862. $subelement = 'task';
  10863. $table_element = 'projet_task';
  10864. } elseif ($element_type == 'facture' || $element_type == 'invoice') {
  10865. $classpath = 'compta/facture/class';
  10866. $module = 'facture';
  10867. $subelement = 'facture';
  10868. $table_element = 'facture';
  10869. } elseif ($element_type == 'commande' || $element_type == 'order') {
  10870. $classpath = 'commande/class';
  10871. $module = 'commande';
  10872. $subelement = 'commande';
  10873. $table_element = 'commande';
  10874. } elseif ($element_type == 'propal') {
  10875. $classpath = 'comm/propal/class';
  10876. $table_element = 'propal';
  10877. } elseif ($element_type == 'shipping') {
  10878. $classpath = 'expedition/class';
  10879. $classfile = 'expedition';
  10880. $classname = 'Expedition';
  10881. $module = 'expedition';
  10882. $table_element = 'expedition';
  10883. } elseif ($element_type == 'supplier_proposal') {
  10884. $classpath = 'supplier_proposal/class';
  10885. $module = 'supplier_proposal';
  10886. $element = 'supplierproposal';
  10887. $classfile = 'supplier_proposal';
  10888. $subelement = 'supplierproposal';
  10889. } elseif ($element_type == 'shipping') {
  10890. $classpath = 'expedition/class';
  10891. $subelement = 'expedition';
  10892. $module = 'expedition_bon';
  10893. } elseif ($element_type == 'delivery') {
  10894. $classpath = 'delivery/class';
  10895. $subelement = 'delivery';
  10896. $module = 'expedition';
  10897. } elseif ($element_type == 'contract') {
  10898. $classpath = 'contrat/class';
  10899. $module = 'contrat';
  10900. $subelement = 'contrat';
  10901. $table_element = 'contract';
  10902. } elseif ($element_type == 'mailing') {
  10903. $classpath = 'comm/mailing/class';
  10904. $module = 'mailing';
  10905. $classfile = 'mailing';
  10906. $classname = 'Mailing';
  10907. $subelement = '';
  10908. } elseif ($element_type == 'member') {
  10909. $classpath = 'adherents/class';
  10910. $module = 'adherent';
  10911. $subelement = 'adherent';
  10912. $table_element = 'adherent';
  10913. } elseif ($element_type == 'usergroup') {
  10914. $classpath = 'user/class';
  10915. $module = 'user';
  10916. } elseif ($element_type == 'mo') {
  10917. $classpath = 'mrp/class';
  10918. $classfile = 'mo';
  10919. $classname = 'Mo';
  10920. $module = 'mrp';
  10921. $subelement = '';
  10922. $table_element = 'mrp_mo';
  10923. } elseif ($element_type == 'cabinetmed_cons') {
  10924. $classpath = 'cabinetmed/class';
  10925. $module = 'cabinetmed';
  10926. $subelement = 'cabinetmedcons';
  10927. $table_element = 'cabinetmedcons';
  10928. } elseif ($element_type == 'fichinter') {
  10929. $classpath = 'fichinter/class';
  10930. $module = 'ficheinter';
  10931. $subelement = 'fichinter';
  10932. $table_element = 'fichinter';
  10933. } elseif ($element_type == 'dolresource' || $element_type == 'resource') {
  10934. $classpath = 'resource/class';
  10935. $module = 'resource';
  10936. $subelement = 'dolresource';
  10937. $table_element = 'resource';
  10938. } elseif ($element_type == 'propaldet') {
  10939. $classpath = 'comm/propal/class';
  10940. $module = 'propal';
  10941. $subelement = 'propaleligne';
  10942. } elseif ($element_type == 'opensurvey_sondage') {
  10943. $classpath = 'opensurvey/class';
  10944. $module = 'opensurvey';
  10945. $subelement = 'opensurveysondage';
  10946. } elseif ($element_type == 'order_supplier') {
  10947. $classpath = 'fourn/class';
  10948. $module = 'fournisseur';
  10949. $classfile = 'fournisseur.commande';
  10950. $element = 'order_supplier';
  10951. $subelement = '';
  10952. $classname = 'CommandeFournisseur';
  10953. $table_element = 'commande_fournisseur';
  10954. } elseif ($element_type == 'commande_fournisseurdet') {
  10955. $classpath = 'fourn/class';
  10956. $module = 'fournisseur';
  10957. $classfile = 'fournisseur.commande';
  10958. $element = 'commande_fournisseurdet';
  10959. $subelement = '';
  10960. $classname = 'CommandeFournisseurLigne';
  10961. $table_element = 'commande_fournisseurdet';
  10962. } elseif ($element_type == 'invoice_supplier') {
  10963. $classpath = 'fourn/class';
  10964. $module = 'fournisseur';
  10965. $classfile = 'fournisseur.facture';
  10966. $element = 'invoice_supplier';
  10967. $subelement = '';
  10968. $classname = 'FactureFournisseur';
  10969. $table_element = 'facture_fourn';
  10970. } elseif ($element_type == "service") {
  10971. $classpath = 'product/class';
  10972. $subelement = 'product';
  10973. $table_element = 'product';
  10974. } elseif ($element_type == 'salary') {
  10975. $classpath = 'salaries/class';
  10976. $module = 'salaries';
  10977. } elseif ($element_type == 'payment_salary') {
  10978. $classpath = 'salaries/class';
  10979. $classfile = 'paymentsalary';
  10980. $classname = 'PaymentSalary';
  10981. $module = 'salaries';
  10982. } elseif ($element_type == 'productlot') {
  10983. $module = 'productbatch';
  10984. $classpath = 'product/stock/class';
  10985. $classfile = 'productlot';
  10986. $classname = 'Productlot';
  10987. $element = 'productlot';
  10988. $subelement = '';
  10989. $table_element = 'product_lot';
  10990. } elseif ($element_type == 'websitepage') {
  10991. $classpath = 'website/class';
  10992. $classfile = 'websitepage';
  10993. $classname = 'Websitepage';
  10994. $module = 'website';
  10995. $subelement = 'websitepage';
  10996. $table_element = 'website_page';
  10997. } elseif ($element_type == 'fiscalyear') {
  10998. $classpath = 'core/class';
  10999. $module = 'accounting';
  11000. $subelement = 'fiscalyear';
  11001. } elseif ($element_type == 'chargesociales') {
  11002. $classpath = 'compta/sociales/class';
  11003. $module = 'tax';
  11004. $table_element = 'chargesociales';
  11005. } elseif ($element_type == 'tva') {
  11006. $classpath = 'compta/tva/class';
  11007. $module = 'tax';
  11008. $subdir = '/vat';
  11009. $table_element = 'tva';
  11010. } elseif ($element_type == 'emailsenderprofile') {
  11011. $module = '';
  11012. $classpath = 'core/class';
  11013. $classfile = 'emailsenderprofile';
  11014. $classname = 'EmailSenderProfile';
  11015. $table_element = 'c_email_senderprofile';
  11016. $subelement = '';
  11017. }
  11018. if (empty($classfile)) {
  11019. $classfile = strtolower($subelement);
  11020. }
  11021. if (empty($classname)) {
  11022. $classname = ucfirst($subelement);
  11023. }
  11024. if (empty($classpath)) {
  11025. $classpath = $module.'/class';
  11026. }
  11027. //print 'getElementProperties subdir='.$subdir;
  11028. // Set dir_output
  11029. if ($module && isset($conf->$module)) { // The generic case
  11030. if (!empty($conf->$module->multidir_output[$conf->entity])) {
  11031. $dir_output = $conf->$module->multidir_output[$conf->entity];
  11032. } elseif (!empty($conf->$module->output[$conf->entity])) {
  11033. $dir_output = $conf->$module->output[$conf->entity];
  11034. } elseif (!empty($conf->$module->dir_output)) {
  11035. $dir_output = $conf->$module->dir_output;
  11036. }
  11037. }
  11038. // Overwrite value for special cases
  11039. if ($element == 'order_supplier') {
  11040. $dir_output = $conf->fournisseur->commande->dir_output;
  11041. } elseif ($element == 'invoice_supplier') {
  11042. $dir_output = $conf->fournisseur->facture->dir_output;
  11043. }
  11044. $dir_output .= $subdir;
  11045. $element_properties = array(
  11046. 'module' => $module,
  11047. 'element' => $element,
  11048. 'table_element' => $table_element,
  11049. 'subelement' => $subelement,
  11050. 'classpath' => $classpath,
  11051. 'classfile' => $classfile,
  11052. 'classname' => $classname,
  11053. 'dir_output' => $dir_output
  11054. );
  11055. //var_dump($element_properties);
  11056. return $element_properties;
  11057. }
  11058. /**
  11059. * Fetch an object from its id and element_type
  11060. * Inclusion of classes is automatic
  11061. *
  11062. * @param int $element_id Element id (Use this or element_id but not both)
  11063. * @param string $element_type Element type ('module' or 'myobject@mymodule' or 'mymodule_myobject')
  11064. * @param string $element_ref Element ref (Use this or element_id but not both)
  11065. * @return int|object object || 0 || <0 if error
  11066. * @see getElementProperties()
  11067. */
  11068. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  11069. {
  11070. global $db;
  11071. $ret = 0;
  11072. $element_prop = getElementProperties($element_type);
  11073. if ($element_prop['module'] == 'product' || $element_prop['module'] == 'service') {
  11074. // For example, for an extrafield 'product' (shared for both product and service) that is a link to an object,
  11075. // this is called with $element_type = 'product' when we need element properties of a service, we must return a product. If we create the
  11076. // extrafield for a service, it is not supported and not found when editing the product/service card. So we must keep 'product' for extrafields
  11077. // of service and we will return properties of a product.
  11078. $ismodenabled = (isModEnabled('product') || isModEnabled('service'));
  11079. } else {
  11080. $ismodenabled = isModEnabled($element_prop['module']);
  11081. }
  11082. //var_dump('element_type='.$element_type);
  11083. //var_dump($element_prop);
  11084. //var_dump($element_prop['module'].' '.$ismodenabled);
  11085. if (is_array($element_prop) && (empty($element_prop['module']) || $ismodenabled)) {
  11086. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  11087. if (class_exists($element_prop['classname'])) {
  11088. $classname = $element_prop['classname'];
  11089. $objecttmp = new $classname($db);
  11090. if ($element_id > 0 || !empty($element_ref)) {
  11091. $ret = $objecttmp->fetch($element_id, $element_ref);
  11092. if ($ret >= 0) {
  11093. if (empty($objecttmp->module)) {
  11094. $objecttmp->module = $element_prop['module'];
  11095. }
  11096. return $objecttmp;
  11097. }
  11098. } else {
  11099. return $objecttmp; // returned an object without fetch
  11100. }
  11101. } else {
  11102. return -1;
  11103. }
  11104. }
  11105. return $ret;
  11106. }
  11107. /**
  11108. * Return if a file can contains executable content
  11109. *
  11110. * @param string $filename File name to test
  11111. * @return boolean True if yes, False if no
  11112. */
  11113. function isAFileWithExecutableContent($filename)
  11114. {
  11115. 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)) {
  11116. return true;
  11117. }
  11118. return false;
  11119. }
  11120. /**
  11121. * Return the value of token currently saved into session with name 'newtoken'.
  11122. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  11123. *
  11124. * @since Dolibarr v10.0.7
  11125. * @return string
  11126. */
  11127. function newToken()
  11128. {
  11129. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  11130. }
  11131. /**
  11132. * Return the value of token currently saved into session with name 'token'.
  11133. * For ajax call, you must use this token as a parameter of the call into the js calling script (the called ajax php page must also set constant NOTOKENRENEWAL).
  11134. *
  11135. * @since Dolibarr v10.0.7
  11136. * @return string
  11137. */
  11138. function currentToken()
  11139. {
  11140. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  11141. }
  11142. /**
  11143. * Return a random string to be used as a nonce value for js
  11144. *
  11145. * @return string
  11146. */
  11147. function getNonce()
  11148. {
  11149. global $conf;
  11150. if (empty($conf->cache['nonce'])) {
  11151. $conf->cache['nonce'] = dolGetRandomBytes(8);
  11152. }
  11153. return $conf->cache['nonce'];
  11154. }
  11155. /**
  11156. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  11157. *
  11158. * @param string $header The first left header of the table (automatic translated)
  11159. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  11160. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  11161. * @param integer $emptyRows (optional) The count of empty rows after the first header
  11162. * @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"
  11163. * @return void
  11164. *
  11165. * @see finishSimpleTable()
  11166. */
  11167. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  11168. {
  11169. global $langs;
  11170. print '<div class="div-table-responsive-no-min">';
  11171. print '<table class="noborder centpercent">';
  11172. print '<tr class="liste_titre">';
  11173. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  11174. print $langs->trans($header);
  11175. // extra space between the first header and the number
  11176. if ($number > -1) {
  11177. print ' ';
  11178. }
  11179. if (!empty($link)) {
  11180. if (!empty($arguments)) {
  11181. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  11182. } else {
  11183. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  11184. }
  11185. }
  11186. if ($number > -1) {
  11187. print '<span class="badge">'.$number.'</span>';
  11188. }
  11189. if (!empty($link)) {
  11190. print '</a>';
  11191. }
  11192. print '</th>';
  11193. if ($number < 0 && !empty($link)) {
  11194. print '<th class="right">';
  11195. if (!empty($arguments)) {
  11196. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  11197. } else {
  11198. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  11199. }
  11200. print $langs->trans("FullList");
  11201. print '</a>';
  11202. print '</th>';
  11203. }
  11204. print '</tr>';
  11205. }
  11206. /**
  11207. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  11208. *
  11209. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  11210. * @return void
  11211. *
  11212. * @see startSimpleTable()
  11213. */
  11214. function finishSimpleTable($addLineBreak = false)
  11215. {
  11216. print '</table>';
  11217. print '</div>';
  11218. if ($addLineBreak) {
  11219. print '<br>';
  11220. }
  11221. }
  11222. /**
  11223. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  11224. *
  11225. * @param integer $tableColumnCount The complete count columns of the table
  11226. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  11227. * @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)
  11228. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  11229. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  11230. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  11231. * @return void
  11232. */
  11233. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  11234. {
  11235. global $langs;
  11236. if ($num === 0) {
  11237. print '<tr class="oddeven">';
  11238. print '<td colspan="'.$tableColumnCount.'"><span class="opacitymedium">'.$langs->trans($noneWord).'</span></td>';
  11239. print '</tr>';
  11240. return;
  11241. }
  11242. if ($nbofloop === 0) {
  11243. // don't show a summary line
  11244. return;
  11245. }
  11246. if ($num === 0) {
  11247. $colspan = $tableColumnCount;
  11248. } elseif ($num > $nbofloop) {
  11249. $colspan = $tableColumnCount;
  11250. } else {
  11251. $colspan = $tableColumnCount - 1;
  11252. }
  11253. if ($extraRightColumn) {
  11254. $colspan--;
  11255. }
  11256. print '<tr class="liste_total">';
  11257. if ($nbofloop > 0 && $num > $nbofloop) {
  11258. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  11259. } else {
  11260. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  11261. print '<td class="right centpercent">'.price($total).'</td>';
  11262. }
  11263. if ($extraRightColumn) {
  11264. print '<td></td>';
  11265. }
  11266. print '</tr>';
  11267. }
  11268. /**
  11269. * Return a file on output using a low memory. It can return very large files with no need of memory.
  11270. * WARNING: This close output buffers.
  11271. *
  11272. * @param string $fullpath_original_file_osencoded Full path of file to return.
  11273. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  11274. * @return void
  11275. */
  11276. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  11277. {
  11278. if ($method == -1) {
  11279. $method = 0;
  11280. if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_FREAD')) {
  11281. $method = 1;
  11282. }
  11283. if (getDolGlobalString('MAIN_FORCE_READFILE_WITH_STREAM_COPY')) {
  11284. $method = 2;
  11285. }
  11286. }
  11287. // Be sure we don't have output buffering enabled to have readfile working correctly
  11288. while (ob_get_level()) {
  11289. ob_end_flush();
  11290. }
  11291. // Solution 0
  11292. if ($method == 0) {
  11293. readfile($fullpath_original_file_osencoded);
  11294. } elseif ($method == 1) {
  11295. // Solution 1
  11296. $handle = fopen($fullpath_original_file_osencoded, "rb");
  11297. while (!feof($handle)) {
  11298. print fread($handle, 8192);
  11299. }
  11300. fclose($handle);
  11301. } elseif ($method == 2) {
  11302. // Solution 2
  11303. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  11304. $handle2 = fopen("php://output", "wb");
  11305. stream_copy_to_stream($handle1, $handle2);
  11306. fclose($handle1);
  11307. fclose($handle2);
  11308. }
  11309. }
  11310. /**
  11311. * Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
  11312. * Code that handle the click is inside core/js/lib_foot.js.php.
  11313. *
  11314. * @param string $valuetocopy The value to print
  11315. * @param int $showonlyonhover Show the copy-paste button only on hover
  11316. * @param string $texttoshow Replace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
  11317. * @return string The string to print for the button
  11318. */
  11319. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  11320. {
  11321. /*
  11322. global $conf;
  11323. if (!empty($conf->dol_no_mouse_hover)) {
  11324. $showonlyonhover = 0;
  11325. }*/
  11326. $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
  11327. if ($texttoshow === 'none') {
  11328. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint"></span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  11329. } elseif ($texttoshow) {
  11330. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint">'.dol_escape_htmltag($texttoshow, 1, 1).'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  11331. } else {
  11332. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  11333. }
  11334. return $result;
  11335. }
  11336. /**
  11337. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  11338. *
  11339. * @param string $stringtodecode String to decode (json or serialize coded)
  11340. * @return mixed The decoded object.
  11341. */
  11342. function jsonOrUnserialize($stringtodecode)
  11343. {
  11344. $result = json_decode($stringtodecode);
  11345. if ($result === null) {
  11346. $result = unserialize($stringtodecode);
  11347. }
  11348. return $result;
  11349. }
  11350. /**
  11351. * forgeSQLFromUniversalSearchCriteria
  11352. *
  11353. * @param string $filter String with universal search string. Must be '(aaa:bbb:...) OR (ccc:ddd:...) ...' with
  11354. * aaa is a field name (with alias or not) and
  11355. * bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'.
  11356. * Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
  11357. * @param string $errorstr Error message string
  11358. * @param int $noand 1=Do not add the AND before the condition string.
  11359. * @param int $nopar 1=Do not add the perenthesis around the condition string.
  11360. * @param int $noerror 1=If search criteria is not valid, does not return an error string but invalidate the SQL
  11361. * @return string Return forged SQL string
  11362. */
  11363. function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0)
  11364. {
  11365. if (!preg_match('/^\(.*\)$/', $filter)) { // If $filter does not start and end with ()
  11366. $filter = '(' . $filter . ')';
  11367. }
  11368. $regexstring = '\(([a-zA-Z0-9_\.]+:[<>!=insotlke]+:[^\(\)]+)\)'; // Must be (aaa:bbb:...) with aaa is a field name (with alias or not) and bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'
  11369. if (!dolCheckFilters($filter, $errorstr)) {
  11370. if ($noerror) {
  11371. return '1 = 2';
  11372. } else {
  11373. return 'Filter syntax error - '.$errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
  11374. }
  11375. }
  11376. // Test the filter syntax
  11377. $t = preg_replace_callback('/'.$regexstring.'/i', 'dolForgeDummyCriteriaCallback', $filter);
  11378. $t = str_replace(array('and','or','AND','OR',' '), '', $t); // Remove the only strings allowed between each () criteria
  11379. // If the string result contains something else than '()', the syntax was wrong
  11380. if (preg_match('/[^\(\)]/', $t)) {
  11381. $errorstr = 'Bad syntax of the search string';
  11382. if ($noerror) {
  11383. return '1 = 2';
  11384. } else {
  11385. return 'Filter syntax error - '.$errorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
  11386. }
  11387. }
  11388. return ($noand ? "" : " AND ").($nopar ? "" : '(').preg_replace_callback('/'.$regexstring.'/i', 'dolForgeCriteriaCallback', $filter).($nopar ? "" : ')');
  11389. }
  11390. /**
  11391. * Return if a $sqlfilters parameter has a valid balance of parenthesis
  11392. *
  11393. * @param string $sqlfilters sqlfilter string
  11394. * @param string $error Error message
  11395. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  11396. */
  11397. function dolCheckFilters($sqlfilters, &$error = '')
  11398. {
  11399. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  11400. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  11401. $tmp = $sqlfilters;
  11402. $i = 0;
  11403. $nb = strlen($tmp);
  11404. $counter = 0;
  11405. while ($i < $nb) {
  11406. if ($tmp[$i] == '(') {
  11407. $counter++;
  11408. }
  11409. if ($tmp[$i] == ')') {
  11410. $counter--;
  11411. }
  11412. if ($counter < 0) {
  11413. $error = "Wrond balance of parenthesis in sqlfilters=".$sqlfilters;
  11414. dol_syslog($error, LOG_WARNING);
  11415. return false;
  11416. }
  11417. $i++;
  11418. }
  11419. return true;
  11420. }
  11421. /**
  11422. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  11423. * This method is called by forgeSQLFromUniversalSearchCriteria()
  11424. *
  11425. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  11426. * @return string Forged criteria. Example: "" or "()"
  11427. */
  11428. function dolForgeDummyCriteriaCallback($matches)
  11429. {
  11430. //dol_syslog("Convert matches ".$matches[1]);
  11431. if (empty($matches[1])) {
  11432. return '';
  11433. }
  11434. $tmp = explode(':', $matches[1]);
  11435. if (count($tmp) < 3) {
  11436. return '';
  11437. }
  11438. return '()'; // An empty criteria
  11439. }
  11440. /**
  11441. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  11442. * This method is called by forgeSQLFromUniversalSearchCriteria()
  11443. *
  11444. * @param array $matches Array of found string by regex search.
  11445. * Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL"
  11446. * @return string Forged criteria. Example: "t.field LIKE 'abc%'"
  11447. */
  11448. function dolForgeCriteriaCallback($matches)
  11449. {
  11450. global $db;
  11451. //dol_syslog("Convert matches ".$matches[1]);
  11452. if (empty($matches[1])) {
  11453. return '';
  11454. }
  11455. $tmp = explode(':', $matches[1]);
  11456. if (count($tmp) < 3) {
  11457. return '';
  11458. }
  11459. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  11460. $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
  11461. $realOperator = [
  11462. 'NOTLIKE' => 'NOT LIKE',
  11463. 'ISNOT' => 'IS NOT',
  11464. 'NOTIN' => 'NOT IN',
  11465. '!=' => '<>',
  11466. ];
  11467. if (array_key_exists($operator, $realOperator)) {
  11468. $operator = $realOperator[$operator];
  11469. }
  11470. $tmpescaped = $tmp[2];
  11471. $regbis = array();
  11472. if ($operator == 'IN' || $operator == 'NOT IN') { // IN is allowed for list of ID or code only
  11473. //if (!preg_match('/^\(.*\)$/', $tmpescaped)) {
  11474. $tmpescaped2 = '(';
  11475. // Explode and sanitize each element in list
  11476. $tmpelemarray = explode(',', $tmpescaped);
  11477. foreach ($tmpelemarray as $tmpkey => $tmpelem) {
  11478. $reg = array();
  11479. if (preg_match('/^\'(.*)\'$/', $tmpelem, $reg)) {
  11480. $tmpelemarray[$tmpkey] = "'".$db->escape($db->sanitize($reg[1], 1, 1, 1))."'";
  11481. } else {
  11482. $tmpelemarray[$tmpkey] = $db->escape($db->sanitize($tmpelem, 1, 1, 1));
  11483. }
  11484. }
  11485. $tmpescaped2 .= join(',', $tmpelemarray);
  11486. $tmpescaped2 .= ')';
  11487. $tmpescaped = $tmpescaped2;
  11488. } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
  11489. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  11490. $tmpescaped = $regbis[1];
  11491. }
  11492. //$tmpescaped = "'".$db->escape($db->escapeforlike($regbis[1]))."'";
  11493. $tmpescaped = "'".$db->escape($tmpescaped)."'"; // We do not escape the _ and % so the like will works
  11494. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  11495. $tmpescaped = "'".$db->escape($regbis[1])."'";
  11496. } else {
  11497. if (strtoupper($tmpescaped) == 'NULL') {
  11498. $tmpescaped = 'NULL';
  11499. } elseif (is_int($tmpescaped)) {
  11500. $tmpescaped = (int) $tmpescaped;
  11501. } else {
  11502. $tmpescaped = (float) $tmpescaped;
  11503. }
  11504. }
  11505. return '('.$db->escape($operand).' '.strtoupper($operator).' '.$tmpescaped.')';
  11506. }
  11507. /**
  11508. * Get timeline icon
  11509. *
  11510. * @param ActionComm $actionstatic actioncomm
  11511. * @param array $histo histo
  11512. * @param int $key key
  11513. * @return string String with timeline icon
  11514. * @deprecated Use actioncomm->getPictoType() instead
  11515. */
  11516. function getTimelineIcon($actionstatic, &$histo, $key)
  11517. {
  11518. global $conf, $langs;
  11519. $out = '<!-- timeline icon -->'."\n";
  11520. $iconClass = 'fa fa-comments';
  11521. $img_picto = '';
  11522. $colorClass = '';
  11523. $pictoTitle = '';
  11524. if ($histo[$key]['percent'] == -1) {
  11525. $colorClass = 'timeline-icon-not-applicble';
  11526. $pictoTitle = $langs->trans('StatusNotApplicable');
  11527. } elseif ($histo[$key]['percent'] == 0) {
  11528. $colorClass = 'timeline-icon-todo';
  11529. $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
  11530. } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
  11531. $colorClass = 'timeline-icon-in-progress';
  11532. $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
  11533. } elseif ($histo[$key]['percent'] >= 100) {
  11534. $colorClass = 'timeline-icon-done';
  11535. $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
  11536. }
  11537. if ($actionstatic->code == 'AC_TICKET_CREATE') {
  11538. $iconClass = 'fa fa-ticket';
  11539. } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
  11540. $iconClass = 'fa fa-pencilxxx';
  11541. } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11542. $iconClass = 'fa fa-comments';
  11543. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  11544. $iconClass = 'fa fa-mask';
  11545. } elseif (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
  11546. if ($actionstatic->type_picto) {
  11547. $img_picto = img_picto('', $actionstatic->type_picto);
  11548. } else {
  11549. if ($actionstatic->type_code == 'AC_RDV') {
  11550. $iconClass = 'fa fa-handshake';
  11551. } elseif ($actionstatic->type_code == 'AC_TEL') {
  11552. $iconClass = 'fa fa-phone';
  11553. } elseif ($actionstatic->type_code == 'AC_FAX') {
  11554. $iconClass = 'fa fa-fax';
  11555. } elseif ($actionstatic->type_code == 'AC_EMAIL') {
  11556. $iconClass = 'fa fa-envelope';
  11557. } elseif ($actionstatic->type_code == 'AC_INT') {
  11558. $iconClass = 'fa fa-shipping-fast';
  11559. } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
  11560. $iconClass = 'fa fa-robot';
  11561. } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
  11562. $iconClass = 'fa fa-robot';
  11563. }
  11564. }
  11565. }
  11566. $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
  11567. return $out;
  11568. }
  11569. /**
  11570. * getActionCommEcmList
  11571. *
  11572. * @param ActionComm $object Object ActionComm
  11573. * @return array Array of documents in index table
  11574. */
  11575. function getActionCommEcmList($object)
  11576. {
  11577. global $conf, $db;
  11578. $documents = array();
  11579. $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename';
  11580. $sql .= ' FROM '.MAIN_DB_PREFIX.'ecm_files ecm';
  11581. $sql .= " WHERE ecm.filepath = 'agenda/".((int) $object->id)."'";
  11582. //$sql.= " ecm.src_object_type = '".$db->escape($object->element)."' AND ecm.src_object_id = ".((int) $object->id); // Old version didn't add object_type during upload
  11583. $sql .= ' ORDER BY ecm.position ASC';
  11584. $resql = $db->query($sql);
  11585. if ($resql) {
  11586. if ($db->num_rows($resql)) {
  11587. while ($obj = $db->fetch_object($resql)) {
  11588. $documents[$obj->id] = $obj;
  11589. }
  11590. }
  11591. }
  11592. return $documents;
  11593. }
  11594. /**
  11595. * Show html area with actions in messaging format.
  11596. * Note: Global parameter $param must be defined.
  11597. *
  11598. * @param Conf $conf Object conf
  11599. * @param Translate $langs Object langs
  11600. * @param DoliDB $db Object db
  11601. * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object
  11602. * @param Contact $objcon Filter on object contact to filter events on a contact
  11603. * @param int $noprint Return string but does not output it
  11604. * @param string $actioncode Filter on actioncode
  11605. * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all).
  11606. * @param array $filters Filter on other fields
  11607. * @param string $sortfield Sort field
  11608. * @param string $sortorder Sort order
  11609. * @return string|void Return html part or void if noprint is 1
  11610. */
  11611. function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
  11612. {
  11613. global $user, $conf;
  11614. global $form;
  11615. global $param, $massactionbutton;
  11616. dol_include_once('/comm/action/class/actioncomm.class.php');
  11617. // Check parameters
  11618. if (!is_object($filterobj) && !is_object($objcon)) {
  11619. dol_print_error('', 'BadParameter');
  11620. }
  11621. $histo = array();
  11622. $numaction = 0;
  11623. $now = dol_now();
  11624. $sortfield_list = explode(',', $sortfield);
  11625. $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
  11626. $sortfield_new_list = array();
  11627. foreach ($sortfield_list as $sortfield_value) {
  11628. $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
  11629. }
  11630. $sortfield_new = implode(',', $sortfield_new_list);
  11631. if (isModEnabled('agenda')) {
  11632. // Search histo on actioncomm
  11633. if (is_object($objcon) && $objcon->id > 0) {
  11634. $sql = "SELECT DISTINCT a.id, a.label as label,";
  11635. } else {
  11636. $sql = "SELECT a.id, a.label as label,";
  11637. }
  11638. $sql .= " a.datep as dp,";
  11639. $sql .= " a.note as message,";
  11640. $sql .= " a.datep2 as dp2,";
  11641. $sql .= " a.percent as percent, 'action' as type,";
  11642. $sql .= " a.fk_element, a.elementtype,";
  11643. $sql .= " a.fk_contact,";
  11644. $sql .= " a.email_from as msg_from,";
  11645. $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
  11646. $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
  11647. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11648. $sql .= ", sp.lastname, sp.firstname";
  11649. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11650. $sql .= ", m.lastname, m.firstname";
  11651. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11652. $sql .= ", o.ref";
  11653. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11654. $sql .= ", o.ref";
  11655. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11656. $sql .= ", o.ref";
  11657. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11658. $sql .= ", o.ref";
  11659. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11660. $sql .= ", o.ref";
  11661. }
  11662. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  11663. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
  11664. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
  11665. $force_filter_contact = false;
  11666. if (is_object($objcon) && $objcon->id > 0) {
  11667. $force_filter_contact = true;
  11668. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
  11669. $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
  11670. }
  11671. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11672. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
  11673. } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
  11674. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
  11675. $sql .= " ON er.resource_type = 'dolresource'";
  11676. $sql .= " AND er.element_id = a.id";
  11677. $sql .= " AND er.resource_id = ".((int) $filterobj->id);
  11678. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11679. $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
  11680. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11681. $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
  11682. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11683. $sql .= ", ".MAIN_DB_PREFIX."product as o";
  11684. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11685. $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
  11686. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11687. $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
  11688. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11689. $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
  11690. }
  11691. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  11692. if ($force_filter_contact === false) {
  11693. if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
  11694. $sql .= " AND a.fk_soc = ".((int) $filterobj->id);
  11695. } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
  11696. $sql .= " AND a.fk_project = ".((int) $filterobj->id);
  11697. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11698. $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
  11699. if ($filterobj->id) {
  11700. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11701. }
  11702. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11703. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
  11704. if ($filterobj->id) {
  11705. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11706. }
  11707. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11708. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
  11709. if ($filterobj->id) {
  11710. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11711. }
  11712. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11713. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
  11714. if ($filterobj->id) {
  11715. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11716. }
  11717. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11718. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
  11719. if ($filterobj->id) {
  11720. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11721. }
  11722. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11723. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
  11724. if ($filterobj->id) {
  11725. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11726. }
  11727. }
  11728. }
  11729. // Condition on actioncode
  11730. if (!empty($actioncode)) {
  11731. if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
  11732. if ($actioncode == 'AC_NON_AUTO') {
  11733. $sql .= " AND c.type != 'systemauto'";
  11734. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11735. $sql .= " AND c.type = 'systemauto'";
  11736. } else {
  11737. if ($actioncode == 'AC_OTH') {
  11738. $sql .= " AND c.type != 'systemauto'";
  11739. } elseif ($actioncode == 'AC_OTH_AUTO') {
  11740. $sql .= " AND c.type = 'systemauto'";
  11741. }
  11742. }
  11743. } else {
  11744. if ($actioncode == 'AC_NON_AUTO') {
  11745. $sql .= " AND c.type != 'systemauto'";
  11746. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11747. $sql .= " AND c.type = 'systemauto'";
  11748. } else {
  11749. $sql .= " AND c.code = '".$db->escape($actioncode)."'";
  11750. }
  11751. }
  11752. }
  11753. if ($donetodo == 'todo') {
  11754. $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11755. } elseif ($donetodo == 'done') {
  11756. $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11757. }
  11758. if (is_array($filters) && $filters['search_agenda_label']) {
  11759. $sql .= natural_search('a.label', $filters['search_agenda_label']);
  11760. }
  11761. }
  11762. // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
  11763. if (isModEnabled('mailing') && !empty($objcon->email)
  11764. && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
  11765. $langs->load("mails");
  11766. $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type";
  11767. $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
  11768. $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
  11769. $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
  11770. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11771. $sql2 .= ", '' as lastname, '' as firstname";
  11772. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11773. $sql2 .= ", '' as lastname, '' as firstname";
  11774. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11775. $sql2 .= ", '' as ref";
  11776. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11777. $sql2 .= ", '' as ref";
  11778. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11779. $sql2 .= ", '' as ref";
  11780. }
  11781. $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
  11782. $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
  11783. $sql2 .= " AND mc.statut = 1";
  11784. $sql2 .= " AND u.rowid = m.fk_user_valid";
  11785. $sql2 .= " AND mc.fk_mailing=m.rowid";
  11786. }
  11787. if (!empty($sql) && !empty($sql2)) {
  11788. $sql = $sql." UNION ".$sql2;
  11789. } elseif (empty($sql) && !empty($sql2)) {
  11790. $sql = $sql2;
  11791. }
  11792. // TODO Add limit in nb of results
  11793. if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too
  11794. $sql .= $db->order($sortfield_new, $sortorder);
  11795. dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
  11796. $resql = $db->query($sql);
  11797. if ($resql) {
  11798. $i = 0;
  11799. $num = $db->num_rows($resql);
  11800. while ($i < $num) {
  11801. $obj = $db->fetch_object($resql);
  11802. if ($obj->type == 'action') {
  11803. $contactaction = new ActionComm($db);
  11804. $contactaction->id = $obj->id;
  11805. $result = $contactaction->fetchResources();
  11806. if ($result < 0) {
  11807. dol_print_error($db);
  11808. setEventMessage("actions.lib::show_actions_messaging Error fetch ressource", 'errors');
  11809. }
  11810. //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11811. //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11812. $tododone = '';
  11813. if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
  11814. $tododone = 'todo';
  11815. }
  11816. $histo[$numaction] = array(
  11817. 'type'=>$obj->type,
  11818. 'tododone'=>$tododone,
  11819. 'id'=>$obj->id,
  11820. 'datestart'=>$db->jdate($obj->dp),
  11821. 'dateend'=>$db->jdate($obj->dp2),
  11822. 'note'=>$obj->label,
  11823. 'message'=>$obj->message,
  11824. 'percent'=>$obj->percent,
  11825. 'userid'=>$obj->user_id,
  11826. 'login'=>$obj->user_login,
  11827. 'userfirstname'=>$obj->user_firstname,
  11828. 'userlastname'=>$obj->user_lastname,
  11829. 'userphoto'=>$obj->user_photo,
  11830. 'msg_from'=>$obj->msg_from,
  11831. 'contact_id'=>$obj->fk_contact,
  11832. 'socpeopleassigned' => $contactaction->socpeopleassigned,
  11833. 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
  11834. 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
  11835. 'fk_element'=>$obj->fk_element,
  11836. 'elementtype'=>$obj->elementtype,
  11837. // Type of event
  11838. 'acode'=>$obj->acode,
  11839. 'alabel'=>$obj->alabel,
  11840. 'libelle'=>$obj->alabel, // deprecated
  11841. 'apicto'=>$obj->apicto
  11842. );
  11843. } else {
  11844. $histo[$numaction] = array(
  11845. 'type'=>$obj->type,
  11846. 'tododone'=>'done',
  11847. 'id'=>$obj->id,
  11848. 'datestart'=>$db->jdate($obj->dp),
  11849. 'dateend'=>$db->jdate($obj->dp2),
  11850. 'note'=>$obj->label,
  11851. 'message'=>$obj->message,
  11852. 'percent'=>$obj->percent,
  11853. 'acode'=>$obj->acode,
  11854. 'userid'=>$obj->user_id,
  11855. 'login'=>$obj->user_login,
  11856. 'userfirstname'=>$obj->user_firstname,
  11857. 'userlastname'=>$obj->user_lastname,
  11858. 'userphoto'=>$obj->user_photo
  11859. );
  11860. }
  11861. $numaction++;
  11862. $i++;
  11863. }
  11864. } else {
  11865. dol_print_error($db);
  11866. }
  11867. }
  11868. // Set $out to show events
  11869. $out = '';
  11870. if (!isModEnabled('agenda')) {
  11871. $langs->loadLangs(array("admin", "errors"));
  11872. $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
  11873. }
  11874. if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
  11875. $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
  11876. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  11877. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  11878. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  11879. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  11880. $formactions = new FormActions($db);
  11881. $actionstatic = new ActionComm($db);
  11882. $userstatic = new User($db);
  11883. $contactstatic = new Contact($db);
  11884. $userGetNomUrlCache = array();
  11885. $contactGetNomUrlCache = array();
  11886. $out .= '<div class="filters-container" >';
  11887. $out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  11888. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  11889. if ($objcon && get_class($objcon) == 'Contact' &&
  11890. (is_null($filterobj) || get_class($filterobj) == 'Societe')) {
  11891. $out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
  11892. } else {
  11893. $out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
  11894. }
  11895. if ($filterobj && get_class($filterobj) == 'Societe') {
  11896. $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
  11897. }
  11898. $out .= "\n";
  11899. $out .= '<div class="div-table-responsive-no-min">';
  11900. $out .= '<table class="noborder borderbottom centpercent">';
  11901. $out .= '<tr class="liste_titre">';
  11902. // Action column
  11903. if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  11904. $out .= '<th class="liste_titre width50 middle">';
  11905. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11906. $out .= $searchpicto;
  11907. $out .= '</th>';
  11908. }
  11909. $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n";
  11910. $out .= '<th class="liste_titre"><strong class="hideonsmartphone">'.$langs->trans("Search").' : </strong></th>';
  11911. if ($donetodo) {
  11912. $out .= '<th class="liste_titre"></th>';
  11913. }
  11914. $out .= '<th class="liste_titre">';
  11915. $out .= '<span class="fas fa-square inline-block fawidth30" style=" color: #ddd;" title="'.$langs->trans("ActionType").'"></span>';
  11916. //$out .= img_picto($langs->trans("Type"), 'type');
  11917. $out .= $formactions->select_type_actions($actioncode, "actioncode", '', !getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 1 : -1, 0, 0, 1, 'minwidth200imp');
  11918. $out .= '</th>';
  11919. $out .= '<th class="liste_titre maxwidth100onsmartphone">';
  11920. $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'" placeholder="'.$langs->trans("Label").'">';
  11921. $out .= '</th>';
  11922. // Action column
  11923. if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  11924. $out .= '<th class="liste_titre width50 middle">';
  11925. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11926. $out .= $searchpicto;
  11927. $out .= '</th>';
  11928. }
  11929. $out .= '</tr>';
  11930. $out .= '</table>';
  11931. $out .= '</form>';
  11932. $out .= '</div>';
  11933. $out .= "\n";
  11934. $out .= '<ul class="timeline">';
  11935. if ($donetodo) {
  11936. $tmp = '';
  11937. if (get_class($filterobj) == 'Societe') {
  11938. $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
  11939. }
  11940. $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
  11941. $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
  11942. $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
  11943. //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
  11944. if (get_class($filterobj) == 'Societe') {
  11945. $tmp .= '</a>';
  11946. }
  11947. $out .= getTitleFieldOfList($tmp);
  11948. }
  11949. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
  11950. $caction = new CActionComm($db);
  11951. $arraylist = $caction->liste_array(1, 'code', '', (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? 1 : 0), '', 1);
  11952. $actualCycleDate = false;
  11953. // Loop on each event to show it
  11954. foreach ($histo as $key => $value) {
  11955. $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
  11956. $actionstatic->type_picto = $histo[$key]['apicto'];
  11957. $actionstatic->type_code = $histo[$key]['acode'];
  11958. $labeltype = $actionstatic->type_code;
  11959. if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && empty($arraylist[$labeltype])) {
  11960. $labeltype = 'AC_OTH';
  11961. }
  11962. if (!empty($actionstatic->code) && preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11963. $labeltype = $langs->trans("Message");
  11964. } else {
  11965. if (!empty($arraylist[$labeltype])) {
  11966. $labeltype = $arraylist[$labeltype];
  11967. }
  11968. if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) {
  11969. $labeltype .= ' - '.$arraylist[$actionstatic->code]; // Use code in priority on type_code
  11970. }
  11971. }
  11972. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
  11973. $tmpa = dol_getdate($histo[$key]['datestart'], false);
  11974. if (isset($tmpa['year']) && isset($tmpa['yday']) && $actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
  11975. $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
  11976. $out .= '<!-- timeline time label -->';
  11977. $out .= '<li class="time-label">';
  11978. $out .= '<span class="timeline-badge-date">';
  11979. $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
  11980. $out .= '</span>';
  11981. $out .= '</li>';
  11982. $out .= '<!-- /.timeline-label -->';
  11983. }
  11984. $out .= '<!-- timeline item -->'."\n";
  11985. $out .= '<li class="timeline-code-'.strtolower($actionstatic->code).'">';
  11986. //$timelineicon = getTimelineIcon($actionstatic, $histo, $key);
  11987. $typeicon = $actionstatic->getTypePicto('pictofixedwidth timeline-icon-not-applicble', $labeltype);
  11988. //$out .= $timelineicon;
  11989. //var_dump($timelineicon);
  11990. $out .= $typeicon;
  11991. $out .= '<div class="timeline-item">'."\n";
  11992. $out .= '<span class="time timeline-header-action2">';
  11993. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
  11994. $out .= '<a class="paddingleft paddingright timeline-btn2 editfielda" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11995. $out .= $histo[$key]['id'];
  11996. $out .= '</a> ';
  11997. } else {
  11998. $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle').' ';
  11999. }
  12000. if ($user->hasRight('agenda', 'allactions', 'create') ||
  12001. (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
  12002. $out .= '<a class="paddingleft paddingright timeline-btn2 editfielda" href="'.DOL_MAIN_URL_ROOT.'/comm/action/card.php?action=edit&token='.newToken().'&id='.$actionstatic->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?'.$param).'">';
  12003. //$out .= '<i class="fa fa-pencil" title="'.$langs->trans("Modify").'" ></i>';
  12004. $out .= img_picto($langs->trans("Modify"), 'edit', 'class="edita"');
  12005. $out .= '</a>';
  12006. }
  12007. $out .= '</span>';
  12008. // Date
  12009. $out .= '<span class="time"><i class="fa fa-clock-o valignmiddle"></i> <span class="valignmiddle">';
  12010. $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
  12011. if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
  12012. $tmpa = dol_getdate($histo[$key]['datestart'], true);
  12013. $tmpb = dol_getdate($histo[$key]['dateend'], true);
  12014. if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
  12015. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
  12016. } else {
  12017. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
  12018. }
  12019. }
  12020. $late = 0;
  12021. if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  12022. $late = 1;
  12023. }
  12024. if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  12025. $late = 1;
  12026. }
  12027. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
  12028. $late = 1;
  12029. }
  12030. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  12031. $late = 1;
  12032. }
  12033. if ($late) {
  12034. $out .= img_warning($langs->trans("Late")).' ';
  12035. }
  12036. $out .= "</span></span>\n";
  12037. // Ref
  12038. $out .= '<h3 class="timeline-header">';
  12039. // Author of event
  12040. $out .= '<div class="messaging-author inline-block tdoverflowmax150 valignmiddle marginrightonly">';
  12041. if ($histo[$key]['userid'] > 0) {
  12042. if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
  12043. $userstatic->fetch($histo[$key]['userid']);
  12044. $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
  12045. }
  12046. $out .= $userGetNomUrlCache[$histo[$key]['userid']];
  12047. } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
  12048. if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
  12049. if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
  12050. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
  12051. } else {
  12052. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
  12053. }
  12054. }
  12055. $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
  12056. }
  12057. $out .= '</div>';
  12058. // Title
  12059. $out .= ' <div class="messaging-title inline-block">';
  12060. //$out .= $actionstatic->getTypePicto();
  12061. if (empty($conf->dol_optimize_smallscreen) && $actionstatic->type_code != 'AC_OTH_AUTO') {
  12062. $out .= $labeltype.' - ';
  12063. }
  12064. $libelle = '';
  12065. if (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  12066. $out .= $langs->trans('TicketNewMessage');
  12067. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  12068. $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
  12069. } elseif (isset($histo[$key]['type'])) {
  12070. if ($histo[$key]['type'] == 'action') {
  12071. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  12072. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
  12073. $libelle = $histo[$key]['note'];
  12074. $actionstatic->id = $histo[$key]['id'];
  12075. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  12076. } elseif ($histo[$key]['type'] == 'mailing') {
  12077. $out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  12078. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  12079. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
  12080. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  12081. } else {
  12082. $libelle .= $histo[$key]['note'];
  12083. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  12084. }
  12085. }
  12086. if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) {
  12087. if (isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']]) && isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']])) {
  12088. $link = $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']];
  12089. } else {
  12090. if (!isset($conf->cache['elementlinkcache'][$histo[$key]['elementtype']])) {
  12091. $conf->cache['elementlinkcache'][$histo[$key]['elementtype']] = array();
  12092. }
  12093. $link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1);
  12094. $conf->cache['elementlinkcache'][$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link;
  12095. }
  12096. if ($link) {
  12097. $out .= ' - '.$link;
  12098. }
  12099. }
  12100. $out .= '</div>';
  12101. $out .= '</h3>';
  12102. // Message
  12103. if (!empty($histo[$key]['message'] && $histo[$key]['message'] != $libelle)
  12104. && $actionstatic->code != 'AC_TICKET_CREATE'
  12105. && $actionstatic->code != 'AC_TICKET_MODIFY'
  12106. ) {
  12107. $out .= '<div class="timeline-body" >';
  12108. $truncateLines = getDolGlobalInt('MAIN_TRUNCATE_TIMELINE_MESSAGE', 3);
  12109. $truncatedText = dolGetFirstLineOfText($histo[$key]['message'], $truncateLines);
  12110. if ($truncateLines > 0 && strlen($histo[$key]['message']) > strlen($truncatedText)) {
  12111. $out .= '<div class="readmore-block --closed" >';
  12112. $out .= ' <div class="readmore-block__excerpt" >';
  12113. $out .= $truncatedText ;
  12114. $out .= ' <a class="read-more-link" data-read-more-action="open" href="'.DOL_MAIN_URL_ROOT.'/comm/action/card.php?id='.$actionstatic->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?'.$param).'" >'.$langs->trans("ReadMore").' <span class="fa fa-chevron-right" aria-hidden="true"></span></a>';
  12115. $out .= ' </div>';
  12116. $out .= ' <div class="readmore-block__full-text" >';
  12117. $out .= $histo[$key]['message'];
  12118. $out .= ' <a class="read-less-link" data-read-more-action="close" href="#" ><span class="fa fa-chevron-up" aria-hidden="true"></span> '.$langs->trans("ReadLess").'</a>';
  12119. $out .= ' </div>';
  12120. $out .= '</div>';
  12121. } else {
  12122. $out .= $histo[$key]['message'];
  12123. }
  12124. $out .= '</div>';
  12125. }
  12126. // Timeline footer
  12127. $footer = '';
  12128. // Contact for this action
  12129. if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
  12130. $contactList = '';
  12131. foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
  12132. if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
  12133. $contact = new Contact($db);
  12134. $contact->fetch($cid);
  12135. $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
  12136. } else {
  12137. $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
  12138. }
  12139. if ($contact) {
  12140. $contactList .= !empty($contactList) ? ', ' : '';
  12141. $contactList .= $contact->getNomUrl(1);
  12142. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  12143. if (!empty($contact->phone_pro)) {
  12144. $contactList .= '('.dol_print_phone($contact->phone_pro).')';
  12145. }
  12146. }
  12147. }
  12148. }
  12149. $footer .= $langs->trans('ActionOnContact').' : '.$contactList;
  12150. } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
  12151. if (empty($conf->cache['contact'][$histo[$key]['contact_id']])) {
  12152. $contact = new Contact($db);
  12153. $result = $contact->fetch($histo[$key]['contact_id']);
  12154. $conf->cache['contact'][$histo[$key]['contact_id']] = $contact;
  12155. } else {
  12156. $contact = $conf->cache['contact'][$histo[$key]['contact_id']];
  12157. }
  12158. if ($result > 0) {
  12159. $footer .= $contact->getNomUrl(1);
  12160. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  12161. if (!empty($contact->phone_pro)) {
  12162. $footer .= '('.dol_print_phone($contact->phone_pro).')';
  12163. }
  12164. }
  12165. }
  12166. }
  12167. $documents = getActionCommEcmList($actionstatic);
  12168. if (!empty($documents)) {
  12169. $footer .= '<div class="timeline-documents-container">';
  12170. foreach ($documents as $doc) {
  12171. $footer .= '<span id="document_'.$doc->id.'" class="timeline-documents" ';
  12172. $footer .= ' data-id="'.$doc->id.'" ';
  12173. $footer .= ' data-path="'.$doc->filepath.'"';
  12174. $footer .= ' data-filename="'.dol_escape_htmltag($doc->filename).'" ';
  12175. $footer .= '>';
  12176. $filePath = DOL_DATA_ROOT.'/'.$doc->filepath.'/'.$doc->filename;
  12177. $mime = dol_mimetype($filePath);
  12178. $file = $actionstatic->id.'/'.$doc->filename;
  12179. $thumb = $actionstatic->id.'/thumbs/'.substr($doc->filename, 0, strrpos($doc->filename, '.')).'_mini'.substr($doc->filename, strrpos($doc->filename, '.'));
  12180. $doclink = dol_buildpath('document.php', 1).'?modulepart=actions&attachment=0&file='.urlencode($file).'&entity='.$conf->entity;
  12181. $viewlink = dol_buildpath('viewimage.php', 1).'?modulepart=actions&file='.urlencode($thumb).'&entity='.$conf->entity;
  12182. $mimeAttr = ' mime="'.$mime.'" ';
  12183. $class = '';
  12184. if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
  12185. $class .= ' documentpreview';
  12186. }
  12187. $footer .= '<a href="'.$doclink.'" class="btn-link '.$class.'" target="_blank" rel="noopener noreferrer" '.$mimeAttr.' >';
  12188. $footer .= img_mime($filePath).' '.$doc->filename;
  12189. $footer .= '</a>';
  12190. $footer .= '</span>';
  12191. }
  12192. $footer .= '</div>';
  12193. }
  12194. if (!empty($footer)) {
  12195. $out .= '<div class="timeline-footer">'.$footer.'</div>';
  12196. }
  12197. $out .= '</div>'."\n"; // end timeline-item
  12198. $out .= '</li>';
  12199. $out .= '<!-- END timeline item -->';
  12200. $i++;
  12201. }
  12202. $out .= "</ul>\n";
  12203. $out .= '<script>
  12204. jQuery(document).ready(function () {
  12205. $(document).on("click", "[data-read-more-action]", function(e){
  12206. let readMoreBloc = $(this).closest(".readmore-block");
  12207. if(readMoreBloc.length > 0){
  12208. e.preventDefault();
  12209. if($(this).attr("data-read-more-action") == "close"){
  12210. readMoreBloc.addClass("--closed").removeClass("--open");
  12211. $("html, body").animate({
  12212. scrollTop: readMoreBloc.offset().top - 200
  12213. }, 100);
  12214. }else{
  12215. readMoreBloc.addClass("--open").removeClass("--closed");
  12216. }
  12217. }
  12218. });
  12219. });
  12220. </script>';
  12221. if (empty($histo)) {
  12222. $out .= '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
  12223. }
  12224. }
  12225. if ($noprint) {
  12226. return $out;
  12227. } else {
  12228. print $out;
  12229. }
  12230. }
  12231. /**
  12232. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  12233. * optionally hour, minute, second) fields to return a timestamp.
  12234. *
  12235. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  12236. * @param string $hourTime 'getpost' to include hour, minute, second values from the HTTP request, 'XX:YY:ZZ' to set
  12237. * hour, minute, second respectively (for instance '23:59:59')
  12238. * @param string $gm Passed to dol_mktime
  12239. * @return int|string Date as a timestamp, '' or false if error
  12240. */
  12241. function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto')
  12242. {
  12243. if ($hourTime === 'getpost') {
  12244. $hour = GETPOSTINT($prefix . 'hour');
  12245. $minute = GETPOSTINT($prefix . 'minute');
  12246. $second = GETPOSTINT($prefix . 'second');
  12247. } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
  12248. $hour = intval($m[1]);
  12249. $minute = intval($m[2]);
  12250. $second = intval($m[3]);
  12251. } else {
  12252. $hour = $minute = $second = 0;
  12253. }
  12254. // normalize out of range values
  12255. $hour = min($hour, 23);
  12256. $minute = min($minute, 59);
  12257. $second = min($second, 59);
  12258. return dol_mktime($hour, $minute, $second, GETPOSTINT($prefix . 'month'), GETPOSTINT($prefix . 'day'), GETPOSTINT($prefix . 'year'), $gm);
  12259. }
  12260. /**
  12261. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  12262. * optionally hour, minute, second) fields to return a a portion of URL reproducing the values from the current HTTP
  12263. * request.
  12264. *
  12265. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  12266. * @param int $timestamp If null, the timestamp will be created from request data
  12267. * @param bool $hourTime If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  12268. * @param bool $gm If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  12269. * @return string Portion of URL with query parameters for the specified date
  12270. */
  12271. function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
  12272. {
  12273. if ($timestamp === null) {
  12274. $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
  12275. }
  12276. $TParam = array(
  12277. $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
  12278. $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
  12279. $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
  12280. );
  12281. if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
  12282. $TParam = array_merge($TParam, array(
  12283. $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
  12284. $prefix . 'minute' => intval(dol_print_date($timestamp, '%M')),
  12285. $prefix . 'second' => intval(dol_print_date($timestamp, '%S'))
  12286. ));
  12287. }
  12288. return '&' . http_build_query($TParam);
  12289. }