Results.php 197 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Hold the PhpMyAdmin\Display\Results class
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. declare(strict_types=1);
  9. namespace PhpMyAdmin\Display;
  10. use PhpMyAdmin\Config\SpecialSchemaLinks;
  11. use PhpMyAdmin\Core;
  12. use PhpMyAdmin\DatabaseInterface;
  13. use PhpMyAdmin\Index;
  14. use PhpMyAdmin\Message;
  15. use PhpMyAdmin\Plugins\Transformations\Output\Text_Octetstream_Sql;
  16. use PhpMyAdmin\Plugins\Transformations\Output\Text_Plain_Json;
  17. use PhpMyAdmin\Plugins\Transformations\Output\Text_Plain_Sql;
  18. use PhpMyAdmin\Plugins\Transformations\Text_Plain_Link;
  19. use PhpMyAdmin\Plugins\TransformationsPlugin;
  20. use PhpMyAdmin\Relation;
  21. use PhpMyAdmin\Response;
  22. use PhpMyAdmin\Sanitize;
  23. use PhpMyAdmin\Sql;
  24. use PhpMyAdmin\SqlParser\Statements\SelectStatement;
  25. use PhpMyAdmin\SqlParser\Utils\Query;
  26. use PhpMyAdmin\Table;
  27. use PhpMyAdmin\Template;
  28. use PhpMyAdmin\Transformations;
  29. use PhpMyAdmin\Url;
  30. use PhpMyAdmin\Util;
  31. use stdClass;
  32. /**
  33. * Handle all the functionalities related to displaying results
  34. * of sql queries, stored procedure, browsing sql processes or
  35. * displaying binary log.
  36. *
  37. * @package PhpMyAdmin
  38. */
  39. class Results
  40. {
  41. // Define constants
  42. public const NO_EDIT_OR_DELETE = 'nn';
  43. public const UPDATE_ROW = 'ur';
  44. public const DELETE_ROW = 'dr';
  45. public const KILL_PROCESS = 'kp';
  46. public const POSITION_LEFT = 'left';
  47. public const POSITION_RIGHT = 'right';
  48. public const POSITION_BOTH = 'both';
  49. public const POSITION_NONE = 'none';
  50. public const DISPLAY_FULL_TEXT = 'F';
  51. public const DISPLAY_PARTIAL_TEXT = 'P';
  52. public const HEADER_FLIP_TYPE_AUTO = 'auto';
  53. public const HEADER_FLIP_TYPE_CSS = 'css';
  54. public const HEADER_FLIP_TYPE_FAKE = 'fake';
  55. public const DATE_FIELD = 'date';
  56. public const DATETIME_FIELD = 'datetime';
  57. public const TIMESTAMP_FIELD = 'timestamp';
  58. public const TIME_FIELD = 'time';
  59. public const STRING_FIELD = 'string';
  60. public const GEOMETRY_FIELD = 'geometry';
  61. public const BLOB_FIELD = 'BLOB';
  62. public const BINARY_FIELD = 'BINARY';
  63. public const RELATIONAL_KEY = 'K';
  64. public const RELATIONAL_DISPLAY_COLUMN = 'D';
  65. public const GEOMETRY_DISP_GEOM = 'GEOM';
  66. public const GEOMETRY_DISP_WKT = 'WKT';
  67. public const GEOMETRY_DISP_WKB = 'WKB';
  68. public const SMART_SORT_ORDER = 'SMART';
  69. public const ASCENDING_SORT_DIR = 'ASC';
  70. public const DESCENDING_SORT_DIR = 'DESC';
  71. public const TABLE_TYPE_INNO_DB = 'InnoDB';
  72. public const ALL_ROWS = 'all';
  73. public const QUERY_TYPE_SELECT = 'SELECT';
  74. public const ROUTINE_PROCEDURE = 'procedure';
  75. public const ROUTINE_FUNCTION = 'function';
  76. public const ACTION_LINK_CONTENT_ICONS = 'icons';
  77. public const ACTION_LINK_CONTENT_TEXT = 'text';
  78. // Declare global fields
  79. /** array with properties of the class */
  80. private $_property_array = [
  81. /** integer server id */
  82. 'server' => null,
  83. /** string Database name */
  84. 'db' => null,
  85. /** string Table name */
  86. 'table' => null,
  87. /** string the URL to go back in case of errors */
  88. 'goto' => null,
  89. /** string the SQL query */
  90. 'sql_query' => null,
  91. /**
  92. * integer the total number of rows returned by the SQL query without any
  93. * appended "LIMIT" clause programmatically
  94. */
  95. 'unlim_num_rows' => null,
  96. /** array meta information about fields */
  97. 'fields_meta' => null,
  98. /** boolean */
  99. 'is_count' => null,
  100. /** integer */
  101. 'is_export' => null,
  102. /** boolean */
  103. 'is_func' => null,
  104. /** integer */
  105. 'is_analyse' => null,
  106. /** integer the total number of rows returned by the SQL query */
  107. 'num_rows' => null,
  108. /** integer the total number of fields returned by the SQL query */
  109. 'fields_cnt' => null,
  110. /** double time taken for execute the SQL query */
  111. 'querytime' => null,
  112. /** string path for theme images directory */
  113. 'pma_theme_image' => null,
  114. /** string */
  115. 'text_dir' => null,
  116. /** boolean */
  117. 'is_maint' => null,
  118. /** boolean */
  119. 'is_explain' => null,
  120. /** boolean */
  121. 'is_show' => null,
  122. /** boolean */
  123. 'is_browse_distinct' => null,
  124. /** array table definitions */
  125. 'showtable' => null,
  126. /** string */
  127. 'printview' => null,
  128. /** string URL query */
  129. 'url_query' => null,
  130. /** array column names to highlight */
  131. 'highlight_columns' => null,
  132. /** array holding various display information */
  133. 'display_params' => null,
  134. /** array mime types information of fields */
  135. 'mime_map' => null,
  136. /** boolean */
  137. 'editable' => null,
  138. /** random unique ID to distinguish result set */
  139. 'unique_id' => null,
  140. /** where clauses for each row, each table in the row */
  141. 'whereClauseMap' => [],
  142. ];
  143. /**
  144. * This variable contains the column transformation information
  145. * for some of the system databases.
  146. * One element of this array represent all relevant columns in all tables in
  147. * one specific database
  148. */
  149. public $transformation_info;
  150. /**
  151. * @var Relation
  152. */
  153. private $relation;
  154. /**
  155. * @var Transformations
  156. */
  157. private $transformations;
  158. /**
  159. * @var Template
  160. */
  161. public $template;
  162. /**
  163. * Constructor for PhpMyAdmin\Display\Results class
  164. *
  165. * @param string $db the database name
  166. * @param string $table the table name
  167. * @param int $server the server id
  168. * @param string $goto the URL to go back in case of errors
  169. * @param string $sql_query the SQL query
  170. *
  171. * @access public
  172. */
  173. public function __construct($db, $table, $server, $goto, $sql_query)
  174. {
  175. $this->relation = new Relation($GLOBALS['dbi']);
  176. $this->transformations = new Transformations();
  177. $this->template = new Template();
  178. $this->_setDefaultTransformations();
  179. $this->__set('db', $db);
  180. $this->__set('table', $table);
  181. $this->__set('server', $server);
  182. $this->__set('goto', $goto);
  183. $this->__set('sql_query', $sql_query);
  184. $this->__set('unique_id', mt_rand());
  185. }
  186. /**
  187. * Get any property of this class
  188. *
  189. * @param string $property name of the property
  190. *
  191. * @return mixed|void if property exist, value of the relevant property
  192. */
  193. public function __get($property)
  194. {
  195. return $this->_property_array[$property] ?? null;
  196. }
  197. /**
  198. * Set values for any property of this class
  199. *
  200. * @param string $property name of the property
  201. * @param mixed $value value to set
  202. *
  203. * @return void
  204. */
  205. public function __set($property, $value)
  206. {
  207. if (array_key_exists($property, $this->_property_array)) {
  208. $this->_property_array[$property] = $value;
  209. }
  210. }
  211. /**
  212. * Sets default transformations for some columns
  213. *
  214. * @return void
  215. */
  216. private function _setDefaultTransformations()
  217. {
  218. $json_highlighting_data = [
  219. 'libraries/classes/Plugins/Transformations/Output/Text_Plain_Json.php',
  220. Text_Plain_Json::class,
  221. 'Text_Plain',
  222. ];
  223. $sql_highlighting_data = [
  224. 'libraries/classes/Plugins/Transformations/Output/Text_Plain_Sql.php',
  225. Text_Plain_Sql::class,
  226. 'Text_Plain',
  227. ];
  228. $blob_sql_highlighting_data = [
  229. 'libraries/classes/Plugins/Transformations/Output/Text_Octetstream_Sql.php',
  230. Text_Octetstream_Sql::class,
  231. 'Text_Octetstream',
  232. ];
  233. $link_data = [
  234. 'libraries/classes/Plugins/Transformations/Text_Plain_Link.php',
  235. Text_Plain_Link::class,
  236. 'Text_Plain',
  237. ];
  238. $this->transformation_info = [
  239. 'information_schema' => [
  240. 'events' => [
  241. 'event_definition' => $sql_highlighting_data,
  242. ],
  243. 'processlist' => [
  244. 'info' => $sql_highlighting_data,
  245. ],
  246. 'routines' => [
  247. 'routine_definition' => $sql_highlighting_data,
  248. ],
  249. 'triggers' => [
  250. 'action_statement' => $sql_highlighting_data,
  251. ],
  252. 'views' => [
  253. 'view_definition' => $sql_highlighting_data,
  254. ],
  255. ],
  256. 'mysql' => [
  257. 'event' => [
  258. 'body' => $blob_sql_highlighting_data,
  259. 'body_utf8' => $blob_sql_highlighting_data,
  260. ],
  261. 'general_log' => [
  262. 'argument' => $sql_highlighting_data,
  263. ],
  264. 'help_category' => [
  265. 'url' => $link_data,
  266. ],
  267. 'help_topic' => [
  268. 'example' => $sql_highlighting_data,
  269. 'url' => $link_data,
  270. ],
  271. 'proc' => [
  272. 'param_list' => $blob_sql_highlighting_data,
  273. 'returns' => $blob_sql_highlighting_data,
  274. 'body' => $blob_sql_highlighting_data,
  275. 'body_utf8' => $blob_sql_highlighting_data,
  276. ],
  277. 'slow_log' => [
  278. 'sql_text' => $sql_highlighting_data,
  279. ],
  280. ],
  281. ];
  282. $cfgRelation = $this->relation->getRelationsParam();
  283. if ($cfgRelation['db']) {
  284. $this->transformation_info[$cfgRelation['db']] = [];
  285. $relDb = &$this->transformation_info[$cfgRelation['db']];
  286. if (! empty($cfgRelation['history'])) {
  287. $relDb[$cfgRelation['history']] = [
  288. 'sqlquery' => $sql_highlighting_data,
  289. ];
  290. }
  291. if (! empty($cfgRelation['bookmark'])) {
  292. $relDb[$cfgRelation['bookmark']] = [
  293. 'query' => $sql_highlighting_data,
  294. ];
  295. }
  296. if (! empty($cfgRelation['tracking'])) {
  297. $relDb[$cfgRelation['tracking']] = [
  298. 'schema_sql' => $sql_highlighting_data,
  299. 'data_sql' => $sql_highlighting_data,
  300. ];
  301. }
  302. if (! empty($cfgRelation['favorite'])) {
  303. $relDb[$cfgRelation['favorite']] = [
  304. 'tables' => $json_highlighting_data,
  305. ];
  306. }
  307. if (! empty($cfgRelation['recent'])) {
  308. $relDb[$cfgRelation['recent']] = [
  309. 'tables' => $json_highlighting_data,
  310. ];
  311. }
  312. if (! empty($cfgRelation['savedsearches'])) {
  313. $relDb[$cfgRelation['savedsearches']] = [
  314. 'search_data' => $json_highlighting_data,
  315. ];
  316. }
  317. if (! empty($cfgRelation['designer_settings'])) {
  318. $relDb[$cfgRelation['designer_settings']] = [
  319. 'settings_data' => $json_highlighting_data,
  320. ];
  321. }
  322. if (! empty($cfgRelation['table_uiprefs'])) {
  323. $relDb[$cfgRelation['table_uiprefs']] = [
  324. 'prefs' => $json_highlighting_data,
  325. ];
  326. }
  327. if (! empty($cfgRelation['userconfig'])) {
  328. $relDb[$cfgRelation['userconfig']] = [
  329. 'config_data' => $json_highlighting_data,
  330. ];
  331. }
  332. if (! empty($cfgRelation['export_templates'])) {
  333. $relDb[$cfgRelation['export_templates']] = [
  334. 'template_data' => $json_highlighting_data,
  335. ];
  336. }
  337. }
  338. }
  339. /**
  340. * Set properties which were not initialized at the constructor
  341. *
  342. * @param integer $unlim_num_rows the total number of rows returned by
  343. * the SQL query without any appended
  344. * "LIMIT" clause programmatically
  345. * @param stdClass $fields_meta meta information about fields
  346. * @param boolean $is_count statement is SELECT COUNT
  347. * @param integer $is_export statement contains INTO OUTFILE
  348. * @param boolean $is_func statement contains a function like SUM()
  349. * @param integer $is_analyse statement contains PROCEDURE ANALYSE
  350. * @param integer $num_rows total no. of rows returned by SQL query
  351. * @param integer $fields_cnt total no.of fields returned by SQL query
  352. * @param double $querytime time taken for execute the SQL query
  353. * @param string $pmaThemeImage path for theme images directory
  354. * @param string $text_dir text direction
  355. * @param boolean $is_maint statement contains a maintenance command
  356. * @param boolean $is_explain statement contains EXPLAIN
  357. * @param boolean $is_show statement contains SHOW
  358. * @param array $showtable table definitions
  359. * @param string $printview print view was requested
  360. * @param string $url_query URL query
  361. * @param boolean $editable whether the results set is editable
  362. * @param boolean $is_browse_dist whether browsing distinct values
  363. *
  364. * @return void
  365. *
  366. * @see sql.php
  367. */
  368. public function setProperties(
  369. $unlim_num_rows,
  370. $fields_meta,
  371. $is_count,
  372. $is_export,
  373. $is_func,
  374. $is_analyse,
  375. $num_rows,
  376. $fields_cnt,
  377. $querytime,
  378. $pmaThemeImage,
  379. $text_dir,
  380. $is_maint,
  381. $is_explain,
  382. $is_show,
  383. $showtable,
  384. $printview,
  385. $url_query,
  386. $editable,
  387. $is_browse_dist
  388. ) {
  389. $this->__set('unlim_num_rows', $unlim_num_rows);
  390. $this->__set('fields_meta', $fields_meta);
  391. $this->__set('is_count', $is_count);
  392. $this->__set('is_export', $is_export);
  393. $this->__set('is_func', $is_func);
  394. $this->__set('is_analyse', $is_analyse);
  395. $this->__set('num_rows', $num_rows);
  396. $this->__set('fields_cnt', $fields_cnt);
  397. $this->__set('querytime', $querytime);
  398. $this->__set('pma_theme_image', $pmaThemeImage);
  399. $this->__set('text_dir', $text_dir);
  400. $this->__set('is_maint', $is_maint);
  401. $this->__set('is_explain', $is_explain);
  402. $this->__set('is_show', $is_show);
  403. $this->__set('showtable', $showtable);
  404. $this->__set('printview', $printview);
  405. $this->__set('url_query', $url_query);
  406. $this->__set('editable', $editable);
  407. $this->__set('is_browse_distinct', $is_browse_dist);
  408. }
  409. /**
  410. * Defines the parts to display for a print view
  411. *
  412. * @param array $displayParts the parts to display
  413. *
  414. * @return array the modified display parts
  415. *
  416. * @access private
  417. *
  418. */
  419. private function _setDisplayPartsForPrintView(array $displayParts)
  420. {
  421. // set all elements to false!
  422. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE; // no edit link
  423. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE; // no delete link
  424. $displayParts['sort_lnk'] = (string) '0';
  425. $displayParts['nav_bar'] = (string) '0';
  426. $displayParts['bkm_form'] = (string) '0';
  427. $displayParts['text_btn'] = (string) '0';
  428. $displayParts['pview_lnk'] = (string) '0';
  429. return $displayParts;
  430. }
  431. /**
  432. * Defines the parts to display for a SHOW statement
  433. *
  434. * @param array $displayParts the parts to display
  435. *
  436. * @return array the modified display parts
  437. *
  438. * @access private
  439. *
  440. */
  441. private function _setDisplayPartsForShow(array $displayParts)
  442. {
  443. preg_match(
  444. '@^SHOW[[:space:]]+(VARIABLES|(FULL[[:space:]]+)?'
  445. . 'PROCESSLIST|STATUS|TABLE|GRANTS|CREATE|LOGS|DATABASES|FIELDS'
  446. . ')@i',
  447. $this->__get('sql_query'),
  448. $which
  449. );
  450. $bIsProcessList = isset($which[1]);
  451. if ($bIsProcessList) {
  452. $str = ' ' . strtoupper($which[1]);
  453. $bIsProcessList = $bIsProcessList
  454. && strpos($str, 'PROCESSLIST') > 0;
  455. }
  456. if ($bIsProcessList) {
  457. // no edit link
  458. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
  459. // "kill process" type edit link
  460. $displayParts['del_lnk'] = self::KILL_PROCESS;
  461. } else {
  462. // Default case -> no links
  463. // no edit link
  464. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
  465. // no delete link
  466. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
  467. }
  468. // Other settings
  469. $displayParts['sort_lnk'] = (string) '0';
  470. $displayParts['nav_bar'] = (string) '0';
  471. $displayParts['bkm_form'] = (string) '1';
  472. $displayParts['text_btn'] = (string) '1';
  473. $displayParts['pview_lnk'] = (string) '1';
  474. return $displayParts;
  475. }
  476. /**
  477. * Defines the parts to display for statements not related to data
  478. *
  479. * @param array $displayParts the parts to display
  480. *
  481. * @return array the modified display parts
  482. *
  483. * @access private
  484. *
  485. */
  486. private function _setDisplayPartsForNonData(array $displayParts)
  487. {
  488. // Statement is a "SELECT COUNT", a
  489. // "CHECK/ANALYZE/REPAIR/OPTIMIZE/CHECKSUM", an "EXPLAIN" one or
  490. // contains a "PROC ANALYSE" part
  491. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE; // no edit link
  492. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE; // no delete link
  493. $displayParts['sort_lnk'] = (string) '0';
  494. $displayParts['nav_bar'] = (string) '0';
  495. $displayParts['bkm_form'] = (string) '1';
  496. if ($this->__get('is_maint')) {
  497. $displayParts['text_btn'] = (string) '1';
  498. } else {
  499. $displayParts['text_btn'] = (string) '0';
  500. }
  501. $displayParts['pview_lnk'] = (string) '1';
  502. return $displayParts;
  503. }
  504. /**
  505. * Defines the parts to display for other statements (probably SELECT)
  506. *
  507. * @param array $displayParts the parts to display
  508. *
  509. * @return array the modified display parts
  510. *
  511. * @access private
  512. *
  513. */
  514. private function _setDisplayPartsForSelect(array $displayParts)
  515. {
  516. // Other statements (ie "SELECT" ones) -> updates
  517. // $displayParts['edit_lnk'], $displayParts['del_lnk'] and
  518. // $displayParts['text_btn'] (keeps other default values)
  519. $fields_meta = $this->__get('fields_meta');
  520. $prev_table = '';
  521. $displayParts['text_btn'] = (string) '1';
  522. $number_of_columns = $this->__get('fields_cnt');
  523. for ($i = 0; $i < $number_of_columns; $i++) {
  524. $is_link = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  525. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
  526. || ($displayParts['sort_lnk'] != '0');
  527. // Displays edit/delete/sort/insert links?
  528. if ($is_link
  529. && $prev_table != ''
  530. && $fields_meta[$i]->table != ''
  531. && $fields_meta[$i]->table != $prev_table
  532. ) {
  533. // don't display links
  534. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
  535. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
  536. /**
  537. * @todo May be problematic with same field names
  538. * in two joined table.
  539. */
  540. // $displayParts['sort_lnk'] = (string) '0';
  541. if ($displayParts['text_btn'] == '1') {
  542. break;
  543. }
  544. } // end if
  545. // Always display print view link
  546. $displayParts['pview_lnk'] = (string) '1';
  547. if ($fields_meta[$i]->table != '') {
  548. $prev_table = $fields_meta[$i]->table;
  549. }
  550. } // end for
  551. if ($prev_table == '') { // no table for any of the columns
  552. // don't display links
  553. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
  554. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
  555. }
  556. return $displayParts;
  557. }
  558. /**
  559. * Defines the parts to display for the results of a SQL query
  560. * and the total number of rows
  561. *
  562. * @param array $displayParts the parts to display (see a few
  563. * lines above for explanations)
  564. *
  565. * @return array the first element is an array with explicit indexes
  566. * for all the display elements
  567. * the second element is the total number of rows returned
  568. * by the SQL query without any programmatically appended
  569. * LIMIT clause (just a copy of $unlim_num_rows if it exists,
  570. * else computed inside this function)
  571. *
  572. *
  573. * @access private
  574. *
  575. * @see getTable()
  576. */
  577. private function _setDisplayPartsAndTotal(array $displayParts)
  578. {
  579. $the_total = 0;
  580. // 1. Following variables are needed for use in isset/empty or
  581. // use with array indexes or safe use in foreach
  582. $db = $this->__get('db');
  583. $table = $this->__get('table');
  584. $unlim_num_rows = $this->__get('unlim_num_rows');
  585. $num_rows = $this->__get('num_rows');
  586. $printview = $this->__get('printview');
  587. // 2. Updates the display parts
  588. if ($printview == '1') {
  589. $displayParts = $this->_setDisplayPartsForPrintView($displayParts);
  590. } elseif ($this->__get('is_count') || $this->__get('is_analyse')
  591. || $this->__get('is_maint') || $this->__get('is_explain')
  592. ) {
  593. $displayParts = $this->_setDisplayPartsForNonData($displayParts);
  594. } elseif ($this->__get('is_show')) {
  595. $displayParts = $this->_setDisplayPartsForShow($displayParts);
  596. } else {
  597. $displayParts = $this->_setDisplayPartsForSelect($displayParts);
  598. } // end if..elseif...else
  599. // 3. Gets the total number of rows if it is unknown
  600. if (isset($unlim_num_rows) && $unlim_num_rows != '') {
  601. $the_total = $unlim_num_rows;
  602. } elseif (($displayParts['nav_bar'] == '1')
  603. || ($displayParts['sort_lnk'] == '1')
  604. && (strlen($db) > 0 && strlen($table) > 0)
  605. ) {
  606. $the_total = $GLOBALS['dbi']->getTable($db, $table)->countRecords();
  607. }
  608. // if for COUNT query, number of rows returned more than 1
  609. // (may be being used GROUP BY)
  610. if ($this->__get('is_count') && isset($num_rows) && $num_rows > 1) {
  611. $displayParts['nav_bar'] = (string) '1';
  612. $displayParts['sort_lnk'] = (string) '1';
  613. }
  614. // 4. If navigation bar or sorting fields names URLs should be
  615. // displayed but there is only one row, change these settings to
  616. // false
  617. if ($displayParts['nav_bar'] == '1' || $displayParts['sort_lnk'] == '1') {
  618. // - Do not display sort links if less than 2 rows.
  619. // - For a VIEW we (probably) did not count the number of rows
  620. // so don't test this number here, it would remove the possibility
  621. // of sorting VIEW results.
  622. $_table = new Table($table, $db);
  623. if (isset($unlim_num_rows)
  624. && ($unlim_num_rows < 2)
  625. && ! $_table->isView()
  626. ) {
  627. $displayParts['sort_lnk'] = (string) '0';
  628. }
  629. } // end if (3)
  630. return [
  631. $displayParts,
  632. $the_total,
  633. ];
  634. }
  635. /**
  636. * Return true if we are executing a query in the form of
  637. * "SELECT * FROM <a table> ..."
  638. *
  639. * @param array $analyzed_sql_results analyzed sql results
  640. *
  641. * @return boolean
  642. *
  643. * @access private
  644. *
  645. * @see _getTableHeaders(), _getColumnParams()
  646. */
  647. private function _isSelect(array $analyzed_sql_results)
  648. {
  649. return ! ($this->__get('is_count')
  650. || $this->__get('is_export')
  651. || $this->__get('is_func')
  652. || $this->__get('is_analyse'))
  653. && ! empty($analyzed_sql_results['select_from'])
  654. && ! empty($analyzed_sql_results['statement']->from)
  655. && (count($analyzed_sql_results['statement']->from) === 1)
  656. && ! empty($analyzed_sql_results['statement']->from[0]->table);
  657. }
  658. /**
  659. * Get a navigation button
  660. *
  661. * @param string $caption iconic caption for button
  662. * @param string $title text for button
  663. * @param integer $pos position for next query
  664. * @param string $html_sql_query query ready for display
  665. * @param boolean $back whether 'begin' or 'previous'
  666. * @param string $onsubmit optional onsubmit clause
  667. * @param string $input_for_real_end optional hidden field for special treatment
  668. * @param string $onclick optional onclick clause
  669. *
  670. * @return string html content
  671. *
  672. * @access private
  673. *
  674. * @see _getMoveBackwardButtonsForTableNavigation(),
  675. * _getMoveForwardButtonsForTableNavigation()
  676. */
  677. private function _getTableNavigationButton(
  678. $caption,
  679. $title,
  680. $pos,
  681. $html_sql_query,
  682. $back,
  683. $onsubmit = '',
  684. $input_for_real_end = '',
  685. $onclick = ''
  686. ) {
  687. $caption_output = '';
  688. if ($back) {
  689. if (Util::showIcons('TableNavigationLinksMode')) {
  690. $caption_output .= $caption;
  691. }
  692. if (Util::showText('TableNavigationLinksMode')) {
  693. $caption_output .= '&nbsp;' . $title;
  694. }
  695. } else {
  696. if (Util::showText('TableNavigationLinksMode')) {
  697. $caption_output .= $title;
  698. }
  699. if (Util::showIcons('TableNavigationLinksMode')) {
  700. $caption_output .= '&nbsp;' . $caption;
  701. }
  702. }
  703. return $this->template->render('display/results/table_navigation_button', [
  704. 'db' => $this->__get('db'),
  705. 'table' => $this->__get('table'),
  706. 'sql_query' => $html_sql_query,
  707. 'pos' => $pos,
  708. 'is_browse_distinct' => $this->__get('is_browse_distinct'),
  709. 'goto' => $this->__get('goto'),
  710. 'input_for_real_end' => $input_for_real_end,
  711. 'caption_output' => $caption_output,
  712. 'title' => $title,
  713. 'onsubmit' => $onsubmit,
  714. 'onclick' => $onclick,
  715. ]);
  716. }
  717. /**
  718. * Possibly return a page selector for table navigation
  719. *
  720. * @return array ($output, $nbTotalPage)
  721. *
  722. * @access private
  723. */
  724. private function _getHtmlPageSelector(): array
  725. {
  726. $pageNow = @floor(
  727. $_SESSION['tmpval']['pos']
  728. / $_SESSION['tmpval']['max_rows']
  729. ) + 1;
  730. $nbTotalPage = @ceil(
  731. $this->__get('unlim_num_rows')
  732. / $_SESSION['tmpval']['max_rows']
  733. );
  734. $output = '';
  735. if ($nbTotalPage > 1) {
  736. $_url_params = [
  737. 'db' => $this->__get('db'),
  738. 'table' => $this->__get('table'),
  739. 'sql_query' => $this->__get('sql_query'),
  740. 'goto' => $this->__get('goto'),
  741. 'is_browse_distinct' => $this->__get('is_browse_distinct'),
  742. ];
  743. $output = $this->template->render('display/results/page_selector', [
  744. 'url_params' => $_url_params,
  745. 'page_selector' => Util::pageselector(
  746. 'pos',
  747. $_SESSION['tmpval']['max_rows'],
  748. $pageNow,
  749. $nbTotalPage,
  750. 200,
  751. 5,
  752. 5,
  753. 20,
  754. 10
  755. ),
  756. ]);
  757. }
  758. return [
  759. $output,
  760. $nbTotalPage,
  761. ];
  762. }
  763. /**
  764. * Get a navigation bar to browse among the results of a SQL query
  765. *
  766. * @param integer $posNext the offset for the "next" page
  767. * @param integer $posPrevious the offset for the "previous" page
  768. * @param boolean $isInnodb whether its InnoDB or not
  769. * @param string $sortByKeyHtml the sort by key dialog
  770. *
  771. * @return string html content
  772. *
  773. * @access private
  774. *
  775. * @see getTable()
  776. */
  777. private function _getTableNavigation(
  778. $posNext,
  779. $posPrevious,
  780. $isInnodb,
  781. $sortByKeyHtml
  782. ): string {
  783. $isShowingAll = $_SESSION['tmpval']['max_rows'] === self::ALL_ROWS;
  784. // Move to the beginning or to the previous page
  785. $moveBackwardButtons = '';
  786. if ($_SESSION['tmpval']['pos'] && ! $isShowingAll) {
  787. $moveBackwardButtons = $this->_getMoveBackwardButtonsForTableNavigation(
  788. htmlspecialchars($this->__get('sql_query')),
  789. $posPrevious
  790. );
  791. }
  792. $pageSelector = '';
  793. $numberTotalPage = 1;
  794. if (! $isShowingAll) {
  795. list(
  796. $pageSelector,
  797. $numberTotalPage
  798. ) = $this->_getHtmlPageSelector();
  799. }
  800. // Move to the next page or to the last one
  801. $moveForwardButtons = '';
  802. if ($this->__get('unlim_num_rows') === false // view with unknown number of rows
  803. || (! $isShowingAll
  804. && $_SESSION['tmpval']['pos'] + $_SESSION['tmpval']['max_rows'] < $this->__get('unlim_num_rows')
  805. && $this->__get('num_rows') >= $_SESSION['tmpval']['max_rows'])
  806. ) {
  807. $moveForwardButtons = $this->_getMoveForwardButtonsForTableNavigation(
  808. htmlspecialchars($this->__get('sql_query')),
  809. $posNext,
  810. $isInnodb
  811. );
  812. }
  813. $hiddenFields = [
  814. 'db' => $this->__get('db'),
  815. 'table' => $this->__get('table'),
  816. 'server' => $this->__get('server'),
  817. 'sql_query' => $this->__get('sql_query'),
  818. 'is_browse_distinct' => $this->__get('is_browse_distinct'),
  819. 'goto' => $this->__get('goto'),
  820. ];
  821. return $this->template->render('display/results/table_navigation', [
  822. 'move_backward_buttons' => $moveBackwardButtons,
  823. 'page_selector' => $pageSelector,
  824. 'move_forward_buttons' => $moveForwardButtons,
  825. 'number_total_page' => $numberTotalPage,
  826. 'has_show_all' => $GLOBALS['cfg']['ShowAll'] || ($this->__get('unlim_num_rows') <= 500),
  827. 'hidden_fields' => $hiddenFields,
  828. 'session_max_rows' => $isShowingAll ? $GLOBALS['cfg']['MaxRows'] : 'all',
  829. 'unique_id' => $this->__get('unique_id'),
  830. 'is_showing_all' => $isShowingAll,
  831. 'unlim_num_rows' => $this->__get('unlim_num_rows'),
  832. 'max_rows' => $_SESSION['tmpval']['max_rows'],
  833. 'pos' => $_SESSION['tmpval']['pos'],
  834. 'sort_by_key' => $sortByKeyHtml,
  835. ]);
  836. }
  837. /**
  838. * Prepare move backward buttons - previous and first
  839. *
  840. * @param string $html_sql_query the sql encoded by html special characters
  841. * @param integer $pos_prev the offset for the "previous" page
  842. *
  843. * @return string html content
  844. *
  845. * @access private
  846. *
  847. * @see _getTableNavigation()
  848. */
  849. private function _getMoveBackwardButtonsForTableNavigation(
  850. $html_sql_query,
  851. $pos_prev
  852. ) {
  853. return $this->_getTableNavigationButton(
  854. '&lt;&lt;',
  855. _pgettext('First page', 'Begin'),
  856. 0,
  857. $html_sql_query,
  858. true
  859. )
  860. . $this->_getTableNavigationButton(
  861. '&lt;',
  862. _pgettext('Previous page', 'Previous'),
  863. $pos_prev,
  864. $html_sql_query,
  865. true
  866. );
  867. }
  868. /**
  869. * Prepare move forward buttons - next and last
  870. *
  871. * @param string $html_sql_query the sql encoded by htmlspecialchars()
  872. * @param integer $pos_next the offset for the "next" page
  873. * @param boolean $is_innodb whether it's InnoDB or not
  874. *
  875. * @return string html content
  876. *
  877. * @access private
  878. *
  879. * @see _getTableNavigation()
  880. */
  881. private function _getMoveForwardButtonsForTableNavigation(
  882. $html_sql_query,
  883. $pos_next,
  884. $is_innodb
  885. ) {
  886. // display the Next button
  887. $buttons_html = $this->_getTableNavigationButton(
  888. '&gt;',
  889. _pgettext('Next page', 'Next'),
  890. $pos_next,
  891. $html_sql_query,
  892. false
  893. );
  894. // prepare some options for the End button
  895. if ($is_innodb
  896. && $this->__get('unlim_num_rows') > $GLOBALS['cfg']['MaxExactCount']
  897. ) {
  898. $input_for_real_end = '<input id="real_end_input" type="hidden" '
  899. . 'name="find_real_end" value="1">';
  900. // no backquote around this message
  901. $onclick = '';
  902. } else {
  903. $input_for_real_end = $onclick = '';
  904. }
  905. $maxRows = $_SESSION['tmpval']['max_rows'];
  906. $onsubmit = 'onsubmit="return '
  907. . ($_SESSION['tmpval']['pos']
  908. + $maxRows
  909. < $this->__get('unlim_num_rows')
  910. && $this->__get('num_rows') >= $maxRows
  911. ? 'true'
  912. : 'false') . '"';
  913. // display the End button
  914. $buttons_html .= $this->_getTableNavigationButton(
  915. '&gt;&gt;',
  916. _pgettext('Last page', 'End'),
  917. @((ceil(
  918. $this->__get('unlim_num_rows')
  919. / $_SESSION['tmpval']['max_rows']
  920. ) - 1) * $maxRows),
  921. $html_sql_query,
  922. false,
  923. $onsubmit,
  924. $input_for_real_end,
  925. $onclick
  926. );
  927. return $buttons_html;
  928. }
  929. /**
  930. * Get the headers of the results table, for all of the columns
  931. *
  932. * @param array $displayParts which elements to display
  933. * @param array $analyzed_sql_results analyzed sql results
  934. * @param array $sort_expression sort expression
  935. * @param array $sort_expression_nodirection sort expression
  936. * without direction
  937. * @param array $sort_direction sort direction
  938. * @param boolean $is_limited_display with limited operations
  939. * or not
  940. * @param string $unsorted_sql_query query without the sort part
  941. *
  942. * @return string html content
  943. *
  944. * @access private
  945. *
  946. * @see getTableHeaders()
  947. */
  948. private function _getTableHeadersForColumns(
  949. array $displayParts,
  950. array $analyzed_sql_results,
  951. array $sort_expression,
  952. array $sort_expression_nodirection,
  953. array $sort_direction,
  954. $is_limited_display,
  955. $unsorted_sql_query
  956. ) {
  957. $html = '';
  958. // required to generate sort links that will remember whether the
  959. // "Show all" button has been clicked
  960. $sql_md5 = md5($this->__get('sql_query'));
  961. $session_max_rows = $is_limited_display
  962. ? 0
  963. : $_SESSION['tmpval']['query'][$sql_md5]['max_rows'];
  964. // Following variable are needed for use in isset/empty or
  965. // use with array indexes/safe use in the for loop
  966. $highlight_columns = $this->__get('highlight_columns');
  967. $fields_meta = $this->__get('fields_meta');
  968. // Prepare Display column comments if enabled
  969. // ($GLOBALS['cfg']['ShowBrowseComments']).
  970. $comments_map = $this->_getTableCommentsArray($analyzed_sql_results);
  971. list($col_order, $col_visib) = $this->_getColumnParams(
  972. $analyzed_sql_results
  973. );
  974. // optimize: avoid calling a method on each iteration
  975. $number_of_columns = $this->__get('fields_cnt');
  976. for ($j = 0; $j < $number_of_columns; $j++) {
  977. // PHP 7.4 fix for accessing array offset on bool
  978. $col_visib_current = is_array($col_visib) && isset($col_visib[$j]) ? $col_visib[$j] : null;
  979. // assign $i with the appropriate column order
  980. $i = $col_order ? $col_order[$j] : $j;
  981. // See if this column should get highlight because it's used in the
  982. // where-query.
  983. $name = $fields_meta[$i]->name;
  984. $condition_field = isset($highlight_columns[$name])
  985. || isset($highlight_columns[Util::backquote($name)])
  986. ? true
  987. : false;
  988. // Prepare comment-HTML-wrappers for each row, if defined/enabled.
  989. $comments = $this->_getCommentForRow($comments_map, $fields_meta[$i]);
  990. $display_params = $this->__get('display_params');
  991. if (($displayParts['sort_lnk'] == '1') && ! $is_limited_display) {
  992. list($order_link, $sorted_header_html)
  993. = $this->_getOrderLinkAndSortedHeaderHtml(
  994. $fields_meta[$i],
  995. $sort_expression,
  996. $sort_expression_nodirection,
  997. $i,
  998. $unsorted_sql_query,
  999. $session_max_rows,
  1000. $comments,
  1001. $sort_direction,
  1002. $col_visib,
  1003. $col_visib_current
  1004. );
  1005. $html .= $sorted_header_html;
  1006. $display_params['desc'][] = ' <th '
  1007. . 'class="draggable'
  1008. . ($condition_field ? ' condition' : '')
  1009. . '" data-column="' . htmlspecialchars($fields_meta[$i]->name)
  1010. . '">' . "\n" . $order_link . $comments . ' </th>' . "\n";
  1011. } else {
  1012. // Results can't be sorted
  1013. $html
  1014. .= $this->_getDraggableClassForNonSortableColumns(
  1015. $col_visib,
  1016. $col_visib_current,
  1017. $condition_field,
  1018. $fields_meta[$i],
  1019. $comments
  1020. );
  1021. $display_params['desc'][] = ' <th '
  1022. . 'class="draggable'
  1023. . ($condition_field ? ' condition"' : '')
  1024. . '" data-column="' . htmlspecialchars((string) $fields_meta[$i]->name)
  1025. . '"> '
  1026. . htmlspecialchars((string) $fields_meta[$i]->name)
  1027. . $comments . ' </th>';
  1028. } // end else
  1029. $this->__set('display_params', $display_params);
  1030. } // end for
  1031. return $html;
  1032. }
  1033. /**
  1034. * Get the headers of the results table
  1035. *
  1036. * @param array $displayParts which elements to display
  1037. * @param array $analyzedSqlResults analyzed sql results
  1038. * @param string $unsortedSqlQuery the unsorted sql query
  1039. * @param array $sortExpression sort expression
  1040. * @param array|string $sortExpressionNoDirection sort expression without direction
  1041. * @param array $sortDirection sort direction
  1042. * @param boolean $isLimitedDisplay with limited operations or not
  1043. *
  1044. * @return string html content
  1045. *
  1046. * @access private
  1047. *
  1048. * @see getTable()
  1049. */
  1050. private function _getTableHeaders(
  1051. array &$displayParts,
  1052. array $analyzedSqlResults,
  1053. $unsortedSqlQuery,
  1054. array $sortExpression = [],
  1055. $sortExpressionNoDirection = '',
  1056. array $sortDirection = [],
  1057. $isLimitedDisplay = false
  1058. ): string {
  1059. // Needed for use in isset/empty or
  1060. // use with array indexes/safe use in foreach
  1061. $printView = $this->__get('printview');
  1062. $displayParams = $this->__get('display_params');
  1063. // Output data needed for column reordering and show/hide column
  1064. $dataForResettingColumnOrder = $this->_getDataForResettingColumnOrder($analyzedSqlResults);
  1065. $displayParams['emptypre'] = 0;
  1066. $displayParams['emptyafter'] = 0;
  1067. $displayParams['textbtn'] = '';
  1068. $fullOrPartialTextLink = '';
  1069. $this->__set('display_params', $displayParams);
  1070. // Display options (if we are not in print view)
  1071. $optionsBlock = '';
  1072. if (! (isset($printView) && ($printView == '1')) && ! $isLimitedDisplay) {
  1073. $optionsBlock = $this->_getOptionsBlock();
  1074. // prepare full/partial text button or link
  1075. $fullOrPartialTextLink = $this->_getFullOrPartialTextButtonOrLink();
  1076. }
  1077. // 1. Set $colspan and generate html with full/partial
  1078. // text button or link
  1079. list($colspan, $buttonHtml) = $this->_getFieldVisibilityParams(
  1080. $displayParts,
  1081. $fullOrPartialTextLink
  1082. );
  1083. // 2. Displays the fields' name
  1084. // 2.0 If sorting links should be used, checks if the query is a "JOIN"
  1085. // statement (see 2.1.3)
  1086. // See if we have to highlight any header fields of a WHERE query.
  1087. // Uses SQL-Parser results.
  1088. $this->_setHighlightedColumnGlobalField($analyzedSqlResults);
  1089. // Get the headers for all of the columns
  1090. $tableHeadersForColumns = $this->_getTableHeadersForColumns(
  1091. $displayParts,
  1092. $analyzedSqlResults,
  1093. $sortExpression,
  1094. $sortExpressionNoDirection,
  1095. $sortDirection,
  1096. $isLimitedDisplay,
  1097. $unsortedSqlQuery
  1098. );
  1099. // Display column at rightside - checkboxes or empty column
  1100. $columnAtRightSide = '';
  1101. if (! $printView) {
  1102. $columnAtRightSide = $this->_getColumnAtRightSide(
  1103. $displayParts,
  1104. $fullOrPartialTextLink,
  1105. $colspan
  1106. );
  1107. }
  1108. return $this->template->render('display/results/table_headers', [
  1109. 'db' => $this->__get('db'),
  1110. 'table' => $this->__get('table'),
  1111. 'unique_id' => $this->__get('unique_id'),
  1112. 'save_cells_at_once' => $GLOBALS['cfg']['SaveCellsAtOnce'],
  1113. 'data_for_resetting_column_order' => $dataForResettingColumnOrder,
  1114. 'options_block' => $optionsBlock,
  1115. 'delete_link' => $displayParts['del_lnk'],
  1116. 'delete_row' => self::DELETE_ROW,
  1117. 'kill_process' => self::KILL_PROCESS,
  1118. 'button' => $buttonHtml,
  1119. 'table_headers_for_columns' => $tableHeadersForColumns,
  1120. 'column_at_right_side' => $columnAtRightSide,
  1121. ]);
  1122. }
  1123. /**
  1124. * Prepare unsorted sql query and sort by key drop down
  1125. *
  1126. * @param array $analyzed_sql_results analyzed sql results
  1127. * @param array|null $sort_expression sort expression
  1128. *
  1129. * @return array two element array - $unsorted_sql_query, $drop_down_html
  1130. *
  1131. * @access private
  1132. *
  1133. * @see _getTableHeaders()
  1134. */
  1135. private function _getUnsortedSqlAndSortByKeyDropDown(
  1136. array $analyzed_sql_results,
  1137. ?array $sort_expression
  1138. ) {
  1139. $drop_down_html = '';
  1140. $unsorted_sql_query = Query::replaceClause(
  1141. $analyzed_sql_results['statement'],
  1142. $analyzed_sql_results['parser']->list,
  1143. 'ORDER BY',
  1144. ''
  1145. );
  1146. // Data is sorted by indexes only if it there is only one table.
  1147. if ($this->_isSelect($analyzed_sql_results)) {
  1148. // grab indexes data:
  1149. $indexes = Index::getFromTable(
  1150. $this->__get('table'),
  1151. $this->__get('db')
  1152. );
  1153. // do we have any index?
  1154. if (! empty($indexes)) {
  1155. $drop_down_html = $this->_getSortByKeyDropDown(
  1156. $indexes,
  1157. $sort_expression,
  1158. $unsorted_sql_query
  1159. );
  1160. }
  1161. }
  1162. return [
  1163. $unsorted_sql_query,
  1164. $drop_down_html,
  1165. ];
  1166. }
  1167. /**
  1168. * Prepare sort by key dropdown - html code segment
  1169. *
  1170. * @param Index[] $indexes the indexes of the table for sort criteria
  1171. * @param array|null $sortExpression the sort expression
  1172. * @param string $unsortedSqlQuery the unsorted sql query
  1173. *
  1174. * @return string html content
  1175. *
  1176. * @access private
  1177. *
  1178. * @see _getTableHeaders()
  1179. */
  1180. private function _getSortByKeyDropDown(
  1181. $indexes,
  1182. ?array $sortExpression,
  1183. $unsortedSqlQuery
  1184. ): string {
  1185. $hiddenFields = [
  1186. 'db' => $this->__get('db'),
  1187. 'table' => $this->__get('table'),
  1188. 'server' => $this->__get('server'),
  1189. 'sort_by_key' => '1',
  1190. ];
  1191. $isIndexUsed = false;
  1192. $localOrder = is_array($sortExpression) ? implode(', ', $sortExpression) : '';
  1193. $options = [];
  1194. foreach ($indexes as $index) {
  1195. $ascSort = '`'
  1196. . implode('` ASC, `', array_keys($index->getColumns()))
  1197. . '` ASC';
  1198. $descSort = '`'
  1199. . implode('` DESC, `', array_keys($index->getColumns()))
  1200. . '` DESC';
  1201. $isIndexUsed = $isIndexUsed
  1202. || $localOrder === $ascSort
  1203. || $localOrder === $descSort;
  1204. $unsortedSqlQueryFirstPart = $unsortedSqlQuery;
  1205. $unsortedSqlQuerySecondPart = '';
  1206. if (preg_match(
  1207. '@(.*)([[:space:]](LIMIT (.*)|PROCEDURE (.*)|'
  1208. . 'FOR UPDATE|LOCK IN SHARE MODE))@is',
  1209. $unsortedSqlQuery,
  1210. $myReg
  1211. )) {
  1212. $unsortedSqlQueryFirstPart = $myReg[1];
  1213. $unsortedSqlQuerySecondPart = $myReg[2];
  1214. }
  1215. $options[] = [
  1216. 'value' => $unsortedSqlQueryFirstPart . ' ORDER BY '
  1217. . $ascSort . $unsortedSqlQuerySecondPart,
  1218. 'content' => $index->getName() . ' (ASC)',
  1219. 'is_selected' => $localOrder === $ascSort,
  1220. ];
  1221. $options[] = [
  1222. 'value' => $unsortedSqlQueryFirstPart . ' ORDER BY '
  1223. . $descSort . $unsortedSqlQuerySecondPart,
  1224. 'content' => $index->getName() . ' (DESC)',
  1225. 'is_selected' => $localOrder === $descSort,
  1226. ];
  1227. }
  1228. $options[] = [
  1229. 'value' => $unsortedSqlQuery,
  1230. 'content' => __('None'),
  1231. 'is_selected' => ! $isIndexUsed,
  1232. ];
  1233. return $this->template->render('display/results/sort_by_key', [
  1234. 'hidden_fields' => $hiddenFields,
  1235. 'options' => $options,
  1236. ]);
  1237. }
  1238. /**
  1239. * Set column span, row span and prepare html with full/partial
  1240. * text button or link
  1241. *
  1242. * @param array $displayParts which elements to display
  1243. * @param string $full_or_partial_text_link full/partial link or text button
  1244. *
  1245. * @return array 2 element array - $colspan, $button_html
  1246. *
  1247. * @access private
  1248. *
  1249. * @see _getTableHeaders()
  1250. */
  1251. private function _getFieldVisibilityParams(
  1252. array &$displayParts,
  1253. $full_or_partial_text_link
  1254. ) {
  1255. $button_html = '';
  1256. $display_params = $this->__get('display_params');
  1257. // 1. Displays the full/partial text button (part 1)...
  1258. $button_html .= '<thead><tr>' . "\n";
  1259. $emptyPreCondition = $displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE
  1260. && $displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE;
  1261. $colspan = $emptyPreCondition ? ' colspan="4"'
  1262. : '';
  1263. $leftOrBoth = $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT
  1264. || $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH;
  1265. // ... before the result table
  1266. if (($displayParts['edit_lnk'] == self::NO_EDIT_OR_DELETE)
  1267. && ($displayParts['del_lnk'] == self::NO_EDIT_OR_DELETE)
  1268. && ($displayParts['text_btn'] == '1')
  1269. ) {
  1270. $display_params['emptypre'] = $emptyPreCondition ? 4 : 0;
  1271. } elseif ($leftOrBoth && ($displayParts['text_btn'] == '1')
  1272. ) {
  1273. // ... at the left column of the result table header if possible
  1274. // and required
  1275. $display_params['emptypre'] = $emptyPreCondition ? 4 : 0;
  1276. $button_html .= '<th class="column_action print_ignore" ' . $colspan
  1277. . '>' . $full_or_partial_text_link . '</th>';
  1278. } elseif ($leftOrBoth
  1279. && (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  1280. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE))
  1281. ) {
  1282. // ... elseif no button, displays empty(ies) col(s) if required
  1283. $display_params['emptypre'] = $emptyPreCondition ? 4 : 0;
  1284. $button_html .= '<td ' . $colspan . '></td>';
  1285. } elseif ($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_NONE) {
  1286. // ... elseif display an empty column if the actions links are
  1287. // disabled to match the rest of the table
  1288. $button_html .= '<th class="column_action"></th>';
  1289. }
  1290. $this->__set('display_params', $display_params);
  1291. return [
  1292. $colspan,
  1293. $button_html,
  1294. ];
  1295. }
  1296. /**
  1297. * Get table comments as array
  1298. *
  1299. * @param array $analyzed_sql_results analyzed sql results
  1300. *
  1301. * @return array table comments
  1302. *
  1303. * @access private
  1304. *
  1305. * @see _getTableHeaders()
  1306. */
  1307. private function _getTableCommentsArray(array $analyzed_sql_results)
  1308. {
  1309. if (! $GLOBALS['cfg']['ShowBrowseComments']
  1310. || empty($analyzed_sql_results['statement']->from)
  1311. ) {
  1312. return [];
  1313. }
  1314. $ret = [];
  1315. foreach ($analyzed_sql_results['statement']->from as $field) {
  1316. if (empty($field->table)) {
  1317. continue;
  1318. }
  1319. $ret[$field->table] = $this->relation->getComments(
  1320. empty($field->database) ? $this->__get('db') : $field->database,
  1321. $field->table
  1322. );
  1323. }
  1324. return $ret;
  1325. }
  1326. /**
  1327. * Set global array for store highlighted header fields
  1328. *
  1329. * @param array $analyzed_sql_results analyzed sql results
  1330. *
  1331. * @return void
  1332. *
  1333. * @access private
  1334. *
  1335. * @see _getTableHeaders()
  1336. */
  1337. private function _setHighlightedColumnGlobalField(array $analyzed_sql_results)
  1338. {
  1339. $highlight_columns = [];
  1340. if (! empty($analyzed_sql_results['statement']->where)) {
  1341. foreach ($analyzed_sql_results['statement']->where as $expr) {
  1342. foreach ($expr->identifiers as $identifier) {
  1343. $highlight_columns[$identifier] = 'true';
  1344. }
  1345. }
  1346. }
  1347. $this->__set('highlight_columns', $highlight_columns);
  1348. }
  1349. /**
  1350. * Prepare data for column restoring and show/hide
  1351. *
  1352. * @param array $analyzedSqlResults analyzed sql results
  1353. *
  1354. * @return string html content
  1355. *
  1356. * @access private
  1357. *
  1358. * @see _getTableHeaders()
  1359. */
  1360. private function _getDataForResettingColumnOrder(array $analyzedSqlResults): string
  1361. {
  1362. if (! $this->_isSelect($analyzedSqlResults)) {
  1363. return '';
  1364. }
  1365. list($columnOrder, $columnVisibility) = $this->_getColumnParams(
  1366. $analyzedSqlResults
  1367. );
  1368. $tableCreateTime = '';
  1369. $table = new Table($this->__get('table'), $this->__get('db'));
  1370. if (! $table->isView()) {
  1371. $tableCreateTime = $GLOBALS['dbi']->getTable(
  1372. $this->__get('db'),
  1373. $this->__get('table')
  1374. )->getStatusInfo('Create_time');
  1375. }
  1376. return $this->template->render('display/results/data_for_resetting_column_order', [
  1377. 'column_order' => $columnOrder,
  1378. 'column_visibility' => $columnVisibility,
  1379. 'is_view' => $table->isView(),
  1380. 'table_create_time' => $tableCreateTime,
  1381. ]);
  1382. }
  1383. /**
  1384. * Prepare option fields block
  1385. *
  1386. * @return string html content
  1387. *
  1388. * @access private
  1389. *
  1390. * @see _getTableHeaders()
  1391. */
  1392. private function _getOptionsBlock()
  1393. {
  1394. if (isset($_SESSION['tmpval']['possible_as_geometry']) && $_SESSION['tmpval']['possible_as_geometry'] == false) {
  1395. if ($_SESSION['tmpval']['geoOption'] == self::GEOMETRY_DISP_GEOM) {
  1396. $_SESSION['tmpval']['geoOption'] = self::GEOMETRY_DISP_WKT;
  1397. }
  1398. }
  1399. return $this->template->render('display/results/options_block', [
  1400. 'unique_id' => $this->__get('unique_id'),
  1401. 'geo_option' => $_SESSION['tmpval']['geoOption'],
  1402. 'hide_transformation' => $_SESSION['tmpval']['hide_transformation'],
  1403. 'display_blob' => $_SESSION['tmpval']['display_blob'],
  1404. 'display_binary' => $_SESSION['tmpval']['display_binary'],
  1405. 'relational_display' => $_SESSION['tmpval']['relational_display'],
  1406. 'displaywork' => $GLOBALS['cfgRelation']['displaywork'],
  1407. 'relwork' => $GLOBALS['cfgRelation']['relwork'],
  1408. 'possible_as_geometry' => $_SESSION['tmpval']['possible_as_geometry'],
  1409. 'pftext' => $_SESSION['tmpval']['pftext'],
  1410. 'db' => $this->__get('db'),
  1411. 'table' => $this->__get('table'),
  1412. 'sql_query' => $this->__get('sql_query'),
  1413. 'goto' => $this->__get('goto'),
  1414. 'default_sliders_state' => $GLOBALS['cfg']['InitialSlidersState'],
  1415. ]);
  1416. }
  1417. /**
  1418. * Get full/partial text button or link
  1419. *
  1420. * @return string html content
  1421. *
  1422. * @access private
  1423. *
  1424. * @see _getTableHeaders()
  1425. */
  1426. private function _getFullOrPartialTextButtonOrLink()
  1427. {
  1428. $url_params_full_text = [
  1429. 'db' => $this->__get('db'),
  1430. 'table' => $this->__get('table'),
  1431. 'sql_query' => $this->__get('sql_query'),
  1432. 'goto' => $this->__get('goto'),
  1433. 'full_text_button' => 1,
  1434. ];
  1435. if ($_SESSION['tmpval']['pftext'] == self::DISPLAY_FULL_TEXT) {
  1436. // currently in fulltext mode so show the opposite link
  1437. $tmp_image_file = $this->__get('pma_theme_image') . 's_partialtext.png';
  1438. $tmp_txt = __('Partial texts');
  1439. $url_params_full_text['pftext'] = self::DISPLAY_PARTIAL_TEXT;
  1440. } else {
  1441. $tmp_image_file = $this->__get('pma_theme_image') . 's_fulltext.png';
  1442. $tmp_txt = __('Full texts');
  1443. $url_params_full_text['pftext'] = self::DISPLAY_FULL_TEXT;
  1444. }
  1445. $tmp_image = '<img class="fulltext" src="' . $tmp_image_file . '" alt="'
  1446. . $tmp_txt . '" title="' . $tmp_txt . '">';
  1447. $tmp_url = 'sql.php' . Url::getCommon($url_params_full_text);
  1448. return Util::linkOrButton($tmp_url, $tmp_image);
  1449. }
  1450. /**
  1451. * Get comment for row
  1452. *
  1453. * @param array $commentsMap comments array
  1454. * @param array $fieldsMeta set of field properties
  1455. *
  1456. * @return string html content
  1457. *
  1458. * @access private
  1459. *
  1460. * @see _getTableHeaders()
  1461. */
  1462. private function _getCommentForRow(array $commentsMap, $fieldsMeta)
  1463. {
  1464. return $this->template->render('display/results/comment_for_row', [
  1465. 'comments_map' => $commentsMap,
  1466. 'fields_meta' => $fieldsMeta,
  1467. 'limit_chars' => $GLOBALS['cfg']['LimitChars'],
  1468. ]);
  1469. }
  1470. /**
  1471. * Prepare parameters and html for sorted table header fields
  1472. *
  1473. * @param stdClass $fields_meta set of field properties
  1474. * @param array $sort_expression sort expression
  1475. * @param array $sort_expression_nodirection sort expression without direction
  1476. * @param integer $column_index the index of the column
  1477. * @param string $unsorted_sql_query the unsorted sql query
  1478. * @param integer $session_max_rows maximum rows resulted by sql
  1479. * @param string $comments comment for row
  1480. * @param array $sort_direction sort direction
  1481. * @param boolean $col_visib column is visible(false)
  1482. * array column isn't visible(string array)
  1483. * @param string $col_visib_j element of $col_visib array
  1484. *
  1485. * @return array 2 element array - $order_link, $sorted_header_html
  1486. *
  1487. * @access private
  1488. *
  1489. * @see _getTableHeaders()
  1490. */
  1491. private function _getOrderLinkAndSortedHeaderHtml(
  1492. $fields_meta,
  1493. array $sort_expression,
  1494. array $sort_expression_nodirection,
  1495. $column_index,
  1496. $unsorted_sql_query,
  1497. $session_max_rows,
  1498. $comments,
  1499. array $sort_direction,
  1500. $col_visib,
  1501. $col_visib_j
  1502. ) {
  1503. $sorted_header_html = '';
  1504. // Checks if the table name is required; it's the case
  1505. // for a query with a "JOIN" statement and if the column
  1506. // isn't aliased, or in queries like
  1507. // SELECT `1`.`master_field` , `2`.`master_field`
  1508. // FROM `PMA_relation` AS `1` , `PMA_relation` AS `2`
  1509. $sort_tbl = isset($fields_meta->table)
  1510. && strlen($fields_meta->table) > 0
  1511. && $fields_meta->orgname == $fields_meta->name
  1512. ? Util::backquote(
  1513. $fields_meta->table
  1514. ) . '.'
  1515. : '';
  1516. $name_to_use_in_sort = $fields_meta->name;
  1517. // Generates the orderby clause part of the query which is part
  1518. // of URL
  1519. list($single_sort_order, $multi_sort_order, $order_img)
  1520. = $this->_getSingleAndMultiSortUrls(
  1521. $sort_expression,
  1522. $sort_expression_nodirection,
  1523. $sort_tbl,
  1524. $name_to_use_in_sort,
  1525. $sort_direction,
  1526. $fields_meta
  1527. );
  1528. if (preg_match(
  1529. '@(.*)([[:space:]](LIMIT (.*)|PROCEDURE (.*)|FOR UPDATE|'
  1530. . 'LOCK IN SHARE MODE))@is',
  1531. $unsorted_sql_query,
  1532. $regs3
  1533. )) {
  1534. $single_sorted_sql_query = $regs3[1] . $single_sort_order . $regs3[2];
  1535. $multi_sorted_sql_query = $regs3[1] . $multi_sort_order . $regs3[2];
  1536. } else {
  1537. $single_sorted_sql_query = $unsorted_sql_query . $single_sort_order;
  1538. $multi_sorted_sql_query = $unsorted_sql_query . $multi_sort_order;
  1539. }
  1540. $_single_url_params = [
  1541. 'db' => $this->__get('db'),
  1542. 'table' => $this->__get('table'),
  1543. 'sql_query' => $single_sorted_sql_query,
  1544. 'sql_signature' => Core::signSqlQuery($single_sorted_sql_query),
  1545. 'session_max_rows' => $session_max_rows,
  1546. 'is_browse_distinct' => $this->__get('is_browse_distinct'),
  1547. ];
  1548. $_multi_url_params = [
  1549. 'db' => $this->__get('db'),
  1550. 'table' => $this->__get('table'),
  1551. 'sql_query' => $multi_sorted_sql_query,
  1552. 'sql_signature' => Core::signSqlQuery($multi_sorted_sql_query),
  1553. 'session_max_rows' => $session_max_rows,
  1554. 'is_browse_distinct' => $this->__get('is_browse_distinct'),
  1555. ];
  1556. $single_order_url = 'sql.php' . Url::getCommon($_single_url_params);
  1557. $multi_order_url = 'sql.php' . Url::getCommon($_multi_url_params);
  1558. // Displays the sorting URL
  1559. // enable sort order swapping for image
  1560. $order_link = $this->_getSortOrderLink(
  1561. $order_img,
  1562. $fields_meta,
  1563. $single_order_url,
  1564. $multi_order_url
  1565. );
  1566. $sorted_header_html .= $this->_getDraggableClassForSortableColumns(
  1567. $col_visib,
  1568. $col_visib_j,
  1569. $fields_meta,
  1570. $order_link,
  1571. $comments
  1572. );
  1573. return [
  1574. $order_link,
  1575. $sorted_header_html,
  1576. ];
  1577. }
  1578. /**
  1579. * Prepare parameters and html for sorted table header fields
  1580. *
  1581. * @param array $sort_expression sort expression
  1582. * @param array $sort_expression_nodirection sort expression without direction
  1583. * @param string $sort_tbl The name of the table to which
  1584. * the current column belongs to
  1585. * @param string $name_to_use_in_sort The current column under
  1586. * consideration
  1587. * @param array $sort_direction sort direction
  1588. * @param stdClass $fields_meta set of field properties
  1589. *
  1590. * @return array 3 element array - $single_sort_order, $sort_order, $order_img
  1591. *
  1592. * @access private
  1593. *
  1594. * @see _getOrderLinkAndSortedHeaderHtml()
  1595. */
  1596. private function _getSingleAndMultiSortUrls(
  1597. array $sort_expression,
  1598. array $sort_expression_nodirection,
  1599. $sort_tbl,
  1600. $name_to_use_in_sort,
  1601. array $sort_direction,
  1602. $fields_meta
  1603. ) {
  1604. $sort_order = "";
  1605. // Check if the current column is in the order by clause
  1606. $is_in_sort = $this->_isInSorted(
  1607. $sort_expression,
  1608. $sort_expression_nodirection,
  1609. $sort_tbl,
  1610. $name_to_use_in_sort
  1611. );
  1612. $current_name = $name_to_use_in_sort;
  1613. if ($sort_expression_nodirection[0] == '' || ! $is_in_sort) {
  1614. $special_index = $sort_expression_nodirection[0] == ''
  1615. ? 0
  1616. : count($sort_expression_nodirection);
  1617. $sort_expression_nodirection[$special_index]
  1618. = Util::backquote(
  1619. $current_name
  1620. );
  1621. $sort_direction[$special_index] = preg_match(
  1622. '@time|date@i',
  1623. $fields_meta->type ?? ''
  1624. ) ? self::DESCENDING_SORT_DIR : self::ASCENDING_SORT_DIR;
  1625. }
  1626. $sort_expression_nodirection = array_filter($sort_expression_nodirection);
  1627. $single_sort_order = null;
  1628. foreach ($sort_expression_nodirection as $index => $expression) {
  1629. // check if this is the first clause,
  1630. // if it is then we have to add "order by"
  1631. $is_first_clause = ($index == 0);
  1632. $name_to_use_in_sort = $expression;
  1633. $sort_tbl_new = $sort_tbl;
  1634. // Test to detect if the column name is a standard name
  1635. // Standard name has the table name prefixed to the column name
  1636. if (mb_strpos($name_to_use_in_sort, '.') !== false) {
  1637. $matches = explode('.', $name_to_use_in_sort);
  1638. // Matches[0] has the table name
  1639. // Matches[1] has the column name
  1640. $name_to_use_in_sort = $matches[1];
  1641. $sort_tbl_new = $matches[0];
  1642. }
  1643. // $name_to_use_in_sort might contain a space due to
  1644. // formatting of function expressions like "COUNT(name )"
  1645. // so we remove the space in this situation
  1646. $name_to_use_in_sort = str_replace([' )', '``'], [')', '`'], $name_to_use_in_sort);
  1647. $name_to_use_in_sort = trim($name_to_use_in_sort, '`');
  1648. // If this the first column name in the order by clause add
  1649. // order by clause to the column name
  1650. $query_head = $is_first_clause ? "\nORDER BY " : "";
  1651. // Again a check to see if the given column is a aggregate column
  1652. if (mb_strpos($name_to_use_in_sort, '(') !== false) {
  1653. $sort_order .= $query_head . $name_to_use_in_sort . ' ' ;
  1654. } else {
  1655. if (strlen($sort_tbl_new) > 0) {
  1656. $sort_tbl_new .= ".";
  1657. }
  1658. $sort_order .= $query_head . $sort_tbl_new
  1659. . Util::backquote(
  1660. $name_to_use_in_sort
  1661. ) . ' ' ;
  1662. }
  1663. // For a special case where the code generates two dots between
  1664. // column name and table name.
  1665. $sort_order = preg_replace("/\.\./", ".", $sort_order);
  1666. // Incase this is the current column save $single_sort_order
  1667. if ($current_name == $name_to_use_in_sort) {
  1668. if (mb_strpos($current_name, '(') !== false) {
  1669. $single_sort_order = "\n" . 'ORDER BY ' . Util::backquote($current_name) . ' ';
  1670. } else {
  1671. $single_sort_order = "\n" . 'ORDER BY ' . $sort_tbl
  1672. . Util::backquote(
  1673. $current_name
  1674. ) . ' ';
  1675. }
  1676. if ($is_in_sort) {
  1677. list($single_sort_order, $order_img)
  1678. = $this->_getSortingUrlParams(
  1679. $sort_direction,
  1680. $single_sort_order,
  1681. $index
  1682. );
  1683. } else {
  1684. $single_sort_order .= strtoupper($sort_direction[$index]);
  1685. }
  1686. }
  1687. if ($current_name == $name_to_use_in_sort && $is_in_sort) {
  1688. // We need to generate the arrow button and related html
  1689. list($sort_order, $order_img) = $this->_getSortingUrlParams(
  1690. $sort_direction,
  1691. $sort_order,
  1692. $index
  1693. );
  1694. $order_img .= " <small>" . ($index + 1) . "</small>";
  1695. } else {
  1696. $sort_order .= strtoupper($sort_direction[$index]);
  1697. }
  1698. // Separate columns by a comma
  1699. $sort_order .= ", ";
  1700. }
  1701. // remove the comma from the last column name in the newly
  1702. // constructed clause
  1703. $sort_order = mb_substr(
  1704. $sort_order,
  1705. 0,
  1706. mb_strlen($sort_order) - 2
  1707. );
  1708. if (empty($order_img)) {
  1709. $order_img = '';
  1710. }
  1711. return [
  1712. $single_sort_order,
  1713. $sort_order,
  1714. $order_img,
  1715. ];
  1716. }
  1717. /**
  1718. * Check whether the column is sorted
  1719. *
  1720. * @param array $sort_expression sort expression
  1721. * @param array $sort_expression_nodirection sort expression without direction
  1722. * @param string $sort_tbl the table name
  1723. * @param string $name_to_use_in_sort the sorting column name
  1724. *
  1725. * @return boolean the column sorted or not
  1726. *
  1727. * @access private
  1728. *
  1729. * @see _getTableHeaders()
  1730. */
  1731. private function _isInSorted(
  1732. array $sort_expression,
  1733. array $sort_expression_nodirection,
  1734. $sort_tbl,
  1735. $name_to_use_in_sort
  1736. ) {
  1737. $index_in_expression = 0;
  1738. foreach ($sort_expression_nodirection as $index => $clause) {
  1739. if (mb_strpos($clause, '.') !== false) {
  1740. $fragments = explode('.', $clause);
  1741. $clause2 = $fragments[0] . "." . str_replace('`', '', $fragments[1]);
  1742. } else {
  1743. $clause2 = $sort_tbl . str_replace('`', '', $clause);
  1744. }
  1745. if ($clause2 === $sort_tbl . $name_to_use_in_sort) {
  1746. $index_in_expression = $index;
  1747. break;
  1748. }
  1749. }
  1750. if (empty($sort_expression[$index_in_expression])) {
  1751. $is_in_sort = false;
  1752. } else {
  1753. // Field name may be preceded by a space, or any number
  1754. // of characters followed by a dot (tablename.fieldname)
  1755. // so do a direct comparison for the sort expression;
  1756. // this avoids problems with queries like
  1757. // "SELECT id, count(id)..." and clicking to sort
  1758. // on id or on count(id).
  1759. // Another query to test this:
  1760. // SELECT p.*, FROM_UNIXTIME(p.temps) FROM mytable AS p
  1761. // (and try clicking on each column's header twice)
  1762. $noSortTable = empty($sort_tbl) || mb_strpos(
  1763. $sort_expression_nodirection[$index_in_expression],
  1764. $sort_tbl
  1765. ) === false;
  1766. $noOpenParenthesis = mb_strpos(
  1767. $sort_expression_nodirection[$index_in_expression],
  1768. '('
  1769. ) === false;
  1770. if (! empty($sort_tbl) && $noSortTable && $noOpenParenthesis) {
  1771. $new_sort_expression_nodirection = $sort_tbl
  1772. . $sort_expression_nodirection[$index_in_expression];
  1773. } else {
  1774. $new_sort_expression_nodirection
  1775. = $sort_expression_nodirection[$index_in_expression];
  1776. }
  1777. //Back quotes are removed in next comparison, so remove them from value
  1778. //to compare.
  1779. $name_to_use_in_sort = str_replace('`', '', $name_to_use_in_sort);
  1780. $is_in_sort = false;
  1781. $sort_name = str_replace('`', '', $sort_tbl) . $name_to_use_in_sort;
  1782. if ($sort_name == str_replace('`', '', $new_sort_expression_nodirection)
  1783. || $sort_name == str_replace('`', '', $sort_expression_nodirection[$index_in_expression])
  1784. ) {
  1785. $is_in_sort = true;
  1786. }
  1787. }
  1788. return $is_in_sort;
  1789. }
  1790. /**
  1791. * Get sort url parameters - sort order and order image
  1792. *
  1793. * @param array $sort_direction the sort direction
  1794. * @param string $sort_order the sorting order
  1795. * @param integer $index the index of sort direction array.
  1796. *
  1797. * @return array 2 element array - $sort_order, $order_img
  1798. *
  1799. * @access private
  1800. *
  1801. * @see _getSingleAndMultiSortUrls()
  1802. */
  1803. private function _getSortingUrlParams(array $sort_direction, $sort_order, $index)
  1804. {
  1805. if (strtoupper(trim($sort_direction[$index])) == self::DESCENDING_SORT_DIR) {
  1806. $sort_order .= ' ASC';
  1807. $order_img = ' ' . Util::getImage(
  1808. 's_desc',
  1809. __('Descending'),
  1810. [
  1811. 'class' => "soimg",
  1812. 'title' => '',
  1813. ]
  1814. );
  1815. $order_img .= ' ' . Util::getImage(
  1816. 's_asc',
  1817. __('Ascending'),
  1818. [
  1819. 'class' => "soimg hide",
  1820. 'title' => '',
  1821. ]
  1822. );
  1823. } else {
  1824. $sort_order .= ' DESC';
  1825. $order_img = ' ' . Util::getImage(
  1826. 's_asc',
  1827. __('Ascending'),
  1828. [
  1829. 'class' => "soimg",
  1830. 'title' => '',
  1831. ]
  1832. );
  1833. $order_img .= ' ' . Util::getImage(
  1834. 's_desc',
  1835. __('Descending'),
  1836. [
  1837. 'class' => "soimg hide",
  1838. 'title' => '',
  1839. ]
  1840. );
  1841. }
  1842. return [
  1843. $sort_order,
  1844. $order_img,
  1845. ];
  1846. }
  1847. /**
  1848. * Get sort order link
  1849. *
  1850. * @param string $order_img the sort order image
  1851. * @param stdClass $fields_meta set of field properties
  1852. * @param string $order_url the url for sort
  1853. * @param string $multi_order_url the url for sort
  1854. *
  1855. * @return string the sort order link
  1856. *
  1857. * @access private
  1858. *
  1859. * @see _getTableHeaders()
  1860. */
  1861. private function _getSortOrderLink(
  1862. $order_img,
  1863. $fields_meta,
  1864. $order_url,
  1865. $multi_order_url
  1866. ) {
  1867. $order_link_params = [
  1868. 'class' => 'sortlink',
  1869. ];
  1870. $order_link_content = htmlspecialchars($fields_meta->name);
  1871. $inner_link_content = $order_link_content . $order_img
  1872. . '<input type="hidden" value="' . $multi_order_url . '">';
  1873. return Util::linkOrButton(
  1874. $order_url,
  1875. $inner_link_content,
  1876. $order_link_params
  1877. );
  1878. }
  1879. /**
  1880. * Check if the column contains numeric data. If yes, then set the
  1881. * column header's alignment right
  1882. *
  1883. * @param stdClass $fields_meta set of field properties
  1884. * @param array $th_class array containing classes
  1885. *
  1886. * @return void
  1887. *
  1888. * @see _getDraggableClassForSortableColumns()
  1889. */
  1890. private function _getClassForNumericColumnType($fields_meta, array &$th_class)
  1891. {
  1892. if (preg_match(
  1893. '@int|decimal|float|double|real|bit|boolean|serial@i',
  1894. (string) $fields_meta->type
  1895. )) {
  1896. $th_class[] = 'right';
  1897. }
  1898. }
  1899. /**
  1900. * Prepare columns to draggable effect for sortable columns
  1901. *
  1902. * @param boolean $col_visib the column is visible (false)
  1903. * array the column is not visible (string array)
  1904. * @param string $col_visib_j element of $col_visib array
  1905. * @param stdClass $fields_meta set of field properties
  1906. * @param string $order_link the order link
  1907. * @param string $comments the comment for the column
  1908. *
  1909. * @return string html content
  1910. *
  1911. * @access private
  1912. *
  1913. * @see _getTableHeaders()
  1914. */
  1915. private function _getDraggableClassForSortableColumns(
  1916. $col_visib,
  1917. $col_visib_j,
  1918. $fields_meta,
  1919. $order_link,
  1920. $comments
  1921. ) {
  1922. $draggable_html = '<th';
  1923. $th_class = [];
  1924. $th_class[] = 'draggable';
  1925. $this->_getClassForNumericColumnType($fields_meta, $th_class);
  1926. if ($col_visib && ! $col_visib_j) {
  1927. $th_class[] = 'hide';
  1928. }
  1929. $th_class[] = 'column_heading';
  1930. if ($GLOBALS['cfg']['BrowsePointerEnable'] == true) {
  1931. $th_class[] = 'pointer';
  1932. }
  1933. if ($GLOBALS['cfg']['BrowseMarkerEnable'] == true) {
  1934. $th_class[] = 'marker';
  1935. }
  1936. $draggable_html .= ' class="' . implode(' ', $th_class) . '"';
  1937. $draggable_html .= ' data-column="' . htmlspecialchars($fields_meta->name)
  1938. . '">' . $order_link . $comments . '</th>';
  1939. return $draggable_html;
  1940. }
  1941. /**
  1942. * Prepare columns to draggable effect for non sortable columns
  1943. *
  1944. * @param boolean $col_visib the column is visible (false)
  1945. * array the column is not visible (string array)
  1946. * @param string $col_visib_j element of $col_visib array
  1947. * @param boolean $condition_field whether to add CSS class condition
  1948. * @param stdClass $fields_meta set of field properties
  1949. * @param string $comments the comment for the column
  1950. *
  1951. * @return string html content
  1952. *
  1953. * @access private
  1954. *
  1955. * @see _getTableHeaders()
  1956. */
  1957. private function _getDraggableClassForNonSortableColumns(
  1958. $col_visib,
  1959. $col_visib_j,
  1960. $condition_field,
  1961. $fields_meta,
  1962. $comments
  1963. ) {
  1964. $draggable_html = '<th';
  1965. $th_class = [];
  1966. $th_class[] = 'draggable';
  1967. $this->_getClassForNumericColumnType($fields_meta, $th_class);
  1968. if ($col_visib && ! $col_visib_j) {
  1969. $th_class[] = 'hide';
  1970. }
  1971. if ($condition_field) {
  1972. $th_class[] = 'condition';
  1973. }
  1974. $draggable_html .= ' class="' . implode(' ', $th_class) . '"';
  1975. $draggable_html .= ' data-column="'
  1976. . htmlspecialchars((string) $fields_meta->name) . '">';
  1977. $draggable_html .= htmlspecialchars((string) $fields_meta->name);
  1978. $draggable_html .= "\n" . $comments . '</th>';
  1979. return $draggable_html;
  1980. }
  1981. /**
  1982. * Prepare column to show at right side - check boxes or empty column
  1983. *
  1984. * @param array $displayParts which elements to display
  1985. * @param string $full_or_partial_text_link full/partial link or text button
  1986. * @param string $colspan column span of table header
  1987. *
  1988. * @return string html content
  1989. *
  1990. * @access private
  1991. *
  1992. * @see _getTableHeaders()
  1993. */
  1994. private function _getColumnAtRightSide(
  1995. array &$displayParts,
  1996. $full_or_partial_text_link,
  1997. $colspan
  1998. ) {
  1999. $right_column_html = '';
  2000. $display_params = $this->__get('display_params');
  2001. // Displays the needed checkboxes at the right
  2002. // column of the result table header if possible and required...
  2003. if (($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_RIGHT)
  2004. || ($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_BOTH)
  2005. && (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  2006. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE))
  2007. && ($displayParts['text_btn'] == '1')
  2008. ) {
  2009. $display_params['emptyafter']
  2010. = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  2011. && ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE) ? 4 : 1;
  2012. $right_column_html .= "\n"
  2013. . '<th class="column_action print_ignore" ' . $colspan . '>'
  2014. . $full_or_partial_text_link
  2015. . '</th>';
  2016. } elseif (($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_LEFT)
  2017. || ($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_BOTH)
  2018. && (($displayParts['edit_lnk'] == self::NO_EDIT_OR_DELETE)
  2019. && ($displayParts['del_lnk'] == self::NO_EDIT_OR_DELETE))
  2020. && (! isset($GLOBALS['is_header_sent']) || ! $GLOBALS['is_header_sent'])
  2021. ) {
  2022. // ... elseif no button, displays empty columns if required
  2023. // (unless coming from Browse mode print view)
  2024. $display_params['emptyafter']
  2025. = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  2026. && ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE) ? 4 : 1;
  2027. $right_column_html .= "\n" . '<td class="print_ignore" ' . $colspan
  2028. . '></td>';
  2029. }
  2030. $this->__set('display_params', $display_params);
  2031. return $right_column_html;
  2032. }
  2033. /**
  2034. * Prepares the display for a value
  2035. *
  2036. * @param string $class class of table cell
  2037. * @param bool $conditionField whether to add CSS class condition
  2038. * @param string $value value to display
  2039. *
  2040. * @return string the td
  2041. *
  2042. * @access private
  2043. *
  2044. * @see _getDataCellForGeometryColumns(),
  2045. * _getDataCellForNonNumericColumns()
  2046. */
  2047. private function _buildValueDisplay($class, $conditionField, $value)
  2048. {
  2049. return $this->template->render('display/results/value_display', [
  2050. 'class' => $class,
  2051. 'condition_field' => $conditionField,
  2052. 'value' => $value,
  2053. ]);
  2054. }
  2055. /**
  2056. * Prepares the display for a null value
  2057. *
  2058. * @param string $class class of table cell
  2059. * @param bool $conditionField whether to add CSS class condition
  2060. * @param stdClass $meta the meta-information about this field
  2061. * @param string $align cell alignment
  2062. *
  2063. * @return string the td
  2064. *
  2065. * @access private
  2066. *
  2067. * @see _getDataCellForNumericColumns(),
  2068. * _getDataCellForGeometryColumns(),
  2069. * _getDataCellForNonNumericColumns()
  2070. */
  2071. private function _buildNullDisplay($class, $conditionField, $meta, $align = '')
  2072. {
  2073. $classes = $this->_addClass($class, $conditionField, $meta, '');
  2074. return $this->template->render('display/results/null_display', [
  2075. 'align' => $align,
  2076. 'meta' => $meta,
  2077. 'classes' => $classes,
  2078. ]);
  2079. }
  2080. /**
  2081. * Prepares the display for an empty value
  2082. *
  2083. * @param string $class class of table cell
  2084. * @param bool $conditionField whether to add CSS class condition
  2085. * @param stdClass $meta the meta-information about this field
  2086. * @param string $align cell alignment
  2087. *
  2088. * @return string the td
  2089. *
  2090. * @access private
  2091. *
  2092. * @see _getDataCellForNumericColumns(),
  2093. * _getDataCellForGeometryColumns(),
  2094. * _getDataCellForNonNumericColumns()
  2095. */
  2096. private function _buildEmptyDisplay($class, $conditionField, $meta, $align = '')
  2097. {
  2098. $classes = $this->_addClass($class, $conditionField, $meta, 'nowrap');
  2099. return $this->template->render('display/results/empty_display', [
  2100. 'align' => $align,
  2101. 'classes' => $classes,
  2102. ]);
  2103. }
  2104. /**
  2105. * Adds the relevant classes.
  2106. *
  2107. * @param string $class class of table cell
  2108. * @param bool $condition_field whether to add CSS class
  2109. * condition
  2110. * @param stdClass $meta the meta-information about the
  2111. * field
  2112. * @param string $nowrap avoid wrapping
  2113. * @param bool $is_field_truncated is field truncated (display ...)
  2114. * @param TransformationsPlugin|string $transformation_plugin transformation plugin.
  2115. * Can also be the default function:
  2116. * Core::mimeDefaultFunction
  2117. * @param string $default_function default transformation function
  2118. *
  2119. * @return string the list of classes
  2120. *
  2121. * @access private
  2122. *
  2123. * @see _buildNullDisplay(), _getRowData()
  2124. */
  2125. private function _addClass(
  2126. $class,
  2127. $condition_field,
  2128. $meta,
  2129. $nowrap,
  2130. $is_field_truncated = false,
  2131. $transformation_plugin = '',
  2132. $default_function = ''
  2133. ) {
  2134. $classes = [
  2135. $class,
  2136. $nowrap,
  2137. ];
  2138. if (isset($meta->mimetype)) {
  2139. $classes[] = preg_replace('/\//', '_', $meta->mimetype);
  2140. }
  2141. if ($condition_field) {
  2142. $classes[] = 'condition';
  2143. }
  2144. if ($is_field_truncated) {
  2145. $classes[] = 'truncated';
  2146. }
  2147. $mime_map = $this->__get('mime_map');
  2148. $orgFullColName = $this->__get('db') . '.' . $meta->orgtable
  2149. . '.' . $meta->orgname;
  2150. if ($transformation_plugin != $default_function
  2151. || ! empty($mime_map[$orgFullColName]['input_transformation'])
  2152. ) {
  2153. $classes[] = 'transformed';
  2154. }
  2155. // Define classes to be added to this data field based on the type of data
  2156. $matches = [
  2157. 'enum' => 'enum',
  2158. 'set' => 'set',
  2159. 'binary' => 'hex',
  2160. ];
  2161. foreach ($matches as $key => $value) {
  2162. if (mb_strpos($meta->flags, $key) !== false) {
  2163. $classes[] = $value;
  2164. }
  2165. }
  2166. if (mb_strpos($meta->type, 'bit') !== false) {
  2167. $classes[] = 'bit';
  2168. }
  2169. return implode(' ', $classes);
  2170. }
  2171. /**
  2172. * Prepare the body of the results table
  2173. *
  2174. * @param integer $dt_result the link id associated to the query
  2175. * which results have to be displayed
  2176. * @param array $displayParts which elements to display
  2177. * @param array $map the list of relations
  2178. * @param array $analyzed_sql_results analyzed sql results
  2179. * @param boolean $is_limited_display with limited operations or not
  2180. *
  2181. * @return string html content
  2182. *
  2183. * @global array $row current row data
  2184. *
  2185. * @access private
  2186. *
  2187. * @see getTable()
  2188. */
  2189. private function _getTableBody(
  2190. &$dt_result,
  2191. array &$displayParts,
  2192. array $map,
  2193. array $analyzed_sql_results,
  2194. $is_limited_display = false
  2195. ) {
  2196. global $row; // mostly because of browser transformations,
  2197. // to make the row-data accessible in a plugin
  2198. $table_body_html = '';
  2199. // query without conditions to shorten URLs when needed, 200 is just
  2200. // guess, it should depend on remaining URL length
  2201. $url_sql_query = $this->_getUrlSqlQuery($analyzed_sql_results);
  2202. $display_params = $this->__get('display_params');
  2203. if (! is_array($map)) {
  2204. $map = [];
  2205. }
  2206. $row_no = 0;
  2207. $display_params['edit'] = [];
  2208. $display_params['copy'] = [];
  2209. $display_params['delete'] = [];
  2210. $display_params['data'] = [];
  2211. $display_params['row_delete'] = [];
  2212. $this->__set('display_params', $display_params);
  2213. // name of the class added to all grid editable elements;
  2214. // if we don't have all the columns of a unique key in the result set,
  2215. // do not permit grid editing
  2216. if ($is_limited_display || ! $this->__get('editable')) {
  2217. $grid_edit_class = '';
  2218. } else {
  2219. switch ($GLOBALS['cfg']['GridEditing']) {
  2220. case 'double-click':
  2221. // trying to reduce generated HTML by using shorter
  2222. // classes like click1 and click2
  2223. $grid_edit_class = 'grid_edit click2';
  2224. break;
  2225. case 'click':
  2226. $grid_edit_class = 'grid_edit click1';
  2227. break;
  2228. default: // 'disabled'
  2229. $grid_edit_class = '';
  2230. break;
  2231. }
  2232. }
  2233. // prepare to get the column order, if available
  2234. list($col_order, $col_visib) = $this->_getColumnParams(
  2235. $analyzed_sql_results
  2236. );
  2237. // Correction University of Virginia 19991216 in the while below
  2238. // Previous code assumed that all tables have keys, specifically that
  2239. // the phpMyAdmin GUI should support row delete/edit only for such
  2240. // tables.
  2241. // Although always using keys is arguably the prescribed way of
  2242. // defining a relational table, it is not required. This will in
  2243. // particular be violated by the novice.
  2244. // We want to encourage phpMyAdmin usage by such novices. So the code
  2245. // below has been changed to conditionally work as before when the
  2246. // table being displayed has one or more keys; but to display
  2247. // delete/edit options correctly for tables without keys.
  2248. $whereClauseMap = $this->__get('whereClauseMap');
  2249. while ($row = $GLOBALS['dbi']->fetchRow($dt_result)) {
  2250. // add repeating headers
  2251. if (($row_no != 0) && ($_SESSION['tmpval']['repeat_cells'] != 0)
  2252. && ! ($row_no % $_SESSION['tmpval']['repeat_cells'])
  2253. ) {
  2254. $table_body_html .= $this->_getRepeatingHeaders(
  2255. $display_params
  2256. );
  2257. }
  2258. $tr_class = [];
  2259. if ($GLOBALS['cfg']['BrowsePointerEnable'] != true) {
  2260. $tr_class[] = 'nopointer';
  2261. }
  2262. if ($GLOBALS['cfg']['BrowseMarkerEnable'] != true) {
  2263. $tr_class[] = 'nomarker';
  2264. }
  2265. // pointer code part
  2266. $classes = (empty($tr_class) ? ' ' : 'class="' . implode(' ', $tr_class) . '"');
  2267. $table_body_html .= '<tr ' . $classes . ' >';
  2268. // 1. Prepares the row
  2269. // In print view these variable needs to be initialized
  2270. $del_url = $del_str = $edit_anchor_class
  2271. = $edit_str = $js_conf = $copy_url = $copy_str = $edit_url = null;
  2272. // 1.2 Defines the URLs for the modify/delete link(s)
  2273. if (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  2274. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
  2275. ) {
  2276. // Results from a "SELECT" statement -> builds the
  2277. // WHERE clause to use in links (a unique key if possible)
  2278. /**
  2279. * @todo $where_clause could be empty, for example a table
  2280. * with only one field and it's a BLOB; in this case,
  2281. * avoid to display the delete and edit links
  2282. */
  2283. list($where_clause, $clause_is_unique, $condition_array)
  2284. = Util::getUniqueCondition(
  2285. $dt_result, // handle
  2286. $this->__get('fields_cnt'), // fields_cnt
  2287. $this->__get('fields_meta'), // fields_meta
  2288. $row, // row
  2289. false, // force_unique
  2290. $this->__get('table'), // restrict_to_table
  2291. $analyzed_sql_results // analyzed_sql_results
  2292. );
  2293. $whereClauseMap[$row_no][$this->__get('table')] = $where_clause;
  2294. $this->__set('whereClauseMap', $whereClauseMap);
  2295. $where_clause_html = htmlspecialchars($where_clause);
  2296. // 1.2.1 Modify link(s) - update row case
  2297. if ($displayParts['edit_lnk'] == self::UPDATE_ROW) {
  2298. list($edit_url, $copy_url, $edit_str, $copy_str,
  2299. $edit_anchor_class)
  2300. = $this->_getModifiedLinks(
  2301. $where_clause,
  2302. $clause_is_unique,
  2303. $url_sql_query
  2304. );
  2305. } // end if (1.2.1)
  2306. // 1.2.2 Delete/Kill link(s)
  2307. list($del_url, $del_str, $js_conf)
  2308. = $this->_getDeleteAndKillLinks(
  2309. $where_clause,
  2310. $clause_is_unique,
  2311. $url_sql_query,
  2312. $displayParts['del_lnk'],
  2313. $row
  2314. );
  2315. // 1.3 Displays the links at left if required
  2316. if (($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_LEFT)
  2317. || ($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_BOTH)
  2318. ) {
  2319. $table_body_html .= $this->_getPlacedLinks(
  2320. self::POSITION_LEFT,
  2321. $del_url,
  2322. $displayParts,
  2323. $row_no,
  2324. $where_clause,
  2325. $where_clause_html,
  2326. $condition_array,
  2327. $edit_url,
  2328. $copy_url,
  2329. $edit_anchor_class,
  2330. $edit_str,
  2331. $copy_str,
  2332. $del_str,
  2333. $js_conf
  2334. );
  2335. } elseif ($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_NONE) {
  2336. $table_body_html .= $this->_getPlacedLinks(
  2337. self::POSITION_NONE,
  2338. $del_url,
  2339. $displayParts,
  2340. $row_no,
  2341. $where_clause,
  2342. $where_clause_html,
  2343. $condition_array,
  2344. $edit_url,
  2345. $copy_url,
  2346. $edit_anchor_class,
  2347. $edit_str,
  2348. $copy_str,
  2349. $del_str,
  2350. $js_conf
  2351. );
  2352. } // end if (1.3)
  2353. } // end if (1)
  2354. // 2. Displays the rows' values
  2355. if ($this->__get('mime_map') === null) {
  2356. $this->_setMimeMap();
  2357. }
  2358. $table_body_html .= $this->_getRowValues(
  2359. $dt_result,
  2360. $row,
  2361. $row_no,
  2362. $col_order,
  2363. $map,
  2364. $grid_edit_class,
  2365. $col_visib,
  2366. $url_sql_query,
  2367. $analyzed_sql_results
  2368. );
  2369. // 3. Displays the modify/delete links on the right if required
  2370. if (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  2371. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
  2372. ) {
  2373. if (($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_RIGHT)
  2374. || ($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_BOTH)
  2375. ) {
  2376. $table_body_html .= $this->_getPlacedLinks(
  2377. self::POSITION_RIGHT,
  2378. $del_url,
  2379. $displayParts,
  2380. $row_no,
  2381. $where_clause,
  2382. $where_clause_html,
  2383. $condition_array,
  2384. $edit_url,
  2385. $copy_url,
  2386. $edit_anchor_class,
  2387. $edit_str,
  2388. $copy_str,
  2389. $del_str,
  2390. $js_conf
  2391. );
  2392. }
  2393. } // end if (3)
  2394. $table_body_html .= '</tr>';
  2395. $table_body_html .= "\n";
  2396. $row_no++;
  2397. } // end while
  2398. return $table_body_html;
  2399. }
  2400. /**
  2401. * Sets the MIME details of the columns in the results set
  2402. *
  2403. * @return void
  2404. */
  2405. private function _setMimeMap()
  2406. {
  2407. $fields_meta = $this->__get('fields_meta');
  2408. $mimeMap = [];
  2409. $added = [];
  2410. for ($currentColumn = 0; $currentColumn < $this->__get('fields_cnt'); ++$currentColumn) {
  2411. $meta = $fields_meta[$currentColumn];
  2412. $orgFullTableName = $this->__get('db') . '.' . $meta->orgtable;
  2413. if ($GLOBALS['cfgRelation']['commwork']
  2414. && $GLOBALS['cfgRelation']['mimework']
  2415. && $GLOBALS['cfg']['BrowseMIME']
  2416. && ! $_SESSION['tmpval']['hide_transformation']
  2417. && empty($added[$orgFullTableName])
  2418. ) {
  2419. $mimeMap = array_merge(
  2420. $mimeMap,
  2421. $this->transformations->getMime($this->__get('db'), $meta->orgtable, false, true)
  2422. );
  2423. $added[$orgFullTableName] = true;
  2424. }
  2425. }
  2426. // special browser transformation for some SHOW statements
  2427. if ($this->__get('is_show')
  2428. && ! $_SESSION['tmpval']['hide_transformation']
  2429. ) {
  2430. preg_match(
  2431. '@^SHOW[[:space:]]+(VARIABLES|(FULL[[:space:]]+)?'
  2432. . 'PROCESSLIST|STATUS|TABLE|GRANTS|CREATE|LOGS|DATABASES|FIELDS'
  2433. . ')@i',
  2434. $this->__get('sql_query'),
  2435. $which
  2436. );
  2437. if (isset($which[1])) {
  2438. $str = ' ' . strtoupper($which[1]);
  2439. $isShowProcessList = strpos($str, 'PROCESSLIST') > 0;
  2440. if ($isShowProcessList) {
  2441. $mimeMap['..Info'] = [
  2442. 'mimetype' => 'Text_Plain',
  2443. 'transformation' => 'output/Text_Plain_Sql.php',
  2444. ];
  2445. }
  2446. $isShowCreateTable = preg_match(
  2447. '@CREATE[[:space:]]+TABLE@i',
  2448. $this->__get('sql_query')
  2449. );
  2450. if ($isShowCreateTable) {
  2451. $mimeMap['..Create Table'] = [
  2452. 'mimetype' => 'Text_Plain',
  2453. 'transformation' => 'output/Text_Plain_Sql.php',
  2454. ];
  2455. }
  2456. }
  2457. }
  2458. $this->__set('mime_map', $mimeMap);
  2459. }
  2460. /**
  2461. * Get the values for one data row
  2462. *
  2463. * @param integer $dt_result the link id associated to
  2464. * the query which results
  2465. * have to be displayed
  2466. * @param array $row current row data
  2467. * @param integer $row_no the index of current row
  2468. * @param array|boolean $col_order the column order false when
  2469. * a property not found false
  2470. * when a property not found
  2471. * @param array $map the list of relations
  2472. * @param string $grid_edit_class the class for all editable
  2473. * columns
  2474. * @param boolean|array|string $col_visib column is visible(false);
  2475. * column isn't visible(string
  2476. * array)
  2477. * @param string $url_sql_query the analyzed sql query
  2478. * @param array $analyzed_sql_results analyzed sql results
  2479. *
  2480. * @return string html content
  2481. *
  2482. * @access private
  2483. *
  2484. * @see _getTableBody()
  2485. */
  2486. private function _getRowValues(
  2487. &$dt_result,
  2488. array $row,
  2489. $row_no,
  2490. $col_order,
  2491. array $map,
  2492. $grid_edit_class,
  2493. $col_visib,
  2494. $url_sql_query,
  2495. array $analyzed_sql_results
  2496. ) {
  2497. $row_values_html = '';
  2498. // Following variable are needed for use in isset/empty or
  2499. // use with array indexes/safe use in foreach
  2500. $sql_query = $this->__get('sql_query');
  2501. $fields_meta = $this->__get('fields_meta');
  2502. $highlight_columns = $this->__get('highlight_columns');
  2503. $mime_map = $this->__get('mime_map');
  2504. $row_info = $this->_getRowInfoForSpecialLinks($row, $col_order);
  2505. $whereClauseMap = $this->__get('whereClauseMap');
  2506. $columnCount = $this->__get('fields_cnt');
  2507. for ($currentColumn = 0; $currentColumn < $columnCount; ++$currentColumn) {
  2508. // assign $i with appropriate column order
  2509. $i = $col_order ? $col_order[$currentColumn] : $currentColumn;
  2510. $meta = $fields_meta[$i];
  2511. $orgFullColName
  2512. = $this->__get('db') . '.' . $meta->orgtable . '.' . $meta->orgname;
  2513. $not_null_class = $meta->not_null ? 'not_null' : '';
  2514. $relation_class = isset($map[$meta->name]) ? 'relation' : '';
  2515. $hide_class = $col_visib && isset($col_visib[$currentColumn]) && ! $col_visib[$currentColumn]
  2516. ? 'hide'
  2517. : '';
  2518. $grid_edit = $meta->orgtable != '' ? $grid_edit_class : '';
  2519. // handle datetime-related class, for grid editing
  2520. $field_type_class
  2521. = $this->_getClassForDateTimeRelatedFields($meta->type);
  2522. $is_field_truncated = false;
  2523. // combine all the classes applicable to this column's value
  2524. $class = $this->_getClassesForColumn(
  2525. $grid_edit,
  2526. $not_null_class,
  2527. $relation_class,
  2528. $hide_class,
  2529. $field_type_class
  2530. );
  2531. // See if this column should get highlight because it's used in the
  2532. // where-query.
  2533. $condition_field = isset($highlight_columns)
  2534. && (isset($highlight_columns[$meta->name])
  2535. || isset($highlight_columns[Util::backquote($meta->name)]))
  2536. ? true
  2537. : false;
  2538. // Wrap MIME-transformations. [MIME]
  2539. $default_function = [
  2540. Core::class,
  2541. 'mimeDefaultFunction',
  2542. ]; // default_function
  2543. $transformation_plugin = $default_function;
  2544. $transform_options = [];
  2545. if ($GLOBALS['cfgRelation']['mimework']
  2546. && $GLOBALS['cfg']['BrowseMIME']
  2547. ) {
  2548. if (isset($mime_map[$orgFullColName]['mimetype'])
  2549. && ! empty($mime_map[$orgFullColName]['transformation'])
  2550. ) {
  2551. $file = $mime_map[$orgFullColName]['transformation'];
  2552. $include_file = 'libraries/classes/Plugins/Transformations/' . $file;
  2553. if (@file_exists($include_file)) {
  2554. $class_name = $this->transformations->getClassName($include_file);
  2555. if (class_exists($class_name)) {
  2556. // todo add $plugin_manager
  2557. $plugin_manager = null;
  2558. $transformation_plugin = new $class_name(
  2559. $plugin_manager
  2560. );
  2561. $transform_options = $this->transformations->getOptions(
  2562. isset(
  2563. $mime_map[$orgFullColName]['transformation_options']
  2564. )
  2565. ? $mime_map[$orgFullColName]['transformation_options']
  2566. : ''
  2567. );
  2568. $meta->mimetype = str_replace(
  2569. '_',
  2570. '/',
  2571. $mime_map[$orgFullColName]['mimetype']
  2572. );
  2573. }
  2574. } // end if file_exists
  2575. } // end if transformation is set
  2576. } // end if mime/transformation works.
  2577. // Check whether the field needs to display with syntax highlighting
  2578. $dbLower = mb_strtolower($this->__get('db'));
  2579. $tblLower = mb_strtolower($meta->orgtable);
  2580. $nameLower = mb_strtolower($meta->orgname);
  2581. if (! empty($this->transformation_info[$dbLower][$tblLower][$nameLower])
  2582. && isset($row[$i])
  2583. && (trim($row[$i]) != '')
  2584. && ! $_SESSION['tmpval']['hide_transformation']
  2585. ) {
  2586. include_once $this->transformation_info[$dbLower][$tblLower][$nameLower][0];
  2587. $transformation_plugin = new $this->transformation_info[$dbLower][$tblLower][$nameLower][1](null);
  2588. $transform_options = $this->transformations->getOptions(
  2589. isset($mime_map[$orgFullColName]['transformation_options'])
  2590. ? $mime_map[$orgFullColName]['transformation_options']
  2591. : ''
  2592. );
  2593. $meta->mimetype = str_replace(
  2594. '_',
  2595. '/',
  2596. $this->transformation_info[$dbLower][mb_strtolower($meta->orgtable)][mb_strtolower($meta->orgname)][2]
  2597. );
  2598. }
  2599. // Check for the predefined fields need to show as link in schemas
  2600. $specialSchemaLinks = SpecialSchemaLinks::get();
  2601. if (! empty($specialSchemaLinks[$dbLower][$tblLower][$nameLower])) {
  2602. $linking_url = $this->_getSpecialLinkUrl(
  2603. $specialSchemaLinks,
  2604. $row[$i],
  2605. $row_info,
  2606. mb_strtolower($meta->orgname)
  2607. );
  2608. $transformation_plugin = new Text_Plain_Link();
  2609. $transform_options = [
  2610. 0 => $linking_url,
  2611. 2 => true,
  2612. ];
  2613. $meta->mimetype = str_replace(
  2614. '_',
  2615. '/',
  2616. 'Text/Plain'
  2617. );
  2618. }
  2619. /*
  2620. * The result set can have columns from more than one table,
  2621. * this is why we have to check for the unique conditions
  2622. * related to this table; however getUniqueCondition() is
  2623. * costly and does not need to be called if we already know
  2624. * the conditions for the current table.
  2625. */
  2626. if (! isset($whereClauseMap[$row_no][$meta->orgtable])) {
  2627. $unique_conditions = Util::getUniqueCondition(
  2628. $dt_result, // handle
  2629. $this->__get('fields_cnt'), // fields_cnt
  2630. $this->__get('fields_meta'), // fields_meta
  2631. $row, // row
  2632. false, // force_unique
  2633. $meta->orgtable, // restrict_to_table
  2634. $analyzed_sql_results // analyzed_sql_results
  2635. );
  2636. $whereClauseMap[$row_no][$meta->orgtable] = $unique_conditions[0];
  2637. }
  2638. $_url_params = [
  2639. 'db' => $this->__get('db'),
  2640. 'table' => $meta->orgtable,
  2641. 'where_clause' => $whereClauseMap[$row_no][$meta->orgtable],
  2642. 'transform_key' => $meta->orgname,
  2643. ];
  2644. if (! empty($sql_query)) {
  2645. $_url_params['sql_query'] = $url_sql_query;
  2646. }
  2647. $transform_options['wrapper_link'] = Url::getCommon($_url_params);
  2648. $display_params = $this->__get('display_params');
  2649. // in some situations (issue 11406), numeric returns 1
  2650. // even for a string type
  2651. // for decimal numeric is returning 1
  2652. // have to improve logic
  2653. if (($meta->numeric == 1 && $meta->type != 'string') || $meta->type == 'real') {
  2654. // n u m e r i c
  2655. $display_params['data'][$row_no][$i]
  2656. = $this->_getDataCellForNumericColumns(
  2657. $row[$i] === null ? null : (string) $row[$i],
  2658. $class,
  2659. $condition_field,
  2660. $meta,
  2661. $map,
  2662. $is_field_truncated,
  2663. $analyzed_sql_results,
  2664. $transformation_plugin,
  2665. $default_function,
  2666. $transform_options
  2667. );
  2668. } elseif ($meta->type == self::GEOMETRY_FIELD) {
  2669. // g e o m e t r y
  2670. // Remove 'grid_edit' from $class as we do not allow to
  2671. // inline-edit geometry data.
  2672. $class = str_replace('grid_edit', '', $class);
  2673. $display_params['data'][$row_no][$i]
  2674. = $this->_getDataCellForGeometryColumns(
  2675. $row[$i],
  2676. $class,
  2677. $meta,
  2678. $map,
  2679. $_url_params,
  2680. $condition_field,
  2681. $transformation_plugin,
  2682. $default_function,
  2683. $transform_options,
  2684. $analyzed_sql_results
  2685. );
  2686. } else {
  2687. // n o t n u m e r i c
  2688. $display_params['data'][$row_no][$i]
  2689. = $this->_getDataCellForNonNumericColumns(
  2690. $row[$i],
  2691. $class,
  2692. $meta,
  2693. $map,
  2694. $_url_params,
  2695. $condition_field,
  2696. $transformation_plugin,
  2697. $default_function,
  2698. $transform_options,
  2699. $is_field_truncated,
  2700. $analyzed_sql_results,
  2701. $dt_result,
  2702. $i
  2703. );
  2704. }
  2705. // output stored cell
  2706. $row_values_html .= $display_params['data'][$row_no][$i];
  2707. if (isset($display_params['rowdata'][$i][$row_no])) {
  2708. $display_params['rowdata'][$i][$row_no]
  2709. .= $display_params['data'][$row_no][$i];
  2710. } else {
  2711. $display_params['rowdata'][$i][$row_no]
  2712. = $display_params['data'][$row_no][$i];
  2713. }
  2714. $this->__set('display_params', $display_params);
  2715. } // end for
  2716. return $row_values_html;
  2717. }
  2718. /**
  2719. * Get link for display special schema links
  2720. *
  2721. * @param array $specialSchemaLinks special schema links
  2722. * @param string $column_value column value
  2723. * @param array $row_info information about row
  2724. * @param string $field_name column name
  2725. *
  2726. * @return string generated link
  2727. */
  2728. private function _getSpecialLinkUrl(
  2729. array $specialSchemaLinks,
  2730. $column_value,
  2731. array $row_info,
  2732. $field_name
  2733. ) {
  2734. $linking_url_params = [];
  2735. $link_relations = $specialSchemaLinks[mb_strtolower($this->__get('db'))][mb_strtolower($this->__get('table'))][$field_name];
  2736. if (! is_array($link_relations['link_param'])) {
  2737. $linking_url_params[$link_relations['link_param']] = $column_value;
  2738. } else {
  2739. // Consider only the case of creating link for column field
  2740. // sql query that needs to be passed as url param
  2741. $sql = 'SELECT `' . $column_value . '` FROM `'
  2742. . $row_info[$link_relations['link_param'][1]] . '`.`'
  2743. . $row_info[$link_relations['link_param'][2]] . '`';
  2744. $linking_url_params[$link_relations['link_param'][0]] = $sql;
  2745. }
  2746. $divider = strpos($link_relations['default_page'], '?') ? '&' : '?';
  2747. if (empty($link_relations['link_dependancy_params'])) {
  2748. return $link_relations['default_page']
  2749. . Url::getCommonRaw($linking_url_params, $divider);
  2750. }
  2751. foreach ($link_relations['link_dependancy_params'] as $new_param) {
  2752. // If param_info is an array, set the key and value
  2753. // from that array
  2754. if (is_array($new_param['param_info'])) {
  2755. $linking_url_params[$new_param['param_info'][0]]
  2756. = $new_param['param_info'][1];
  2757. continue;
  2758. }
  2759. $linking_url_params[$new_param['param_info']]
  2760. = $row_info[mb_strtolower($new_param['column_name'])];
  2761. // Special case 1 - when executing routines, according
  2762. // to the type of the routine, url param changes
  2763. if (empty($row_info['routine_type'])) {
  2764. continue;
  2765. }
  2766. }
  2767. return $link_relations['default_page']
  2768. . Url::getCommonRaw($linking_url_params, $divider);
  2769. }
  2770. /**
  2771. * Prepare row information for display special links
  2772. *
  2773. * @param array $row current row data
  2774. * @param array|boolean $col_order the column order
  2775. *
  2776. * @return array associative array with column nama -> value
  2777. */
  2778. private function _getRowInfoForSpecialLinks(array $row, $col_order)
  2779. {
  2780. $row_info = [];
  2781. $fields_meta = $this->__get('fields_meta');
  2782. for ($n = 0; $n < $this->__get('fields_cnt'); ++$n) {
  2783. $m = $col_order ? $col_order[$n] : $n;
  2784. $row_info[mb_strtolower($fields_meta[$m]->orgname)]
  2785. = $row[$m];
  2786. }
  2787. return $row_info;
  2788. }
  2789. /**
  2790. * Get url sql query without conditions to shorten URLs
  2791. *
  2792. * @param array $analyzed_sql_results analyzed sql results
  2793. *
  2794. * @return string analyzed sql query
  2795. *
  2796. * @access private
  2797. *
  2798. * @see _getTableBody()
  2799. */
  2800. private function _getUrlSqlQuery(array $analyzed_sql_results)
  2801. {
  2802. if (($analyzed_sql_results['querytype'] != 'SELECT')
  2803. || (mb_strlen($this->__get('sql_query')) < 200)
  2804. ) {
  2805. return $this->__get('sql_query');
  2806. }
  2807. $query = 'SELECT ' . Query::getClause(
  2808. $analyzed_sql_results['statement'],
  2809. $analyzed_sql_results['parser']->list,
  2810. 'SELECT'
  2811. );
  2812. $from_clause = Query::getClause(
  2813. $analyzed_sql_results['statement'],
  2814. $analyzed_sql_results['parser']->list,
  2815. 'FROM'
  2816. );
  2817. if (! empty($from_clause)) {
  2818. $query .= ' FROM ' . $from_clause;
  2819. }
  2820. return $query;
  2821. }
  2822. /**
  2823. * Get column order and column visibility
  2824. *
  2825. * @param array $analyzed_sql_results analyzed sql results
  2826. *
  2827. * @return array 2 element array - $col_order, $col_visib
  2828. *
  2829. * @access private
  2830. *
  2831. * @see _getTableBody()
  2832. */
  2833. private function _getColumnParams(array $analyzed_sql_results)
  2834. {
  2835. if ($this->_isSelect($analyzed_sql_results)) {
  2836. $pmatable = new Table($this->__get('table'), $this->__get('db'));
  2837. $col_order = $pmatable->getUiProp(Table::PROP_COLUMN_ORDER);
  2838. /* Validate the value */
  2839. if ($col_order !== false) {
  2840. $fields_cnt = $this->__get('fields_cnt');
  2841. foreach ($col_order as $value) {
  2842. if ($value >= $fields_cnt) {
  2843. $pmatable->removeUiProp(Table::PROP_COLUMN_ORDER);
  2844. $fields_cnt = false;
  2845. }
  2846. }
  2847. }
  2848. $col_visib = $pmatable->getUiProp(Table::PROP_COLUMN_VISIB);
  2849. } else {
  2850. $col_order = false;
  2851. $col_visib = false;
  2852. }
  2853. return [
  2854. $col_order,
  2855. $col_visib,
  2856. ];
  2857. }
  2858. /**
  2859. * Get HTML for repeating headers
  2860. *
  2861. * @param array $display_params holds various display info
  2862. *
  2863. * @return string html content
  2864. *
  2865. * @access private
  2866. *
  2867. * @see _getTableBody()
  2868. */
  2869. private function _getRepeatingHeaders(
  2870. array $display_params
  2871. ) {
  2872. $header_html = '<tr>' . "\n";
  2873. if ($display_params['emptypre'] > 0) {
  2874. $header_html .= ' <th colspan="'
  2875. . $display_params['emptypre'] . '">'
  2876. . "\n" . ' &nbsp;</th>' . "\n";
  2877. } elseif ($GLOBALS['cfg']['RowActionLinks'] == self::POSITION_NONE) {
  2878. $header_html .= ' <th></th>' . "\n";
  2879. }
  2880. foreach ($display_params['desc'] as $val) {
  2881. $header_html .= $val;
  2882. }
  2883. if ($display_params['emptyafter'] > 0) {
  2884. $header_html
  2885. .= ' <th colspan="' . $display_params['emptyafter']
  2886. . '">'
  2887. . "\n" . ' &nbsp;</th>' . "\n";
  2888. }
  2889. $header_html .= '</tr>' . "\n";
  2890. return $header_html;
  2891. }
  2892. /**
  2893. * Get modified links
  2894. *
  2895. * @param string $where_clause the where clause of the sql
  2896. * @param boolean $clause_is_unique the unique condition of clause
  2897. * @param string $url_sql_query the analyzed sql query
  2898. *
  2899. * @return array 5 element array - $edit_url, $copy_url,
  2900. * $edit_str, $copy_str, $edit_anchor_class
  2901. *
  2902. * @access private
  2903. *
  2904. * @see _getTableBody()
  2905. */
  2906. private function _getModifiedLinks(
  2907. $where_clause,
  2908. $clause_is_unique,
  2909. $url_sql_query
  2910. ) {
  2911. $_url_params = [
  2912. 'db' => $this->__get('db'),
  2913. 'table' => $this->__get('table'),
  2914. 'where_clause' => $where_clause,
  2915. 'clause_is_unique' => $clause_is_unique,
  2916. 'sql_query' => $url_sql_query,
  2917. 'goto' => 'sql.php',
  2918. ];
  2919. $edit_url = 'tbl_change.php'
  2920. . Url::getCommon(
  2921. $_url_params + ['default_action' => 'update']
  2922. );
  2923. $copy_url = 'tbl_change.php'
  2924. . Url::getCommon(
  2925. $_url_params + ['default_action' => 'insert']
  2926. );
  2927. $edit_str = $this->_getActionLinkContent(
  2928. 'b_edit',
  2929. __('Edit')
  2930. );
  2931. $copy_str = $this->_getActionLinkContent(
  2932. 'b_insrow',
  2933. __('Copy')
  2934. );
  2935. // Class definitions required for grid editing jQuery scripts
  2936. $edit_anchor_class = "edit_row_anchor";
  2937. if ($clause_is_unique == 0) {
  2938. $edit_anchor_class .= ' nonunique';
  2939. }
  2940. return [
  2941. $edit_url,
  2942. $copy_url,
  2943. $edit_str,
  2944. $copy_str,
  2945. $edit_anchor_class,
  2946. ];
  2947. }
  2948. /**
  2949. * Get delete and kill links
  2950. *
  2951. * @param string $where_clause the where clause of the sql
  2952. * @param boolean $clause_is_unique the unique condition of clause
  2953. * @param string $url_sql_query the analyzed sql query
  2954. * @param string $del_lnk the delete link of current row
  2955. * @param array $row the current row
  2956. *
  2957. * @return array 3 element array
  2958. * $del_url, $del_str, $js_conf
  2959. *
  2960. * @access private
  2961. *
  2962. * @see _getTableBody()
  2963. */
  2964. private function _getDeleteAndKillLinks(
  2965. $where_clause,
  2966. $clause_is_unique,
  2967. $url_sql_query,
  2968. $del_lnk,
  2969. array $row
  2970. ) {
  2971. $goto = $this->__get('goto');
  2972. if ($del_lnk == self::DELETE_ROW) { // delete row case
  2973. $_url_params = [
  2974. 'db' => $this->__get('db'),
  2975. 'table' => $this->__get('table'),
  2976. 'sql_query' => $url_sql_query,
  2977. 'message_to_show' => __('The row has been deleted.'),
  2978. 'goto' => empty($goto) ? 'tbl_sql.php' : $goto,
  2979. ];
  2980. $lnk_goto = 'sql.php' . Url::getCommonRaw($_url_params);
  2981. $del_query = 'DELETE FROM '
  2982. . Util::backquote($this->__get('table'))
  2983. . ' WHERE ' . $where_clause .
  2984. ($clause_is_unique ? '' : ' LIMIT 1');
  2985. $_url_params = [
  2986. 'db' => $this->__get('db'),
  2987. 'table' => $this->__get('table'),
  2988. 'sql_query' => $del_query,
  2989. 'message_to_show' => __('The row has been deleted.'),
  2990. 'goto' => $lnk_goto,
  2991. ];
  2992. $del_url = 'sql.php' . Url::getCommon($_url_params);
  2993. $js_conf = 'DELETE FROM ' . Sanitize::jsFormat($this->__get('table'))
  2994. . ' WHERE ' . Sanitize::jsFormat($where_clause, false)
  2995. . ($clause_is_unique ? '' : ' LIMIT 1');
  2996. $del_str = $this->_getActionLinkContent('b_drop', __('Delete'));
  2997. } elseif ($del_lnk == self::KILL_PROCESS) { // kill process case
  2998. $_url_params = [
  2999. 'db' => $this->__get('db'),
  3000. 'table' => $this->__get('table'),
  3001. 'sql_query' => $url_sql_query,
  3002. 'goto' => 'index.php',
  3003. ];
  3004. $lnk_goto = 'sql.php' . Url::getCommonRaw($_url_params);
  3005. $kill = $GLOBALS['dbi']->getKillQuery((int) $row[0]);
  3006. $_url_params = [
  3007. 'db' => 'mysql',
  3008. 'sql_query' => $kill,
  3009. 'goto' => $lnk_goto,
  3010. ];
  3011. $del_url = 'sql.php' . Url::getCommon($_url_params);
  3012. $js_conf = $kill;
  3013. $del_str = Util::getIcon(
  3014. 'b_drop',
  3015. __('Kill')
  3016. );
  3017. } else {
  3018. $del_url = $del_str = $js_conf = null;
  3019. }
  3020. return [
  3021. $del_url,
  3022. $del_str,
  3023. $js_conf,
  3024. ];
  3025. }
  3026. /**
  3027. * Get content inside the table row action links (Edit/Copy/Delete)
  3028. *
  3029. * @param string $icon The name of the file to get
  3030. * @param string $display_text The text displaying after the image icon
  3031. *
  3032. * @return string
  3033. *
  3034. * @access private
  3035. *
  3036. * @see _getModifiedLinks(), _getDeleteAndKillLinks()
  3037. */
  3038. private function _getActionLinkContent($icon, $display_text)
  3039. {
  3040. $linkContent = '';
  3041. if (isset($GLOBALS['cfg']['RowActionType'])
  3042. && $GLOBALS['cfg']['RowActionType'] == self::ACTION_LINK_CONTENT_ICONS
  3043. ) {
  3044. $linkContent .= '<span class="nowrap">'
  3045. . Util::getImage(
  3046. $icon,
  3047. $display_text
  3048. )
  3049. . '</span>';
  3050. } elseif (isset($GLOBALS['cfg']['RowActionType'])
  3051. && $GLOBALS['cfg']['RowActionType'] == self::ACTION_LINK_CONTENT_TEXT
  3052. ) {
  3053. $linkContent .= '<span class="nowrap">' . $display_text . '</span>';
  3054. } else {
  3055. $linkContent .= Util::getIcon(
  3056. $icon,
  3057. $display_text
  3058. );
  3059. }
  3060. return $linkContent;
  3061. }
  3062. /**
  3063. * Prepare placed links
  3064. *
  3065. * @param string $dir the direction of links should place
  3066. * @param string $del_url the url for delete row
  3067. * @param array $displayParts which elements to display
  3068. * @param integer $row_no the index of current row
  3069. * @param string $where_clause the where clause of the sql
  3070. * @param string $where_clause_html the html encoded where clause
  3071. * @param array $condition_array array of keys (primary, unique, condition)
  3072. * @param string $edit_url the url for edit row
  3073. * @param string $copy_url the url for copy row
  3074. * @param string $edit_anchor_class the class for html element for edit
  3075. * @param string $edit_str the label for edit row
  3076. * @param string $copy_str the label for copy row
  3077. * @param string $del_str the label for delete row
  3078. * @param string|null $js_conf text for the JS confirmation
  3079. *
  3080. * @return string html content
  3081. *
  3082. * @access private
  3083. *
  3084. * @see _getTableBody()
  3085. */
  3086. private function _getPlacedLinks(
  3087. $dir,
  3088. $del_url,
  3089. array $displayParts,
  3090. $row_no,
  3091. $where_clause,
  3092. $where_clause_html,
  3093. array $condition_array,
  3094. $edit_url,
  3095. $copy_url,
  3096. $edit_anchor_class,
  3097. $edit_str,
  3098. $copy_str,
  3099. $del_str,
  3100. ?string $js_conf
  3101. ) {
  3102. if (! isset($js_conf)) {
  3103. $js_conf = '';
  3104. }
  3105. return $this->_getCheckboxAndLinks(
  3106. $dir,
  3107. $del_url,
  3108. $displayParts,
  3109. $row_no,
  3110. $where_clause,
  3111. $where_clause_html,
  3112. $condition_array,
  3113. $edit_url,
  3114. $copy_url,
  3115. $edit_anchor_class,
  3116. $edit_str,
  3117. $copy_str,
  3118. $del_str,
  3119. $js_conf
  3120. );
  3121. }
  3122. /**
  3123. * Get the combined classes for a column
  3124. *
  3125. * @param string $grid_edit_class the class for all editable columns
  3126. * @param string $not_null_class the class for not null columns
  3127. * @param string $relation_class the class for relations in a column
  3128. * @param string $hide_class the class for visibility of a column
  3129. * @param string $field_type_class the class related to type of the field
  3130. *
  3131. * @return string the combined classes
  3132. *
  3133. * @access private
  3134. *
  3135. * @see _getTableBody()
  3136. */
  3137. private function _getClassesForColumn(
  3138. $grid_edit_class,
  3139. $not_null_class,
  3140. $relation_class,
  3141. $hide_class,
  3142. $field_type_class
  3143. ) {
  3144. return 'data ' . $grid_edit_class . ' ' . $not_null_class . ' '
  3145. . $relation_class . ' ' . $hide_class . ' ' . $field_type_class;
  3146. }
  3147. /**
  3148. * Get class for datetime related fields
  3149. *
  3150. * @param string $type the type of the column field
  3151. *
  3152. * @return string the class for the column
  3153. *
  3154. * @access private
  3155. *
  3156. * @see _getTableBody()
  3157. */
  3158. private function _getClassForDateTimeRelatedFields($type)
  3159. {
  3160. if ((substr($type, 0, 9) == self::TIMESTAMP_FIELD)
  3161. || ($type == self::DATETIME_FIELD)
  3162. ) {
  3163. $field_type_class = 'datetimefield';
  3164. } elseif ($type == self::DATE_FIELD) {
  3165. $field_type_class = 'datefield';
  3166. } elseif ($type == self::TIME_FIELD) {
  3167. $field_type_class = 'timefield';
  3168. } elseif ($type == self::STRING_FIELD) {
  3169. $field_type_class = 'text';
  3170. } else {
  3171. $field_type_class = '';
  3172. }
  3173. return $field_type_class;
  3174. }
  3175. /**
  3176. * Prepare data cell for numeric type fields
  3177. *
  3178. * @param string|null $column the column's value
  3179. * @param string $class the html class for column
  3180. * @param boolean $condition_field the column should highlighted
  3181. * or not
  3182. * @param stdClass $meta the meta-information about this
  3183. * field
  3184. * @param array $map the list of relations
  3185. * @param boolean $is_field_truncated the condition for blob data
  3186. * replacements
  3187. * @param array $analyzed_sql_results the analyzed query
  3188. * @param TransformationsPlugin $transformation_plugin the name of transformation plugin
  3189. * @param string $default_function the default transformation
  3190. * function
  3191. * @param array $transform_options the transformation parameters
  3192. *
  3193. * @return string the prepared cell, html content
  3194. *
  3195. * @access private
  3196. *
  3197. * @see _getTableBody()
  3198. */
  3199. private function _getDataCellForNumericColumns(
  3200. ?string $column,
  3201. $class,
  3202. $condition_field,
  3203. $meta,
  3204. array $map,
  3205. $is_field_truncated,
  3206. array $analyzed_sql_results,
  3207. $transformation_plugin,
  3208. $default_function,
  3209. array $transform_options
  3210. ) {
  3211. if (! isset($column) || $column === null) {
  3212. $cell = $this->_buildNullDisplay(
  3213. 'right ' . $class,
  3214. $condition_field,
  3215. $meta,
  3216. ''
  3217. );
  3218. } elseif ($column != '') {
  3219. $nowrap = ' nowrap';
  3220. $where_comparison = ' = ' . $column;
  3221. $cell = $this->_getRowData(
  3222. 'right ' . $class,
  3223. $condition_field,
  3224. $analyzed_sql_results,
  3225. $meta,
  3226. $map,
  3227. $column,
  3228. $column,
  3229. $transformation_plugin,
  3230. $default_function,
  3231. $nowrap,
  3232. $where_comparison,
  3233. $transform_options,
  3234. $is_field_truncated,
  3235. ''
  3236. );
  3237. } else {
  3238. $cell = $this->_buildEmptyDisplay(
  3239. 'right ' . $class,
  3240. $condition_field,
  3241. $meta,
  3242. ''
  3243. );
  3244. }
  3245. return $cell;
  3246. }
  3247. /**
  3248. * Get data cell for geometry type fields
  3249. *
  3250. * @param string|null $column the relevant column in data row
  3251. * @param string $class the html class for column
  3252. * @param stdClass $meta the meta-information about
  3253. * this field
  3254. * @param array $map the list of relations
  3255. * @param array $_url_params the parameters for generate url
  3256. * @param boolean $condition_field the column should highlighted
  3257. * or not
  3258. * @param TransformationsPlugin $transformation_plugin the name of transformation
  3259. * function
  3260. * @param string $default_function the default transformation
  3261. * function
  3262. * @param string $transform_options the transformation parameters
  3263. * @param array $analyzed_sql_results the analyzed query
  3264. *
  3265. * @return string the prepared data cell, html content
  3266. *
  3267. * @access private
  3268. *
  3269. * @see _getTableBody()
  3270. */
  3271. private function _getDataCellForGeometryColumns(
  3272. ?string $column,
  3273. $class,
  3274. $meta,
  3275. array $map,
  3276. array $_url_params,
  3277. $condition_field,
  3278. $transformation_plugin,
  3279. $default_function,
  3280. $transform_options,
  3281. array $analyzed_sql_results
  3282. ) {
  3283. if (! isset($column) || $column === null) {
  3284. $cell = $this->_buildNullDisplay($class, $condition_field, $meta);
  3285. return $cell;
  3286. }
  3287. if ($column == '') {
  3288. $cell = $this->_buildEmptyDisplay($class, $condition_field, $meta);
  3289. return $cell;
  3290. }
  3291. // Display as [GEOMETRY - (size)]
  3292. if ($_SESSION['tmpval']['geoOption'] == self::GEOMETRY_DISP_GEOM) {
  3293. $geometry_text = $this->_handleNonPrintableContents(
  3294. strtoupper(self::GEOMETRY_FIELD),
  3295. $column,
  3296. $transformation_plugin,
  3297. $transform_options,
  3298. $default_function,
  3299. $meta,
  3300. $_url_params
  3301. );
  3302. $cell = $this->_buildValueDisplay(
  3303. $class,
  3304. $condition_field,
  3305. $geometry_text
  3306. );
  3307. return $cell;
  3308. }
  3309. if ($_SESSION['tmpval']['geoOption'] == self::GEOMETRY_DISP_WKT) {
  3310. // Prepare in Well Known Text(WKT) format.
  3311. $where_comparison = ' = ' . $column;
  3312. // Convert to WKT format
  3313. $wktval = Util::asWKT($column);
  3314. list(
  3315. $is_field_truncated,
  3316. $displayedColumn,
  3317. // skip 3rd param
  3318. ) = $this->_getPartialText($wktval);
  3319. $cell = $this->_getRowData(
  3320. $class,
  3321. $condition_field,
  3322. $analyzed_sql_results,
  3323. $meta,
  3324. $map,
  3325. $wktval,
  3326. $displayedColumn,
  3327. $transformation_plugin,
  3328. $default_function,
  3329. '',
  3330. $where_comparison,
  3331. $transform_options,
  3332. $is_field_truncated,
  3333. ''
  3334. );
  3335. return $cell;
  3336. }
  3337. // Prepare in Well Known Binary (WKB) format.
  3338. if ($_SESSION['tmpval']['display_binary']) {
  3339. $where_comparison = ' = ' . $column;
  3340. $wkbval = substr(bin2hex($column), 8);
  3341. list(
  3342. $is_field_truncated,
  3343. $displayedColumn,
  3344. // skip 3rd param
  3345. ) = $this->_getPartialText($wkbval);
  3346. $cell = $this->_getRowData(
  3347. $class,
  3348. $condition_field,
  3349. $analyzed_sql_results,
  3350. $meta,
  3351. $map,
  3352. $wkbval,
  3353. $displayedColumn,
  3354. $transformation_plugin,
  3355. $default_function,
  3356. '',
  3357. $where_comparison,
  3358. $transform_options,
  3359. $is_field_truncated,
  3360. ''
  3361. );
  3362. return $cell;
  3363. }
  3364. $wkbval = $this->_handleNonPrintableContents(
  3365. self::BINARY_FIELD,
  3366. $column,
  3367. $transformation_plugin,
  3368. $transform_options,
  3369. $default_function,
  3370. $meta,
  3371. $_url_params
  3372. );
  3373. $cell = $this->_buildValueDisplay(
  3374. $class,
  3375. $condition_field,
  3376. $wkbval
  3377. );
  3378. return $cell;
  3379. }
  3380. /**
  3381. * Get data cell for non numeric type fields
  3382. *
  3383. * @param string|null $column the relevant column in data row
  3384. * @param string $class the html class for column
  3385. * @param stdClass $meta the meta-information about
  3386. * the field
  3387. * @param array $map the list of relations
  3388. * @param array $_url_params the parameters for generate
  3389. * url
  3390. * @param boolean $condition_field the column should highlighted
  3391. * or not
  3392. * @param TransformationsPlugin $transformation_plugin the name of transformation
  3393. * function
  3394. * @param string $default_function the default transformation
  3395. * function
  3396. * @param string $transform_options the transformation parameters
  3397. * @param boolean $is_field_truncated is data truncated due to
  3398. * LimitChars
  3399. * @param array $analyzed_sql_results the analyzed query
  3400. * @param integer $dt_result the link id associated to
  3401. * the query which results
  3402. * have to be displayed
  3403. * @param integer $col_index the column index
  3404. *
  3405. * @return string the prepared data cell, html content
  3406. *
  3407. * @access private
  3408. *
  3409. * @see _getTableBody()
  3410. */
  3411. private function _getDataCellForNonNumericColumns(
  3412. ?string $column,
  3413. $class,
  3414. $meta,
  3415. array $map,
  3416. array $_url_params,
  3417. $condition_field,
  3418. $transformation_plugin,
  3419. $default_function,
  3420. $transform_options,
  3421. $is_field_truncated,
  3422. array $analyzed_sql_results,
  3423. &$dt_result,
  3424. $col_index
  3425. ) {
  3426. $original_length = 0;
  3427. $is_analyse = $this->__get('is_analyse');
  3428. $field_flags = $GLOBALS['dbi']->fieldFlags($dt_result, $col_index);
  3429. $bIsText = gettype($transformation_plugin) === 'object'
  3430. && strpos($transformation_plugin->getMIMEType(), 'Text')
  3431. === false;
  3432. // disable inline grid editing
  3433. // if binary fields are protected
  3434. // or transformation plugin is of non text type
  3435. // such as image
  3436. if ((false !== stripos($field_flags, self::BINARY_FIELD)
  3437. && ($GLOBALS['cfg']['ProtectBinary'] === 'all'
  3438. || ($GLOBALS['cfg']['ProtectBinary'] === 'noblob'
  3439. && false === stripos($meta->type, self::BLOB_FIELD))
  3440. || ($GLOBALS['cfg']['ProtectBinary'] === 'blob'
  3441. && false !== stripos($meta->type, self::BLOB_FIELD))))
  3442. || $bIsText
  3443. ) {
  3444. $class = str_replace('grid_edit', '', $class);
  3445. }
  3446. if (! isset($column) || $column === null) {
  3447. $cell = $this->_buildNullDisplay($class, $condition_field, $meta);
  3448. return $cell;
  3449. }
  3450. if ($column == '') {
  3451. $cell = $this->_buildEmptyDisplay($class, $condition_field, $meta);
  3452. return $cell;
  3453. }
  3454. // Cut all fields to $GLOBALS['cfg']['LimitChars']
  3455. // (unless it's a link-type transformation or binary)
  3456. $displayedColumn = $column;
  3457. if (! (gettype($transformation_plugin) === "object"
  3458. && strpos($transformation_plugin->getName(), 'Link') !== false)
  3459. && false === stripos($field_flags, self::BINARY_FIELD)
  3460. ) {
  3461. list(
  3462. $is_field_truncated,
  3463. $column,
  3464. $original_length
  3465. ) = $this->_getPartialText($column);
  3466. }
  3467. $formatted = false;
  3468. if (isset($meta->_type) && $meta->_type === MYSQLI_TYPE_BIT) {
  3469. $displayedColumn = Util::printableBitValue(
  3470. (int) $displayedColumn,
  3471. (int) $meta->length
  3472. );
  3473. // some results of PROCEDURE ANALYSE() are reported as
  3474. // being BINARY but they are quite readable,
  3475. // so don't treat them as BINARY
  3476. } elseif (false !== stripos($field_flags, self::BINARY_FIELD)
  3477. && ! (isset($is_analyse) && $is_analyse)
  3478. ) {
  3479. // we show the BINARY or BLOB message and field's size
  3480. // (or maybe use a transformation)
  3481. $binary_or_blob = self::BLOB_FIELD;
  3482. if ($meta->type === self::STRING_FIELD) {
  3483. $binary_or_blob = self::BINARY_FIELD;
  3484. }
  3485. $displayedColumn = $this->_handleNonPrintableContents(
  3486. $binary_or_blob,
  3487. $displayedColumn,
  3488. $transformation_plugin,
  3489. $transform_options,
  3490. $default_function,
  3491. $meta,
  3492. $_url_params,
  3493. $is_field_truncated
  3494. );
  3495. $class = $this->_addClass(
  3496. $class,
  3497. $condition_field,
  3498. $meta,
  3499. '',
  3500. $is_field_truncated,
  3501. $transformation_plugin,
  3502. $default_function
  3503. );
  3504. $result = strip_tags($column);
  3505. // disable inline grid editing
  3506. // if binary or blob data is not shown
  3507. if (false !== stripos($result, $binary_or_blob)) {
  3508. $class = str_replace('grid_edit', '', $class);
  3509. }
  3510. $formatted = true;
  3511. }
  3512. if ($formatted) {
  3513. $cell = $this->_buildValueDisplay(
  3514. $class,
  3515. $condition_field,
  3516. $displayedColumn
  3517. );
  3518. return $cell;
  3519. }
  3520. // transform functions may enable no-wrapping:
  3521. $function_nowrap = 'applyTransformationNoWrap';
  3522. $bool_nowrap = ($default_function != $transformation_plugin)
  3523. && function_exists((string) $transformation_plugin->$function_nowrap())
  3524. ? $transformation_plugin->$function_nowrap($transform_options)
  3525. : false;
  3526. // do not wrap if date field type
  3527. $nowrap = preg_match('@DATE|TIME@i', $meta->type)
  3528. || $bool_nowrap ? ' nowrap' : '';
  3529. $where_comparison = ' = \''
  3530. . $GLOBALS['dbi']->escapeString($column)
  3531. . '\'';
  3532. $cell = $this->_getRowData(
  3533. $class,
  3534. $condition_field,
  3535. $analyzed_sql_results,
  3536. $meta,
  3537. $map,
  3538. $column,
  3539. $displayedColumn,
  3540. $transformation_plugin,
  3541. $default_function,
  3542. $nowrap,
  3543. $where_comparison,
  3544. $transform_options,
  3545. $is_field_truncated,
  3546. $original_length
  3547. );
  3548. return $cell;
  3549. }
  3550. /**
  3551. * Checks the posted options for viewing query results
  3552. * and sets appropriate values in the session.
  3553. *
  3554. * @todo make maximum remembered queries configurable
  3555. * @todo move/split into SQL class!?
  3556. * @todo currently this is called twice unnecessary
  3557. * @todo ignore LIMIT and ORDER in query!?
  3558. *
  3559. * @return void
  3560. *
  3561. * @access public
  3562. *
  3563. * @see sql.php file
  3564. */
  3565. public function setConfigParamsForDisplayTable()
  3566. {
  3567. $sql_md5 = md5($this->__get('sql_query'));
  3568. $query = [];
  3569. if (isset($_SESSION['tmpval']['query'][$sql_md5])) {
  3570. $query = $_SESSION['tmpval']['query'][$sql_md5];
  3571. }
  3572. $query['sql'] = $this->__get('sql_query');
  3573. if (empty($query['repeat_cells'])) {
  3574. $query['repeat_cells'] = $GLOBALS['cfg']['RepeatCells'];
  3575. }
  3576. // as this is a form value, the type is always string so we cannot
  3577. // use Core::isValid($_POST['session_max_rows'], 'integer')
  3578. if (Core::isValid($_POST['session_max_rows'], 'numeric')) {
  3579. $query['max_rows'] = (int) $_POST['session_max_rows'];
  3580. unset($_POST['session_max_rows']);
  3581. } elseif ($_POST['session_max_rows'] == self::ALL_ROWS) {
  3582. $query['max_rows'] = self::ALL_ROWS;
  3583. unset($_POST['session_max_rows']);
  3584. } elseif (empty($query['max_rows'])) {
  3585. $query['max_rows'] = intval($GLOBALS['cfg']['MaxRows']);
  3586. }
  3587. if (Core::isValid($_REQUEST['pos'], 'numeric')) {
  3588. $query['pos'] = $_REQUEST['pos'];
  3589. unset($_REQUEST['pos']);
  3590. } elseif (empty($query['pos'])) {
  3591. $query['pos'] = 0;
  3592. }
  3593. if (Core::isValid(
  3594. $_REQUEST['pftext'],
  3595. [
  3596. self::DISPLAY_PARTIAL_TEXT,
  3597. self::DISPLAY_FULL_TEXT,
  3598. ]
  3599. )
  3600. ) {
  3601. $query['pftext'] = $_REQUEST['pftext'];
  3602. unset($_REQUEST['pftext']);
  3603. } elseif (empty($query['pftext'])) {
  3604. $query['pftext'] = self::DISPLAY_PARTIAL_TEXT;
  3605. }
  3606. if (Core::isValid(
  3607. $_REQUEST['relational_display'],
  3608. [
  3609. self::RELATIONAL_KEY,
  3610. self::RELATIONAL_DISPLAY_COLUMN,
  3611. ]
  3612. )
  3613. ) {
  3614. $query['relational_display'] = $_REQUEST['relational_display'];
  3615. unset($_REQUEST['relational_display']);
  3616. } elseif (empty($query['relational_display'])) {
  3617. // The current session value has priority over a
  3618. // change via Settings; this change will be apparent
  3619. // starting from the next session
  3620. $query['relational_display'] = $GLOBALS['cfg']['RelationalDisplay'];
  3621. }
  3622. if (Core::isValid(
  3623. $_REQUEST['geoOption'],
  3624. [
  3625. self::GEOMETRY_DISP_WKT,
  3626. self::GEOMETRY_DISP_WKB,
  3627. self::GEOMETRY_DISP_GEOM,
  3628. ]
  3629. )
  3630. ) {
  3631. $query['geoOption'] = $_REQUEST['geoOption'];
  3632. unset($_REQUEST['geoOption']);
  3633. } elseif (empty($query['geoOption'])) {
  3634. $query['geoOption'] = self::GEOMETRY_DISP_GEOM;
  3635. }
  3636. if (isset($_REQUEST['display_binary'])) {
  3637. $query['display_binary'] = true;
  3638. unset($_REQUEST['display_binary']);
  3639. } elseif (isset($_REQUEST['display_options_form'])) {
  3640. // we know that the checkbox was unchecked
  3641. unset($query['display_binary']);
  3642. } elseif (! isset($_REQUEST['full_text_button'])) {
  3643. // selected by default because some operations like OPTIMIZE TABLE
  3644. // and all queries involving functions return "binary" contents,
  3645. // according to low-level field flags
  3646. $query['display_binary'] = true;
  3647. }
  3648. if (isset($_REQUEST['display_blob'])) {
  3649. $query['display_blob'] = true;
  3650. unset($_REQUEST['display_blob']);
  3651. } elseif (isset($_REQUEST['display_options_form'])) {
  3652. // we know that the checkbox was unchecked
  3653. unset($query['display_blob']);
  3654. }
  3655. if (isset($_REQUEST['hide_transformation'])) {
  3656. $query['hide_transformation'] = true;
  3657. unset($_REQUEST['hide_transformation']);
  3658. } elseif (isset($_REQUEST['display_options_form'])) {
  3659. // we know that the checkbox was unchecked
  3660. unset($query['hide_transformation']);
  3661. }
  3662. // move current query to the last position, to be removed last
  3663. // so only least executed query will be removed if maximum remembered
  3664. // queries limit is reached
  3665. unset($_SESSION['tmpval']['query'][$sql_md5]);
  3666. $_SESSION['tmpval']['query'][$sql_md5] = $query;
  3667. // do not exceed a maximum number of queries to remember
  3668. if (count($_SESSION['tmpval']['query']) > 10) {
  3669. array_shift($_SESSION['tmpval']['query']);
  3670. //echo 'deleting one element ...';
  3671. }
  3672. // populate query configuration
  3673. $_SESSION['tmpval']['pftext']
  3674. = $query['pftext'];
  3675. $_SESSION['tmpval']['relational_display']
  3676. = $query['relational_display'];
  3677. $_SESSION['tmpval']['geoOption']
  3678. = $query['geoOption'];
  3679. $_SESSION['tmpval']['display_binary'] = isset(
  3680. $query['display_binary']
  3681. );
  3682. $_SESSION['tmpval']['display_blob'] = isset(
  3683. $query['display_blob']
  3684. );
  3685. $_SESSION['tmpval']['hide_transformation'] = isset(
  3686. $query['hide_transformation']
  3687. );
  3688. $_SESSION['tmpval']['pos']
  3689. = $query['pos'];
  3690. $_SESSION['tmpval']['max_rows']
  3691. = $query['max_rows'];
  3692. $_SESSION['tmpval']['repeat_cells']
  3693. = $query['repeat_cells'];
  3694. }
  3695. /**
  3696. * Prepare a table of results returned by a SQL query.
  3697. *
  3698. * @param integer $dt_result the link id associated to the query
  3699. * which results have to be displayed
  3700. * @param array $displayParts the parts to display
  3701. * @param array $analyzed_sql_results analyzed sql results
  3702. * @param boolean $is_limited_display With limited operations or not
  3703. *
  3704. * @return string Generated HTML content for resulted table
  3705. *
  3706. * @access public
  3707. *
  3708. * @see sql.php file
  3709. */
  3710. public function getTable(
  3711. &$dt_result,
  3712. array &$displayParts,
  3713. array $analyzed_sql_results,
  3714. $is_limited_display = false
  3715. ) {
  3716. /**
  3717. * The statement this table is built for.
  3718. * @var SelectStatement
  3719. */
  3720. if (isset($analyzed_sql_results['statement'])) {
  3721. $statement = $analyzed_sql_results['statement'];
  3722. } else {
  3723. $statement = null;
  3724. }
  3725. // Following variable are needed for use in isset/empty or
  3726. // use with array indexes/safe use in foreach
  3727. $fields_meta = $this->__get('fields_meta');
  3728. $showtable = $this->__get('showtable');
  3729. $printview = $this->__get('printview');
  3730. /**
  3731. * @todo move this to a central place
  3732. * @todo for other future table types
  3733. */
  3734. $is_innodb = (isset($showtable['Type'])
  3735. && $showtable['Type'] == self::TABLE_TYPE_INNO_DB);
  3736. $sql = new Sql();
  3737. if ($is_innodb && $sql->isJustBrowsing($analyzed_sql_results, true)) {
  3738. $pre_count = '~';
  3739. $after_count = Util::showHint(
  3740. Sanitize::sanitizeMessage(
  3741. __('May be approximate. See [doc@faq3-11]FAQ 3.11[/doc].')
  3742. )
  3743. );
  3744. } else {
  3745. $pre_count = '';
  3746. $after_count = '';
  3747. }
  3748. // 1. ----- Prepares the work -----
  3749. // 1.1 Gets the information about which functionalities should be
  3750. // displayed
  3751. list(
  3752. $displayParts,
  3753. $total
  3754. ) = $this->_setDisplayPartsAndTotal($displayParts);
  3755. // 1.2 Defines offsets for the next and previous pages
  3756. if ($displayParts['nav_bar'] == '1') {
  3757. list($pos_next, $pos_prev) = $this->_getOffsets();
  3758. } // end if
  3759. // 1.3 Extract sorting expressions.
  3760. // we need $sort_expression and $sort_expression_nodirection
  3761. // even if there are many table references
  3762. $sort_expression = [];
  3763. $sort_expression_nodirection = [];
  3764. $sort_direction = [];
  3765. if ($statement !== null && ! empty($statement->order)) {
  3766. foreach ($statement->order as $o) {
  3767. $sort_expression[] = $o->expr->expr . ' ' . $o->type;
  3768. $sort_expression_nodirection[] = $o->expr->expr;
  3769. $sort_direction[] = $o->type;
  3770. }
  3771. } else {
  3772. $sort_expression[] = '';
  3773. $sort_expression_nodirection[] = '';
  3774. $sort_direction[] = '';
  3775. }
  3776. $number_of_columns = count($sort_expression_nodirection);
  3777. // 1.4 Prepares display of first and last value of the sorted column
  3778. $sorted_column_message = '';
  3779. for ($i = 0; $i < $number_of_columns; $i++) {
  3780. $sorted_column_message .= $this->_getSortedColumnMessage(
  3781. $dt_result,
  3782. $sort_expression_nodirection[$i]
  3783. );
  3784. }
  3785. // 2. ----- Prepare to display the top of the page -----
  3786. // 2.1 Prepares a messages with position information
  3787. $sqlQueryMessage = '';
  3788. if (($displayParts['nav_bar'] == '1') && isset($pos_next)) {
  3789. $message = $this->_setMessageInformation(
  3790. $sorted_column_message,
  3791. $analyzed_sql_results,
  3792. $total,
  3793. $pos_next,
  3794. $pre_count,
  3795. $after_count
  3796. );
  3797. $sqlQueryMessage = Util::getMessage(
  3798. $message,
  3799. $this->__get('sql_query'),
  3800. 'success'
  3801. );
  3802. } elseif ((! isset($printview) || ($printview != '1')) && ! $is_limited_display) {
  3803. $sqlQueryMessage = Util::getMessage(
  3804. __('Your SQL query has been executed successfully.'),
  3805. $this->__get('sql_query'),
  3806. 'success'
  3807. );
  3808. }
  3809. // 2.3 Prepare the navigation bars
  3810. if (strlen($this->__get('table')) === 0) {
  3811. if ($analyzed_sql_results['querytype'] == 'SELECT') {
  3812. // table does not always contain a real table name,
  3813. // for example in MySQL 5.0.x, the query SHOW STATUS
  3814. // returns STATUS as a table name
  3815. $this->__set('table', $fields_meta[0]->table);
  3816. } else {
  3817. $this->__set('table', '');
  3818. }
  3819. }
  3820. // can the result be sorted?
  3821. if ($displayParts['sort_lnk'] == '1' && $analyzed_sql_results['statement'] !== null) {
  3822. // At this point, $sort_expression is an array
  3823. list($unsorted_sql_query, $sort_by_key_html)
  3824. = $this->_getUnsortedSqlAndSortByKeyDropDown(
  3825. $analyzed_sql_results,
  3826. $sort_expression
  3827. );
  3828. } else {
  3829. $sort_by_key_html = $unsorted_sql_query = '';
  3830. }
  3831. $navigation = '';
  3832. if ($displayParts['nav_bar'] == '1' && $statement !== null && empty($statement->limit)) {
  3833. $navigation = $this->_getTableNavigation(
  3834. $pos_next,
  3835. $pos_prev,
  3836. $is_innodb,
  3837. $sort_by_key_html
  3838. );
  3839. }
  3840. // 2b ----- Get field references from Database -----
  3841. // (see the 'relation' configuration variable)
  3842. // initialize map
  3843. $map = [];
  3844. if (strlen($this->__get('table')) > 0) {
  3845. // This method set the values for $map array
  3846. $this->_setParamForLinkForeignKeyRelatedTables($map);
  3847. // Coming from 'Distinct values' action of structure page
  3848. // We manipulate relations mechanism to show a link to related rows.
  3849. if ($this->__get('is_browse_distinct')) {
  3850. $map[$fields_meta[1]->name] = [
  3851. $this->__get('table'),
  3852. $fields_meta[1]->name,
  3853. '',
  3854. $this->__get('db'),
  3855. ];
  3856. }
  3857. } // end if
  3858. // end 2b
  3859. // 3. ----- Prepare the results table -----
  3860. $headers = $this->_getTableHeaders(
  3861. $displayParts,
  3862. $analyzed_sql_results,
  3863. $unsorted_sql_query,
  3864. $sort_expression,
  3865. $sort_expression_nodirection,
  3866. $sort_direction,
  3867. $is_limited_display
  3868. );
  3869. $body = $this->_getTableBody(
  3870. $dt_result,
  3871. $displayParts,
  3872. $map,
  3873. $analyzed_sql_results,
  3874. $is_limited_display
  3875. );
  3876. $this->__set('display_params', null);
  3877. // 4. ----- Prepares the link for multi-fields edit and delete
  3878. $multiRowOperationLinks = '';
  3879. if ($displayParts['del_lnk'] == self::DELETE_ROW
  3880. && $displayParts['del_lnk'] != self::KILL_PROCESS
  3881. ) {
  3882. $multiRowOperationLinks = $this->_getMultiRowOperationLinks(
  3883. $dt_result,
  3884. $analyzed_sql_results,
  3885. $displayParts['del_lnk']
  3886. );
  3887. }
  3888. // 5. ----- Prepare "Query results operations"
  3889. $operations = '';
  3890. if ((! isset($printview) || ($printview != '1')) && ! $is_limited_display) {
  3891. $operations = $this->_getResultsOperations(
  3892. $displayParts,
  3893. $analyzed_sql_results
  3894. );
  3895. }
  3896. return $this->template->render('display/results/table', [
  3897. 'sql_query_message' => $sqlQueryMessage,
  3898. 'navigation' => $navigation,
  3899. 'headers' => $headers,
  3900. 'body' => $body,
  3901. 'multi_row_operation_links' => $multiRowOperationLinks,
  3902. 'operations' => $operations,
  3903. ]);
  3904. }
  3905. /**
  3906. * Get offsets for next page and previous page
  3907. *
  3908. * @return array array with two elements - $pos_next, $pos_prev
  3909. *
  3910. * @access private
  3911. *
  3912. * @see getTable()
  3913. */
  3914. private function _getOffsets()
  3915. {
  3916. if ($_SESSION['tmpval']['max_rows'] == self::ALL_ROWS) {
  3917. $pos_next = 0;
  3918. $pos_prev = 0;
  3919. } else {
  3920. $pos_next = $_SESSION['tmpval']['pos']
  3921. + $_SESSION['tmpval']['max_rows'];
  3922. $pos_prev = $_SESSION['tmpval']['pos']
  3923. - $_SESSION['tmpval']['max_rows'];
  3924. if ($pos_prev < 0) {
  3925. $pos_prev = 0;
  3926. }
  3927. }
  3928. return [
  3929. $pos_next,
  3930. $pos_prev,
  3931. ];
  3932. }
  3933. /**
  3934. * Prepare sorted column message
  3935. *
  3936. * @param integer $dt_result the link id associated to the
  3937. * query which results have to
  3938. * be displayed
  3939. * @param string $sort_expression_nodirection sort expression without direction
  3940. *
  3941. * @return string|null html content, null if not found sorted column
  3942. *
  3943. * @access private
  3944. *
  3945. * @see getTable()
  3946. */
  3947. private function _getSortedColumnMessage(
  3948. &$dt_result,
  3949. $sort_expression_nodirection
  3950. ) {
  3951. $fields_meta = $this->__get('fields_meta'); // To use array indexes
  3952. if (empty($sort_expression_nodirection)) {
  3953. return null;
  3954. }
  3955. if (mb_strpos($sort_expression_nodirection, '.') === false) {
  3956. $sort_table = $this->__get('table');
  3957. $sort_column = $sort_expression_nodirection;
  3958. } else {
  3959. list($sort_table, $sort_column)
  3960. = explode('.', $sort_expression_nodirection);
  3961. }
  3962. $sort_table = Util::unQuote($sort_table);
  3963. $sort_column = Util::unQuote($sort_column);
  3964. // find the sorted column index in row result
  3965. // (this might be a multi-table query)
  3966. $sorted_column_index = false;
  3967. foreach ($fields_meta as $key => $meta) {
  3968. if (($meta->table == $sort_table) && ($meta->name == $sort_column)) {
  3969. $sorted_column_index = $key;
  3970. break;
  3971. }
  3972. }
  3973. if ($sorted_column_index === false) {
  3974. return null;
  3975. }
  3976. // fetch first row of the result set
  3977. $row = $GLOBALS['dbi']->fetchRow($dt_result);
  3978. // initializing default arguments
  3979. $default_function = [
  3980. Core::class,
  3981. 'mimeDefaultFunction',
  3982. ];
  3983. $transformation_plugin = $default_function;
  3984. $transform_options = [];
  3985. // check for non printable sorted row data
  3986. $meta = $fields_meta[$sorted_column_index];
  3987. if (false !== stripos($meta->type, self::BLOB_FIELD)
  3988. || ($meta->type == self::GEOMETRY_FIELD)
  3989. ) {
  3990. $column_for_first_row = $this->_handleNonPrintableContents(
  3991. $meta->type,
  3992. $row[$sorted_column_index],
  3993. $transformation_plugin,
  3994. $transform_options,
  3995. $default_function,
  3996. $meta
  3997. );
  3998. } else {
  3999. $column_for_first_row = ($row !== null) ? $row[$sorted_column_index] : '';
  4000. }
  4001. $column_for_first_row = mb_strtoupper(
  4002. mb_substr(
  4003. (string) $column_for_first_row,
  4004. 0,
  4005. (int) $GLOBALS['cfg']['LimitChars']
  4006. ) . '...'
  4007. );
  4008. // fetch last row of the result set
  4009. $GLOBALS['dbi']->dataSeek($dt_result, $this->__get('num_rows') - 1);
  4010. $row = $GLOBALS['dbi']->fetchRow($dt_result);
  4011. // check for non printable sorted row data
  4012. $meta = $fields_meta[$sorted_column_index];
  4013. if (false !== stripos($meta->type, self::BLOB_FIELD)
  4014. || ($meta->type == self::GEOMETRY_FIELD)
  4015. ) {
  4016. $column_for_last_row = $this->_handleNonPrintableContents(
  4017. $meta->type,
  4018. $row[$sorted_column_index],
  4019. $transformation_plugin,
  4020. $transform_options,
  4021. $default_function,
  4022. $meta
  4023. );
  4024. } else {
  4025. $column_for_last_row = ($row !== null) ? $row[$sorted_column_index] : '';
  4026. }
  4027. $column_for_last_row = mb_strtoupper(
  4028. mb_substr(
  4029. (string) $column_for_last_row,
  4030. 0,
  4031. (int) $GLOBALS['cfg']['LimitChars']
  4032. ) . '...'
  4033. );
  4034. // reset to first row for the loop in _getTableBody()
  4035. $GLOBALS['dbi']->dataSeek($dt_result, 0);
  4036. // we could also use here $sort_expression_nodirection
  4037. return ' [' . htmlspecialchars($sort_column)
  4038. . ': <strong>' . htmlspecialchars($column_for_first_row) . ' - '
  4039. . htmlspecialchars($column_for_last_row) . '</strong>]';
  4040. }
  4041. /**
  4042. * Set the content that needs to be shown in message
  4043. *
  4044. * @param string $sorted_column_message the message for sorted column
  4045. * @param array $analyzed_sql_results the analyzed query
  4046. * @param integer $total the total number of rows returned by
  4047. * the SQL query without any
  4048. * programmatically appended LIMIT clause
  4049. * @param integer $pos_next the offset for next page
  4050. * @param string $pre_count the string renders before row count
  4051. * @param string $after_count the string renders after row count
  4052. *
  4053. * @return Message an object of Message
  4054. *
  4055. * @access private
  4056. *
  4057. * @see getTable()
  4058. */
  4059. private function _setMessageInformation(
  4060. $sorted_column_message,
  4061. array $analyzed_sql_results,
  4062. $total,
  4063. $pos_next,
  4064. $pre_count,
  4065. $after_count
  4066. ) {
  4067. $unlim_num_rows = $this->__get('unlim_num_rows'); // To use in isset()
  4068. if (! empty($analyzed_sql_results['statement']->limit)) {
  4069. $first_shown_rec = $analyzed_sql_results['statement']->limit->offset;
  4070. $row_count = $analyzed_sql_results['statement']->limit->rowCount;
  4071. if ($row_count < $total) {
  4072. $last_shown_rec = $first_shown_rec + $row_count - 1;
  4073. } else {
  4074. $last_shown_rec = $first_shown_rec + $total - 1;
  4075. }
  4076. } elseif (($_SESSION['tmpval']['max_rows'] == self::ALL_ROWS)
  4077. || ($pos_next > $total)
  4078. ) {
  4079. $first_shown_rec = $_SESSION['tmpval']['pos'];
  4080. $last_shown_rec = $total - 1;
  4081. } else {
  4082. $first_shown_rec = $_SESSION['tmpval']['pos'];
  4083. $last_shown_rec = $pos_next - 1;
  4084. }
  4085. $table = new Table($this->__get('table'), $this->__get('db'));
  4086. if ($table->isView()
  4087. && ($total == $GLOBALS['cfg']['MaxExactCountViews'])
  4088. ) {
  4089. $message = Message::notice(
  4090. __(
  4091. 'This view has at least this number of rows. '
  4092. . 'Please refer to %sdocumentation%s.'
  4093. )
  4094. );
  4095. $message->addParam('[doc@cfg_MaxExactCount]');
  4096. $message->addParam('[/doc]');
  4097. $message_view_warning = Util::showHint($message);
  4098. } else {
  4099. $message_view_warning = false;
  4100. }
  4101. $message = Message::success(__('Showing rows %1s - %2s'));
  4102. $message->addParam($first_shown_rec);
  4103. if ($message_view_warning !== false) {
  4104. $message->addParamHtml('... ' . $message_view_warning);
  4105. } else {
  4106. $message->addParam($last_shown_rec);
  4107. }
  4108. $message->addText('(');
  4109. if ($message_view_warning === false) {
  4110. if (isset($unlim_num_rows) && ($unlim_num_rows != $total)) {
  4111. $message_total = Message::notice(
  4112. $pre_count . __('%1$d total, %2$d in query')
  4113. );
  4114. $message_total->addParam($total);
  4115. $message_total->addParam($unlim_num_rows);
  4116. } else {
  4117. $message_total = Message::notice($pre_count . __('%d total'));
  4118. $message_total->addParam($total);
  4119. }
  4120. if (! empty($after_count)) {
  4121. $message_total->addHtml($after_count);
  4122. }
  4123. $message->addMessage($message_total, '');
  4124. $message->addText(', ', '');
  4125. }
  4126. $message_qt = Message::notice(__('Query took %01.4f seconds.') . ')');
  4127. $message_qt->addParam($this->__get('querytime'));
  4128. $message->addMessage($message_qt, '');
  4129. if ($sorted_column_message !== null) {
  4130. $message->addHtml($sorted_column_message, '');
  4131. }
  4132. return $message;
  4133. }
  4134. /**
  4135. * Set the value of $map array for linking foreign key related tables
  4136. *
  4137. * @param array $map the list of relations
  4138. *
  4139. * @return void
  4140. *
  4141. * @access private
  4142. *
  4143. * @see getTable()
  4144. */
  4145. private function _setParamForLinkForeignKeyRelatedTables(array &$map)
  4146. {
  4147. // To be able to later display a link to the related table,
  4148. // we verify both types of relations: either those that are
  4149. // native foreign keys or those defined in the phpMyAdmin
  4150. // configuration storage. If no PMA storage, we won't be able
  4151. // to use the "column to display" notion (for example show
  4152. // the name related to a numeric id).
  4153. $exist_rel = $this->relation->getForeigners(
  4154. $this->__get('db'),
  4155. $this->__get('table'),
  4156. '',
  4157. self::POSITION_BOTH
  4158. );
  4159. if (! empty($exist_rel)) {
  4160. foreach ($exist_rel as $master_field => $rel) {
  4161. if ($master_field != 'foreign_keys_data') {
  4162. $display_field = $this->relation->getDisplayField(
  4163. $rel['foreign_db'],
  4164. $rel['foreign_table']
  4165. );
  4166. $map[$master_field] = [
  4167. $rel['foreign_table'],
  4168. $rel['foreign_field'],
  4169. $display_field,
  4170. $rel['foreign_db'],
  4171. ];
  4172. } else {
  4173. foreach ($rel as $key => $one_key) {
  4174. foreach ($one_key['index_list'] as $index => $one_field) {
  4175. $display_field = $this->relation->getDisplayField(
  4176. isset($one_key['ref_db_name'])
  4177. ? $one_key['ref_db_name']
  4178. : $GLOBALS['db'],
  4179. $one_key['ref_table_name']
  4180. );
  4181. $map[$one_field] = [
  4182. $one_key['ref_table_name'],
  4183. $one_key['ref_index_list'][$index],
  4184. $display_field,
  4185. isset($one_key['ref_db_name'])
  4186. ? $one_key['ref_db_name']
  4187. : $GLOBALS['db'],
  4188. ];
  4189. }
  4190. }
  4191. }
  4192. }
  4193. }
  4194. }
  4195. /**
  4196. * Prepare multi field edit/delete links
  4197. *
  4198. * @param integer $dt_result the link id associated to the query which
  4199. * results have to be displayed
  4200. * @param array $analyzed_sql_results analyzed sql results
  4201. * @param string $del_link the display element - 'del_link'
  4202. *
  4203. * @return string html content
  4204. *
  4205. * @access private
  4206. *
  4207. * @see getTable()
  4208. */
  4209. private function _getMultiRowOperationLinks(
  4210. &$dt_result,
  4211. array $analyzed_sql_results,
  4212. $del_link
  4213. ) {
  4214. $links_html = '<div class="print_ignore" >';
  4215. $url_query = $this->__get('url_query');
  4216. $delete_text = $del_link == self::DELETE_ROW ? __('Delete') : __('Kill');
  4217. $links_html .= $this->template->render('select_all', [
  4218. 'pma_theme_image' => $this->__get('pma_theme_image'),
  4219. 'text_dir' => $this->__get('text_dir'),
  4220. 'form_name' => 'resultsForm_' . $this->__get('unique_id'),
  4221. ]);
  4222. $links_html .= Util::getButtonOrImage(
  4223. 'submit_mult',
  4224. 'mult_submit',
  4225. __('Edit'),
  4226. 'b_edit',
  4227. 'edit'
  4228. );
  4229. $links_html .= Util::getButtonOrImage(
  4230. 'submit_mult',
  4231. 'mult_submit',
  4232. __('Copy'),
  4233. 'b_insrow',
  4234. 'copy'
  4235. );
  4236. $links_html .= Util::getButtonOrImage(
  4237. 'submit_mult',
  4238. 'mult_submit',
  4239. $delete_text,
  4240. 'b_drop',
  4241. 'delete'
  4242. );
  4243. if ($analyzed_sql_results['querytype'] == 'SELECT') {
  4244. $links_html .= Util::getButtonOrImage(
  4245. 'submit_mult',
  4246. 'mult_submit',
  4247. __('Export'),
  4248. 'b_tblexport',
  4249. 'export'
  4250. );
  4251. }
  4252. $links_html .= "</div>\n";
  4253. $links_html .= '<input type="hidden" name="sql_query"'
  4254. . ' value="' . htmlspecialchars($this->__get('sql_query')) . '">'
  4255. . "\n";
  4256. if (! empty($url_query)) {
  4257. $links_html .= '<input type="hidden" name="url_query"'
  4258. . ' value="' . $url_query . '">' . "\n";
  4259. }
  4260. // fetch last row of the result set
  4261. $GLOBALS['dbi']->dataSeek($dt_result, $this->__get('num_rows') - 1);
  4262. $row = $GLOBALS['dbi']->fetchRow($dt_result);
  4263. // @see DbiMysqi::fetchRow & DatabaseInterface::fetchRow
  4264. if (! is_array($row)) {
  4265. $row = [];
  4266. }
  4267. // $clause_is_unique is needed by getTable() to generate the proper param
  4268. // in the multi-edit and multi-delete form
  4269. list($where_clause, $clause_is_unique, $condition_array)
  4270. = Util::getUniqueCondition(
  4271. $dt_result, // handle
  4272. $this->__get('fields_cnt'), // fields_cnt
  4273. $this->__get('fields_meta'), // fields_meta
  4274. $row, // row
  4275. false, // force_unique
  4276. false, // restrict_to_table
  4277. $analyzed_sql_results // analyzed_sql_results
  4278. );
  4279. unset($where_clause, $condition_array);
  4280. // reset to first row for the loop in _getTableBody()
  4281. $GLOBALS['dbi']->dataSeek($dt_result, 0);
  4282. $links_html .= '<input type="hidden" name="clause_is_unique"'
  4283. . ' value="' . $clause_is_unique . '">' . "\n";
  4284. $links_html .= '</form>' . "\n";
  4285. return $links_html;
  4286. }
  4287. /**
  4288. * Generates HTML to display the Create view in span tag
  4289. *
  4290. * @param array $analyzed_sql_results analyzed sql results
  4291. * @param string $url_query String with URL Parameters
  4292. *
  4293. * @return string
  4294. *
  4295. * @access private
  4296. *
  4297. * @see _getResultsOperations()
  4298. */
  4299. private function _getLinkForCreateView(array $analyzed_sql_results, $url_query)
  4300. {
  4301. $results_operations_html = '';
  4302. if (empty($analyzed_sql_results['procedure'])) {
  4303. $results_operations_html .= '<span>'
  4304. . Util::linkOrButton(
  4305. 'view_create.php' . $url_query,
  4306. Util::getIcon(
  4307. 'b_view_add',
  4308. __('Create view'),
  4309. true
  4310. ),
  4311. ['class' => 'create_view ajax btn']
  4312. )
  4313. . '</span>' . "\n";
  4314. }
  4315. return $results_operations_html;
  4316. }
  4317. /**
  4318. * Calls the _getResultsOperations with $only_view as true
  4319. *
  4320. * @param array $analyzed_sql_results analyzed sql results
  4321. *
  4322. * @return string
  4323. *
  4324. * @access public
  4325. *
  4326. */
  4327. public function getCreateViewQueryResultOp(array $analyzed_sql_results)
  4328. {
  4329. $results_operations_html = '';
  4330. //calling to _getResultOperations with a fake $displayParts
  4331. //and setting only_view parameter to be true to generate just view
  4332. $results_operations_html .= $this->_getResultsOperations(
  4333. [],
  4334. $analyzed_sql_results,
  4335. true
  4336. );
  4337. return $results_operations_html;
  4338. }
  4339. /**
  4340. * Get copy to clipboard links for results operations
  4341. *
  4342. * @return string
  4343. *
  4344. * @access private
  4345. */
  4346. private function _getCopytoclipboardLinks()
  4347. {
  4348. return Util::linkOrButton(
  4349. '#',
  4350. Util::getIcon(
  4351. 'b_insrow',
  4352. __('Copy to clipboard'),
  4353. true
  4354. ),
  4355. [
  4356. 'id' => 'copyToClipBoard' ,
  4357. 'class' => 'btn',
  4358. ]
  4359. );
  4360. }
  4361. /**
  4362. * Get printview links for results operations
  4363. *
  4364. * @return string
  4365. *
  4366. * @access private
  4367. */
  4368. private function _getPrintviewLinks()
  4369. {
  4370. return Util::linkOrButton(
  4371. '#',
  4372. Util::getIcon(
  4373. 'b_print',
  4374. __('Print'),
  4375. true
  4376. ),
  4377. [
  4378. 'id' => 'printView' ,
  4379. 'class' => 'btn',
  4380. ],
  4381. 'print_view'
  4382. );
  4383. }
  4384. /**
  4385. * Get operations that are available on results.
  4386. *
  4387. * @param array $displayParts the parts to display
  4388. * @param array $analyzed_sql_results analyzed sql results
  4389. * @param boolean $only_view Whether to show only view
  4390. *
  4391. * @return string html content
  4392. *
  4393. * @access private
  4394. *
  4395. * @see getTable()
  4396. */
  4397. private function _getResultsOperations(
  4398. array $displayParts,
  4399. array $analyzed_sql_results,
  4400. $only_view = false
  4401. ) {
  4402. global $printview;
  4403. $results_operations_html = '';
  4404. $fields_meta = $this->__get('fields_meta'); // To safe use in foreach
  4405. $header_shown = false;
  4406. $header = '<fieldset class="print_ignore" ><legend>'
  4407. . __('Query results operations') . '</legend>';
  4408. $_url_params = [
  4409. 'db' => $this->__get('db'),
  4410. 'table' => $this->__get('table'),
  4411. 'printview' => '1',
  4412. 'sql_query' => $this->__get('sql_query'),
  4413. ];
  4414. $url_query = Url::getCommon($_url_params);
  4415. if (! $header_shown) {
  4416. $results_operations_html .= $header;
  4417. $header_shown = true;
  4418. }
  4419. // if empty result set was produced we need to
  4420. // show only view and not other options
  4421. if ($only_view) {
  4422. $results_operations_html .= $this->_getLinkForCreateView(
  4423. $analyzed_sql_results,
  4424. $url_query
  4425. );
  4426. if ($header_shown) {
  4427. $results_operations_html .= '</fieldset><br>';
  4428. }
  4429. return $results_operations_html;
  4430. }
  4431. // Displays "printable view" link if required
  4432. if ($displayParts['pview_lnk'] == '1') {
  4433. $results_operations_html .= $this->_getPrintviewLinks();
  4434. $results_operations_html .= $this->_getCopytoclipboardLinks();
  4435. } // end displays "printable view"
  4436. // Export link
  4437. // (the url_query has extra parameters that won't be used to export)
  4438. // (the single_table parameter is used in \PhpMyAdmin\Export->getDisplay()
  4439. // to hide the SQL and the structure export dialogs)
  4440. // If the parser found a PROCEDURE clause
  4441. // (most probably PROCEDURE ANALYSE()) it makes no sense to
  4442. // display the Export link).
  4443. if (($analyzed_sql_results['querytype'] == self::QUERY_TYPE_SELECT)
  4444. && ! isset($printview)
  4445. && empty($analyzed_sql_results['procedure'])
  4446. ) {
  4447. if (count($analyzed_sql_results['select_tables']) === 1) {
  4448. $_url_params['single_table'] = 'true';
  4449. }
  4450. if (! $header_shown) {
  4451. $results_operations_html .= $header;
  4452. $header_shown = true;
  4453. }
  4454. $_url_params['unlim_num_rows'] = $this->__get('unlim_num_rows');
  4455. /**
  4456. * At this point we don't know the table name; this can happen
  4457. * for example with a query like
  4458. * SELECT bike_code FROM (SELECT bike_code FROM bikes) tmp
  4459. * As a workaround we set in the table parameter the name of the
  4460. * first table of this database, so that tbl_export.php and
  4461. * the script it calls do not fail
  4462. */
  4463. if (empty($_url_params['table']) && ! empty($_url_params['db'])) {
  4464. $_url_params['table'] = $GLOBALS['dbi']->fetchValue("SHOW TABLES");
  4465. /* No result (probably no database selected) */
  4466. if ($_url_params['table'] === false) {
  4467. unset($_url_params['table']);
  4468. }
  4469. }
  4470. $results_operations_html .= Util::linkOrButton(
  4471. 'tbl_export.php' . Url::getCommon($_url_params),
  4472. Util::getIcon(
  4473. 'b_tblexport',
  4474. __('Export'),
  4475. true
  4476. ),
  4477. ['class' => 'btn']
  4478. );
  4479. // prepare chart
  4480. $results_operations_html .= Util::linkOrButton(
  4481. 'tbl_chart.php' . Url::getCommon($_url_params),
  4482. Util::getIcon(
  4483. 'b_chart',
  4484. __('Display chart'),
  4485. true
  4486. ),
  4487. ['class' => 'btn']
  4488. );
  4489. // prepare GIS chart
  4490. $geometry_found = false;
  4491. // If at least one geometry field is found
  4492. foreach ($fields_meta as $meta) {
  4493. if ($meta->type == self::GEOMETRY_FIELD) {
  4494. $geometry_found = true;
  4495. break;
  4496. }
  4497. }
  4498. if ($geometry_found) {
  4499. $results_operations_html
  4500. .= Util::linkOrButton(
  4501. 'tbl_gis_visualization.php'
  4502. . Url::getCommon($_url_params),
  4503. Util::getIcon(
  4504. 'b_globe',
  4505. __('Visualize GIS data'),
  4506. true
  4507. ),
  4508. ['class' => 'btn']
  4509. );
  4510. }
  4511. }
  4512. // CREATE VIEW
  4513. /**
  4514. *
  4515. * @todo detect privileges to create a view
  4516. * (but see 2006-01-19 note in PhpMyAdmin\Display\CreateTable,
  4517. * I think we cannot detect db-specific privileges reliably)
  4518. * Note: we don't display a Create view link if we found a PROCEDURE clause
  4519. */
  4520. if (! $header_shown) {
  4521. $results_operations_html .= $header;
  4522. $header_shown = true;
  4523. }
  4524. $results_operations_html .= $this->_getLinkForCreateView(
  4525. $analyzed_sql_results,
  4526. $url_query
  4527. );
  4528. if ($header_shown) {
  4529. $results_operations_html .= '</fieldset><br>';
  4530. }
  4531. return $results_operations_html;
  4532. }
  4533. /**
  4534. * Verifies what to do with non-printable contents (binary or BLOB)
  4535. * in Browse mode.
  4536. *
  4537. * @param string $category BLOB|BINARY|GEOMETRY
  4538. * @param string|null $content the binary content
  4539. * @param mixed $transformation_plugin transformation plugin.
  4540. * Can also be the
  4541. * default function:
  4542. * Core::mimeDefaultFunction
  4543. * @param string $transform_options transformation parameters
  4544. * @param string $default_function default transformation function
  4545. * @param stdClass $meta the meta-information about the field
  4546. * @param array $url_params parameters that should go to the
  4547. * download link
  4548. * @param boolean $is_truncated the result is truncated or not
  4549. *
  4550. * @return mixed string or float
  4551. *
  4552. * @access private
  4553. *
  4554. * @see _getDataCellForGeometryColumns(),
  4555. * _getDataCellForNonNumericColumns(),
  4556. * _getSortedColumnMessage()
  4557. */
  4558. private function _handleNonPrintableContents(
  4559. $category,
  4560. ?string $content,
  4561. $transformation_plugin,
  4562. $transform_options,
  4563. $default_function,
  4564. $meta,
  4565. array $url_params = [],
  4566. &$is_truncated = null
  4567. ) {
  4568. $is_truncated = false;
  4569. $result = '[' . $category;
  4570. if ($content !== null) {
  4571. $size = strlen($content);
  4572. $display_size = Util::formatByteDown($size, 3, 1);
  4573. $result .= ' - ' . $display_size[0] . ' ' . $display_size[1];
  4574. } else {
  4575. $result .= ' - NULL';
  4576. $size = 0;
  4577. $content = '';
  4578. }
  4579. $result .= ']';
  4580. // if we want to use a text transformation on a BLOB column
  4581. if (gettype($transformation_plugin) === "object") {
  4582. $posMimeOctetstream = strpos(
  4583. $transformation_plugin->getMIMESubtype(),
  4584. 'Octetstream'
  4585. );
  4586. $posMimeText = strpos($transformation_plugin->getMIMEtype(), 'Text');
  4587. if ($posMimeOctetstream
  4588. || $posMimeText !== false
  4589. ) {
  4590. // Applying Transformations on hex string of binary data
  4591. // seems more appropriate
  4592. $result = pack("H*", bin2hex($content));
  4593. }
  4594. }
  4595. if ($size <= 0) {
  4596. return $result;
  4597. }
  4598. if ($default_function != $transformation_plugin) {
  4599. $result = $transformation_plugin->applyTransformation(
  4600. $result,
  4601. $transform_options,
  4602. $meta
  4603. );
  4604. return $result;
  4605. }
  4606. $result = $default_function($result, [], $meta);
  4607. if (($_SESSION['tmpval']['display_binary']
  4608. && $meta->type === self::STRING_FIELD)
  4609. || ($_SESSION['tmpval']['display_blob']
  4610. && false !== stripos($meta->type, self::BLOB_FIELD))
  4611. ) {
  4612. // in this case, restart from the original $content
  4613. if (mb_check_encoding($content, 'utf-8')
  4614. && ! preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\x9F]/u', $content)
  4615. ) {
  4616. // show as text if it's valid utf-8
  4617. $result = htmlspecialchars($content);
  4618. } else {
  4619. $result = '0x' . bin2hex($content);
  4620. }
  4621. list(
  4622. $is_truncated,
  4623. $result,
  4624. // skip 3rd param
  4625. ) = $this->_getPartialText($result);
  4626. }
  4627. /* Create link to download */
  4628. // in PHP < 5.5, empty() only checks variables
  4629. $tmpdb = $this->__get('db');
  4630. if (count($url_params) > 0
  4631. && (! empty($tmpdb) && ! empty($meta->orgtable))
  4632. ) {
  4633. $url_params['where_clause_sign'] = Core::signSqlQuery($url_params['where_clause']);
  4634. $result = '<a href="tbl_get_field.php'
  4635. . Url::getCommon($url_params)
  4636. . '" class="disableAjax">'
  4637. . $result . '</a>';
  4638. }
  4639. return $result;
  4640. }
  4641. /**
  4642. * Retrieves the associated foreign key info for a data cell
  4643. *
  4644. * @param array $map the list of relations
  4645. * @param stdClass $meta the meta-information about the field
  4646. * @param string $where_comparison data for the where clause
  4647. *
  4648. * @return string|null formatted data
  4649. *
  4650. * @access private
  4651. *
  4652. */
  4653. private function _getFromForeign(array $map, $meta, $where_comparison)
  4654. {
  4655. $dispsql = 'SELECT '
  4656. . Util::backquote($map[$meta->name][2])
  4657. . ' FROM '
  4658. . Util::backquote($map[$meta->name][3])
  4659. . '.'
  4660. . Util::backquote($map[$meta->name][0])
  4661. . ' WHERE '
  4662. . Util::backquote($map[$meta->name][1])
  4663. . $where_comparison;
  4664. $dispresult = $GLOBALS['dbi']->tryQuery(
  4665. $dispsql,
  4666. DatabaseInterface::CONNECT_USER,
  4667. DatabaseInterface::QUERY_STORE
  4668. );
  4669. if ($dispresult && $GLOBALS['dbi']->numRows($dispresult) > 0) {
  4670. list($dispval) = $GLOBALS['dbi']->fetchRow($dispresult, 0);
  4671. } else {
  4672. $dispval = __('Link not found!');
  4673. }
  4674. $GLOBALS['dbi']->freeResult($dispresult);
  4675. return $dispval;
  4676. }
  4677. /**
  4678. * Prepares the displayable content of a data cell in Browse mode,
  4679. * taking into account foreign key description field and transformations
  4680. *
  4681. * @param string $class css classes for the td element
  4682. * @param bool $condition_field whether the column is a part of
  4683. * the where clause
  4684. * @param array $analyzed_sql_results the analyzed query
  4685. * @param stdClass $meta the meta-information about the
  4686. * field
  4687. * @param array $map the list of relations
  4688. * @param string $data data
  4689. * @param string $displayedData data that will be displayed (maybe be chunked)
  4690. * @param TransformationsPlugin $transformation_plugin transformation plugin.
  4691. * Can also be the default function:
  4692. * Core::mimeDefaultFunction
  4693. * @param string $default_function default function
  4694. * @param string $nowrap 'nowrap' if the content should
  4695. * not be wrapped
  4696. * @param string $where_comparison data for the where clause
  4697. * @param array $transform_options options for transformation
  4698. * @param bool $is_field_truncated whether the field is truncated
  4699. * @param string $original_length of a truncated column, or ''
  4700. *
  4701. * @return string formatted data
  4702. *
  4703. * @access private
  4704. *
  4705. * @see _getDataCellForNumericColumns(), _getDataCellForGeometryColumns(),
  4706. * _getDataCellForNonNumericColumns(),
  4707. *
  4708. */
  4709. private function _getRowData(
  4710. $class,
  4711. $condition_field,
  4712. array $analyzed_sql_results,
  4713. $meta,
  4714. array $map,
  4715. $data,
  4716. $displayedData,
  4717. $transformation_plugin,
  4718. $default_function,
  4719. $nowrap,
  4720. $where_comparison,
  4721. array $transform_options,
  4722. $is_field_truncated,
  4723. $original_length = ''
  4724. ) {
  4725. $relational_display = $_SESSION['tmpval']['relational_display'];
  4726. $printview = $this->__get('printview');
  4727. $decimals = isset($meta->decimals) ? $meta->decimals : '-1';
  4728. $result = '<td data-decimals="' . $decimals . '"'
  4729. . ' data-type="' . $meta->type . '"';
  4730. if (! empty($original_length)) {
  4731. // cannot use data-original-length
  4732. $result .= ' data-originallength="' . $original_length . '"';
  4733. }
  4734. $result .= ' class="'
  4735. . $this->_addClass(
  4736. $class,
  4737. $condition_field,
  4738. $meta,
  4739. $nowrap,
  4740. $is_field_truncated,
  4741. $transformation_plugin,
  4742. $default_function
  4743. )
  4744. . '">';
  4745. if (! empty($analyzed_sql_results['statement']->expr)) {
  4746. foreach ($analyzed_sql_results['statement']->expr as $expr) {
  4747. if (empty($expr->alias) || empty($expr->column)) {
  4748. continue;
  4749. }
  4750. if (strcasecmp($meta->name, $expr->alias) == 0) {
  4751. $meta->name = $expr->column;
  4752. }
  4753. }
  4754. }
  4755. if (isset($map[$meta->name])) {
  4756. // Field to display from the foreign table?
  4757. if (isset($map[$meta->name][2])
  4758. && strlen((string) $map[$meta->name][2]) > 0
  4759. ) {
  4760. $dispval = $this->_getFromForeign(
  4761. $map,
  4762. $meta,
  4763. $where_comparison
  4764. );
  4765. } else {
  4766. $dispval = '';
  4767. } // end if... else...
  4768. if (isset($printview) && ($printview == '1')) {
  4769. $result .= ($transformation_plugin != $default_function
  4770. ? $transformation_plugin->applyTransformation(
  4771. $data,
  4772. $transform_options,
  4773. $meta
  4774. )
  4775. : $default_function($data)
  4776. )
  4777. . ' <code>[-&gt;' . $dispval . ']</code>';
  4778. } else {
  4779. if ($relational_display == self::RELATIONAL_KEY) {
  4780. // user chose "relational key" in the display options, so
  4781. // the title contains the display field
  4782. $title = ! empty($dispval)
  4783. ? htmlspecialchars($dispval)
  4784. : '';
  4785. } else {
  4786. $title = htmlspecialchars($data);
  4787. }
  4788. $sqlQuery = 'SELECT * FROM '
  4789. . Util::backquote($map[$meta->name][3]) . '.'
  4790. . Util::backquote($map[$meta->name][0])
  4791. . ' WHERE '
  4792. . Util::backquote($map[$meta->name][1])
  4793. . $where_comparison;
  4794. $_url_params = [
  4795. 'db' => $map[$meta->name][3],
  4796. 'table' => $map[$meta->name][0],
  4797. 'pos' => '0',
  4798. 'sql_signature' => Core::signSqlQuery($sqlQuery),
  4799. 'sql_query' => $sqlQuery,
  4800. ];
  4801. if ($transformation_plugin != $default_function) {
  4802. // always apply a transformation on the real data,
  4803. // not on the display field
  4804. $displayedData = $transformation_plugin->applyTransformation(
  4805. $data,
  4806. $transform_options,
  4807. $meta
  4808. );
  4809. } else {
  4810. if ($relational_display == self::RELATIONAL_DISPLAY_COLUMN
  4811. && ! empty($map[$meta->name][2])
  4812. ) {
  4813. // user chose "relational display field" in the
  4814. // display options, so show display field in the cell
  4815. $displayedData = $dispval === null ? '<em>NULL</em>' : $default_function($dispval);
  4816. } else {
  4817. // otherwise display data in the cell
  4818. $displayedData = $default_function($displayedData);
  4819. }
  4820. }
  4821. $tag_params = ['title' => $title];
  4822. if (strpos($class, 'grid_edit') !== false) {
  4823. $tag_params['class'] = 'ajax';
  4824. }
  4825. $result .= Util::linkOrButton(
  4826. 'sql.php' . Url::getCommon($_url_params),
  4827. $displayedData,
  4828. $tag_params
  4829. );
  4830. }
  4831. } else {
  4832. $result .= ($transformation_plugin != $default_function
  4833. ? $transformation_plugin->applyTransformation(
  4834. $data,
  4835. $transform_options,
  4836. $meta
  4837. )
  4838. : $default_function($data)
  4839. );
  4840. }
  4841. $result .= '</td>' . "\n";
  4842. return $result;
  4843. }
  4844. /**
  4845. * Prepares a checkbox for multi-row submits
  4846. *
  4847. * @param string $del_url delete url
  4848. * @param array $displayParts array with explicit indexes for all
  4849. * the display elements
  4850. * @param string $row_no the row number
  4851. * @param string $where_clause_html url encoded where clause
  4852. * @param array $condition_array array of conditions in the where clause
  4853. * @param string $id_suffix suffix for the id
  4854. * @param string $class css classes for the td element
  4855. *
  4856. * @return string the generated HTML
  4857. *
  4858. * @access private
  4859. *
  4860. * @see _getTableBody(), _getCheckboxAndLinks()
  4861. */
  4862. private function _getCheckboxForMultiRowSubmissions(
  4863. $del_url,
  4864. array $displayParts,
  4865. $row_no,
  4866. $where_clause_html,
  4867. array $condition_array,
  4868. $id_suffix,
  4869. $class
  4870. ) {
  4871. $ret = '';
  4872. if (! empty($del_url) && $displayParts['del_lnk'] != self::KILL_PROCESS) {
  4873. $ret .= '<td ';
  4874. if (! empty($class)) {
  4875. $ret .= 'class="' . $class . '"';
  4876. }
  4877. $ret .= ' class="center print_ignore">'
  4878. . '<input type="checkbox" id="id_rows_to_delete'
  4879. . $row_no . $id_suffix
  4880. . '" name="rows_to_delete[' . $row_no . ']"'
  4881. . ' class="multi_checkbox checkall"'
  4882. . ' value="' . $where_clause_html . '">'
  4883. . '<input type="hidden" class="condition_array" value="'
  4884. . htmlspecialchars(json_encode($condition_array)) . '">'
  4885. . ' </td>';
  4886. }
  4887. return $ret;
  4888. }
  4889. /**
  4890. * Prepares an Edit link
  4891. *
  4892. * @param string $edit_url edit url
  4893. * @param string $class css classes for td element
  4894. * @param string $edit_str text for the edit link
  4895. * @param string $where_clause where clause
  4896. * @param string $where_clause_html url encoded where clause
  4897. *
  4898. * @return string the generated HTML
  4899. *
  4900. * @access private
  4901. *
  4902. * @see _getTableBody(), _getCheckboxAndLinks()
  4903. */
  4904. private function _getEditLink(
  4905. $edit_url,
  4906. $class,
  4907. $edit_str,
  4908. $where_clause,
  4909. $where_clause_html
  4910. ) {
  4911. $ret = '';
  4912. if (! empty($edit_url)) {
  4913. $ret .= '<td class="' . $class . ' center print_ignore">'
  4914. . '<span class="nowrap">'
  4915. . Util::linkOrButton($edit_url, $edit_str);
  4916. /*
  4917. * Where clause for selecting this row uniquely is provided as
  4918. * a hidden input. Used by jQuery scripts for handling grid editing
  4919. */
  4920. if (! empty($where_clause)) {
  4921. $ret .= '<input type="hidden" class="where_clause" value ="'
  4922. . $where_clause_html . '">';
  4923. }
  4924. $ret .= '</span></td>';
  4925. }
  4926. return $ret;
  4927. }
  4928. /**
  4929. * Prepares an Copy link
  4930. *
  4931. * @param string $copy_url copy url
  4932. * @param string $copy_str text for the copy link
  4933. * @param string $where_clause where clause
  4934. * @param string $where_clause_html url encoded where clause
  4935. * @param string $class css classes for the td element
  4936. *
  4937. * @return string the generated HTML
  4938. *
  4939. * @access private
  4940. *
  4941. * @see _getTableBody(), _getCheckboxAndLinks()
  4942. */
  4943. private function _getCopyLink(
  4944. $copy_url,
  4945. $copy_str,
  4946. $where_clause,
  4947. $where_clause_html,
  4948. $class
  4949. ) {
  4950. $ret = '';
  4951. if (! empty($copy_url)) {
  4952. $ret .= '<td class="';
  4953. if (! empty($class)) {
  4954. $ret .= $class . ' ';
  4955. }
  4956. $ret .= 'center print_ignore"><span class="nowrap">'
  4957. . Util::linkOrButton($copy_url, $copy_str);
  4958. /*
  4959. * Where clause for selecting this row uniquely is provided as
  4960. * a hidden input. Used by jQuery scripts for handling grid editing
  4961. */
  4962. if (! empty($where_clause)) {
  4963. $ret .= '<input type="hidden" class="where_clause" value="'
  4964. . $where_clause_html . '">';
  4965. }
  4966. $ret .= '</span></td>';
  4967. }
  4968. return $ret;
  4969. }
  4970. /**
  4971. * Prepares a Delete link
  4972. *
  4973. * @param string $del_url delete url
  4974. * @param string $del_str text for the delete link
  4975. * @param string $js_conf text for the JS confirmation
  4976. * @param string $class css classes for the td element
  4977. *
  4978. * @return string the generated HTML
  4979. *
  4980. * @access private
  4981. *
  4982. * @see _getTableBody(), _getCheckboxAndLinks()
  4983. */
  4984. private function _getDeleteLink($del_url, $del_str, $js_conf, $class)
  4985. {
  4986. $ret = '';
  4987. if (empty($del_url)) {
  4988. return $ret;
  4989. }
  4990. $ret .= '<td class="';
  4991. if (! empty($class)) {
  4992. $ret .= $class . ' ';
  4993. }
  4994. $ajax = Response::getInstance()->isAjax() ? ' ajax' : '';
  4995. $ret .= 'center print_ignore">'
  4996. . Util::linkOrButton(
  4997. $del_url,
  4998. $del_str,
  4999. ['class' => 'delete_row requireConfirm' . $ajax]
  5000. )
  5001. . '<div class="hide">' . $js_conf . '</div>'
  5002. . '</td>';
  5003. return $ret;
  5004. }
  5005. /**
  5006. * Prepare checkbox and links at some position (left or right)
  5007. * (only called for horizontal mode)
  5008. *
  5009. * @param string $position the position of the checkbox and links
  5010. * @param string $del_url delete url
  5011. * @param array $displayParts array with explicit indexes for all the
  5012. * display elements
  5013. * @param string $row_no row number
  5014. * @param string $where_clause where clause
  5015. * @param string $where_clause_html url encoded where clause
  5016. * @param array $condition_array array of conditions in the where clause
  5017. * @param string $edit_url edit url
  5018. * @param string $copy_url copy url
  5019. * @param string $class css classes for the td elements
  5020. * @param string $edit_str text for the edit link
  5021. * @param string $copy_str text for the copy link
  5022. * @param string $del_str text for the delete link
  5023. * @param string $js_conf text for the JS confirmation
  5024. *
  5025. * @return string the generated HTML
  5026. *
  5027. * @access private
  5028. *
  5029. * @see _getPlacedLinks()
  5030. */
  5031. private function _getCheckboxAndLinks(
  5032. $position,
  5033. $del_url,
  5034. array $displayParts,
  5035. $row_no,
  5036. $where_clause,
  5037. $where_clause_html,
  5038. array $condition_array,
  5039. $edit_url,
  5040. $copy_url,
  5041. $class,
  5042. $edit_str,
  5043. $copy_str,
  5044. $del_str,
  5045. $js_conf
  5046. ) {
  5047. $ret = '';
  5048. if ($position == self::POSITION_LEFT) {
  5049. $ret .= $this->_getCheckboxForMultiRowSubmissions(
  5050. $del_url,
  5051. $displayParts,
  5052. $row_no,
  5053. $where_clause_html,
  5054. $condition_array,
  5055. '_left',
  5056. ''
  5057. );
  5058. $ret .= $this->_getEditLink(
  5059. $edit_url,
  5060. $class,
  5061. $edit_str,
  5062. $where_clause,
  5063. $where_clause_html
  5064. );
  5065. $ret .= $this->_getCopyLink(
  5066. $copy_url,
  5067. $copy_str,
  5068. $where_clause,
  5069. $where_clause_html,
  5070. ''
  5071. );
  5072. $ret .= $this->_getDeleteLink($del_url, $del_str, $js_conf, '');
  5073. } elseif ($position == self::POSITION_RIGHT) {
  5074. $ret .= $this->_getDeleteLink($del_url, $del_str, $js_conf, '');
  5075. $ret .= $this->_getCopyLink(
  5076. $copy_url,
  5077. $copy_str,
  5078. $where_clause,
  5079. $where_clause_html,
  5080. ''
  5081. );
  5082. $ret .= $this->_getEditLink(
  5083. $edit_url,
  5084. $class,
  5085. $edit_str,
  5086. $where_clause,
  5087. $where_clause_html
  5088. );
  5089. $ret .= $this->_getCheckboxForMultiRowSubmissions(
  5090. $del_url,
  5091. $displayParts,
  5092. $row_no,
  5093. $where_clause_html,
  5094. $condition_array,
  5095. '_right',
  5096. ''
  5097. );
  5098. } else { // $position == self::POSITION_NONE
  5099. $ret .= $this->_getCheckboxForMultiRowSubmissions(
  5100. $del_url,
  5101. $displayParts,
  5102. $row_no,
  5103. $where_clause_html,
  5104. $condition_array,
  5105. '_left',
  5106. ''
  5107. );
  5108. }
  5109. return $ret;
  5110. }
  5111. /**
  5112. * Truncates given string based on LimitChars configuration
  5113. * and Session pftext variable
  5114. * (string is truncated only if necessary)
  5115. *
  5116. * @param string $str string to be truncated
  5117. *
  5118. * @return mixed
  5119. *
  5120. * @access private
  5121. *
  5122. * @see _handleNonPrintableContents(), _getDataCellForGeometryColumns(),
  5123. * _getDataCellForNonNumericColumns
  5124. */
  5125. private function _getPartialText($str)
  5126. {
  5127. $original_length = mb_strlen($str);
  5128. if ($original_length > $GLOBALS['cfg']['LimitChars']
  5129. && $_SESSION['tmpval']['pftext'] === self::DISPLAY_PARTIAL_TEXT
  5130. ) {
  5131. $str = mb_substr(
  5132. $str,
  5133. 0,
  5134. (int) $GLOBALS['cfg']['LimitChars']
  5135. ) . '...';
  5136. $truncated = true;
  5137. } else {
  5138. $truncated = false;
  5139. }
  5140. return [
  5141. $truncated,
  5142. $str,
  5143. $original_length,
  5144. ];
  5145. }
  5146. }