Results.php 180 KB

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