Results.php 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin\Display;
  4. use PhpMyAdmin\Config\SpecialSchemaLinks;
  5. use PhpMyAdmin\ConfigStorage\Relation;
  6. use PhpMyAdmin\Core;
  7. use PhpMyAdmin\DatabaseInterface;
  8. use PhpMyAdmin\Dbal\ResultInterface;
  9. use PhpMyAdmin\FieldMetadata;
  10. use PhpMyAdmin\Html\Generator;
  11. use PhpMyAdmin\Index;
  12. use PhpMyAdmin\Message;
  13. use PhpMyAdmin\Plugins\Transformations\Output\Text_Octetstream_Sql;
  14. use PhpMyAdmin\Plugins\Transformations\Output\Text_Plain_Json;
  15. use PhpMyAdmin\Plugins\Transformations\Output\Text_Plain_Sql;
  16. use PhpMyAdmin\Plugins\Transformations\Text_Plain_Link;
  17. use PhpMyAdmin\Plugins\TransformationsPlugin;
  18. use PhpMyAdmin\ResponseRenderer;
  19. use PhpMyAdmin\Sanitize;
  20. use PhpMyAdmin\Sql;
  21. use PhpMyAdmin\SqlParser\Parser;
  22. use PhpMyAdmin\SqlParser\Statements\SelectStatement;
  23. use PhpMyAdmin\SqlParser\Utils\Query;
  24. use PhpMyAdmin\Table;
  25. use PhpMyAdmin\Template;
  26. use PhpMyAdmin\Theme;
  27. use PhpMyAdmin\Transformations;
  28. use PhpMyAdmin\Url;
  29. use PhpMyAdmin\Util;
  30. use PhpMyAdmin\Utils\Gis;
  31. use function __;
  32. use function _pgettext;
  33. use function array_filter;
  34. use function array_keys;
  35. use function array_merge;
  36. use function array_shift;
  37. use function bin2hex;
  38. use function ceil;
  39. use function class_exists;
  40. use function count;
  41. use function explode;
  42. use function file_exists;
  43. use function floor;
  44. use function htmlspecialchars;
  45. use function implode;
  46. use function in_array;
  47. use function intval;
  48. use function is_array;
  49. use function is_numeric;
  50. use function json_encode;
  51. use function max;
  52. use function mb_check_encoding;
  53. use function mb_strlen;
  54. use function mb_strpos;
  55. use function mb_strtolower;
  56. use function mb_strtoupper;
  57. use function mb_substr;
  58. use function md5;
  59. use function mt_getrandmax;
  60. use function pack;
  61. use function preg_match;
  62. use function preg_replace;
  63. use function random_int;
  64. use function str_contains;
  65. use function str_ends_with;
  66. use function str_replace;
  67. use function strcasecmp;
  68. use function strip_tags;
  69. use function stripos;
  70. use function strlen;
  71. use function strpos;
  72. use function strtoupper;
  73. use function substr;
  74. use function trim;
  75. /**
  76. * Handle all the functionalities related to displaying results
  77. * of sql queries, stored procedure, browsing sql processes or
  78. * displaying binary log.
  79. */
  80. class Results
  81. {
  82. // Define constants
  83. public const NO_EDIT_OR_DELETE = 'nn';
  84. public const UPDATE_ROW = 'ur';
  85. public const DELETE_ROW = 'dr';
  86. public const KILL_PROCESS = 'kp';
  87. public const POSITION_LEFT = 'left';
  88. public const POSITION_RIGHT = 'right';
  89. public const POSITION_BOTH = 'both';
  90. public const POSITION_NONE = 'none';
  91. public const DISPLAY_FULL_TEXT = 'F';
  92. public const DISPLAY_PARTIAL_TEXT = 'P';
  93. public const HEADER_FLIP_TYPE_AUTO = 'auto';
  94. public const HEADER_FLIP_TYPE_CSS = 'css';
  95. public const HEADER_FLIP_TYPE_FAKE = 'fake';
  96. public const RELATIONAL_KEY = 'K';
  97. public const RELATIONAL_DISPLAY_COLUMN = 'D';
  98. public const GEOMETRY_DISP_GEOM = 'GEOM';
  99. public const GEOMETRY_DISP_WKT = 'WKT';
  100. public const GEOMETRY_DISP_WKB = 'WKB';
  101. public const SMART_SORT_ORDER = 'SMART';
  102. public const ASCENDING_SORT_DIR = 'ASC';
  103. public const DESCENDING_SORT_DIR = 'DESC';
  104. public const TABLE_TYPE_INNO_DB = 'InnoDB';
  105. public const ALL_ROWS = 'all';
  106. public const QUERY_TYPE_SELECT = 'SELECT';
  107. public const ROUTINE_PROCEDURE = 'procedure';
  108. public const ROUTINE_FUNCTION = 'function';
  109. public const ACTION_LINK_CONTENT_ICONS = 'icons';
  110. public const ACTION_LINK_CONTENT_TEXT = 'text';
  111. /**
  112. * @psalm-var array{
  113. * server: int,
  114. * db: string,
  115. * table: string,
  116. * goto: string,
  117. * sql_query: string,
  118. * unlim_num_rows: int|numeric-string|false,
  119. * fields_meta: FieldMetadata[],
  120. * is_count: bool|null,
  121. * is_export: bool|null,
  122. * is_func: bool|null,
  123. * is_analyse: bool|null,
  124. * num_rows: int|numeric-string,
  125. * fields_cnt: int,
  126. * querytime: float|null,
  127. * text_dir: string|null,
  128. * is_maint: bool|null,
  129. * is_explain: bool|null,
  130. * is_show: bool|null,
  131. * is_browse_distinct: bool|null,
  132. * showtable: array<string, mixed>|null,
  133. * printview: string|null,
  134. * highlight_columns: array|null,
  135. * display_params: array|null,
  136. * mime_map: array|null,
  137. * editable: bool|null,
  138. * unique_id: int,
  139. * whereClauseMap: array,
  140. * }
  141. */
  142. public $properties = [
  143. /* server id */
  144. 'server' => 0,
  145. /* Database name */
  146. 'db' => '',
  147. /* Table name */
  148. 'table' => '',
  149. /* the URL to go back in case of errors */
  150. 'goto' => '',
  151. /* the SQL query */
  152. 'sql_query' => '',
  153. /* the total number of rows returned by the SQL query without any appended "LIMIT" clause programmatically */
  154. 'unlim_num_rows' => 0,
  155. /* meta information about fields */
  156. 'fields_meta' => [],
  157. 'is_count' => null,
  158. 'is_export' => null,
  159. 'is_func' => null,
  160. 'is_analyse' => null,
  161. /* the total number of rows returned by the SQL query */
  162. 'num_rows' => 0,
  163. /* the total number of fields returned by the SQL query */
  164. 'fields_cnt' => 0,
  165. /* time taken for execute the SQL query */
  166. 'querytime' => null,
  167. 'text_dir' => null,
  168. 'is_maint' => null,
  169. 'is_explain' => null,
  170. 'is_show' => null,
  171. 'is_browse_distinct' => null,
  172. /* table definitions */
  173. 'showtable' => null,
  174. 'printview' => null,
  175. /* column names to highlight */
  176. 'highlight_columns' => null,
  177. /* display information */
  178. 'display_params' => null,
  179. /* mime types information of fields */
  180. 'mime_map' => null,
  181. 'editable' => null,
  182. /* random unique ID to distinguish result set */
  183. 'unique_id' => 0,
  184. /* where clauses for each row, each table in the row */
  185. 'whereClauseMap' => [],
  186. ];
  187. /**
  188. * This variable contains the column transformation information
  189. * for some of the system databases.
  190. * One element of this array represent all relevant columns in all tables in
  191. * one specific database
  192. *
  193. * @var array<string, array<string, array<string, string[]>>>
  194. * @psalm-var array<string, array<string, array<string, array{string, class-string, string}>>> $transformationInfo
  195. */
  196. public $transformationInfo;
  197. /** @var DatabaseInterface */
  198. private $dbi;
  199. /** @var Relation */
  200. private $relation;
  201. /** @var Transformations */
  202. private $transformations;
  203. /** @var Template */
  204. public $template;
  205. /**
  206. * @param string $db the database name
  207. * @param string $table the table name
  208. * @param int $server the server id
  209. * @param string $goto the URL to go back in case of errors
  210. * @param string $sqlQuery the SQL query
  211. */
  212. public function __construct(DatabaseInterface $dbi, $db, $table, $server, $goto, $sqlQuery)
  213. {
  214. $this->dbi = $dbi;
  215. $this->relation = new Relation($this->dbi);
  216. $this->transformations = new Transformations();
  217. $this->template = new Template();
  218. $this->setDefaultTransformations();
  219. $this->properties['db'] = $db;
  220. $this->properties['table'] = $table;
  221. $this->properties['server'] = $server;
  222. $this->properties['goto'] = $goto;
  223. $this->properties['sql_query'] = $sqlQuery;
  224. $this->properties['unique_id'] = random_int(0, mt_getrandmax());
  225. }
  226. /**
  227. * Sets default transformations for some columns
  228. */
  229. private function setDefaultTransformations(): void
  230. {
  231. $jsonHighlightingData = [
  232. 'libraries/classes/Plugins/Transformations/Output/Text_Plain_Json.php',
  233. Text_Plain_Json::class,
  234. 'Text_Plain',
  235. ];
  236. $sqlHighlightingData = [
  237. 'libraries/classes/Plugins/Transformations/Output/Text_Plain_Sql.php',
  238. Text_Plain_Sql::class,
  239. 'Text_Plain',
  240. ];
  241. $blobSqlHighlightingData = [
  242. 'libraries/classes/Plugins/Transformations/Output/Text_Octetstream_Sql.php',
  243. Text_Octetstream_Sql::class,
  244. 'Text_Octetstream',
  245. ];
  246. $linkData = [
  247. 'libraries/classes/Plugins/Transformations/Text_Plain_Link.php',
  248. Text_Plain_Link::class,
  249. 'Text_Plain',
  250. ];
  251. $this->transformationInfo = [
  252. 'information_schema' => [
  253. 'events' => ['event_definition' => $sqlHighlightingData],
  254. 'processlist' => ['info' => $sqlHighlightingData],
  255. 'routines' => ['routine_definition' => $sqlHighlightingData],
  256. 'triggers' => ['action_statement' => $sqlHighlightingData],
  257. 'views' => ['view_definition' => $sqlHighlightingData],
  258. ],
  259. 'mysql' => [
  260. 'event' => [
  261. 'body' => $blobSqlHighlightingData,
  262. 'body_utf8' => $blobSqlHighlightingData,
  263. ],
  264. 'general_log' => ['argument' => $sqlHighlightingData],
  265. 'help_category' => ['url' => $linkData],
  266. 'help_topic' => [
  267. 'example' => $sqlHighlightingData,
  268. 'url' => $linkData,
  269. ],
  270. 'proc' => [
  271. 'param_list' => $blobSqlHighlightingData,
  272. 'returns' => $blobSqlHighlightingData,
  273. 'body' => $blobSqlHighlightingData,
  274. 'body_utf8' => $blobSqlHighlightingData,
  275. ],
  276. 'slow_log' => ['sql_text' => $sqlHighlightingData],
  277. ],
  278. ];
  279. $relationParameters = $this->relation->getRelationParameters();
  280. if ($relationParameters->db === null) {
  281. return;
  282. }
  283. $relDb = [];
  284. if ($relationParameters->sqlHistoryFeature !== null) {
  285. $relDb[$relationParameters->sqlHistoryFeature->history->getName()] = ['sqlquery' => $sqlHighlightingData];
  286. }
  287. if ($relationParameters->bookmarkFeature !== null) {
  288. $relDb[$relationParameters->bookmarkFeature->bookmark->getName()] = ['query' => $sqlHighlightingData];
  289. }
  290. if ($relationParameters->trackingFeature !== null) {
  291. $relDb[$relationParameters->trackingFeature->tracking->getName()] = [
  292. 'schema_sql' => $sqlHighlightingData,
  293. 'data_sql' => $sqlHighlightingData,
  294. ];
  295. }
  296. if ($relationParameters->favoriteTablesFeature !== null) {
  297. $table = $relationParameters->favoriteTablesFeature->favorite->getName();
  298. $relDb[$table] = ['tables' => $jsonHighlightingData];
  299. }
  300. if ($relationParameters->recentlyUsedTablesFeature !== null) {
  301. $table = $relationParameters->recentlyUsedTablesFeature->recent->getName();
  302. $relDb[$table] = ['tables' => $jsonHighlightingData];
  303. }
  304. if ($relationParameters->savedQueryByExampleSearchesFeature !== null) {
  305. $table = $relationParameters->savedQueryByExampleSearchesFeature->savedSearches->getName();
  306. $relDb[$table] = ['search_data' => $jsonHighlightingData];
  307. }
  308. if ($relationParameters->databaseDesignerSettingsFeature !== null) {
  309. $table = $relationParameters->databaseDesignerSettingsFeature->designerSettings->getName();
  310. $relDb[$table] = ['settings_data' => $jsonHighlightingData];
  311. }
  312. if ($relationParameters->uiPreferencesFeature !== null) {
  313. $table = $relationParameters->uiPreferencesFeature->tableUiPrefs->getName();
  314. $relDb[$table] = ['prefs' => $jsonHighlightingData];
  315. }
  316. if ($relationParameters->userPreferencesFeature !== null) {
  317. $table = $relationParameters->userPreferencesFeature->userConfig->getName();
  318. $relDb[$table] = ['config_data' => $jsonHighlightingData];
  319. }
  320. if ($relationParameters->exportTemplatesFeature !== null) {
  321. $table = $relationParameters->exportTemplatesFeature->exportTemplates->getName();
  322. $relDb[$table] = ['template_data' => $jsonHighlightingData];
  323. }
  324. $this->transformationInfo[$relationParameters->db->getName()] = $relDb;
  325. }
  326. /**
  327. * Set properties which were not initialized at the constructor
  328. *
  329. * @param int|string $unlimNumRows the total number of rows returned by the SQL query without
  330. * any appended "LIMIT" clause programmatically
  331. * @param FieldMetadata[] $fieldsMeta meta information about fields
  332. * @param bool $isCount statement is SELECT COUNT
  333. * @param bool $isExport statement contains INTO OUTFILE
  334. * @param bool $isFunction statement contains a function like SUM()
  335. * @param bool $isAnalyse statement contains PROCEDURE ANALYSE
  336. * @param int|string $numRows total no. of rows returned by SQL query
  337. * @param int $fieldsCount total no.of fields returned by SQL query
  338. * @param double $queryTime time taken for execute the SQL query
  339. * @param string $textDirection text direction
  340. * @param bool $isMaintenance statement contains a maintenance command
  341. * @param bool $isExplain statement contains EXPLAIN
  342. * @param bool $isShow statement contains SHOW
  343. * @param array<string, mixed>|null $showTable table definitions
  344. * @param string|null $printView print view was requested
  345. * @param bool $editable whether the results set is editable
  346. * @param bool $isBrowseDistinct whether browsing distinct values
  347. * @psalm-param int|numeric-string $unlimNumRows
  348. * @psalm-param int|numeric-string $numRows
  349. */
  350. public function setProperties(
  351. $unlimNumRows,
  352. array $fieldsMeta,
  353. $isCount,
  354. $isExport,
  355. $isFunction,
  356. $isAnalyse,
  357. $numRows,
  358. $fieldsCount,
  359. $queryTime,
  360. $textDirection,
  361. $isMaintenance,
  362. $isExplain,
  363. $isShow,
  364. ?array $showTable,
  365. $printView,
  366. $editable,
  367. $isBrowseDistinct
  368. ): void {
  369. $this->properties['unlim_num_rows'] = $unlimNumRows;
  370. $this->properties['fields_meta'] = $fieldsMeta;
  371. $this->properties['is_count'] = $isCount;
  372. $this->properties['is_export'] = $isExport;
  373. $this->properties['is_func'] = $isFunction;
  374. $this->properties['is_analyse'] = $isAnalyse;
  375. $this->properties['num_rows'] = $numRows;
  376. $this->properties['fields_cnt'] = $fieldsCount;
  377. $this->properties['querytime'] = $queryTime;
  378. $this->properties['text_dir'] = $textDirection;
  379. $this->properties['is_maint'] = $isMaintenance;
  380. $this->properties['is_explain'] = $isExplain;
  381. $this->properties['is_show'] = $isShow;
  382. $this->properties['showtable'] = $showTable;
  383. $this->properties['printview'] = $printView;
  384. $this->properties['editable'] = $editable;
  385. $this->properties['is_browse_distinct'] = $isBrowseDistinct;
  386. }
  387. /**
  388. * Defines the parts to display for a print view
  389. *
  390. * @param array $displayParts the parts to display
  391. *
  392. * @return array the modified display parts
  393. */
  394. private function setDisplayPartsForPrintView(array $displayParts)
  395. {
  396. // set all elements to false!
  397. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE; // no edit link
  398. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE; // no delete link
  399. $displayParts['sort_lnk'] = '0';
  400. $displayParts['nav_bar'] = '0';
  401. $displayParts['bkm_form'] = '0';
  402. $displayParts['text_btn'] = '0';
  403. $displayParts['pview_lnk'] = '0';
  404. return $displayParts;
  405. }
  406. /**
  407. * Defines the parts to display for a SHOW statement
  408. *
  409. * @param array $displayParts the parts to display
  410. *
  411. * @return array the modified display parts
  412. */
  413. private function setDisplayPartsForShow(array $displayParts)
  414. {
  415. preg_match(
  416. '@^SHOW[[:space:]]+(VARIABLES|(FULL[[:space:]]+)?'
  417. . 'PROCESSLIST|STATUS|TABLE|GRANTS|CREATE|LOGS|DATABASES|FIELDS'
  418. . ')@i',
  419. $this->properties['sql_query'],
  420. $which
  421. );
  422. $bIsProcessList = isset($which[1]);
  423. if ($bIsProcessList) {
  424. $str = ' ' . strtoupper($which[1]);
  425. $bIsProcessList = strpos($str, 'PROCESSLIST') > 0;
  426. }
  427. // no edit link
  428. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
  429. if ($bIsProcessList) {
  430. // "kill process" type edit link
  431. $displayParts['del_lnk'] = self::KILL_PROCESS;
  432. } else {
  433. // Default case -> no links
  434. // no delete link
  435. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
  436. }
  437. // Other settings
  438. $displayParts['sort_lnk'] = '0';
  439. $displayParts['nav_bar'] = '0';
  440. $displayParts['bkm_form'] = '1';
  441. $displayParts['text_btn'] = '1';
  442. $displayParts['pview_lnk'] = '1';
  443. return $displayParts;
  444. }
  445. /**
  446. * Defines the parts to display for statements not related to data
  447. *
  448. * @param array $displayParts the parts to display
  449. *
  450. * @return array the modified display parts
  451. */
  452. private function setDisplayPartsForNonData(array $displayParts)
  453. {
  454. // Statement is a "SELECT COUNT", a
  455. // "CHECK/ANALYZE/REPAIR/OPTIMIZE/CHECKSUM", an "EXPLAIN" one or
  456. // contains a "PROC ANALYSE" part
  457. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE; // no edit link
  458. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE; // no delete link
  459. $displayParts['sort_lnk'] = '0';
  460. $displayParts['nav_bar'] = '0';
  461. $displayParts['bkm_form'] = '1';
  462. if ($this->properties['is_maint']) {
  463. $displayParts['text_btn'] = '1';
  464. } else {
  465. $displayParts['text_btn'] = '0';
  466. }
  467. $displayParts['pview_lnk'] = '1';
  468. return $displayParts;
  469. }
  470. /**
  471. * Defines the parts to display for other statements (probably SELECT)
  472. *
  473. * @param array $displayParts the parts to display
  474. *
  475. * @return array the modified display parts
  476. */
  477. private function setDisplayPartsForSelect(array $displayParts)
  478. {
  479. // Other statements (ie "SELECT" ones) -> updates
  480. // $displayParts['edit_lnk'], $displayParts['del_lnk'] and
  481. // $displayParts['text_btn'] (keeps other default values)
  482. $fieldsMeta = $this->properties['fields_meta'];
  483. $previousTable = '';
  484. $displayParts['text_btn'] = '1';
  485. $numberOfColumns = $this->properties['fields_cnt'];
  486. for ($i = 0; $i < $numberOfColumns; $i++) {
  487. $isLink = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  488. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
  489. || ($displayParts['sort_lnk'] != '0');
  490. // Displays edit/delete/sort/insert links?
  491. if (
  492. $isLink
  493. && $previousTable != ''
  494. && $fieldsMeta[$i]->table != ''
  495. && $fieldsMeta[$i]->table != $previousTable
  496. ) {
  497. // don't display links
  498. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
  499. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
  500. /**
  501. * @todo May be problematic with same field names
  502. * in two joined table.
  503. */
  504. if ($displayParts['text_btn'] == '1') {
  505. break;
  506. }
  507. }
  508. // Always display print view link
  509. $displayParts['pview_lnk'] = '1';
  510. if ($fieldsMeta[$i]->table == '') {
  511. continue;
  512. }
  513. $previousTable = $fieldsMeta[$i]->table;
  514. }
  515. if ($previousTable == '') { // no table for any of the columns
  516. // don't display links
  517. $displayParts['edit_lnk'] = self::NO_EDIT_OR_DELETE;
  518. $displayParts['del_lnk'] = self::NO_EDIT_OR_DELETE;
  519. }
  520. return $displayParts;
  521. }
  522. /**
  523. * Defines the parts to display for the results of a SQL query
  524. * and the total number of rows
  525. *
  526. * @see getTable()
  527. *
  528. * @param array $displayParts the parts to display (see a few
  529. * lines above for explanations)
  530. *
  531. * @return array the first element is an array with explicit indexes
  532. * for all the display elements
  533. * the second element is the total number of rows returned
  534. * by the SQL query without any programmatically appended
  535. * LIMIT clause (just a copy of $unlim_num_rows if it exists,
  536. * else computed inside this function)
  537. */
  538. private function setDisplayPartsAndTotal(array $displayParts)
  539. {
  540. $theTotal = 0;
  541. // 1. Following variables are needed for use in isset/empty or
  542. // use with array indexes or safe use in foreach
  543. $db = $this->properties['db'];
  544. $table = $this->properties['table'];
  545. $unlimNumRows = $this->properties['unlim_num_rows'];
  546. $numRows = $this->properties['num_rows'];
  547. $printView = $this->properties['printview'];
  548. // 2. Updates the display parts
  549. if ($printView == '1') {
  550. $displayParts = $this->setDisplayPartsForPrintView($displayParts);
  551. } elseif (
  552. $this->properties['is_count'] || $this->properties['is_analyse']
  553. || $this->properties['is_maint'] || $this->properties['is_explain']
  554. ) {
  555. $displayParts = $this->setDisplayPartsForNonData($displayParts);
  556. } elseif ($this->properties['is_show']) {
  557. $displayParts = $this->setDisplayPartsForShow($displayParts);
  558. } else {
  559. $displayParts = $this->setDisplayPartsForSelect($displayParts);
  560. }
  561. // 3. Gets the total number of rows if it is unknown
  562. if ($unlimNumRows > 0) {
  563. $theTotal = $unlimNumRows;
  564. } elseif (
  565. ($displayParts['nav_bar'] == '1')
  566. || ($displayParts['sort_lnk'] == '1')
  567. && $db !== '' && $table !== ''
  568. ) {
  569. $theTotal = $this->dbi->getTable($db, $table)->countRecords();
  570. }
  571. // if for COUNT query, number of rows returned more than 1
  572. // (may be being used GROUP BY)
  573. if ($this->properties['is_count'] && $numRows > 1) {
  574. $displayParts['nav_bar'] = '1';
  575. $displayParts['sort_lnk'] = '1';
  576. }
  577. // 4. If navigation bar or sorting fields names URLs should be
  578. // displayed but there is only one row, change these settings to
  579. // false
  580. if ($displayParts['nav_bar'] == '1' || $displayParts['sort_lnk'] == '1') {
  581. // - Do not display sort links if less than 2 rows.
  582. // - For a VIEW we (probably) did not count the number of rows
  583. // so don't test this number here, it would remove the possibility
  584. // of sorting VIEW results.
  585. $tableObject = new Table($table, $db);
  586. if ($unlimNumRows < 2 && ! $tableObject->isView()) {
  587. $displayParts['sort_lnk'] = '0';
  588. }
  589. }
  590. return [
  591. $displayParts,
  592. $theTotal,
  593. ];
  594. }
  595. /**
  596. * Return true if we are executing a query in the form of
  597. * "SELECT * FROM <a table> ..."
  598. *
  599. * @see getTableHeaders(), getColumnParams()
  600. *
  601. * @param array $analyzedSqlResults analyzed sql results
  602. */
  603. private function isSelect(array $analyzedSqlResults): bool
  604. {
  605. return ! ($this->properties['is_count']
  606. || $this->properties['is_export']
  607. || $this->properties['is_func']
  608. || $this->properties['is_analyse'])
  609. && ! empty($analyzedSqlResults['select_from'])
  610. && ! empty($analyzedSqlResults['statement']->from)
  611. && (count($analyzedSqlResults['statement']->from) === 1)
  612. && ! empty($analyzedSqlResults['statement']->from[0]->table);
  613. }
  614. /**
  615. * Get a navigation button
  616. *
  617. * @see getMoveBackwardButtonsForTableNavigation(),
  618. * getMoveForwardButtonsForTableNavigation()
  619. *
  620. * @param string $caption iconic caption for button
  621. * @param string $title text for button
  622. * @param int $pos position for next query
  623. * @param string $htmlSqlQuery query ready for display
  624. * @param bool $back whether 'begin' or 'previous'
  625. * @param string $onsubmit optional onsubmit clause
  626. * @param string $inputForRealEnd optional hidden field for special treatment
  627. *
  628. * @return string html content
  629. */
  630. private function getTableNavigationButton(
  631. $caption,
  632. $title,
  633. $pos,
  634. $htmlSqlQuery,
  635. $back,
  636. $onsubmit = '',
  637. $inputForRealEnd = ''
  638. ): string {
  639. $captionOutput = '';
  640. if ($back) {
  641. if (Util::showIcons('TableNavigationLinksMode')) {
  642. $captionOutput .= $caption;
  643. }
  644. if (Util::showText('TableNavigationLinksMode')) {
  645. $captionOutput .= '&nbsp;' . $title;
  646. }
  647. } else {
  648. if (Util::showText('TableNavigationLinksMode')) {
  649. $captionOutput .= $title;
  650. }
  651. if (Util::showIcons('TableNavigationLinksMode')) {
  652. $captionOutput .= '&nbsp;' . $caption;
  653. }
  654. }
  655. return $this->template->render('display/results/table_navigation_button', [
  656. 'db' => $this->properties['db'],
  657. 'table' => $this->properties['table'],
  658. 'sql_query' => $htmlSqlQuery,
  659. 'pos' => $pos,
  660. 'is_browse_distinct' => $this->properties['is_browse_distinct'],
  661. 'goto' => $this->properties['goto'],
  662. 'input_for_real_end' => $inputForRealEnd,
  663. 'caption_output' => $captionOutput,
  664. 'title' => $title,
  665. 'onsubmit' => $onsubmit,
  666. ]);
  667. }
  668. /**
  669. * Possibly return a page selector for table navigation
  670. *
  671. * @return array{string, int} ($output, $nbTotalPage)
  672. */
  673. private function getHtmlPageSelector(): array
  674. {
  675. $pageNow = (int) floor($_SESSION['tmpval']['pos'] / $_SESSION['tmpval']['max_rows']) + 1;
  676. $nbTotalPage = (int) ceil((int) $this->properties['unlim_num_rows'] / $_SESSION['tmpval']['max_rows']);
  677. $output = '';
  678. if ($nbTotalPage > 1) {
  679. $urlParams = [
  680. 'db' => $this->properties['db'],
  681. 'table' => $this->properties['table'],
  682. 'sql_query' => $this->properties['sql_query'],
  683. 'goto' => $this->properties['goto'],
  684. 'is_browse_distinct' => $this->properties['is_browse_distinct'],
  685. ];
  686. $output = $this->template->render('display/results/page_selector', [
  687. 'url_params' => $urlParams,
  688. 'page_selector' => Util::pageselector(
  689. 'pos',
  690. $_SESSION['tmpval']['max_rows'],
  691. $pageNow,
  692. $nbTotalPage
  693. ),
  694. ]);
  695. }
  696. return [
  697. $output,
  698. $nbTotalPage,
  699. ];
  700. }
  701. /**
  702. * Get a navigation bar to browse among the results of a SQL query
  703. *
  704. * @see getTable()
  705. *
  706. * @param int $posNext the offset for the "next" page
  707. * @param int $posPrevious the offset for the "previous" page
  708. * @param bool $isInnodb whether its InnoDB or not
  709. * @param array $sortByKeyData the sort by key dialog
  710. *
  711. * @return array
  712. */
  713. private function getTableNavigation(
  714. int $posNext,
  715. int $posPrevious,
  716. bool $isInnodb,
  717. array $sortByKeyData
  718. ): array {
  719. $isShowingAll = $_SESSION['tmpval']['max_rows'] === self::ALL_ROWS;
  720. // Move to the beginning or to the previous page
  721. $moveBackwardButtons = '';
  722. if ($_SESSION['tmpval']['pos'] && ! $isShowingAll) {
  723. $moveBackwardButtons = $this->getMoveBackwardButtonsForTableNavigation(
  724. htmlspecialchars($this->properties['sql_query']),
  725. $posPrevious
  726. );
  727. }
  728. $pageSelector = '';
  729. $numberTotalPage = 1;
  730. if (! $isShowingAll) {
  731. [
  732. $pageSelector,
  733. $numberTotalPage,
  734. ] = $this->getHtmlPageSelector();
  735. }
  736. // Move to the next page or to the last one
  737. $moveForwardButtons = '';
  738. if (
  739. // view with unknown number of rows
  740. ($this->properties['unlim_num_rows'] === -1 || $this->properties['unlim_num_rows'] === false)
  741. || (! $isShowingAll
  742. && intval($_SESSION['tmpval']['pos']) + intval($_SESSION['tmpval']['max_rows'])
  743. < $this->properties['unlim_num_rows']
  744. && $this->properties['num_rows'] >= $_SESSION['tmpval']['max_rows'])
  745. ) {
  746. $moveForwardButtons = $this->getMoveForwardButtonsForTableNavigation(
  747. htmlspecialchars($this->properties['sql_query']),
  748. $posNext,
  749. $isInnodb
  750. );
  751. }
  752. $hiddenFields = [
  753. 'db' => $this->properties['db'],
  754. 'table' => $this->properties['table'],
  755. 'server' => $this->properties['server'],
  756. 'sql_query' => $this->properties['sql_query'],
  757. 'is_browse_distinct' => $this->properties['is_browse_distinct'],
  758. 'goto' => $this->properties['goto'],
  759. ];
  760. return [
  761. 'move_backward_buttons' => $moveBackwardButtons,
  762. 'page_selector' => $pageSelector,
  763. 'move_forward_buttons' => $moveForwardButtons,
  764. 'number_total_page' => $numberTotalPage,
  765. 'has_show_all' => $GLOBALS['cfg']['ShowAll'] || ($this->properties['unlim_num_rows'] <= 500),
  766. 'hidden_fields' => $hiddenFields,
  767. 'session_max_rows' => $isShowingAll ? $GLOBALS['cfg']['MaxRows'] : 'all',
  768. 'is_showing_all' => $isShowingAll,
  769. 'max_rows' => $_SESSION['tmpval']['max_rows'],
  770. 'pos' => $_SESSION['tmpval']['pos'],
  771. 'sort_by_key' => $sortByKeyData,
  772. ];
  773. }
  774. /**
  775. * Prepare move backward buttons - previous and first
  776. *
  777. * @see getTableNavigation()
  778. *
  779. * @param string $htmlSqlQuery the sql encoded by html special characters
  780. * @param int $posPrev the offset for the "previous" page
  781. *
  782. * @return string html content
  783. */
  784. private function getMoveBackwardButtonsForTableNavigation(
  785. string $htmlSqlQuery,
  786. int $posPrev
  787. ): string {
  788. return $this->getTableNavigationButton(
  789. '&lt;&lt;',
  790. _pgettext('First page', 'Begin'),
  791. 0,
  792. $htmlSqlQuery,
  793. true
  794. )
  795. . $this->getTableNavigationButton(
  796. '&lt;',
  797. _pgettext('Previous page', 'Previous'),
  798. $posPrev,
  799. $htmlSqlQuery,
  800. true
  801. );
  802. }
  803. /**
  804. * Prepare move forward buttons - next and last
  805. *
  806. * @see getTableNavigation()
  807. *
  808. * @param string $htmlSqlQuery the sql encoded by htmlspecialchars()
  809. * @param int $posNext the offset for the "next" page
  810. * @param bool $isInnodb whether it's InnoDB or not
  811. *
  812. * @return string html content
  813. */
  814. private function getMoveForwardButtonsForTableNavigation(
  815. string $htmlSqlQuery,
  816. int $posNext,
  817. bool $isInnodb
  818. ): string {
  819. // display the Next button
  820. $buttonsHtml = $this->getTableNavigationButton(
  821. '&gt;',
  822. _pgettext('Next page', 'Next'),
  823. $posNext,
  824. $htmlSqlQuery,
  825. false
  826. );
  827. // If the number of rows is unknown, stop here (don't add the End button)
  828. if ($this->properties['unlim_num_rows'] === false) {
  829. return $buttonsHtml;
  830. }
  831. $inputForRealEnd = '';
  832. // prepare some options for the End button
  833. if ($isInnodb && $this->properties['unlim_num_rows'] > $GLOBALS['cfg']['MaxExactCount']) {
  834. $inputForRealEnd = '<input id="real_end_input" type="hidden" name="find_real_end" value="1">';
  835. // no backquote around this message
  836. }
  837. $maxRows = (int) $_SESSION['tmpval']['max_rows'];
  838. $onsubmit = 'onsubmit="return '
  839. . (intval($_SESSION['tmpval']['pos'])
  840. + $maxRows
  841. < $this->properties['unlim_num_rows']
  842. && $this->properties['num_rows'] >= $maxRows
  843. ? 'true'
  844. : 'false') . '"';
  845. // display the End button
  846. return $buttonsHtml . $this->getTableNavigationButton(
  847. '&gt;&gt;',
  848. _pgettext('Last page', 'End'),
  849. @((int) ceil(
  850. (int) $this->properties['unlim_num_rows']
  851. / $_SESSION['tmpval']['max_rows']
  852. ) - 1) * $maxRows,
  853. $htmlSqlQuery,
  854. false,
  855. $onsubmit,
  856. $inputForRealEnd
  857. );
  858. }
  859. /**
  860. * Get the headers of the results table, for all of the columns
  861. *
  862. * @see getTableHeaders()
  863. *
  864. * @param array $displayParts which elements to display
  865. * @param array $analyzedSqlResults analyzed sql results
  866. * @param array $sortExpression sort expression
  867. * @param array<int, string> $sortExpressionNoDirection sort expression
  868. * without direction
  869. * @param array $sortDirection sort direction
  870. * @param bool $isLimitedDisplay with limited operations
  871. * or not
  872. *
  873. * @return string html content
  874. */
  875. private function getTableHeadersForColumns(
  876. array $displayParts,
  877. array $analyzedSqlResults,
  878. array $sortExpression,
  879. array $sortExpressionNoDirection,
  880. array $sortDirection,
  881. $isLimitedDisplay
  882. ) {
  883. // required to generate sort links that will remember whether the
  884. // "Show all" button has been clicked
  885. $sqlMd5 = md5($this->properties['server'] . $this->properties['db'] . $this->properties['sql_query']);
  886. $sessionMaxRows = $isLimitedDisplay
  887. ? 0
  888. : $_SESSION['tmpval']['query'][$sqlMd5]['max_rows'];
  889. // Following variable are needed for use in isset/empty or
  890. // use with array indexes/safe use in the for loop
  891. $highlightColumns = $this->properties['highlight_columns'];
  892. $fieldsMeta = $this->properties['fields_meta'];
  893. // Prepare Display column comments if enabled
  894. // ($GLOBALS['cfg']['ShowBrowseComments']).
  895. $commentsMap = $this->getTableCommentsArray($analyzedSqlResults);
  896. [$colOrder, $colVisib] = $this->getColumnParams($analyzedSqlResults);
  897. // optimize: avoid calling a method on each iteration
  898. $numberOfColumns = $this->properties['fields_cnt'];
  899. $columns = [];
  900. for ($j = 0; $j < $numberOfColumns; $j++) {
  901. // PHP 7.4 fix for accessing array offset on bool
  902. $colVisibCurrent = $colVisib[$j] ?? null;
  903. // assign $i with the appropriate column order
  904. $i = $colOrder ? $colOrder[$j] : $j;
  905. // See if this column should get highlight because it's used in the
  906. // where-query.
  907. $name = $fieldsMeta[$i]->name;
  908. $conditionField = isset($highlightColumns[$name])
  909. || isset($highlightColumns[Util::backquote($name)]);
  910. // Prepare comment-HTML-wrappers for each row, if defined/enabled.
  911. $comments = $this->getCommentForRow($commentsMap, $fieldsMeta[$i]);
  912. $displayParams = $this->properties['display_params'] ?? [];
  913. if (($displayParts['sort_lnk'] == '1') && ! $isLimitedDisplay) {
  914. $sortedHeaderData = $this->getOrderLinkAndSortedHeaderHtml(
  915. $fieldsMeta[$i],
  916. $sortExpression,
  917. $sortExpressionNoDirection,
  918. $analyzedSqlResults,
  919. $sessionMaxRows,
  920. $comments,
  921. $sortDirection,
  922. $colVisib,
  923. $colVisibCurrent
  924. );
  925. $orderLink = $sortedHeaderData['order_link'];
  926. $columns[] = $sortedHeaderData;
  927. $displayParams['desc'][] = ' <th '
  928. . 'class="draggable'
  929. . ($conditionField ? ' condition' : '')
  930. . '" data-column="' . htmlspecialchars($fieldsMeta[$i]->name)
  931. . '">' . "\n" . $orderLink . $comments . ' </th>' . "\n";
  932. } else {
  933. // Results can't be sorted
  934. // Prepare columns to draggable effect for non sortable columns
  935. $columns[] = [
  936. 'column_name' => $fieldsMeta[$i]->name,
  937. 'comments' => $comments,
  938. 'is_column_hidden' => $colVisib && ! $colVisibCurrent,
  939. 'is_column_numeric' => $this->isColumnNumeric($fieldsMeta[$i]),
  940. 'has_condition' => $conditionField,
  941. ];
  942. $displayParams['desc'][] = ' <th '
  943. . 'class="draggable'
  944. . ($conditionField ? ' condition"' : '')
  945. . '" data-column="' . htmlspecialchars((string) $fieldsMeta[$i]->name)
  946. . '"> '
  947. . htmlspecialchars((string) $fieldsMeta[$i]->name)
  948. . $comments . ' </th>';
  949. }
  950. $this->properties['display_params'] = $displayParams;
  951. }
  952. return $this->template->render('display/results/table_headers_for_columns', [
  953. 'is_sortable' => $displayParts['sort_lnk'] == '1' && ! $isLimitedDisplay,
  954. 'columns' => $columns,
  955. ]);
  956. }
  957. /**
  958. * Get the headers of the results table
  959. *
  960. * @see getTable()
  961. *
  962. * @param array $displayParts which elements to display
  963. * @param array $analyzedSqlResults analyzed sql results
  964. * @param array $sortExpression sort expression
  965. * @param array<int, string> $sortExpressionNoDirection sort expression without direction
  966. * @param array $sortDirection sort direction
  967. * @param bool $isLimitedDisplay with limited operations or not
  968. *
  969. * @psalm-return array{
  970. * column_order: array,
  971. * options: array,
  972. * has_bulk_actions_form: bool,
  973. * button: string,
  974. * table_headers_for_columns: string,
  975. * column_at_right_side: string,
  976. * }
  977. */
  978. private function getTableHeaders(
  979. array $displayParts,
  980. array $analyzedSqlResults,
  981. array $sortExpression = [],
  982. array $sortExpressionNoDirection = [],
  983. array $sortDirection = [],
  984. $isLimitedDisplay = false
  985. ): array {
  986. // Needed for use in isset/empty or
  987. // use with array indexes/safe use in foreach
  988. $printView = $this->properties['printview'];
  989. $displayParams = $this->properties['display_params'];
  990. // Output data needed for column reordering and show/hide column
  991. $columnOrder = $this->getDataForResettingColumnOrder($analyzedSqlResults);
  992. $displayParams['emptypre'] = 0;
  993. $displayParams['emptyafter'] = 0;
  994. $displayParams['textbtn'] = '';
  995. $fullOrPartialTextLink = '';
  996. $this->properties['display_params'] = $displayParams;
  997. // Display options (if we are not in print view)
  998. $optionsBlock = [];
  999. if (! (isset($printView) && ($printView == '1')) && ! $isLimitedDisplay) {
  1000. $optionsBlock = $this->getOptionsBlock();
  1001. // prepare full/partial text button or link
  1002. $fullOrPartialTextLink = $this->getFullOrPartialTextButtonOrLink();
  1003. }
  1004. // 1. Set $colspan and generate html with full/partial
  1005. // text button or link
  1006. $colspan = $displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE
  1007. && $displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE ? ' colspan="4"' : '';
  1008. $buttonHtml = $this->getFieldVisibilityParams($displayParts, $fullOrPartialTextLink, $colspan);
  1009. // 2. Displays the fields' name
  1010. // 2.0 If sorting links should be used, checks if the query is a "JOIN"
  1011. // statement (see 2.1.3)
  1012. // See if we have to highlight any header fields of a WHERE query.
  1013. // Uses SQL-Parser results.
  1014. $this->setHighlightedColumnGlobalField($analyzedSqlResults);
  1015. // Get the headers for all of the columns
  1016. $tableHeadersForColumns = $this->getTableHeadersForColumns(
  1017. $displayParts,
  1018. $analyzedSqlResults,
  1019. $sortExpression,
  1020. $sortExpressionNoDirection,
  1021. $sortDirection,
  1022. $isLimitedDisplay
  1023. );
  1024. // Display column at rightside - checkboxes or empty column
  1025. $columnAtRightSide = '';
  1026. if (! $printView) {
  1027. $columnAtRightSide = $this->getColumnAtRightSide($displayParts, $fullOrPartialTextLink, $colspan);
  1028. }
  1029. return [
  1030. 'column_order' => $columnOrder,
  1031. 'options' => $optionsBlock,
  1032. 'has_bulk_actions_form' => $displayParts['del_lnk'] === self::DELETE_ROW
  1033. || $displayParts['del_lnk'] === self::KILL_PROCESS,
  1034. 'button' => $buttonHtml,
  1035. 'table_headers_for_columns' => $tableHeadersForColumns,
  1036. 'column_at_right_side' => $columnAtRightSide,
  1037. ];
  1038. }
  1039. /**
  1040. * Prepare sort by key dropdown - html code segment
  1041. *
  1042. * @see getTableHeaders()
  1043. *
  1044. * @param array|null $sortExpression the sort expression
  1045. * @param string $unsortedSqlQuery the unsorted sql query
  1046. *
  1047. * @return array[]
  1048. * @psalm-return array{hidden_fields?:array, options?:array}
  1049. */
  1050. private function getSortByKeyDropDown(
  1051. ?array $sortExpression,
  1052. string $unsortedSqlQuery
  1053. ): array {
  1054. // grab indexes data:
  1055. $indexes = Index::getFromTable($this->properties['table'], $this->properties['db']);
  1056. // do we have any index?
  1057. if ($indexes === []) {
  1058. return [];
  1059. }
  1060. $hiddenFields = [
  1061. 'db' => $this->properties['db'],
  1062. 'table' => $this->properties['table'],
  1063. 'server' => $this->properties['server'],
  1064. 'sort_by_key' => '1',
  1065. ];
  1066. // Keep the number of rows (25, 50, 100, ...) when changing sort key value
  1067. if (isset($_SESSION['tmpval']) && isset($_SESSION['tmpval']['max_rows'])) {
  1068. $hiddenFields['session_max_rows'] = $_SESSION['tmpval']['max_rows'];
  1069. }
  1070. $isIndexUsed = false;
  1071. $localOrder = is_array($sortExpression) ? implode(', ', $sortExpression) : '';
  1072. $options = [];
  1073. foreach ($indexes as $index) {
  1074. $ascSort = '`'
  1075. . implode('` ASC, `', array_keys($index->getColumns()))
  1076. . '` ASC';
  1077. $descSort = '`'
  1078. . implode('` DESC, `', array_keys($index->getColumns()))
  1079. . '` DESC';
  1080. $isIndexUsed = $isIndexUsed
  1081. || $localOrder === $ascSort
  1082. || $localOrder === $descSort;
  1083. $unsortedSqlQueryFirstPart = $unsortedSqlQuery;
  1084. $unsortedSqlQuerySecondPart = '';
  1085. if (
  1086. preg_match(
  1087. '@(.*)([[:space:]](LIMIT (.*)|PROCEDURE (.*)|FOR UPDATE|LOCK IN SHARE MODE))@is',
  1088. $unsortedSqlQuery,
  1089. $myReg
  1090. )
  1091. ) {
  1092. $unsortedSqlQueryFirstPart = $myReg[1];
  1093. $unsortedSqlQuerySecondPart = $myReg[2];
  1094. }
  1095. $options[] = [
  1096. 'value' => $unsortedSqlQueryFirstPart . ' ORDER BY '
  1097. . $ascSort . $unsortedSqlQuerySecondPart,
  1098. 'content' => $index->getName() . ' (ASC)',
  1099. 'is_selected' => $localOrder === $ascSort,
  1100. ];
  1101. $options[] = [
  1102. 'value' => $unsortedSqlQueryFirstPart . ' ORDER BY '
  1103. . $descSort . $unsortedSqlQuerySecondPart,
  1104. 'content' => $index->getName() . ' (DESC)',
  1105. 'is_selected' => $localOrder === $descSort,
  1106. ];
  1107. }
  1108. $options[] = [
  1109. 'value' => $unsortedSqlQuery,
  1110. 'content' => __('None'),
  1111. 'is_selected' => ! $isIndexUsed,
  1112. ];
  1113. return ['hidden_fields' => $hiddenFields, 'options' => $options];
  1114. }
  1115. /**
  1116. * Set column span, row span and prepare html with full/partial
  1117. * text button or link
  1118. *
  1119. * @see getTableHeaders()
  1120. *
  1121. * @param array $displayParts which elements to display
  1122. * @param string $fullOrPartialTextLink full/partial link or text button
  1123. * @param string $colspan column span of table header
  1124. *
  1125. * @return string html with full/partial text button or link
  1126. */
  1127. private function getFieldVisibilityParams(
  1128. array $displayParts,
  1129. string $fullOrPartialTextLink,
  1130. string $colspan
  1131. ) {
  1132. $displayParams = $this->properties['display_params'];
  1133. // 1. Displays the full/partial text button (part 1)...
  1134. $buttonHtml = '<thead><tr>' . "\n";
  1135. $emptyPreCondition = $displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE
  1136. && $displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE;
  1137. $leftOrBoth = $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT
  1138. || $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH;
  1139. // ... before the result table
  1140. if (
  1141. ($displayParts['edit_lnk'] === self::NO_EDIT_OR_DELETE)
  1142. && ($displayParts['del_lnk'] === self::NO_EDIT_OR_DELETE)
  1143. && ($displayParts['text_btn'] == '1')
  1144. ) {
  1145. $displayParams['emptypre'] = $emptyPreCondition ? 4 : 0;
  1146. } elseif ($leftOrBoth && ($displayParts['text_btn'] == '1')) {
  1147. // ... at the left column of the result table header if possible
  1148. // and required
  1149. $displayParams['emptypre'] = $emptyPreCondition ? 4 : 0;
  1150. $buttonHtml .= '<th class="column_action position-sticky d-print-none"' . $colspan
  1151. . '>' . $fullOrPartialTextLink . '</th>';
  1152. } elseif (
  1153. $leftOrBoth
  1154. && (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  1155. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE))
  1156. ) {
  1157. // ... elseif no button, displays empty(ies) col(s) if required
  1158. $displayParams['emptypre'] = $emptyPreCondition ? 4 : 0;
  1159. $buttonHtml .= '<td' . $colspan . '></td>';
  1160. } elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
  1161. // ... elseif display an empty column if the actions links are
  1162. // disabled to match the rest of the table
  1163. $buttonHtml .= '<th class="column_action position-sticky"></th>';
  1164. }
  1165. $this->properties['display_params'] = $displayParams;
  1166. return $buttonHtml;
  1167. }
  1168. /**
  1169. * Get table comments as array
  1170. *
  1171. * @see getTableHeaders()
  1172. *
  1173. * @param array $analyzedSqlResults analyzed sql results
  1174. *
  1175. * @return array table comments
  1176. */
  1177. private function getTableCommentsArray(array $analyzedSqlResults)
  1178. {
  1179. if (! $GLOBALS['cfg']['ShowBrowseComments'] || empty($analyzedSqlResults['statement']->from)) {
  1180. return [];
  1181. }
  1182. $ret = [];
  1183. foreach ($analyzedSqlResults['statement']->from as $field) {
  1184. if (empty($field->table)) {
  1185. continue;
  1186. }
  1187. $ret[$field->table] = $this->relation->getComments(
  1188. empty($field->database) ? $this->properties['db'] : $field->database,
  1189. $field->table
  1190. );
  1191. }
  1192. return $ret;
  1193. }
  1194. /**
  1195. * Set global array for store highlighted header fields
  1196. *
  1197. * @see getTableHeaders()
  1198. *
  1199. * @param array $analyzedSqlResults analyzed sql results
  1200. */
  1201. private function setHighlightedColumnGlobalField(array $analyzedSqlResults): void
  1202. {
  1203. $highlightColumns = [];
  1204. if (! empty($analyzedSqlResults['statement']->where)) {
  1205. foreach ($analyzedSqlResults['statement']->where as $expr) {
  1206. foreach ($expr->identifiers as $identifier) {
  1207. $highlightColumns[$identifier] = 'true';
  1208. }
  1209. }
  1210. }
  1211. $this->properties['highlight_columns'] = $highlightColumns;
  1212. }
  1213. /**
  1214. * Prepare data for column restoring and show/hide
  1215. *
  1216. * @see getTableHeaders()
  1217. *
  1218. * @param array $analyzedSqlResults analyzed sql results
  1219. *
  1220. * @return array
  1221. */
  1222. private function getDataForResettingColumnOrder(array $analyzedSqlResults): array
  1223. {
  1224. if (! $this->isSelect($analyzedSqlResults)) {
  1225. return [];
  1226. }
  1227. [$columnOrder, $columnVisibility] = $this->getColumnParams($analyzedSqlResults);
  1228. $tableCreateTime = '';
  1229. $table = new Table($this->properties['table'], $this->properties['db']);
  1230. if (! $table->isView()) {
  1231. $tableCreateTime = $this->dbi->getTable(
  1232. $this->properties['db'],
  1233. $this->properties['table']
  1234. )->getStatusInfo('Create_time');
  1235. }
  1236. return [
  1237. 'order' => $columnOrder,
  1238. 'visibility' => $columnVisibility,
  1239. 'is_view' => $table->isView(),
  1240. 'table_create_time' => $tableCreateTime,
  1241. ];
  1242. }
  1243. /**
  1244. * Prepare option fields block
  1245. *
  1246. * @see getTableHeaders()
  1247. *
  1248. * @return array
  1249. */
  1250. private function getOptionsBlock(): array
  1251. {
  1252. if (
  1253. isset($_SESSION['tmpval']['possible_as_geometry'])
  1254. && $_SESSION['tmpval']['possible_as_geometry'] == false
  1255. && $_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_GEOM
  1256. ) {
  1257. $_SESSION['tmpval']['geoOption'] = self::GEOMETRY_DISP_WKT;
  1258. }
  1259. return [
  1260. 'geo_option' => $_SESSION['tmpval']['geoOption'],
  1261. 'hide_transformation' => $_SESSION['tmpval']['hide_transformation'],
  1262. 'display_blob' => $_SESSION['tmpval']['display_blob'],
  1263. 'display_binary' => $_SESSION['tmpval']['display_binary'],
  1264. 'relational_display' => $_SESSION['tmpval']['relational_display'],
  1265. 'possible_as_geometry' => $_SESSION['tmpval']['possible_as_geometry'],
  1266. 'pftext' => $_SESSION['tmpval']['pftext'],
  1267. ];
  1268. }
  1269. /**
  1270. * Get full/partial text button or link
  1271. *
  1272. * @see getTableHeaders()
  1273. *
  1274. * @return string html content
  1275. */
  1276. private function getFullOrPartialTextButtonOrLink(): string
  1277. {
  1278. global $theme;
  1279. $urlParamsFullText = [
  1280. 'db' => $this->properties['db'],
  1281. 'table' => $this->properties['table'],
  1282. 'sql_query' => $this->properties['sql_query'],
  1283. 'goto' => $this->properties['goto'],
  1284. 'full_text_button' => 1,
  1285. ];
  1286. if ($_SESSION['tmpval']['pftext'] === self::DISPLAY_FULL_TEXT) {
  1287. // currently in fulltext mode so show the opposite link
  1288. $tmpImageFile = 's_partialtext.png';
  1289. $tmpTxt = __('Partial texts');
  1290. $urlParamsFullText['pftext'] = self::DISPLAY_PARTIAL_TEXT;
  1291. } else {
  1292. $tmpImageFile = 's_fulltext.png';
  1293. $tmpTxt = __('Full texts');
  1294. $urlParamsFullText['pftext'] = self::DISPLAY_FULL_TEXT;
  1295. }
  1296. $tmpImage = '<img class="fulltext" src="'
  1297. . ($theme instanceof Theme ? $theme->getImgPath($tmpImageFile) : '')
  1298. . '" alt="' . $tmpTxt . '" title="' . $tmpTxt . '">';
  1299. return Generator::linkOrButton(Url::getFromRoute('/sql', $urlParamsFullText, false), null, $tmpImage);
  1300. }
  1301. /**
  1302. * Get comment for row
  1303. *
  1304. * @see getTableHeaders()
  1305. *
  1306. * @param array $commentsMap comments array
  1307. * @param FieldMetadata $fieldsMeta set of field properties
  1308. *
  1309. * @return string html content
  1310. */
  1311. private function getCommentForRow(array $commentsMap, FieldMetadata $fieldsMeta): string
  1312. {
  1313. return $this->template->render('display/results/comment_for_row', [
  1314. 'comments_map' => $commentsMap,
  1315. 'column_name' => $fieldsMeta->name,
  1316. 'table_name' => $fieldsMeta->table,
  1317. 'limit_chars' => $GLOBALS['cfg']['LimitChars'],
  1318. ]);
  1319. }
  1320. /**
  1321. * Prepare parameters and html for sorted table header fields
  1322. *
  1323. * @see getTableHeaders()
  1324. *
  1325. * @param FieldMetadata $fieldsMeta set of field properties
  1326. * @param array $sortExpression sort expression
  1327. * @param array<int, string> $sortExpressionNoDirection sort expression without direction
  1328. * @param array $analyzedSqlResults analyzed sql results
  1329. * @param int $sessionMaxRows maximum rows resulted by sql
  1330. * @param string $comments comment for row
  1331. * @param array $sortDirection sort direction
  1332. * @param bool $colVisib column is visible(false)
  1333. * or column isn't visible(string array)
  1334. * @param string $colVisibElement element of $col_visib array
  1335. *
  1336. * @return array 2 element array - $orderLink, $sortedHeaderHtml
  1337. * @psalm-return array{
  1338. * column_name: string,
  1339. * order_link: string,
  1340. * comments: string,
  1341. * is_browse_pointer_enabled: bool,
  1342. * is_browse_marker_enabled: bool,
  1343. * is_column_hidden: bool,
  1344. * is_column_numeric: bool,
  1345. * }
  1346. */
  1347. private function getOrderLinkAndSortedHeaderHtml(
  1348. FieldMetadata $fieldsMeta,
  1349. array $sortExpression,
  1350. array $sortExpressionNoDirection,
  1351. array $analyzedSqlResults,
  1352. $sessionMaxRows,
  1353. string $comments,
  1354. array $sortDirection,
  1355. $colVisib,
  1356. $colVisibElement
  1357. ): array {
  1358. // Checks if the table name is required; it's the case
  1359. // for a query with a "JOIN" statement and if the column
  1360. // isn't aliased, or in queries like
  1361. // SELECT `1`.`master_field` , `2`.`master_field`
  1362. // FROM `PMA_relation` AS `1` , `PMA_relation` AS `2`
  1363. $sortTable = $fieldsMeta->table !== ''
  1364. && $fieldsMeta->orgname === $fieldsMeta->name
  1365. ? Util::backquote($fieldsMeta->table) . '.'
  1366. : '';
  1367. // Generates the orderby clause part of the query which is part
  1368. // of URL
  1369. [$singleSortOrder, $multiSortOrder, $orderImg] = $this->getSingleAndMultiSortUrls(
  1370. $sortExpression,
  1371. $sortExpressionNoDirection,
  1372. $sortTable,
  1373. $fieldsMeta->name,
  1374. $sortDirection,
  1375. $fieldsMeta
  1376. );
  1377. $singleSortedSqlQuery = Query::replaceClause(
  1378. $analyzedSqlResults['statement'],
  1379. $analyzedSqlResults['parser']->list,
  1380. $singleSortOrder
  1381. );
  1382. $multiSortedSqlQuery = Query::replaceClause(
  1383. $analyzedSqlResults['statement'],
  1384. $analyzedSqlResults['parser']->list,
  1385. $multiSortOrder
  1386. );
  1387. $singleUrlParams = [
  1388. 'db' => $this->properties['db'],
  1389. 'table' => $this->properties['table'],
  1390. 'sql_query' => $singleSortedSqlQuery,
  1391. 'sql_signature' => Core::signSqlQuery($singleSortedSqlQuery),
  1392. 'session_max_rows' => $sessionMaxRows,
  1393. 'is_browse_distinct' => $this->properties['is_browse_distinct'],
  1394. ];
  1395. $multiUrlParams = [
  1396. 'db' => $this->properties['db'],
  1397. 'table' => $this->properties['table'],
  1398. 'sql_query' => $multiSortedSqlQuery,
  1399. 'sql_signature' => Core::signSqlQuery($multiSortedSqlQuery),
  1400. 'session_max_rows' => $sessionMaxRows,
  1401. 'is_browse_distinct' => $this->properties['is_browse_distinct'],
  1402. ];
  1403. // Displays the sorting URL
  1404. // enable sort order swapping for image
  1405. $orderLink = $this->getSortOrderLink($orderImg, $fieldsMeta, $singleUrlParams, $multiUrlParams);
  1406. $orderLink .= $this->getSortOrderHiddenInputs($multiUrlParams, $fieldsMeta->name);
  1407. return [
  1408. 'column_name' => $fieldsMeta->name,
  1409. 'order_link' => $orderLink,
  1410. 'comments' => $comments,
  1411. 'is_browse_pointer_enabled' => $GLOBALS['cfg']['BrowsePointerEnable'] === true,
  1412. 'is_browse_marker_enabled' => $GLOBALS['cfg']['BrowseMarkerEnable'] === true,
  1413. 'is_column_hidden' => $colVisib && ! $colVisibElement,
  1414. 'is_column_numeric' => $this->isColumnNumeric($fieldsMeta),
  1415. ];
  1416. }
  1417. /**
  1418. * Prepare parameters and html for sorted table header fields
  1419. *
  1420. * @param array $sortExpression sort expression
  1421. * @param array<int, string> $sortExpressionNoDirection sort expression without direction
  1422. * @param string $sortTable The name of the table to which
  1423. * the current column belongs to
  1424. * @param string $nameToUseInSort The current column under
  1425. * consideration
  1426. * @param string[] $sortDirection sort direction
  1427. * @param FieldMetadata $fieldsMeta set of field properties
  1428. *
  1429. * @return string[] 3 element array - $single_sort_order, $sort_order, $order_img
  1430. */
  1431. private function getSingleAndMultiSortUrls(
  1432. array $sortExpression,
  1433. array $sortExpressionNoDirection,
  1434. string $sortTable,
  1435. string $nameToUseInSort,
  1436. array $sortDirection,
  1437. FieldMetadata $fieldsMeta
  1438. ): array {
  1439. // Check if the current column is in the order by clause
  1440. $isInSort = $this->isInSorted($sortExpression, $sortExpressionNoDirection, $sortTable, $nameToUseInSort);
  1441. $currentName = $nameToUseInSort;
  1442. if ($sortExpressionNoDirection[0] == '' || ! $isInSort) {
  1443. $specialIndex = $sortExpressionNoDirection[0] == ''
  1444. ? 0
  1445. : count($sortExpressionNoDirection);
  1446. $sortExpressionNoDirection[$specialIndex] = Util::backquote($currentName);
  1447. // Set the direction to the config value
  1448. $sortDirection[$specialIndex] = $GLOBALS['cfg']['Order'];
  1449. // Or perform SMART mode
  1450. if ($GLOBALS['cfg']['Order'] === self::SMART_SORT_ORDER) {
  1451. $isTimeOrDate = $fieldsMeta->isType(FieldMetadata::TYPE_TIME)
  1452. || $fieldsMeta->isType(FieldMetadata::TYPE_DATE)
  1453. || $fieldsMeta->isType(FieldMetadata::TYPE_DATETIME)
  1454. || $fieldsMeta->isType(FieldMetadata::TYPE_TIMESTAMP);
  1455. $sortDirection[$specialIndex] = $isTimeOrDate ? self::DESCENDING_SORT_DIR : self::ASCENDING_SORT_DIR;
  1456. }
  1457. }
  1458. $sortExpressionNoDirection = array_filter($sortExpressionNoDirection);
  1459. $singleSortOrder = '';
  1460. $sortOrderColumns = [];
  1461. foreach ($sortExpressionNoDirection as $index => $expression) {
  1462. $sortOrder = '';
  1463. // check if this is the first clause,
  1464. // if it is then we have to add "order by"
  1465. $isFirstClause = ($index === 0);
  1466. $nameToUseInSort = $expression;
  1467. $sortTableNew = $sortTable;
  1468. // Test to detect if the column name is a standard name
  1469. // Standard name has the table name prefixed to the column name
  1470. if (str_contains($nameToUseInSort, '.') && ! str_contains($nameToUseInSort, '(')) {
  1471. $matches = explode('.', $nameToUseInSort);
  1472. // Matches[0] has the table name
  1473. // Matches[1] has the column name
  1474. $nameToUseInSort = $matches[1];
  1475. $sortTableNew = $matches[0];
  1476. }
  1477. // $name_to_use_in_sort might contain a space due to
  1478. // formatting of function expressions like "COUNT(name )"
  1479. // so we remove the space in this situation
  1480. $nameToUseInSort = str_replace([' )', '``'], [')', '`'], $nameToUseInSort);
  1481. $nameToUseInSort = trim($nameToUseInSort, '`');
  1482. // If this the first column name in the order by clause add
  1483. // order by clause to the column name
  1484. $sortOrder .= $isFirstClause ? "\nORDER BY " : '';
  1485. // Again a check to see if the given column is a aggregate column
  1486. if (str_contains($nameToUseInSort, '(')) {
  1487. $sortOrder .= $nameToUseInSort;
  1488. } else {
  1489. if ($sortTableNew !== '' && ! str_ends_with($sortTableNew, '.')) {
  1490. $sortTableNew .= '.';
  1491. }
  1492. $sortOrder .= $sortTableNew . Util::backquote($nameToUseInSort);
  1493. }
  1494. // Incase this is the current column save $single_sort_order
  1495. if ($currentName === $nameToUseInSort) {
  1496. $singleSortOrder = "\n" . 'ORDER BY ';
  1497. if (! str_contains($currentName, '(')) {
  1498. $singleSortOrder .= $sortTable;
  1499. }
  1500. $singleSortOrder .= Util::backquote($currentName) . ' ';
  1501. if ($isInSort) {
  1502. [$singleSortOrder, $orderImg] = $this->getSortingUrlParams(
  1503. $sortDirection[$index],
  1504. $singleSortOrder
  1505. );
  1506. } else {
  1507. $singleSortOrder .= strtoupper($sortDirection[$index]);
  1508. }
  1509. }
  1510. $sortOrder .= ' ';
  1511. if ($currentName === $nameToUseInSort && $isInSort) {
  1512. // We need to generate the arrow button and related html
  1513. [$sortOrder, $orderImg] = $this->getSortingUrlParams($sortDirection[$index], $sortOrder);
  1514. $orderImg .= ' <small>' . ($index + 1) . '</small>';
  1515. } else {
  1516. $sortOrder .= strtoupper($sortDirection[$index]);
  1517. }
  1518. // Separate columns by a comma
  1519. $sortOrderColumns[] = $sortOrder;
  1520. }
  1521. return [
  1522. $singleSortOrder,
  1523. implode(', ', $sortOrderColumns),
  1524. $orderImg ?? '',
  1525. ];
  1526. }
  1527. /**
  1528. * Check whether the column is sorted
  1529. *
  1530. * @see getTableHeaders()
  1531. *
  1532. * @param array $sortExpression sort expression
  1533. * @param array $sortExpressionNoDirection sort expression without direction
  1534. * @param string $sortTable the table name
  1535. * @param string $nameToUseInSort the sorting column name
  1536. */
  1537. private function isInSorted(
  1538. array $sortExpression,
  1539. array $sortExpressionNoDirection,
  1540. string $sortTable,
  1541. string $nameToUseInSort
  1542. ): bool {
  1543. $indexInExpression = 0;
  1544. foreach ($sortExpressionNoDirection as $index => $clause) {
  1545. if (str_contains($clause, '.')) {
  1546. $fragments = explode('.', $clause);
  1547. $clause2 = $fragments[0] . '.' . str_replace('`', '', $fragments[1]);
  1548. } else {
  1549. $clause2 = $sortTable . str_replace('`', '', $clause);
  1550. }
  1551. if ($clause2 === $sortTable . $nameToUseInSort) {
  1552. $indexInExpression = $index;
  1553. break;
  1554. }
  1555. }
  1556. if (empty($sortExpression[$indexInExpression])) {
  1557. return false;
  1558. }
  1559. // Field name may be preceded by a space, or any number
  1560. // of characters followed by a dot (tablename.fieldname)
  1561. // so do a direct comparison for the sort expression;
  1562. // this avoids problems with queries like
  1563. // "SELECT id, count(id)..." and clicking to sort
  1564. // on id or on count(id).
  1565. // Another query to test this:
  1566. // SELECT p.*, FROM_UNIXTIME(p.temps) FROM mytable AS p
  1567. // (and try clicking on each column's header twice)
  1568. $noSortTable = $sortTable === '' || mb_strpos(
  1569. $sortExpressionNoDirection[$indexInExpression],
  1570. $sortTable
  1571. ) === false;
  1572. $noOpenParenthesis = mb_strpos($sortExpressionNoDirection[$indexInExpression], '(') === false;
  1573. if ($sortTable !== '' && $noSortTable && $noOpenParenthesis) {
  1574. $newSortExpressionNoDirection = $sortTable
  1575. . $sortExpressionNoDirection[$indexInExpression];
  1576. } else {
  1577. $newSortExpressionNoDirection = $sortExpressionNoDirection[$indexInExpression];
  1578. }
  1579. //Back quotes are removed in next comparison, so remove them from value
  1580. //to compare.
  1581. $nameToUseInSort = str_replace('`', '', $nameToUseInSort);
  1582. $sortName = str_replace('`', '', $sortTable) . $nameToUseInSort;
  1583. return $sortName == str_replace('`', '', $newSortExpressionNoDirection)
  1584. || $sortName == str_replace('`', '', $sortExpressionNoDirection[$indexInExpression]);
  1585. }
  1586. /**
  1587. * Get sort url parameters - sort order and order image
  1588. *
  1589. * @see getSingleAndMultiSortUrls()
  1590. *
  1591. * @param string $sortDirection the sort direction
  1592. * @param string $sortOrder the sorting order
  1593. *
  1594. * @return string[] 2 element array - $sort_order, $order_img
  1595. */
  1596. private function getSortingUrlParams(string $sortDirection, $sortOrder): array
  1597. {
  1598. if (strtoupper(trim($sortDirection)) === self::DESCENDING_SORT_DIR) {
  1599. $sortOrder .= self::ASCENDING_SORT_DIR;
  1600. $orderImg = ' ' . Generator::getImage(
  1601. 's_desc',
  1602. __('Descending'),
  1603. [
  1604. 'class' => 'soimg',
  1605. 'title' => '',
  1606. ]
  1607. );
  1608. $orderImg .= ' ' . Generator::getImage(
  1609. 's_asc',
  1610. __('Ascending'),
  1611. [
  1612. 'class' => 'soimg hide',
  1613. 'title' => '',
  1614. ]
  1615. );
  1616. } else {
  1617. $sortOrder .= self::DESCENDING_SORT_DIR;
  1618. $orderImg = ' ' . Generator::getImage(
  1619. 's_asc',
  1620. __('Ascending'),
  1621. [
  1622. 'class' => 'soimg',
  1623. 'title' => '',
  1624. ]
  1625. );
  1626. $orderImg .= ' ' . Generator::getImage(
  1627. 's_desc',
  1628. __('Descending'),
  1629. [
  1630. 'class' => 'soimg hide',
  1631. 'title' => '',
  1632. ]
  1633. );
  1634. }
  1635. return [
  1636. $sortOrder,
  1637. $orderImg,
  1638. ];
  1639. }
  1640. /**
  1641. * Get sort order link
  1642. *
  1643. * @see getTableHeaders()
  1644. *
  1645. * @param string $orderImg the sort order image
  1646. * @param FieldMetadata $fieldsMeta set of field properties
  1647. * @param array<int|string, mixed> $orderUrlParams the url params for sort
  1648. * @param array<int|string, mixed> $multiOrderUrlParams the url params for sort
  1649. *
  1650. * @return string the sort order link
  1651. */
  1652. private function getSortOrderLink(
  1653. string $orderImg,
  1654. FieldMetadata $fieldsMeta,
  1655. array $orderUrlParams,
  1656. array $multiOrderUrlParams
  1657. ): string {
  1658. $urlPath = Url::getFromRoute('/sql', $multiOrderUrlParams, false);
  1659. $innerLinkContent = htmlspecialchars($fieldsMeta->name) . $orderImg
  1660. . '<input type="hidden" value="'
  1661. . $urlPath
  1662. . '">';
  1663. return Generator::linkOrButton(
  1664. Url::getFromRoute('/sql', $orderUrlParams, false),
  1665. null,
  1666. $innerLinkContent,
  1667. ['class' => 'sortlink']
  1668. );
  1669. }
  1670. private function getSortOrderHiddenInputs(
  1671. array $multipleUrlParams,
  1672. string $nameToUseInSort
  1673. ): string {
  1674. $sqlQuery = $multipleUrlParams['sql_query'];
  1675. $sqlQueryAdd = $sqlQuery;
  1676. $sqlQueryRemove = null;
  1677. $parser = new Parser($sqlQuery);
  1678. $firstStatement = $parser->statements[0] ?? null;
  1679. $numberOfClausesFound = null;
  1680. if ($firstStatement instanceof SelectStatement) {
  1681. $orderClauses = $firstStatement->order ?? [];
  1682. foreach ($orderClauses as $key => $order) {
  1683. // If this is the column name, then remove it from the order clause
  1684. if ($order->expr->column !== $nameToUseInSort) {
  1685. continue;
  1686. }
  1687. // remove the order clause for this column and from the counted array
  1688. unset($firstStatement->order[$key], $orderClauses[$key]);
  1689. }
  1690. $numberOfClausesFound = count($orderClauses);
  1691. $sqlQueryRemove = $firstStatement->build();
  1692. }
  1693. $multipleUrlParams['sql_query'] = $sqlQueryRemove ?? $sqlQuery;
  1694. $multipleUrlParams['sql_signature'] = Core::signSqlQuery($multipleUrlParams['sql_query']);
  1695. $urlRemoveOrder = Url::getFromRoute('/sql', $multipleUrlParams);
  1696. if ($numberOfClausesFound === 0) {
  1697. $urlRemoveOrder .= '&discard_remembered_sort=1';
  1698. }
  1699. $multipleUrlParams['sql_query'] = $sqlQueryAdd;
  1700. $multipleUrlParams['sql_signature'] = Core::signSqlQuery($multipleUrlParams['sql_query']);
  1701. $urlAddOrder = Url::getFromRoute('/sql', $multipleUrlParams);
  1702. return '<input type="hidden" name="url-remove-order" value="' . $urlRemoveOrder . '">' . "\n"
  1703. . '<input type="hidden" name="url-add-order" value="' . $urlAddOrder . '">';
  1704. }
  1705. /**
  1706. * Check if the column contains numeric data
  1707. *
  1708. * @param FieldMetadata $fieldsMeta set of field properties
  1709. */
  1710. private function isColumnNumeric(FieldMetadata $fieldsMeta): bool
  1711. {
  1712. // This was defined in commit b661cd7c9b31f8bc564d2f9a1b8527e0eb966de8
  1713. // For issue https://github.com/phpmyadmin/phpmyadmin/issues/4746
  1714. return $fieldsMeta->isType(FieldMetadata::TYPE_REAL)
  1715. || $fieldsMeta->isMappedTypeBit
  1716. || $fieldsMeta->isType(FieldMetadata::TYPE_INT);
  1717. }
  1718. /**
  1719. * Prepare column to show at right side - check boxes or empty column
  1720. *
  1721. * @see getTableHeaders()
  1722. *
  1723. * @param array $displayParts which elements to display
  1724. * @param string $fullOrPartialTextLink full/partial link or text button
  1725. * @param string $colspan column span of table header
  1726. *
  1727. * @return string html content
  1728. */
  1729. private function getColumnAtRightSide(
  1730. array $displayParts,
  1731. string $fullOrPartialTextLink,
  1732. string $colspan
  1733. ) {
  1734. $rightColumnHtml = '';
  1735. $displayParams = $this->properties['display_params'];
  1736. // Displays the needed checkboxes at the right
  1737. // column of the result table header if possible and required...
  1738. if (
  1739. ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_RIGHT)
  1740. || ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
  1741. && (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  1742. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE))
  1743. && ($displayParts['text_btn'] == '1')
  1744. ) {
  1745. $displayParams['emptyafter'] = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  1746. && ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE) ? 4 : 1;
  1747. $rightColumnHtml .= "\n"
  1748. . '<th class="column_action d-print-none"' . $colspan . '>'
  1749. . $fullOrPartialTextLink
  1750. . '</th>';
  1751. } elseif (
  1752. ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT)
  1753. || ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
  1754. && (($displayParts['edit_lnk'] === self::NO_EDIT_OR_DELETE)
  1755. && ($displayParts['del_lnk'] === self::NO_EDIT_OR_DELETE))
  1756. && (! isset($GLOBALS['is_header_sent']) || ! $GLOBALS['is_header_sent'])
  1757. ) {
  1758. // ... elseif no button, displays empty columns if required
  1759. // (unless coming from Browse mode print view)
  1760. $displayParams['emptyafter'] = ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  1761. && ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE) ? 4 : 1;
  1762. $rightColumnHtml .= "\n" . '<td class="d-print-none"' . $colspan
  1763. . '></td>';
  1764. }
  1765. $this->properties['display_params'] = $displayParams;
  1766. return $rightColumnHtml;
  1767. }
  1768. /**
  1769. * Prepares the display for a value
  1770. *
  1771. * @see getDataCellForGeometryColumns(),
  1772. * getDataCellForNonNumericColumns()
  1773. *
  1774. * @param string $class class of table cell
  1775. * @param bool $conditionField whether to add CSS class condition
  1776. * @param string $value value to display
  1777. *
  1778. * @return string the td
  1779. */
  1780. private function buildValueDisplay($class, $conditionField, $value)
  1781. {
  1782. return $this->template->render('display/results/value_display', [
  1783. 'class' => $class,
  1784. 'condition_field' => $conditionField,
  1785. 'value' => $value,
  1786. ]);
  1787. }
  1788. /**
  1789. * Prepares the display for a null value
  1790. *
  1791. * @see getDataCellForNumericColumns(),
  1792. * getDataCellForGeometryColumns(),
  1793. * getDataCellForNonNumericColumns()
  1794. *
  1795. * @param string $class class of table cell
  1796. * @param bool $conditionField whether to add CSS class condition
  1797. * @param FieldMetadata $meta the meta-information about this field
  1798. *
  1799. * @return string the td
  1800. */
  1801. private function buildNullDisplay(string $class, bool $conditionField, FieldMetadata $meta): string
  1802. {
  1803. $classes = $this->addClass($class, $conditionField, $meta, '');
  1804. return $this->template->render('display/results/null_display', [
  1805. 'data_decimals' => $meta->decimals,
  1806. 'data_type' => $meta->getMappedType(),
  1807. 'classes' => $classes,
  1808. ]);
  1809. }
  1810. /**
  1811. * Prepares the display for an empty value
  1812. *
  1813. * @see getDataCellForNumericColumns(),
  1814. * getDataCellForGeometryColumns(),
  1815. * getDataCellForNonNumericColumns()
  1816. *
  1817. * @param string $class class of table cell
  1818. * @param bool $conditionField whether to add CSS class condition
  1819. * @param FieldMetadata $meta the meta-information about this field
  1820. *
  1821. * @return string the td
  1822. */
  1823. private function buildEmptyDisplay(string $class, bool $conditionField, FieldMetadata $meta): string
  1824. {
  1825. $classes = $this->addClass($class, $conditionField, $meta, 'text-nowrap');
  1826. return $this->template->render('display/results/empty_display', ['classes' => $classes]);
  1827. }
  1828. /**
  1829. * Adds the relevant classes.
  1830. *
  1831. * @see buildNullDisplay(), getRowData()
  1832. *
  1833. * @param string $class class of table cell
  1834. * @param bool $conditionField whether to add CSS class condition
  1835. * @param FieldMetadata $meta the meta-information about the field
  1836. * @param string $nowrap avoid wrapping
  1837. * @param bool $isFieldTruncated is field truncated (display ...)
  1838. *
  1839. * @return string the list of classes
  1840. */
  1841. private function addClass(
  1842. string $class,
  1843. bool $conditionField,
  1844. FieldMetadata $meta,
  1845. string $nowrap,
  1846. bool $isFieldTruncated = false,
  1847. bool $hasTransformationPlugin = false
  1848. ): string {
  1849. $classes = array_filter([
  1850. $class,
  1851. $nowrap,
  1852. ]);
  1853. if (isset($meta->internalMediaType)) {
  1854. $classes[] = preg_replace('/\//', '_', $meta->internalMediaType);
  1855. }
  1856. if ($conditionField) {
  1857. $classes[] = 'condition';
  1858. }
  1859. if ($isFieldTruncated) {
  1860. $classes[] = 'truncated';
  1861. }
  1862. $mediaTypeMap = $this->properties['mime_map'];
  1863. $orgFullColName = $this->properties['db'] . '.' . $meta->orgtable
  1864. . '.' . $meta->orgname;
  1865. if ($hasTransformationPlugin || ! empty($mediaTypeMap[$orgFullColName]['input_transformation'])) {
  1866. $classes[] = 'transformed';
  1867. }
  1868. // Define classes to be added to this data field based on the type of data
  1869. if ($meta->isEnum()) {
  1870. $classes[] = 'enum';
  1871. }
  1872. if ($meta->isSet()) {
  1873. $classes[] = 'set';
  1874. }
  1875. if ($meta->isMappedTypeBit) {
  1876. $classes[] = 'bit';
  1877. }
  1878. if ($meta->isBinary()) {
  1879. $classes[] = 'hex';
  1880. }
  1881. return implode(' ', $classes);
  1882. }
  1883. /**
  1884. * Prepare the body of the results table
  1885. *
  1886. * @see getTable()
  1887. *
  1888. * @param ResultInterface $dtResult the link id associated to the query
  1889. * which results have to be displayed
  1890. * @param array $displayParts which elements to display
  1891. * @param array<string, string[]> $map the list of relations
  1892. * @param array $analyzedSqlResults analyzed sql results
  1893. * @param bool $isLimitedDisplay with limited operations or not
  1894. *
  1895. * @return string html content
  1896. *
  1897. * @global array $row current row data
  1898. */
  1899. private function getTableBody(
  1900. ResultInterface $dtResult,
  1901. array $displayParts,
  1902. array $map,
  1903. array $analyzedSqlResults,
  1904. $isLimitedDisplay = false
  1905. ) {
  1906. // Mostly because of browser transformations, to make the row-data accessible in a plugin.
  1907. global $row;
  1908. $tableBodyHtml = '';
  1909. // query without conditions to shorten URLs when needed, 200 is just
  1910. // guess, it should depend on remaining URL length
  1911. $urlSqlQuery = $this->getUrlSqlQuery($analyzedSqlResults);
  1912. $displayParams = $this->properties['display_params'];
  1913. $rowNumber = 0;
  1914. $displayParams['edit'] = [];
  1915. $displayParams['copy'] = [];
  1916. $displayParams['delete'] = [];
  1917. $displayParams['data'] = [];
  1918. $displayParams['row_delete'] = [];
  1919. $this->properties['display_params'] = $displayParams;
  1920. // name of the class added to all grid editable elements;
  1921. // if we don't have all the columns of a unique key in the result set,
  1922. // do not permit grid editing
  1923. if ($isLimitedDisplay || ! $this->properties['editable']) {
  1924. $gridEditClass = '';
  1925. } else {
  1926. switch ($GLOBALS['cfg']['GridEditing']) {
  1927. case 'double-click':
  1928. // trying to reduce generated HTML by using shorter
  1929. // classes like click1 and click2
  1930. $gridEditClass = 'grid_edit click2';
  1931. break;
  1932. case 'click':
  1933. $gridEditClass = 'grid_edit click1';
  1934. break;
  1935. default: // 'disabled'
  1936. $gridEditClass = '';
  1937. break;
  1938. }
  1939. }
  1940. // prepare to get the column order, if available
  1941. [$colOrder, $colVisib] = $this->getColumnParams($analyzedSqlResults);
  1942. // Correction University of Virginia 19991216 in the while below
  1943. // Previous code assumed that all tables have keys, specifically that
  1944. // the phpMyAdmin GUI should support row delete/edit only for such
  1945. // tables.
  1946. // Although always using keys is arguably the prescribed way of
  1947. // defining a relational table, it is not required. This will in
  1948. // particular be violated by the novice.
  1949. // We want to encourage phpMyAdmin usage by such novices. So the code
  1950. // below has been changed to conditionally work as before when the
  1951. // table being displayed has one or more keys; but to display
  1952. // delete/edit options correctly for tables without keys.
  1953. $whereClauseMap = $this->properties['whereClauseMap'];
  1954. while ($row = $dtResult->fetchRow()) {
  1955. // add repeating headers
  1956. if (
  1957. ($rowNumber !== 0) && ($_SESSION['tmpval']['repeat_cells'] > 0)
  1958. && ($rowNumber % $_SESSION['tmpval']['repeat_cells']) === 0
  1959. ) {
  1960. $tableBodyHtml .= $this->getRepeatingHeaders(
  1961. $displayParams['emptypre'],
  1962. $displayParams['desc'],
  1963. $displayParams['emptyafter']
  1964. );
  1965. }
  1966. $trClass = [];
  1967. if ($GLOBALS['cfg']['BrowsePointerEnable'] != true) {
  1968. $trClass[] = 'nopointer';
  1969. }
  1970. if ($GLOBALS['cfg']['BrowseMarkerEnable'] != true) {
  1971. $trClass[] = 'nomarker';
  1972. }
  1973. // pointer code part
  1974. $tableBodyHtml .= '<tr' . ($trClass === [] ? '' : ' class="' . implode(' ', $trClass) . '"') . '>';
  1975. // 1. Prepares the row
  1976. // In print view these variable needs to be initialized
  1977. $deleteUrl = null;
  1978. $deleteString = null;
  1979. $editString = null;
  1980. $jsConf = null;
  1981. $copyUrl = null;
  1982. $copyString = null;
  1983. $editUrl = null;
  1984. $editCopyUrlParams = [];
  1985. $delUrlParams = null;
  1986. // 1.2 Defines the URLs for the modify/delete link(s)
  1987. if (
  1988. ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
  1989. || ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
  1990. ) {
  1991. $expressions = [];
  1992. if (
  1993. isset($analyzedSqlResults['statement'])
  1994. && $analyzedSqlResults['statement'] instanceof SelectStatement
  1995. ) {
  1996. $expressions = $analyzedSqlResults['statement']->expr;
  1997. }
  1998. // Results from a "SELECT" statement -> builds the
  1999. // WHERE clause to use in links (a unique key if possible)
  2000. /**
  2001. * @todo $where_clause could be empty, for example a table
  2002. * with only one field and it's a BLOB; in this case,
  2003. * avoid to display the delete and edit links
  2004. */
  2005. [$whereClause, $clauseIsUnique, $conditionArray] = Util::getUniqueCondition(
  2006. $this->properties['fields_cnt'],
  2007. $this->properties['fields_meta'],
  2008. $row,
  2009. false,
  2010. $this->properties['table'],
  2011. $expressions
  2012. );
  2013. $whereClauseMap[$rowNumber][$this->properties['table']] = $whereClause;
  2014. $this->properties['whereClauseMap'] = $whereClauseMap;
  2015. // 1.2.1 Modify link(s) - update row case
  2016. if ($displayParts['edit_lnk'] === self::UPDATE_ROW) {
  2017. [
  2018. $editUrl,
  2019. $copyUrl,
  2020. $editString,
  2021. $copyString,
  2022. $editCopyUrlParams,
  2023. ] = $this->getModifiedLinks($whereClause, $clauseIsUnique, $urlSqlQuery);
  2024. }
  2025. // 1.2.2 Delete/Kill link(s)
  2026. [$deleteUrl, $deleteString, $jsConf, $delUrlParams] = $this->getDeleteAndKillLinks(
  2027. $whereClause,
  2028. $clauseIsUnique,
  2029. $urlSqlQuery,
  2030. $displayParts['del_lnk'],
  2031. (int) $row[0]
  2032. );
  2033. // 1.3 Displays the links at left if required
  2034. if (
  2035. ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT)
  2036. || ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
  2037. ) {
  2038. $tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
  2039. 'position' => self::POSITION_LEFT,
  2040. 'has_checkbox' => $deleteUrl && $displayParts['del_lnk'] !== self::KILL_PROCESS,
  2041. 'edit' => [
  2042. 'url' => $editUrl,
  2043. 'params' => $editCopyUrlParams + ['default_action' => 'update'],
  2044. 'string' => $editString,
  2045. 'clause_is_unique' => $clauseIsUnique,
  2046. ],
  2047. 'copy' => [
  2048. 'url' => $copyUrl,
  2049. 'params' => $editCopyUrlParams + ['default_action' => 'insert'],
  2050. 'string' => $copyString,
  2051. ],
  2052. 'delete' => ['url' => $deleteUrl, 'params' => $delUrlParams, 'string' => $deleteString],
  2053. 'row_number' => $rowNumber,
  2054. 'where_clause' => $whereClause,
  2055. 'condition' => json_encode($conditionArray),
  2056. 'is_ajax' => ResponseRenderer::getInstance()->isAjax(),
  2057. 'js_conf' => $jsConf ?? '',
  2058. ]);
  2059. } elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
  2060. $tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
  2061. 'position' => self::POSITION_NONE,
  2062. 'has_checkbox' => $deleteUrl && $displayParts['del_lnk'] !== self::KILL_PROCESS,
  2063. 'edit' => [
  2064. 'url' => $editUrl,
  2065. 'params' => $editCopyUrlParams + ['default_action' => 'update'],
  2066. 'string' => $editString,
  2067. 'clause_is_unique' => $clauseIsUnique,
  2068. ],
  2069. 'copy' => [
  2070. 'url' => $copyUrl,
  2071. 'params' => $editCopyUrlParams + ['default_action' => 'insert'],
  2072. 'string' => $copyString,
  2073. ],
  2074. 'delete' => ['url' => $deleteUrl, 'params' => $delUrlParams, 'string' => $deleteString],
  2075. 'row_number' => $rowNumber,
  2076. 'where_clause' => $whereClause,
  2077. 'condition' => json_encode($conditionArray),
  2078. 'is_ajax' => ResponseRenderer::getInstance()->isAjax(),
  2079. 'js_conf' => $jsConf ?? '',
  2080. ]);
  2081. }
  2082. }
  2083. // 2. Displays the rows' values
  2084. if ($this->properties['mime_map'] === null) {
  2085. $this->setMimeMap();
  2086. }
  2087. $tableBodyHtml .= $this->getRowValues(
  2088. $row,
  2089. $rowNumber,
  2090. $colOrder,
  2091. $map,
  2092. $gridEditClass,
  2093. $colVisib,
  2094. $urlSqlQuery,
  2095. $analyzedSqlResults
  2096. );
  2097. // 3. Displays the modify/delete links on the right if required
  2098. if (
  2099. ($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE
  2100. || $displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
  2101. && ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_RIGHT
  2102. || $GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
  2103. ) {
  2104. $tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
  2105. 'position' => self::POSITION_RIGHT,
  2106. 'has_checkbox' => $deleteUrl && $displayParts['del_lnk'] !== self::KILL_PROCESS,
  2107. 'edit' => [
  2108. 'url' => $editUrl,
  2109. 'params' => $editCopyUrlParams + ['default_action' => 'update'],
  2110. 'string' => $editString,
  2111. 'clause_is_unique' => $clauseIsUnique ?? true,
  2112. ],
  2113. 'copy' => [
  2114. 'url' => $copyUrl,
  2115. 'params' => $editCopyUrlParams + ['default_action' => 'insert'],
  2116. 'string' => $copyString,
  2117. ],
  2118. 'delete' => ['url' => $deleteUrl, 'params' => $delUrlParams, 'string' => $deleteString],
  2119. 'row_number' => $rowNumber,
  2120. 'where_clause' => $whereClause ?? '',
  2121. 'condition' => json_encode($conditionArray ?? []),
  2122. 'is_ajax' => ResponseRenderer::getInstance()->isAjax(),
  2123. 'js_conf' => $jsConf ?? '',
  2124. ]);
  2125. }
  2126. $tableBodyHtml .= '</tr>';
  2127. $tableBodyHtml .= "\n";
  2128. $rowNumber++;
  2129. }
  2130. return $tableBodyHtml;
  2131. }
  2132. /**
  2133. * Sets the MIME details of the columns in the results set
  2134. */
  2135. private function setMimeMap(): void
  2136. {
  2137. $fieldsMeta = $this->properties['fields_meta'];
  2138. $mediaTypeMap = [];
  2139. $added = [];
  2140. $relationParameters = $this->relation->getRelationParameters();
  2141. for ($currentColumn = 0; $currentColumn < $this->properties['fields_cnt']; ++$currentColumn) {
  2142. $meta = $fieldsMeta[$currentColumn];
  2143. $orgFullTableName = $this->properties['db'] . '.' . $meta->orgtable;
  2144. if (
  2145. $relationParameters->columnCommentsFeature === null
  2146. || $relationParameters->browserTransformationFeature === null
  2147. || ! $GLOBALS['cfg']['BrowseMIME']
  2148. || $_SESSION['tmpval']['hide_transformation']
  2149. || ! empty($added[$orgFullTableName])
  2150. ) {
  2151. continue;
  2152. }
  2153. $mediaTypeMap = array_merge(
  2154. $mediaTypeMap,
  2155. $this->transformations->getMime($this->properties['db'], $meta->orgtable, false, true) ?? []
  2156. );
  2157. $added[$orgFullTableName] = true;
  2158. }
  2159. // special browser transformation for some SHOW statements
  2160. if ($this->properties['is_show'] && ! $_SESSION['tmpval']['hide_transformation']) {
  2161. preg_match(
  2162. '@^SHOW[[:space:]]+(VARIABLES|(FULL[[:space:]]+)?'
  2163. . 'PROCESSLIST|STATUS|TABLE|GRANTS|CREATE|LOGS|DATABASES|FIELDS'
  2164. . ')@i',
  2165. $this->properties['sql_query'],
  2166. $which
  2167. );
  2168. if (isset($which[1])) {
  2169. $str = ' ' . strtoupper($which[1]);
  2170. $isShowProcessList = strpos($str, 'PROCESSLIST') > 0;
  2171. if ($isShowProcessList) {
  2172. $mediaTypeMap['..Info'] = [
  2173. 'mimetype' => 'Text_Plain',
  2174. 'transformation' => 'output/Text_Plain_Sql.php',
  2175. ];
  2176. }
  2177. $isShowCreateTable = preg_match('@CREATE[[:space:]]+TABLE@i', $this->properties['sql_query']);
  2178. if ($isShowCreateTable) {
  2179. $mediaTypeMap['..Create Table'] = [
  2180. 'mimetype' => 'Text_Plain',
  2181. 'transformation' => 'output/Text_Plain_Sql.php',
  2182. ];
  2183. }
  2184. }
  2185. }
  2186. $this->properties['mime_map'] = $mediaTypeMap;
  2187. }
  2188. /**
  2189. * Get the values for one data row
  2190. *
  2191. * @see getTableBody()
  2192. *
  2193. * @param array $row current row data
  2194. * @param int $rowNumber the index of current row
  2195. * @param array|false $colOrder the column order false when
  2196. * a property not found false
  2197. * when a property not found
  2198. * @param array<string, string[]> $map the list of relations
  2199. * @param string $gridEditClass the class for all editable
  2200. * columns
  2201. * @param bool|array|string $colVisib column is visible(false);
  2202. * column isn't visible(string
  2203. * array)
  2204. * @param string $urlSqlQuery the analyzed sql query
  2205. * @param array $analyzedSqlResults analyzed sql results
  2206. *
  2207. * @return string html content
  2208. */
  2209. private function getRowValues(
  2210. array $row,
  2211. $rowNumber,
  2212. $colOrder,
  2213. array $map,
  2214. $gridEditClass,
  2215. $colVisib,
  2216. $urlSqlQuery,
  2217. array $analyzedSqlResults
  2218. ) {
  2219. $rowValuesHtml = '';
  2220. // Following variable are needed for use in isset/empty or
  2221. // use with array indexes/safe use in foreach
  2222. $sqlQuery = $this->properties['sql_query'];
  2223. $fieldsMeta = $this->properties['fields_meta'];
  2224. $highlightColumns = $this->properties['highlight_columns'];
  2225. $mediaTypeMap = $this->properties['mime_map'];
  2226. $rowInfo = $this->getRowInfoForSpecialLinks($row, $colOrder);
  2227. $whereClauseMap = $this->properties['whereClauseMap'];
  2228. $columnCount = $this->properties['fields_cnt'];
  2229. // Load SpecialSchemaLinks for all rows
  2230. $specialSchemaLinks = SpecialSchemaLinks::get();
  2231. $relationParameters = $this->relation->getRelationParameters();
  2232. for ($currentColumn = 0; $currentColumn < $columnCount; ++$currentColumn) {
  2233. // assign $i with appropriate column order
  2234. $i = is_array($colOrder) ? $colOrder[$currentColumn] : $currentColumn;
  2235. $meta = $fieldsMeta[$i];
  2236. $orgFullColName = $this->properties['db'] . '.' . $meta->orgtable . '.' . $meta->orgname;
  2237. $notNullClass = $meta->isNotNull() ? 'not_null' : '';
  2238. $relationClass = isset($map[$meta->name]) ? 'relation' : '';
  2239. $hideClass = is_array($colVisib) && isset($colVisib[$currentColumn]) && ! $colVisib[$currentColumn]
  2240. ? 'hide'
  2241. : '';
  2242. $gridEdit = $meta->orgtable != '' ? $gridEditClass : '';
  2243. // handle datetime-related class, for grid editing
  2244. $fieldTypeClass = $this->getClassForDateTimeRelatedFields($meta);
  2245. // combine all the classes applicable to this column's value
  2246. $class = implode(' ', array_filter([
  2247. 'data',
  2248. $gridEdit,
  2249. $notNullClass,
  2250. $relationClass,
  2251. $hideClass,
  2252. $fieldTypeClass,
  2253. ]));
  2254. // See if this column should get highlight because it's used in the
  2255. // where-query.
  2256. $conditionField = isset($highlightColumns)
  2257. && (isset($highlightColumns[$meta->name])
  2258. || isset($highlightColumns[Util::backquote($meta->name)]));
  2259. // Wrap MIME-transformations. [MIME]
  2260. $transformationPlugin = null;
  2261. $transformOptions = [];
  2262. if ($relationParameters->browserTransformationFeature !== null && $GLOBALS['cfg']['BrowseMIME']) {
  2263. if (
  2264. isset($mediaTypeMap[$orgFullColName]['mimetype'])
  2265. && ! empty($mediaTypeMap[$orgFullColName]['transformation'])
  2266. ) {
  2267. $file = $mediaTypeMap[$orgFullColName]['transformation'];
  2268. $includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
  2269. if (@file_exists(ROOT_PATH . $includeFile)) {
  2270. $className = $this->transformations->getClassName($includeFile);
  2271. if (class_exists($className)) {
  2272. $plugin = new $className();
  2273. if ($plugin instanceof TransformationsPlugin) {
  2274. $transformationPlugin = $plugin;
  2275. $transformOptions = $this->transformations->getOptions(
  2276. $mediaTypeMap[$orgFullColName]['transformation_options'] ?? ''
  2277. );
  2278. $meta->internalMediaType = str_replace(
  2279. '_',
  2280. '/',
  2281. $mediaTypeMap[$orgFullColName]['mimetype']
  2282. );
  2283. }
  2284. }
  2285. }
  2286. }
  2287. }
  2288. // Check whether the field needs to display with syntax highlighting
  2289. $dbLower = mb_strtolower($this->properties['db']);
  2290. $tblLower = mb_strtolower($meta->orgtable);
  2291. $nameLower = mb_strtolower($meta->orgname);
  2292. if (
  2293. ! empty($this->transformationInfo[$dbLower][$tblLower][$nameLower])
  2294. && isset($row[$i])
  2295. && (trim($row[$i]) != '')
  2296. && ! $_SESSION['tmpval']['hide_transformation']
  2297. ) {
  2298. /** @psalm-suppress UnresolvableInclude */
  2299. include_once ROOT_PATH . $this->transformationInfo[$dbLower][$tblLower][$nameLower][0];
  2300. $plugin = new $this->transformationInfo[$dbLower][$tblLower][$nameLower][1]();
  2301. if ($plugin instanceof TransformationsPlugin) {
  2302. $transformationPlugin = $plugin;
  2303. $transformOptions = $this->transformations->getOptions(
  2304. $mediaTypeMap[$orgFullColName]['transformation_options'] ?? ''
  2305. );
  2306. $orgTable = mb_strtolower($meta->orgtable);
  2307. $orgName = mb_strtolower($meta->orgname);
  2308. $meta->internalMediaType = str_replace(
  2309. '_',
  2310. '/',
  2311. $this->transformationInfo[$dbLower][$orgTable][$orgName][2]
  2312. );
  2313. }
  2314. }
  2315. // Check for the predefined fields need to show as link in schemas
  2316. if (! empty($specialSchemaLinks[$dbLower][$tblLower][$nameLower])) {
  2317. $linkingUrl = $this->getSpecialLinkUrl(
  2318. $specialSchemaLinks[$dbLower][$tblLower][$nameLower],
  2319. $row[$i],
  2320. $rowInfo
  2321. );
  2322. $transformationPlugin = new Text_Plain_Link();
  2323. $transformOptions = [
  2324. 0 => $linkingUrl,
  2325. 2 => true,
  2326. ];
  2327. $meta->internalMediaType = str_replace('_', '/', 'Text/Plain');
  2328. }
  2329. $expressions = [];
  2330. if (
  2331. isset($analyzedSqlResults['statement'])
  2332. && $analyzedSqlResults['statement'] instanceof SelectStatement
  2333. ) {
  2334. $expressions = $analyzedSqlResults['statement']->expr;
  2335. }
  2336. /**
  2337. * The result set can have columns from more than one table,
  2338. * this is why we have to check for the unique conditions
  2339. * related to this table; however getUniqueCondition() is
  2340. * costly and does not need to be called if we already know
  2341. * the conditions for the current table.
  2342. */
  2343. if (! isset($whereClauseMap[$rowNumber][$meta->orgtable])) {
  2344. $uniqueConditions = Util::getUniqueCondition(
  2345. $this->properties['fields_cnt'],
  2346. $this->properties['fields_meta'],
  2347. $row,
  2348. false,
  2349. $meta->orgtable,
  2350. $expressions
  2351. );
  2352. $whereClauseMap[$rowNumber][$meta->orgtable] = $uniqueConditions[0];
  2353. }
  2354. $urlParams = [
  2355. 'db' => $this->properties['db'],
  2356. 'table' => $meta->orgtable,
  2357. 'where_clause_sign' => Core::signSqlQuery($whereClauseMap[$rowNumber][$meta->orgtable]),
  2358. 'where_clause' => $whereClauseMap[$rowNumber][$meta->orgtable],
  2359. 'transform_key' => $meta->orgname,
  2360. ];
  2361. if ($sqlQuery !== '') {
  2362. $urlParams['sql_query'] = $urlSqlQuery;
  2363. }
  2364. $transformOptions['wrapper_link'] = Url::getCommon($urlParams);
  2365. $transformOptions['wrapper_params'] = $urlParams;
  2366. $displayParams = $this->properties['display_params'] ?? [];
  2367. if ($meta->isNumeric) {
  2368. // n u m e r i c
  2369. $displayParams['data'][$rowNumber][$i] = $this->getDataCellForNumericColumns(
  2370. $row[$i] === null ? null : (string) $row[$i],
  2371. 'text-end ' . $class,
  2372. $conditionField,
  2373. $meta,
  2374. $map,
  2375. $analyzedSqlResults,
  2376. $transformationPlugin,
  2377. $transformOptions
  2378. );
  2379. } elseif ($meta->isMappedTypeGeometry) {
  2380. // g e o m e t r y
  2381. // Remove 'grid_edit' from $class as we do not allow to
  2382. // inline-edit geometry data.
  2383. $class = str_replace('grid_edit', '', $class);
  2384. $displayParams['data'][$rowNumber][$i] = $this->getDataCellForGeometryColumns(
  2385. $row[$i] === null ? null : (string) $row[$i],
  2386. $class,
  2387. $meta,
  2388. $map,
  2389. $urlParams,
  2390. $conditionField,
  2391. $transformationPlugin,
  2392. $transformOptions,
  2393. $analyzedSqlResults
  2394. );
  2395. } else {
  2396. // n o t n u m e r i c
  2397. $displayParams['data'][$rowNumber][$i] = $this->getDataCellForNonNumericColumns(
  2398. $row[$i] === null ? null : (string) $row[$i],
  2399. $class,
  2400. $meta,
  2401. $map,
  2402. $urlParams,
  2403. $conditionField,
  2404. $transformationPlugin,
  2405. $transformOptions,
  2406. $analyzedSqlResults
  2407. );
  2408. }
  2409. // output stored cell
  2410. $rowValuesHtml .= $displayParams['data'][$rowNumber][$i];
  2411. if (isset($displayParams['rowdata'][$i][$rowNumber])) {
  2412. $displayParams['rowdata'][$i][$rowNumber] .= $displayParams['data'][$rowNumber][$i];
  2413. } else {
  2414. $displayParams['rowdata'][$i][$rowNumber] = $displayParams['data'][$rowNumber][$i];
  2415. }
  2416. $this->properties['display_params'] = $displayParams;
  2417. }
  2418. return $rowValuesHtml;
  2419. }
  2420. /**
  2421. * Get link for display special schema links
  2422. *
  2423. * @param array<string,array<int,array<string,string>>|string> $linkRelations
  2424. * @param string $columnValue column value
  2425. * @param array $rowInfo information about row
  2426. * @phpstan-param array{
  2427. * 'link_param': string,
  2428. * 'link_dependancy_params'?: array<
  2429. * int,
  2430. * array{'param_info': string, 'column_name': string}
  2431. * >,
  2432. * 'default_page': string
  2433. * } $linkRelations
  2434. *
  2435. * @return string generated link
  2436. */
  2437. private function getSpecialLinkUrl(
  2438. array $linkRelations,
  2439. $columnValue,
  2440. array $rowInfo
  2441. ) {
  2442. $linkingUrlParams = [];
  2443. $linkingUrlParams[$linkRelations['link_param']] = $columnValue;
  2444. $divider = strpos($linkRelations['default_page'], '?') ? '&' : '?';
  2445. if (empty($linkRelations['link_dependancy_params'])) {
  2446. return $linkRelations['default_page']
  2447. . Url::getCommonRaw($linkingUrlParams, $divider);
  2448. }
  2449. foreach ($linkRelations['link_dependancy_params'] as $new_param) {
  2450. $columnName = mb_strtolower($new_param['column_name']);
  2451. // If there is a value for this column name in the rowInfo provided
  2452. if (isset($rowInfo[$columnName])) {
  2453. $linkingUrlParams[$new_param['param_info']] = $rowInfo[$columnName];
  2454. }
  2455. // Special case 1 - when executing routines, according
  2456. // to the type of the routine, url param changes
  2457. if (empty($rowInfo['routine_type'])) {
  2458. continue;
  2459. }
  2460. }
  2461. return $linkRelations['default_page']
  2462. . Url::getCommonRaw($linkingUrlParams, $divider);
  2463. }
  2464. /**
  2465. * Prepare row information for display special links
  2466. *
  2467. * @param array $row current row data
  2468. * @param array|bool $colOrder the column order
  2469. *
  2470. * @return array<string, mixed> associative array with column nama -> value
  2471. */
  2472. private function getRowInfoForSpecialLinks(array $row, $colOrder): array
  2473. {
  2474. $rowInfo = [];
  2475. $fieldsMeta = $this->properties['fields_meta'];
  2476. for ($n = 0; $n < $this->properties['fields_cnt']; ++$n) {
  2477. $m = is_array($colOrder) ? $colOrder[$n] : $n;
  2478. $rowInfo[mb_strtolower($fieldsMeta[$m]->orgname)] = $row[$m];
  2479. }
  2480. return $rowInfo;
  2481. }
  2482. /**
  2483. * Get url sql query without conditions to shorten URLs
  2484. *
  2485. * @see getTableBody()
  2486. *
  2487. * @param array $analyzedSqlResults analyzed sql results
  2488. *
  2489. * @return string analyzed sql query
  2490. */
  2491. private function getUrlSqlQuery(array $analyzedSqlResults)
  2492. {
  2493. if (($analyzedSqlResults['querytype'] !== 'SELECT') || (mb_strlen($this->properties['sql_query']) < 200)) {
  2494. return $this->properties['sql_query'];
  2495. }
  2496. $query = 'SELECT ' . Query::getClause(
  2497. $analyzedSqlResults['statement'],
  2498. $analyzedSqlResults['parser']->list,
  2499. 'SELECT'
  2500. );
  2501. $fromClause = Query::getClause($analyzedSqlResults['statement'], $analyzedSqlResults['parser']->list, 'FROM');
  2502. if ($fromClause !== '') {
  2503. $query .= ' FROM ' . $fromClause;
  2504. }
  2505. return $query;
  2506. }
  2507. /**
  2508. * Get column order and column visibility
  2509. *
  2510. * @see getTableBody()
  2511. *
  2512. * @param array $analyzedSqlResults analyzed sql results
  2513. *
  2514. * @return mixed[] 2 element array - $col_order, $col_visib
  2515. */
  2516. private function getColumnParams(array $analyzedSqlResults): array
  2517. {
  2518. if ($this->isSelect($analyzedSqlResults)) {
  2519. $pmatable = new Table($this->properties['table'], $this->properties['db']);
  2520. $colOrder = $pmatable->getUiProp(Table::PROP_COLUMN_ORDER);
  2521. $fieldsCount = $this->properties['fields_cnt'];
  2522. /* Validate the value */
  2523. if (is_array($colOrder)) {
  2524. foreach ($colOrder as $value) {
  2525. if ($value < $fieldsCount) {
  2526. continue;
  2527. }
  2528. $pmatable->removeUiProp(Table::PROP_COLUMN_ORDER);
  2529. break;
  2530. }
  2531. if ($fieldsCount !== count($colOrder)) {
  2532. $pmatable->removeUiProp(Table::PROP_COLUMN_ORDER);
  2533. $colOrder = false;
  2534. }
  2535. }
  2536. $colVisib = $pmatable->getUiProp(Table::PROP_COLUMN_VISIB);
  2537. if (is_array($colVisib) && $fieldsCount !== count($colVisib)) {
  2538. $pmatable->removeUiProp(Table::PROP_COLUMN_VISIB);
  2539. $colVisib = false;
  2540. }
  2541. } else {
  2542. $colOrder = false;
  2543. $colVisib = false;
  2544. }
  2545. return [
  2546. $colOrder,
  2547. $colVisib,
  2548. ];
  2549. }
  2550. /**
  2551. * Get HTML for repeating headers
  2552. *
  2553. * @see getTableBody()
  2554. *
  2555. * @param int $numEmptyColumnsBefore The number of blank columns before this one
  2556. * @param string[] $descriptions A list of descriptions
  2557. * @param int $numEmptyColumnsAfter The number of blank columns after this one
  2558. *
  2559. * @return string html content
  2560. */
  2561. private function getRepeatingHeaders(
  2562. int $numEmptyColumnsBefore,
  2563. array $descriptions,
  2564. int $numEmptyColumnsAfter
  2565. ): string {
  2566. $headerHtml = '<tr class="repeating_header_row">' . "\n";
  2567. if ($numEmptyColumnsBefore > 0) {
  2568. $headerHtml .= ' <th colspan="'
  2569. . $numEmptyColumnsBefore . '">'
  2570. . "\n" . ' &nbsp;</th>' . "\n";
  2571. } elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
  2572. $headerHtml .= ' <th></th>' . "\n";
  2573. }
  2574. $headerHtml .= implode($descriptions);
  2575. if ($numEmptyColumnsAfter > 0) {
  2576. $headerHtml .= ' <th colspan="' . $numEmptyColumnsAfter
  2577. . '">'
  2578. . "\n" . ' &nbsp;</th>' . "\n";
  2579. }
  2580. $headerHtml .= '</tr>' . "\n";
  2581. return $headerHtml;
  2582. }
  2583. /**
  2584. * Get modified links
  2585. *
  2586. * @see getTableBody()
  2587. *
  2588. * @param string $whereClause the where clause of the sql
  2589. * @param bool $clauseIsUnique the unique condition of clause
  2590. * @param string $urlSqlQuery the analyzed sql query
  2591. *
  2592. * @return array<int,string|array<string, bool|string>>
  2593. */
  2594. private function getModifiedLinks(
  2595. $whereClause,
  2596. $clauseIsUnique,
  2597. $urlSqlQuery
  2598. ) {
  2599. $urlParams = [
  2600. 'db' => $this->properties['db'],
  2601. 'table' => $this->properties['table'],
  2602. 'where_clause' => $whereClause,
  2603. 'where_clause_signature' => Core::signSqlQuery($whereClause),
  2604. 'clause_is_unique' => $clauseIsUnique,
  2605. 'sql_query' => $urlSqlQuery,
  2606. 'sql_signature' => Core::signSqlQuery($urlSqlQuery),
  2607. 'goto' => Url::getFromRoute('/sql'),
  2608. ];
  2609. $editUrl = Url::getFromRoute('/table/change');
  2610. $copyUrl = Url::getFromRoute('/table/change');
  2611. $editStr = $this->getActionLinkContent(
  2612. 'b_edit',
  2613. __('Edit')
  2614. );
  2615. $copyStr = $this->getActionLinkContent(
  2616. 'b_insrow',
  2617. __('Copy')
  2618. );
  2619. return [
  2620. $editUrl,
  2621. $copyUrl,
  2622. $editStr,
  2623. $copyStr,
  2624. $urlParams,
  2625. ];
  2626. }
  2627. /**
  2628. * Get delete and kill links
  2629. *
  2630. * @see getTableBody()
  2631. *
  2632. * @param string $whereClause the where clause of the sql
  2633. * @param bool $clauseIsUnique the unique condition of clause
  2634. * @param string $urlSqlQuery the analyzed sql query
  2635. * @param string $deleteLink the delete link of current row
  2636. * @param int $processId Process ID
  2637. *
  2638. * @return array $del_url, $del_str, $js_conf
  2639. * @psalm-return array{?string, ?string, ?string}
  2640. */
  2641. private function getDeleteAndKillLinks(
  2642. $whereClause,
  2643. $clauseIsUnique,
  2644. $urlSqlQuery,
  2645. $deleteLink,
  2646. int $processId
  2647. ) {
  2648. $goto = $this->properties['goto'];
  2649. if ($deleteLink === self::DELETE_ROW) { // delete row case
  2650. $urlParams = [
  2651. 'db' => $this->properties['db'],
  2652. 'table' => $this->properties['table'],
  2653. 'sql_query' => $urlSqlQuery,
  2654. 'message_to_show' => __('The row has been deleted.'),
  2655. 'goto' => $goto ?: Url::getFromRoute('/table/sql'),
  2656. ];
  2657. $linkGoto = Url::getFromRoute('/sql', $urlParams);
  2658. $deleteQuery = 'DELETE FROM '
  2659. . Util::backquote($this->properties['table'])
  2660. . ' WHERE ' . $whereClause .
  2661. ($clauseIsUnique ? '' : ' LIMIT 1');
  2662. $urlParams = [
  2663. 'db' => $this->properties['db'],
  2664. 'table' => $this->properties['table'],
  2665. 'sql_query' => $deleteQuery,
  2666. 'message_to_show' => __('The row has been deleted.'),
  2667. 'goto' => $linkGoto,
  2668. ];
  2669. $deleteUrl = Url::getFromRoute('/sql');
  2670. $jsConf = 'DELETE FROM ' . $this->properties['table']
  2671. . ' WHERE ' . $whereClause
  2672. . ($clauseIsUnique ? '' : ' LIMIT 1');
  2673. $deleteString = $this->getActionLinkContent('b_drop', __('Delete'));
  2674. } elseif ($deleteLink === self::KILL_PROCESS) { // kill process case
  2675. $urlParams = [
  2676. 'db' => $this->properties['db'],
  2677. 'table' => $this->properties['table'],
  2678. 'sql_query' => $urlSqlQuery,
  2679. 'goto' => Url::getFromRoute('/'),
  2680. ];
  2681. $linkGoto = Url::getFromRoute('/sql', $urlParams);
  2682. $kill = $this->dbi->getKillQuery($processId);
  2683. $urlParams = [
  2684. 'db' => 'mysql',
  2685. 'sql_query' => $kill,
  2686. 'goto' => $linkGoto,
  2687. ];
  2688. $deleteUrl = Url::getFromRoute('/sql');
  2689. $jsConf = $kill;
  2690. $deleteString = Generator::getIcon(
  2691. 'b_drop',
  2692. __('Kill')
  2693. );
  2694. } else {
  2695. $deleteUrl = $deleteString = $jsConf = $urlParams = null;
  2696. }
  2697. return [
  2698. $deleteUrl,
  2699. $deleteString,
  2700. $jsConf,
  2701. $urlParams,
  2702. ];
  2703. }
  2704. /**
  2705. * Get content inside the table row action links (Edit/Copy/Delete)
  2706. *
  2707. * @see getModifiedLinks(), getDeleteAndKillLinks()
  2708. *
  2709. * @param string $icon The name of the file to get
  2710. * @param string $displayText The text displaying after the image icon
  2711. *
  2712. * @return string
  2713. */
  2714. private function getActionLinkContent($icon, $displayText)
  2715. {
  2716. if (
  2717. isset($GLOBALS['cfg']['RowActionType'])
  2718. && $GLOBALS['cfg']['RowActionType'] === self::ACTION_LINK_CONTENT_ICONS
  2719. ) {
  2720. return '<span class="text-nowrap">'
  2721. . Generator::getImage($icon, $displayText)
  2722. . '</span>';
  2723. }
  2724. if (
  2725. isset($GLOBALS['cfg']['RowActionType'])
  2726. && $GLOBALS['cfg']['RowActionType'] === self::ACTION_LINK_CONTENT_TEXT
  2727. ) {
  2728. return '<span class="text-nowrap">' . $displayText . '</span>';
  2729. }
  2730. return Generator::getIcon($icon, $displayText);
  2731. }
  2732. /**
  2733. * Get class for datetime related fields
  2734. *
  2735. * @see getTableBody()
  2736. *
  2737. * @param FieldMetadata $meta the type of the column field
  2738. *
  2739. * @return string the class for the column
  2740. */
  2741. private function getClassForDateTimeRelatedFields(FieldMetadata $meta): string
  2742. {
  2743. $fieldTypeClass = '';
  2744. if ($meta->isMappedTypeTimestamp || $meta->isType(FieldMetadata::TYPE_DATETIME)) {
  2745. $fieldTypeClass = 'datetimefield';
  2746. } elseif ($meta->isType(FieldMetadata::TYPE_DATE)) {
  2747. $fieldTypeClass = 'datefield';
  2748. } elseif ($meta->isType(FieldMetadata::TYPE_TIME)) {
  2749. $fieldTypeClass = 'timefield';
  2750. } elseif ($meta->isType(FieldMetadata::TYPE_STRING)) {
  2751. $fieldTypeClass = 'text';
  2752. }
  2753. return $fieldTypeClass;
  2754. }
  2755. /**
  2756. * Prepare data cell for numeric type fields
  2757. *
  2758. * @see getTableBody()
  2759. *
  2760. * @param string|null $column the column's value
  2761. * @param string $class the html class for column
  2762. * @param bool $conditionField the column should highlighted or not
  2763. * @param FieldMetadata $meta the meta-information about this field
  2764. * @param array<string, string[]> $map the list of relations
  2765. * @param array $analyzedSqlResults the analyzed query
  2766. * @param array $transformOptions the transformation parameters
  2767. *
  2768. * @return string the prepared cell, html content
  2769. */
  2770. private function getDataCellForNumericColumns(
  2771. ?string $column,
  2772. string $class,
  2773. bool $conditionField,
  2774. FieldMetadata $meta,
  2775. array $map,
  2776. array $analyzedSqlResults,
  2777. ?TransformationsPlugin $transformationPlugin,
  2778. array $transformOptions
  2779. ) {
  2780. if ($column === null) {
  2781. return $this->buildNullDisplay($class, $conditionField, $meta);
  2782. }
  2783. if ($column === '') {
  2784. return $this->buildEmptyDisplay($class, $conditionField, $meta);
  2785. }
  2786. $whereComparison = ' = ' . $column;
  2787. return $this->getRowData(
  2788. $class,
  2789. $conditionField,
  2790. $analyzedSqlResults,
  2791. $meta,
  2792. $map,
  2793. $column,
  2794. $column,
  2795. $transformationPlugin,
  2796. 'text-nowrap',
  2797. $whereComparison,
  2798. $transformOptions
  2799. );
  2800. }
  2801. /**
  2802. * Get data cell for geometry type fields
  2803. *
  2804. * @see getTableBody()
  2805. *
  2806. * @param string|null $column the relevant column in data row
  2807. * @param string $class the html class for column
  2808. * @param FieldMetadata $meta the meta-information about this field
  2809. * @param array<string, string[]> $map the list of relations
  2810. * @param array $urlParams the parameters for generate url
  2811. * @param bool $conditionField the column should highlighted or not
  2812. * @param array $transformOptions the transformation parameters
  2813. * @param array $analyzedSqlResults the analyzed query
  2814. *
  2815. * @return string the prepared data cell, html content
  2816. */
  2817. private function getDataCellForGeometryColumns(
  2818. ?string $column,
  2819. string $class,
  2820. FieldMetadata $meta,
  2821. array $map,
  2822. array $urlParams,
  2823. bool $conditionField,
  2824. ?TransformationsPlugin $transformationPlugin,
  2825. $transformOptions,
  2826. array $analyzedSqlResults
  2827. ) {
  2828. if ($column === null) {
  2829. return $this->buildNullDisplay($class, $conditionField, $meta);
  2830. }
  2831. if ($column === '') {
  2832. return $this->buildEmptyDisplay($class, $conditionField, $meta);
  2833. }
  2834. // Display as [GEOMETRY - (size)]
  2835. if ($_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_GEOM) {
  2836. $geometryText = $this->handleNonPrintableContents(
  2837. 'GEOMETRY',
  2838. $column,
  2839. $transformationPlugin,
  2840. $transformOptions,
  2841. $meta,
  2842. $urlParams
  2843. );
  2844. return $this->buildValueDisplay($class, $conditionField, $geometryText);
  2845. }
  2846. if ($_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_WKT) {
  2847. // Prepare in Well Known Text(WKT) format.
  2848. $whereComparison = ' = ' . $column;
  2849. // Convert to WKT format
  2850. $wktval = Gis::convertToWellKnownText($column);
  2851. [
  2852. $isFieldTruncated,
  2853. $displayedColumn,
  2854. // skip 3rd param
  2855. ] = $this->getPartialText($wktval);
  2856. return $this->getRowData(
  2857. $class,
  2858. $conditionField,
  2859. $analyzedSqlResults,
  2860. $meta,
  2861. $map,
  2862. $wktval,
  2863. $displayedColumn,
  2864. $transformationPlugin,
  2865. '',
  2866. $whereComparison,
  2867. $transformOptions,
  2868. $isFieldTruncated
  2869. );
  2870. }
  2871. // Prepare in Well Known Binary (WKB) format.
  2872. if ($_SESSION['tmpval']['display_binary']) {
  2873. $whereComparison = ' = ' . $column;
  2874. $wkbval = substr(bin2hex($column), 8);
  2875. [
  2876. $isFieldTruncated,
  2877. $displayedColumn,
  2878. // skip 3rd param
  2879. ] = $this->getPartialText($wkbval);
  2880. return $this->getRowData(
  2881. $class,
  2882. $conditionField,
  2883. $analyzedSqlResults,
  2884. $meta,
  2885. $map,
  2886. $wkbval,
  2887. $displayedColumn,
  2888. $transformationPlugin,
  2889. '',
  2890. $whereComparison,
  2891. $transformOptions,
  2892. $isFieldTruncated
  2893. );
  2894. }
  2895. $wkbval = $this->handleNonPrintableContents(
  2896. 'BINARY',
  2897. $column,
  2898. $transformationPlugin,
  2899. $transformOptions,
  2900. $meta,
  2901. $urlParams
  2902. );
  2903. return $this->buildValueDisplay($class, $conditionField, $wkbval);
  2904. }
  2905. /**
  2906. * Get data cell for non numeric type fields
  2907. *
  2908. * @see getTableBody()
  2909. *
  2910. * @param string|null $column the relevant column in data row
  2911. * @param string $class the html class for column
  2912. * @param FieldMetadata $meta the meta-information about the field
  2913. * @param array<string, string[]> $map the list of relations
  2914. * @param array $urlParams the parameters for generate url
  2915. * @param bool $conditionField the column should highlighted or not
  2916. * @param array $transformOptions the transformation parameters
  2917. * @param array $analyzedSqlResults the analyzed query
  2918. *
  2919. * @return string the prepared data cell, html content
  2920. */
  2921. private function getDataCellForNonNumericColumns(
  2922. ?string $column,
  2923. string $class,
  2924. FieldMetadata $meta,
  2925. array $map,
  2926. array $urlParams,
  2927. bool $conditionField,
  2928. ?TransformationsPlugin $transformationPlugin,
  2929. $transformOptions,
  2930. array $analyzedSqlResults
  2931. ) {
  2932. $originalLength = 0;
  2933. $isAnalyse = $this->properties['is_analyse'];
  2934. $bIsText = $transformationPlugin !== null && ! str_contains($transformationPlugin->getMIMEType(), 'Text');
  2935. // disable inline grid editing
  2936. // if binary fields are protected
  2937. // or transformation plugin is of non text type
  2938. // such as image
  2939. $isTypeBlob = $meta->isType(FieldMetadata::TYPE_BLOB);
  2940. $cfgProtectBinary = $GLOBALS['cfg']['ProtectBinary'];
  2941. if (
  2942. ($meta->isBinary()
  2943. && (
  2944. $cfgProtectBinary === 'all'
  2945. || ($cfgProtectBinary === 'noblob' && ! $isTypeBlob)
  2946. || ($cfgProtectBinary === 'blob' && $isTypeBlob)
  2947. )
  2948. ) || $bIsText
  2949. ) {
  2950. $class = str_replace('grid_edit', '', $class);
  2951. }
  2952. if ($column === null) {
  2953. return $this->buildNullDisplay($class, $conditionField, $meta);
  2954. }
  2955. if ($column === '') {
  2956. return $this->buildEmptyDisplay($class, $conditionField, $meta);
  2957. }
  2958. // Cut all fields to $GLOBALS['cfg']['LimitChars']
  2959. // (unless it's a link-type transformation or binary)
  2960. $originalDataForWhereClause = $column;
  2961. $displayedColumn = $column;
  2962. $isFieldTruncated = false;
  2963. if (
  2964. ! ($transformationPlugin !== null
  2965. && str_contains($transformationPlugin->getName(), 'Link'))
  2966. && ! $meta->isBinary()
  2967. ) {
  2968. [
  2969. $isFieldTruncated,
  2970. $column,
  2971. $originalLength,
  2972. ] = $this->getPartialText($column);
  2973. }
  2974. if ($meta->isMappedTypeBit) {
  2975. $displayedColumn = Util::printableBitValue((int) $displayedColumn, (int) $meta->length);
  2976. // some results of PROCEDURE ANALYSE() are reported as
  2977. // being BINARY but they are quite readable,
  2978. // so don't treat them as BINARY
  2979. } elseif ($meta->isBinary() && $isAnalyse !== true) {
  2980. // we show the BINARY or BLOB message and field's size
  2981. // (or maybe use a transformation)
  2982. $binaryOrBlob = 'BLOB';
  2983. if ($meta->isType(FieldMetadata::TYPE_STRING)) {
  2984. $binaryOrBlob = 'BINARY';
  2985. }
  2986. $displayedColumn = $this->handleNonPrintableContents(
  2987. $binaryOrBlob,
  2988. $displayedColumn,
  2989. $transformationPlugin,
  2990. $transformOptions,
  2991. $meta,
  2992. $urlParams,
  2993. $isFieldTruncated
  2994. );
  2995. $class = $this->addClass(
  2996. $class,
  2997. $conditionField,
  2998. $meta,
  2999. '',
  3000. $isFieldTruncated,
  3001. $transformationPlugin !== null
  3002. );
  3003. $result = strip_tags($column);
  3004. // disable inline grid editing
  3005. // if binary or blob data is not shown
  3006. if (stripos($result, $binaryOrBlob) !== false) {
  3007. $class = str_replace('grid_edit', '', $class);
  3008. }
  3009. return $this->buildValueDisplay($class, $conditionField, $displayedColumn);
  3010. }
  3011. // transform functions may enable no-wrapping:
  3012. $boolNoWrap = $transformationPlugin !== null
  3013. && $transformationPlugin->applyTransformationNoWrap($transformOptions);
  3014. // do not wrap if date field type or if no-wrapping enabled by transform functions
  3015. // otherwise, preserve whitespaces and wrap
  3016. $nowrap = $meta->isDateTimeType() || $boolNoWrap ? 'text-nowrap' : 'pre_wrap';
  3017. $whereComparison = ' = \''
  3018. . $this->dbi->escapeString($originalDataForWhereClause)
  3019. . '\'';
  3020. return $this->getRowData(
  3021. $class,
  3022. $conditionField,
  3023. $analyzedSqlResults,
  3024. $meta,
  3025. $map,
  3026. $column,
  3027. $displayedColumn,
  3028. $transformationPlugin,
  3029. $nowrap,
  3030. $whereComparison,
  3031. $transformOptions,
  3032. $isFieldTruncated,
  3033. (string) $originalLength
  3034. );
  3035. }
  3036. /**
  3037. * Checks the posted options for viewing query results
  3038. * and sets appropriate values in the session.
  3039. *
  3040. * @param array $analyzedSqlResults the analyzed query results
  3041. *
  3042. * @todo make maximum remembered queries configurable
  3043. * @todo move/split into SQL class!?
  3044. * @todo currently this is called twice unnecessary
  3045. * @todo ignore LIMIT and ORDER in query!?
  3046. */
  3047. public function setConfigParamsForDisplayTable(array $analyzedSqlResults): void
  3048. {
  3049. $sqlMd5 = md5($this->properties['server'] . $this->properties['db'] . $this->properties['sql_query']);
  3050. $query = [];
  3051. if (isset($_SESSION['tmpval']['query'][$sqlMd5])) {
  3052. $query = $_SESSION['tmpval']['query'][$sqlMd5];
  3053. }
  3054. $query['sql'] = $this->properties['sql_query'];
  3055. if (empty($query['repeat_cells'])) {
  3056. $query['repeat_cells'] = $GLOBALS['cfg']['RepeatCells'];
  3057. }
  3058. // The value can also be from _GET as described on issue #16146 when sorting results
  3059. $sessionMaxRows = $_GET['session_max_rows'] ?? $_POST['session_max_rows'] ?? '';
  3060. if (isset($sessionMaxRows) && is_numeric($sessionMaxRows)) {
  3061. $query['max_rows'] = (int) $sessionMaxRows;
  3062. unset($_GET['session_max_rows'], $_POST['session_max_rows']);
  3063. } elseif ($sessionMaxRows === self::ALL_ROWS) {
  3064. $query['max_rows'] = self::ALL_ROWS;
  3065. unset($_GET['session_max_rows'], $_POST['session_max_rows']);
  3066. } elseif (empty($query['max_rows'])) {
  3067. $query['max_rows'] = intval($GLOBALS['cfg']['MaxRows']);
  3068. }
  3069. if (isset($_REQUEST['pos']) && is_numeric($_REQUEST['pos'])) {
  3070. $query['pos'] = (int) $_REQUEST['pos'];
  3071. unset($_REQUEST['pos']);
  3072. } elseif (empty($query['pos'])) {
  3073. $query['pos'] = 0;
  3074. }
  3075. // Full text is needed in case of explain statements, if not specified.
  3076. $fullText = $analyzedSqlResults['is_explain'];
  3077. if (
  3078. isset($_REQUEST['pftext']) && in_array(
  3079. $_REQUEST['pftext'],
  3080. [self::DISPLAY_PARTIAL_TEXT, self::DISPLAY_FULL_TEXT]
  3081. )
  3082. ) {
  3083. $query['pftext'] = $_REQUEST['pftext'];
  3084. unset($_REQUEST['pftext']);
  3085. } elseif ($fullText) {
  3086. $query['pftext'] = self::DISPLAY_FULL_TEXT;
  3087. } elseif (empty($query['pftext'])) {
  3088. $query['pftext'] = self::DISPLAY_PARTIAL_TEXT;
  3089. }
  3090. if (
  3091. isset($_REQUEST['relational_display']) && in_array(
  3092. $_REQUEST['relational_display'],
  3093. [self::RELATIONAL_KEY, self::RELATIONAL_DISPLAY_COLUMN]
  3094. )
  3095. ) {
  3096. $query['relational_display'] = $_REQUEST['relational_display'];
  3097. unset($_REQUEST['relational_display']);
  3098. } elseif (empty($query['relational_display'])) {
  3099. // The current session value has priority over a
  3100. // change via Settings; this change will be apparent
  3101. // starting from the next session
  3102. $query['relational_display'] = $GLOBALS['cfg']['RelationalDisplay'];
  3103. }
  3104. if (
  3105. isset($_REQUEST['geoOption']) && in_array(
  3106. $_REQUEST['geoOption'],
  3107. [self::GEOMETRY_DISP_WKT, self::GEOMETRY_DISP_WKB, self::GEOMETRY_DISP_GEOM]
  3108. )
  3109. ) {
  3110. $query['geoOption'] = $_REQUEST['geoOption'];
  3111. unset($_REQUEST['geoOption']);
  3112. } elseif (empty($query['geoOption'])) {
  3113. $query['geoOption'] = self::GEOMETRY_DISP_GEOM;
  3114. }
  3115. if (isset($_REQUEST['display_binary'])) {
  3116. $query['display_binary'] = true;
  3117. unset($_REQUEST['display_binary']);
  3118. } elseif (isset($_REQUEST['display_options_form'])) {
  3119. // we know that the checkbox was unchecked
  3120. unset($query['display_binary']);
  3121. } elseif (! isset($_REQUEST['full_text_button'])) {
  3122. // selected by default because some operations like OPTIMIZE TABLE
  3123. // and all queries involving functions return "binary" contents,
  3124. // according to low-level field flags
  3125. $query['display_binary'] = true;
  3126. }
  3127. if (isset($_REQUEST['display_blob'])) {
  3128. $query['display_blob'] = true;
  3129. unset($_REQUEST['display_blob']);
  3130. } elseif (isset($_REQUEST['display_options_form'])) {
  3131. // we know that the checkbox was unchecked
  3132. unset($query['display_blob']);
  3133. }
  3134. if (isset($_REQUEST['hide_transformation'])) {
  3135. $query['hide_transformation'] = true;
  3136. unset($_REQUEST['hide_transformation']);
  3137. } elseif (isset($_REQUEST['display_options_form'])) {
  3138. // we know that the checkbox was unchecked
  3139. unset($query['hide_transformation']);
  3140. }
  3141. // move current query to the last position, to be removed last
  3142. // so only least executed query will be removed if maximum remembered
  3143. // queries limit is reached
  3144. unset($_SESSION['tmpval']['query'][$sqlMd5]);
  3145. $_SESSION['tmpval']['query'][$sqlMd5] = $query;
  3146. // do not exceed a maximum number of queries to remember
  3147. if (count($_SESSION['tmpval']['query']) > 10) {
  3148. array_shift($_SESSION['tmpval']['query']);
  3149. //echo 'deleting one element ...';
  3150. }
  3151. // populate query configuration
  3152. $_SESSION['tmpval']['pftext'] = $query['pftext'];
  3153. $_SESSION['tmpval']['relational_display'] = $query['relational_display'];
  3154. $_SESSION['tmpval']['geoOption'] = $query['geoOption'];
  3155. $_SESSION['tmpval']['display_binary'] = isset($query['display_binary']);
  3156. $_SESSION['tmpval']['display_blob'] = isset($query['display_blob']);
  3157. $_SESSION['tmpval']['hide_transformation'] = isset($query['hide_transformation']);
  3158. $_SESSION['tmpval']['pos'] = $query['pos'];
  3159. $_SESSION['tmpval']['max_rows'] = $query['max_rows'];
  3160. $_SESSION['tmpval']['repeat_cells'] = $query['repeat_cells'];
  3161. }
  3162. /**
  3163. * Prepare a table of results returned by a SQL query.
  3164. *
  3165. * @param ResultInterface $dtResult the link id associated to the query
  3166. * which results have to be displayed
  3167. * @param array $displayParts the parts to display
  3168. * @param array $analyzedSqlResults analyzed sql results
  3169. * @param bool $isLimitedDisplay With limited operations or not
  3170. *
  3171. * @return string Generated HTML content for resulted table
  3172. */
  3173. public function getTable(
  3174. ResultInterface $dtResult,
  3175. array &$displayParts,
  3176. array $analyzedSqlResults,
  3177. $isLimitedDisplay = false
  3178. ) {
  3179. // The statement this table is built for.
  3180. if (isset($analyzedSqlResults['statement'])) {
  3181. /** @var SelectStatement $statement */
  3182. $statement = $analyzedSqlResults['statement'];
  3183. } else {
  3184. $statement = null;
  3185. }
  3186. // Following variable are needed for use in isset/empty or
  3187. // use with array indexes/safe use in foreach
  3188. $fieldsMeta = $this->properties['fields_meta'];
  3189. $showTable = $this->properties['showtable'];
  3190. $printView = $this->properties['printview'];
  3191. /**
  3192. * @todo move this to a central place
  3193. * @todo for other future table types
  3194. */
  3195. $isInnodb = (isset($showTable['Type'])
  3196. && $showTable['Type'] === self::TABLE_TYPE_INNO_DB);
  3197. if ($isInnodb && Sql::isJustBrowsing($analyzedSqlResults, true)) {
  3198. $preCount = '~';
  3199. $afterCount = Generator::showHint(
  3200. Sanitize::sanitizeMessage(
  3201. __('May be approximate. See [doc@faq3-11]FAQ 3.11[/doc].')
  3202. )
  3203. );
  3204. } else {
  3205. $preCount = '';
  3206. $afterCount = '';
  3207. }
  3208. // 1. ----- Prepares the work -----
  3209. // 1.1 Gets the information about which functionalities should be
  3210. // displayed
  3211. [
  3212. $displayParts,
  3213. $total,
  3214. ] = $this->setDisplayPartsAndTotal($displayParts);
  3215. // 1.2 Defines offsets for the next and previous pages
  3216. $posNext = 0;
  3217. $posPrev = 0;
  3218. if ($displayParts['nav_bar'] == '1') {
  3219. [$posNext, $posPrev] = $this->getOffsets();
  3220. }
  3221. // 1.3 Extract sorting expressions.
  3222. // we need $sort_expression and $sort_expression_nodirection
  3223. // even if there are many table references
  3224. $sortExpression = [];
  3225. $sortExpressionNoDirection = [];
  3226. $sortDirection = [];
  3227. if ($statement !== null && ! empty($statement->order)) {
  3228. foreach ($statement->order as $o) {
  3229. $sortExpression[] = $o->expr->expr . ' ' . $o->type;
  3230. $sortExpressionNoDirection[] = $o->expr->expr;
  3231. $sortDirection[] = $o->type;
  3232. }
  3233. } else {
  3234. $sortExpression[] = '';
  3235. $sortExpressionNoDirection[] = '';
  3236. $sortDirection[] = '';
  3237. }
  3238. // 1.4 Prepares display of first and last value of the sorted column
  3239. $sortedColumnMessage = '';
  3240. foreach ($sortExpressionNoDirection as $expression) {
  3241. $sortedColumnMessage .= $this->getSortedColumnMessage($dtResult, $expression);
  3242. }
  3243. // 2. ----- Prepare to display the top of the page -----
  3244. // 2.1 Prepares a messages with position information
  3245. $sqlQueryMessage = '';
  3246. if ($displayParts['nav_bar'] == '1') {
  3247. $message = $this->setMessageInformation(
  3248. $sortedColumnMessage,
  3249. $analyzedSqlResults,
  3250. $total,
  3251. $posNext,
  3252. $preCount,
  3253. $afterCount
  3254. );
  3255. $sqlQueryMessage = Generator::getMessage($message, $this->properties['sql_query'], 'success');
  3256. } elseif (($printView === null || $printView != '1') && ! $isLimitedDisplay) {
  3257. $sqlQueryMessage = Generator::getMessage(
  3258. __('Your SQL query has been executed successfully.'),
  3259. $this->properties['sql_query'],
  3260. 'success'
  3261. );
  3262. }
  3263. // 2.3 Prepare the navigation bars
  3264. if ($this->properties['table'] === '' && $analyzedSqlResults['querytype'] === 'SELECT') {
  3265. // table does not always contain a real table name,
  3266. // for example in MySQL 5.0.x, the query SHOW STATUS
  3267. // returns STATUS as a table name
  3268. $this->properties['table'] = $fieldsMeta[0]->table;
  3269. }
  3270. $sortByKeyData = [];
  3271. // can the result be sorted?
  3272. if ($displayParts['sort_lnk'] == '1' && isset($analyzedSqlResults['statement'])) {
  3273. $unsortedSqlQuery = Query::replaceClause(
  3274. $analyzedSqlResults['statement'],
  3275. $analyzedSqlResults['parser']->list,
  3276. 'ORDER BY',
  3277. ''
  3278. );
  3279. // Data is sorted by indexes only if there is only one table.
  3280. if ($this->isSelect($analyzedSqlResults)) {
  3281. $sortByKeyData = $this->getSortByKeyDropDown(
  3282. $sortExpression,
  3283. $unsortedSqlQuery
  3284. );
  3285. }
  3286. }
  3287. $navigation = [];
  3288. if ($displayParts['nav_bar'] == '1' && $statement !== null && empty($statement->limit)) {
  3289. $navigation = $this->getTableNavigation($posNext, $posPrev, $isInnodb, $sortByKeyData);
  3290. }
  3291. // 2b ----- Get field references from Database -----
  3292. // (see the 'relation' configuration variable)
  3293. // initialize map
  3294. $map = [];
  3295. if ($this->properties['table'] !== '') {
  3296. // This method set the values for $map array
  3297. $map = $this->setParamForLinkForeignKeyRelatedTables($map);
  3298. // Coming from 'Distinct values' action of structure page
  3299. // We manipulate relations mechanism to show a link to related rows.
  3300. if ($this->properties['is_browse_distinct']) {
  3301. $map[$fieldsMeta[1]->name] = [
  3302. $this->properties['table'],
  3303. $fieldsMeta[1]->name,
  3304. '',
  3305. $this->properties['db'],
  3306. ];
  3307. }
  3308. }
  3309. // end 2b
  3310. // 3. ----- Prepare the results table -----
  3311. $headers = $this->getTableHeaders(
  3312. $displayParts,
  3313. $analyzedSqlResults,
  3314. $sortExpression,
  3315. $sortExpressionNoDirection,
  3316. $sortDirection,
  3317. $isLimitedDisplay
  3318. );
  3319. $body = $this->getTableBody($dtResult, $displayParts, $map, $analyzedSqlResults, $isLimitedDisplay);
  3320. $this->properties['display_params'] = null;
  3321. // 4. ----- Prepares the link for multi-fields edit and delete
  3322. $bulkLinks = $this->getBulkLinks($dtResult, $analyzedSqlResults, $displayParts['del_lnk']);
  3323. // 5. ----- Prepare "Query results operations"
  3324. $operations = [];
  3325. if (($printView === null || $printView != '1') && ! $isLimitedDisplay) {
  3326. $operations = $this->getResultsOperations($displayParts['pview_lnk'], $analyzedSqlResults);
  3327. }
  3328. $relationParameters = $this->relation->getRelationParameters();
  3329. return $this->template->render('display/results/table', [
  3330. 'sql_query_message' => $sqlQueryMessage,
  3331. 'navigation' => $navigation,
  3332. 'headers' => $headers,
  3333. 'body' => $body,
  3334. 'bulk_links' => $bulkLinks,
  3335. 'operations' => $operations,
  3336. 'db' => $this->properties['db'],
  3337. 'table' => $this->properties['table'],
  3338. 'unique_id' => $this->properties['unique_id'],
  3339. 'sql_query' => $this->properties['sql_query'],
  3340. 'goto' => $this->properties['goto'],
  3341. 'unlim_num_rows' => $this->properties['unlim_num_rows'],
  3342. 'displaywork' => $relationParameters->displayFeature !== null,
  3343. 'relwork' => $relationParameters->relationFeature !== null,
  3344. 'save_cells_at_once' => $GLOBALS['cfg']['SaveCellsAtOnce'],
  3345. 'default_sliders_state' => $GLOBALS['cfg']['InitialSlidersState'],
  3346. 'text_dir' => $this->properties['text_dir'],
  3347. ]);
  3348. }
  3349. /**
  3350. * Get offsets for next page and previous page
  3351. *
  3352. * @see getTable()
  3353. *
  3354. * @return int[] array with two elements - $pos_next, $pos_prev
  3355. */
  3356. private function getOffsets()
  3357. {
  3358. if ($_SESSION['tmpval']['max_rows'] === self::ALL_ROWS) {
  3359. return [0, 0];
  3360. }
  3361. return [
  3362. $_SESSION['tmpval']['pos'] + $_SESSION['tmpval']['max_rows'],
  3363. max(0, $_SESSION['tmpval']['pos'] - $_SESSION['tmpval']['max_rows']),
  3364. ];
  3365. }
  3366. /**
  3367. * Prepare sorted column message
  3368. *
  3369. * @see getTable()
  3370. *
  3371. * @param ResultInterface $dtResult the link id associated to the query
  3372. * which results have to be displayed
  3373. * @param string|null $sortExpressionNoDirection sort expression without direction
  3374. *
  3375. * @return string
  3376. */
  3377. private function getSortedColumnMessage(
  3378. ResultInterface $dtResult,
  3379. $sortExpressionNoDirection
  3380. ) {
  3381. $fieldsMeta = $this->properties['fields_meta']; // To use array indexes
  3382. if (empty($sortExpressionNoDirection)) {
  3383. return '';
  3384. }
  3385. if (! str_contains($sortExpressionNoDirection, '.')) {
  3386. $sortTable = $this->properties['table'];
  3387. $sortColumn = $sortExpressionNoDirection;
  3388. } else {
  3389. [$sortTable, $sortColumn] = explode('.', $sortExpressionNoDirection);
  3390. }
  3391. $sortTable = Util::unQuote($sortTable);
  3392. $sortColumn = Util::unQuote($sortColumn);
  3393. // find the sorted column index in row result
  3394. // (this might be a multi-table query)
  3395. $sortedColumnIndex = false;
  3396. foreach ($fieldsMeta as $key => $meta) {
  3397. if (($meta->table == $sortTable) && ($meta->name == $sortColumn)) {
  3398. $sortedColumnIndex = $key;
  3399. break;
  3400. }
  3401. }
  3402. if ($sortedColumnIndex === false) {
  3403. return '';
  3404. }
  3405. // fetch first row of the result set
  3406. $row = $dtResult->fetchRow();
  3407. // check for non printable sorted row data
  3408. $meta = $fieldsMeta[$sortedColumnIndex];
  3409. $isBlobOrGeometryOrBinary = $meta->isType(FieldMetadata::TYPE_BLOB)
  3410. || $meta->isMappedTypeGeometry || $meta->isBinary;
  3411. if ($isBlobOrGeometryOrBinary) {
  3412. $columnForFirstRow = $this->handleNonPrintableContents(
  3413. $meta->getMappedType(),
  3414. $row ? $row[$sortedColumnIndex] : '',
  3415. null,
  3416. [],
  3417. $meta
  3418. );
  3419. } else {
  3420. $columnForFirstRow = $row !== [] ? $row[$sortedColumnIndex] : '';
  3421. }
  3422. $columnForFirstRow = mb_strtoupper(
  3423. mb_substr(
  3424. (string) $columnForFirstRow,
  3425. 0,
  3426. (int) $GLOBALS['cfg']['LimitChars']
  3427. ) . '...'
  3428. );
  3429. // fetch last row of the result set
  3430. $dtResult->seek($this->properties['num_rows'] > 0 ? $this->properties['num_rows'] - 1 : 0);
  3431. $row = $dtResult->fetchRow();
  3432. // check for non printable sorted row data
  3433. $meta = $fieldsMeta[$sortedColumnIndex];
  3434. if ($isBlobOrGeometryOrBinary) {
  3435. $columnForLastRow = $this->handleNonPrintableContents(
  3436. $meta->getMappedType(),
  3437. $row ? $row[$sortedColumnIndex] : '',
  3438. null,
  3439. [],
  3440. $meta
  3441. );
  3442. } else {
  3443. $columnForLastRow = $row !== [] ? $row[$sortedColumnIndex] : '';
  3444. }
  3445. $columnForLastRow = mb_strtoupper(
  3446. mb_substr(
  3447. (string) $columnForLastRow,
  3448. 0,
  3449. (int) $GLOBALS['cfg']['LimitChars']
  3450. ) . '...'
  3451. );
  3452. // reset to first row for the loop in getTableBody()
  3453. $dtResult->seek(0);
  3454. // we could also use here $sort_expression_nodirection
  3455. return ' [' . htmlspecialchars($sortColumn)
  3456. . ': <strong>' . htmlspecialchars($columnForFirstRow) . ' - '
  3457. . htmlspecialchars($columnForLastRow) . '</strong>]';
  3458. }
  3459. /**
  3460. * Set the content that needs to be shown in message
  3461. *
  3462. * @see getTable()
  3463. *
  3464. * @param string $sortedColumnMessage the message for sorted column
  3465. * @param array $analyzedSqlResults the analyzed query
  3466. * @param int $total the total number of rows returned by
  3467. * the SQL query without any
  3468. * programmatically appended LIMIT clause
  3469. * @param int $posNext the offset for next page
  3470. * @param string $preCount the string renders before row count
  3471. * @param string $afterCount the string renders after row count
  3472. *
  3473. * @return Message an object of Message
  3474. */
  3475. private function setMessageInformation(
  3476. string $sortedColumnMessage,
  3477. array $analyzedSqlResults,
  3478. $total,
  3479. $posNext,
  3480. string $preCount,
  3481. string $afterCount
  3482. ) {
  3483. $unlimNumRows = $this->properties['unlim_num_rows']; // To use in isset()
  3484. if (! empty($analyzedSqlResults['statement']->limit)) {
  3485. $firstShownRec = $analyzedSqlResults['statement']->limit->offset;
  3486. $rowCount = $analyzedSqlResults['statement']->limit->rowCount;
  3487. if ($rowCount < $total) {
  3488. $lastShownRec = $firstShownRec + $rowCount - 1;
  3489. } else {
  3490. $lastShownRec = $firstShownRec + $total - 1;
  3491. }
  3492. } elseif (($_SESSION['tmpval']['max_rows'] === self::ALL_ROWS) || ($posNext > $total)) {
  3493. $firstShownRec = $_SESSION['tmpval']['pos'];
  3494. $lastShownRec = $total - 1;
  3495. } else {
  3496. $firstShownRec = $_SESSION['tmpval']['pos'];
  3497. $lastShownRec = $posNext - 1;
  3498. }
  3499. $messageViewWarning = false;
  3500. $table = new Table($this->properties['table'], $this->properties['db']);
  3501. if ($table->isView() && ($total == $GLOBALS['cfg']['MaxExactCountViews'])) {
  3502. $message = Message::notice(
  3503. __(
  3504. 'This view has at least this number of rows. Please refer to %sdocumentation%s.'
  3505. )
  3506. );
  3507. $message->addParam('[doc@cfg_MaxExactCount]');
  3508. $message->addParam('[/doc]');
  3509. $messageViewWarning = Generator::showHint($message->getMessage());
  3510. }
  3511. $message = Message::success(__('Showing rows %1s - %2s'));
  3512. $message->addParam($firstShownRec);
  3513. if ($messageViewWarning !== false) {
  3514. $message->addParamHtml('... ' . $messageViewWarning);
  3515. } else {
  3516. $message->addParam($lastShownRec);
  3517. }
  3518. $message->addText('(');
  3519. if ($messageViewWarning === false) {
  3520. if ($unlimNumRows != $total) {
  3521. $messageTotal = Message::notice(
  3522. $preCount . __('%1$d total, %2$d in query')
  3523. );
  3524. $messageTotal->addParam($total);
  3525. $messageTotal->addParam($unlimNumRows);
  3526. } else {
  3527. $messageTotal = Message::notice($preCount . __('%d total'));
  3528. $messageTotal->addParam($total);
  3529. }
  3530. if ($afterCount !== '') {
  3531. $messageTotal->addHtml($afterCount);
  3532. }
  3533. $message->addMessage($messageTotal, '');
  3534. $message->addText(', ', '');
  3535. }
  3536. $messageQueryTime = Message::notice(__('Query took %01.4f seconds.') . ')');
  3537. $messageQueryTime->addParam($this->properties['querytime']);
  3538. $message->addMessage($messageQueryTime, '');
  3539. $message->addHtml($sortedColumnMessage, '');
  3540. return $message;
  3541. }
  3542. /**
  3543. * Set the value of $map array for linking foreign key related tables
  3544. *
  3545. * @see getTable()
  3546. *
  3547. * @param array<string, string[]> $map the list of relations
  3548. *
  3549. * @return array<string, string[]>
  3550. */
  3551. private function setParamForLinkForeignKeyRelatedTables(array $map): array
  3552. {
  3553. // To be able to later display a link to the related table,
  3554. // we verify both types of relations: either those that are
  3555. // native foreign keys or those defined in the phpMyAdmin
  3556. // configuration storage. If no PMA storage, we won't be able
  3557. // to use the "column to display" notion (for example show
  3558. // the name related to a numeric id).
  3559. $existRel = $this->relation->getForeigners(
  3560. $this->properties['db'],
  3561. $this->properties['table'],
  3562. '',
  3563. self::POSITION_BOTH
  3564. );
  3565. if ($existRel === []) {
  3566. return $map;
  3567. }
  3568. foreach ($existRel as $masterField => $rel) {
  3569. if ($masterField !== 'foreign_keys_data') {
  3570. $displayField = $this->relation->getDisplayField($rel['foreign_db'], $rel['foreign_table']);
  3571. $map[$masterField] = [
  3572. $rel['foreign_table'],
  3573. $rel['foreign_field'],
  3574. $displayField,
  3575. $rel['foreign_db'],
  3576. ];
  3577. } else {
  3578. foreach ($rel as $oneKey) {
  3579. foreach ($oneKey['index_list'] as $index => $oneField) {
  3580. $displayField = $this->relation->getDisplayField(
  3581. $oneKey['ref_db_name'] ?? $GLOBALS['db'],
  3582. $oneKey['ref_table_name']
  3583. );
  3584. $map[$oneField] = [
  3585. $oneKey['ref_table_name'],
  3586. $oneKey['ref_index_list'][$index],
  3587. $displayField,
  3588. $oneKey['ref_db_name'] ?? $GLOBALS['db'],
  3589. ];
  3590. }
  3591. }
  3592. }
  3593. }
  3594. return $map;
  3595. }
  3596. /**
  3597. * Prepare multi field edit/delete links
  3598. *
  3599. * @see getTable()
  3600. *
  3601. * @param ResultInterface $dtResult the link id associated to the query which
  3602. * results have to be displayed
  3603. * @param array $analyzedSqlResults analyzed sql results
  3604. * @param string $deleteLink the display element - 'del_link'
  3605. *
  3606. * @psalm-return array{has_export_button:bool, clause_is_unique:mixed}|array<empty, empty>
  3607. */
  3608. private function getBulkLinks(
  3609. ResultInterface $dtResult,
  3610. array $analyzedSqlResults,
  3611. $deleteLink
  3612. ): array {
  3613. if ($deleteLink !== self::DELETE_ROW) {
  3614. return [];
  3615. }
  3616. // fetch last row of the result set
  3617. $dtResult->seek($this->properties['num_rows'] > 0 ? $this->properties['num_rows'] - 1 : 0);
  3618. $row = $dtResult->fetchRow();
  3619. $expressions = [];
  3620. if (isset($analyzedSqlResults['statement']) && $analyzedSqlResults['statement'] instanceof SelectStatement) {
  3621. $expressions = $analyzedSqlResults['statement']->expr;
  3622. }
  3623. /**
  3624. * $clause_is_unique is needed by getTable() to generate the proper param
  3625. * in the multi-edit and multi-delete form
  3626. */
  3627. [, $clauseIsUnique] = Util::getUniqueCondition(
  3628. $this->properties['fields_cnt'],
  3629. $this->properties['fields_meta'],
  3630. $row,
  3631. false,
  3632. false,
  3633. $expressions
  3634. );
  3635. // reset to first row for the loop in getTableBody()
  3636. $dtResult->seek(0);
  3637. return [
  3638. 'has_export_button' => $analyzedSqlResults['querytype'] === 'SELECT',
  3639. 'clause_is_unique' => $clauseIsUnique,
  3640. ];
  3641. }
  3642. /**
  3643. * Get operations that are available on results.
  3644. *
  3645. * @see getTable()
  3646. *
  3647. * @param string $printLink the parts to display
  3648. * @param array $analyzedSqlResults analyzed sql results
  3649. *
  3650. * @psalm-return array{
  3651. * has_export_link: bool,
  3652. * has_geometry: bool,
  3653. * has_print_link: bool,
  3654. * has_procedure: bool,
  3655. * url_params: array{
  3656. * db: string,
  3657. * table: string,
  3658. * printview: "1",
  3659. * sql_query: string,
  3660. * single_table?: "true",
  3661. * raw_query?: "true",
  3662. * unlim_num_rows?: int|numeric-string|false
  3663. * }
  3664. * }
  3665. */
  3666. private function getResultsOperations(
  3667. string $printLink,
  3668. array $analyzedSqlResults
  3669. ): array {
  3670. $urlParams = [
  3671. 'db' => $this->properties['db'],
  3672. 'table' => $this->properties['table'],
  3673. 'printview' => '1',
  3674. 'sql_query' => $this->properties['sql_query'],
  3675. ];
  3676. $geometryFound = false;
  3677. // Export link
  3678. // (the single_table parameter is used in \PhpMyAdmin\Export->getDisplay()
  3679. // to hide the SQL and the structure export dialogs)
  3680. // If the parser found a PROCEDURE clause
  3681. // (most probably PROCEDURE ANALYSE()) it makes no sense to
  3682. // display the Export link).
  3683. if (
  3684. ($analyzedSqlResults['querytype'] === self::QUERY_TYPE_SELECT)
  3685. && empty($analyzedSqlResults['is_procedure'])
  3686. ) {
  3687. if (count($analyzedSqlResults['select_tables']) === 1) {
  3688. $urlParams['single_table'] = 'true';
  3689. }
  3690. // In case this query doesn't involve any tables,
  3691. // implies only raw query is to be exported
  3692. if (! $analyzedSqlResults['select_tables']) {
  3693. $urlParams['raw_query'] = 'true';
  3694. }
  3695. $urlParams['unlim_num_rows'] = $this->properties['unlim_num_rows'];
  3696. /**
  3697. * At this point we don't know the table name; this can happen
  3698. * for example with a query like
  3699. * SELECT bike_code FROM (SELECT bike_code FROM bikes) tmp
  3700. * As a workaround we set in the table parameter the name of the
  3701. * first table of this database, so that /table/export and
  3702. * the script it calls do not fail
  3703. */
  3704. if ($urlParams['table'] === '' && $urlParams['db'] !== '') {
  3705. $urlParams['table'] = (string) $this->dbi->fetchValue('SHOW TABLES');
  3706. }
  3707. $fieldsMeta = $this->properties['fields_meta'];
  3708. foreach ($fieldsMeta as $meta) {
  3709. if ($meta->isMappedTypeGeometry) {
  3710. $geometryFound = true;
  3711. break;
  3712. }
  3713. }
  3714. }
  3715. return [
  3716. 'has_procedure' => ! empty($analyzedSqlResults['is_procedure']),
  3717. 'has_geometry' => $geometryFound,
  3718. 'has_print_link' => $printLink == '1',
  3719. 'has_export_link' => $analyzedSqlResults['querytype'] === self::QUERY_TYPE_SELECT,
  3720. 'url_params' => $urlParams,
  3721. ];
  3722. }
  3723. /**
  3724. * Verifies what to do with non-printable contents (binary or BLOB)
  3725. * in Browse mode.
  3726. *
  3727. * @see getDataCellForGeometryColumns(), getDataCellForNonNumericColumns(), getSortedColumnMessage()
  3728. *
  3729. * @param string $category BLOB|BINARY|GEOMETRY
  3730. * @param string|null $content the binary content
  3731. * @param array $transformOptions transformation parameters
  3732. * @param FieldMetadata $meta the meta-information about the field
  3733. * @param array $urlParams parameters that should go to the download link
  3734. * @param bool $isTruncated the result is truncated or not
  3735. */
  3736. private function handleNonPrintableContents(
  3737. $category,
  3738. ?string $content,
  3739. ?TransformationsPlugin $transformationPlugin,
  3740. array $transformOptions,
  3741. FieldMetadata $meta,
  3742. array $urlParams = [],
  3743. &$isTruncated = false
  3744. ): string {
  3745. $isTruncated = false;
  3746. $result = '[' . $category;
  3747. if ($content !== null) {
  3748. $size = strlen($content);
  3749. $displaySize = Util::formatByteDown($size, 3, 1);
  3750. if ($displaySize !== null) {
  3751. $result .= ' - ' . $displaySize[0] . ' ' . $displaySize[1];
  3752. }
  3753. } else {
  3754. $result .= ' - NULL';
  3755. $size = 0;
  3756. $content = '';
  3757. }
  3758. $result .= ']';
  3759. // if we want to use a text transformation on a BLOB column
  3760. if ($transformationPlugin !== null) {
  3761. $posMimeOctetstream = strpos(
  3762. $transformationPlugin->getMIMESubtype(),
  3763. 'Octetstream'
  3764. );
  3765. $posMimeText = strpos($transformationPlugin->getMIMEType(), 'Text');
  3766. if ($posMimeOctetstream || $posMimeText !== false) {
  3767. // Applying Transformations on hex string of binary data
  3768. // seems more appropriate
  3769. $result = pack('H*', bin2hex($content));
  3770. }
  3771. }
  3772. if ($size <= 0) {
  3773. return $result;
  3774. }
  3775. if ($transformationPlugin !== null) {
  3776. return $transformationPlugin->applyTransformation($result, $transformOptions, $meta);
  3777. }
  3778. $result = Core::mimeDefaultFunction($result);
  3779. if (
  3780. ($_SESSION['tmpval']['display_binary']
  3781. && $meta->isType(FieldMetadata::TYPE_STRING))
  3782. || ($_SESSION['tmpval']['display_blob']
  3783. && $meta->isType(FieldMetadata::TYPE_BLOB))
  3784. ) {
  3785. // in this case, restart from the original $content
  3786. if (
  3787. mb_check_encoding($content, 'utf-8')
  3788. && ! preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\x9F]/u', $content)
  3789. ) {
  3790. // show as text if it's valid utf-8
  3791. $result = htmlspecialchars($content);
  3792. } else {
  3793. $result = '0x' . bin2hex($content);
  3794. }
  3795. [
  3796. $isTruncated,
  3797. $result,
  3798. // skip 3rd param
  3799. ] = $this->getPartialText($result);
  3800. }
  3801. /* Create link to download */
  3802. if ($urlParams !== [] && $this->properties['db'] !== '' && $meta->orgtable !== '') {
  3803. $urlParams['where_clause_sign'] = Core::signSqlQuery($urlParams['where_clause']);
  3804. $result = '<a href="'
  3805. . Url::getFromRoute('/table/get-field', $urlParams)
  3806. . '" class="disableAjax">'
  3807. . $result . '</a>';
  3808. }
  3809. return $result;
  3810. }
  3811. /**
  3812. * Retrieves the associated foreign key info for a data cell
  3813. *
  3814. * @param string[] $fieldInfo the relation
  3815. * @param string $whereComparison data for the where clause
  3816. *
  3817. * @return string formatted data
  3818. */
  3819. private function getFromForeign(array $fieldInfo, string $whereComparison): ?string
  3820. {
  3821. $dispsql = 'SELECT '
  3822. . Util::backquote($fieldInfo[2])
  3823. . ' FROM '
  3824. . Util::backquote($fieldInfo[3])
  3825. . '.'
  3826. . Util::backquote($fieldInfo[0])
  3827. . ' WHERE '
  3828. . Util::backquote($fieldInfo[1])
  3829. . $whereComparison;
  3830. $dispval = $this->dbi->fetchValue($dispsql);
  3831. if ($dispval === false) {
  3832. return __('Link not found!');
  3833. }
  3834. if ($dispval === null) {
  3835. return null;
  3836. }
  3837. // Truncate values that are too long, see: #17902
  3838. [, $dispval] = $this->getPartialText($dispval);
  3839. return $dispval;
  3840. }
  3841. /**
  3842. * Prepares the displayable content of a data cell in Browse mode,
  3843. * taking into account foreign key description field and transformations
  3844. *
  3845. * @see getDataCellForNumericColumns(), getDataCellForGeometryColumns(),
  3846. * getDataCellForNonNumericColumns(),
  3847. *
  3848. * @param string $class css classes for the td element
  3849. * @param bool $conditionField whether the column is a part of the where clause
  3850. * @param array $analyzedSqlResults the analyzed query
  3851. * @param FieldMetadata $meta the meta-information about the field
  3852. * @param array<string, string[]> $map the list of relations
  3853. * @param string $data data
  3854. * @param string $displayedData data that will be displayed (maybe be chunked)
  3855. * @param string $nowrap 'nowrap' if the content should not be wrapped
  3856. * @param string $whereComparison data for the where clause
  3857. * @param array $transformOptions options for transformation
  3858. * @param bool $isFieldTruncated whether the field is truncated
  3859. * @param string $originalLength of a truncated column, or ''
  3860. *
  3861. * @return string formatted data
  3862. */
  3863. private function getRowData(
  3864. string $class,
  3865. bool $conditionField,
  3866. array $analyzedSqlResults,
  3867. FieldMetadata $meta,
  3868. array $map,
  3869. $data,
  3870. $displayedData,
  3871. ?TransformationsPlugin $transformationPlugin,
  3872. string $nowrap,
  3873. string $whereComparison,
  3874. array $transformOptions,
  3875. bool $isFieldTruncated = false,
  3876. string $originalLength = ''
  3877. ) {
  3878. $relationalDisplay = $_SESSION['tmpval']['relational_display'];
  3879. $printView = $this->properties['printview'];
  3880. $value = '';
  3881. $tableDataCellClass = $this->addClass(
  3882. $class,
  3883. $conditionField,
  3884. $meta,
  3885. $nowrap,
  3886. $isFieldTruncated,
  3887. $transformationPlugin !== null
  3888. );
  3889. if (! empty($analyzedSqlResults['statement']->expr)) {
  3890. foreach ($analyzedSqlResults['statement']->expr as $expr) {
  3891. if (empty($expr->alias) || empty($expr->column)) {
  3892. continue;
  3893. }
  3894. if (strcasecmp($meta->name, $expr->alias) !== 0) {
  3895. continue;
  3896. }
  3897. $meta->name = $expr->column;
  3898. }
  3899. }
  3900. if (isset($map[$meta->name])) {
  3901. /** @var array{0: string, 1: string, 2: string|false, 3: string} $relation */
  3902. $relation = $map[$meta->name];
  3903. // Field to display from the foreign table?
  3904. $dispval = '';
  3905. // Check that we have a valid column name
  3906. // Relation::getDisplayField() returns false by default
  3907. if ($relation[2] !== '' && $relation[2] !== false) {
  3908. $dispval = $this->getFromForeign($relation, $whereComparison);
  3909. }
  3910. if ($printView == '1') {
  3911. if ($transformationPlugin !== null) {
  3912. $value .= $transformationPlugin->applyTransformation($data, $transformOptions, $meta);
  3913. } else {
  3914. $value .= Core::mimeDefaultFunction($data);
  3915. }
  3916. $value .= ' <code>[-&gt;' . $dispval . ']</code>';
  3917. } else {
  3918. $sqlQuery = 'SELECT * FROM '
  3919. . Util::backquote($relation[3]) . '.'
  3920. . Util::backquote($relation[0])
  3921. . ' WHERE '
  3922. . Util::backquote($relation[1])
  3923. . $whereComparison;
  3924. $urlParams = [
  3925. 'db' => $relation[3],
  3926. 'table' => $relation[0],
  3927. 'pos' => '0',
  3928. 'sql_signature' => Core::signSqlQuery($sqlQuery),
  3929. 'sql_query' => $sqlQuery,
  3930. ];
  3931. if ($transformationPlugin !== null) {
  3932. // always apply a transformation on the real data,
  3933. // not on the display field
  3934. $displayedData = $transformationPlugin->applyTransformation($data, $transformOptions, $meta);
  3935. } elseif ($relationalDisplay === self::RELATIONAL_DISPLAY_COLUMN && $relation[2]) {
  3936. // user chose "relational display field" in the
  3937. // display options, so show display field in the cell
  3938. $displayedData = $dispval === null ? '<em>NULL</em>' : Core::mimeDefaultFunction($dispval);
  3939. } else {
  3940. // otherwise display data in the cell
  3941. $displayedData = Core::mimeDefaultFunction($displayedData);
  3942. }
  3943. if ($relationalDisplay === self::RELATIONAL_KEY) {
  3944. // user chose "relational key" in the display options, so
  3945. // the title contains the display field
  3946. $title = $dispval ?? '';
  3947. } else {
  3948. $title = $data;
  3949. }
  3950. $tagParams = ['title' => $title];
  3951. if (str_contains($class, 'grid_edit')) {
  3952. $tagParams['class'] = 'ajax';
  3953. }
  3954. $value .= Generator::linkOrButton(
  3955. Url::getFromRoute('/sql', $urlParams, false),
  3956. null,
  3957. $displayedData,
  3958. $tagParams
  3959. );
  3960. }
  3961. } elseif ($transformationPlugin !== null) {
  3962. $value .= $transformationPlugin->applyTransformation($data, $transformOptions, $meta);
  3963. } else {
  3964. $value .= Core::mimeDefaultFunction($data);
  3965. }
  3966. return $this->template->render('display/results/row_data', [
  3967. 'value' => $value,
  3968. 'td_class' => $tableDataCellClass,
  3969. 'decimals' => $meta->decimals,
  3970. 'type' => $meta->getMappedType(),
  3971. 'original_length' => $originalLength,
  3972. ]);
  3973. }
  3974. /**
  3975. * Truncates given string based on LimitChars configuration
  3976. * and Session pftext variable
  3977. * (string is truncated only if necessary)
  3978. *
  3979. * @see handleNonPrintableContents(), getDataCellForGeometryColumns(), getDataCellForNonNumericColumns
  3980. *
  3981. * @param string $str string to be truncated
  3982. *
  3983. * @return array
  3984. * @psalm-return array{bool, string, int}
  3985. */
  3986. private function getPartialText($str): array
  3987. {
  3988. $originalLength = mb_strlen($str);
  3989. if (
  3990. $originalLength > $GLOBALS['cfg']['LimitChars']
  3991. && $_SESSION['tmpval']['pftext'] === self::DISPLAY_PARTIAL_TEXT
  3992. ) {
  3993. $str = mb_substr($str, 0, (int) $GLOBALS['cfg']['LimitChars']) . '...';
  3994. $truncated = true;
  3995. } else {
  3996. $truncated = false;
  3997. }
  3998. return [
  3999. $truncated,
  4000. $str,
  4001. $originalLength,
  4002. ];
  4003. }
  4004. }