Sql.php 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Set of functions for the SQL executor
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin;
  9. use PhpMyAdmin\Bookmark;
  10. use PhpMyAdmin\Core;
  11. use PhpMyAdmin\DatabaseInterface;
  12. use PhpMyAdmin\Display\Results as DisplayResults;
  13. use PhpMyAdmin\Index;
  14. use PhpMyAdmin\Message;
  15. use PhpMyAdmin\Operations;
  16. use PhpMyAdmin\ParseAnalyze;
  17. use PhpMyAdmin\Relation;
  18. use PhpMyAdmin\RelationCleanup;
  19. use PhpMyAdmin\Response;
  20. use PhpMyAdmin\SqlParser\Statements\AlterStatement;
  21. use PhpMyAdmin\SqlParser\Statements\DropStatement;
  22. use PhpMyAdmin\SqlParser\Statements\SelectStatement;
  23. use PhpMyAdmin\SqlParser\Utils\Query;
  24. use PhpMyAdmin\Table;
  25. use PhpMyAdmin\Transformations;
  26. use PhpMyAdmin\Url;
  27. use PhpMyAdmin\Util;
  28. /**
  29. * Set of functions for the SQL executor
  30. *
  31. * @package PhpMyAdmin
  32. */
  33. class Sql
  34. {
  35. /**
  36. * @var Relation $relation
  37. */
  38. private $relation;
  39. /**
  40. * Constructor
  41. */
  42. public function __construct()
  43. {
  44. $this->relation = new Relation();
  45. }
  46. /**
  47. * Parses and analyzes the given SQL query.
  48. *
  49. * @param string $sql_query SQL query
  50. * @param string $db DB name
  51. *
  52. * @return mixed
  53. */
  54. public function parseAndAnalyze($sql_query, $db = null)
  55. {
  56. if (is_null($db) && isset($GLOBALS['db']) && strlen($GLOBALS['db'])) {
  57. $db = $GLOBALS['db'];
  58. }
  59. list($analyzed_sql_results,,) = ParseAnalyze::sqlQuery($sql_query, $db);
  60. return $analyzed_sql_results;
  61. }
  62. /**
  63. * Handle remembered sorting order, only for single table query
  64. *
  65. * @param string $db database name
  66. * @param string $table table name
  67. * @param array &$analyzed_sql_results the analyzed query results
  68. * @param string &$full_sql_query SQL query
  69. *
  70. * @return void
  71. */
  72. private function handleSortOrder(
  73. $db, $table, array &$analyzed_sql_results, &$full_sql_query
  74. ) {
  75. $pmatable = new Table($table, $db);
  76. if (empty($analyzed_sql_results['order'])) {
  77. // Retrieving the name of the column we should sort after.
  78. $sortCol = $pmatable->getUiProp(Table::PROP_SORTED_COLUMN);
  79. if (empty($sortCol)) {
  80. return;
  81. }
  82. // Remove the name of the table from the retrieved field name.
  83. $sortCol = str_replace(
  84. Util::backquote($table) . '.',
  85. '',
  86. $sortCol
  87. );
  88. // Create the new query.
  89. $full_sql_query = Query::replaceClause(
  90. $analyzed_sql_results['statement'],
  91. $analyzed_sql_results['parser']->list,
  92. 'ORDER BY ' . $sortCol
  93. );
  94. // TODO: Avoid reparsing the query.
  95. $analyzed_sql_results = Query::getAll($full_sql_query);
  96. } else {
  97. // Store the remembered table into session.
  98. $pmatable->setUiProp(
  99. Table::PROP_SORTED_COLUMN,
  100. Query::getClause(
  101. $analyzed_sql_results['statement'],
  102. $analyzed_sql_results['parser']->list,
  103. 'ORDER BY'
  104. )
  105. );
  106. }
  107. }
  108. /**
  109. * Append limit clause to SQL query
  110. *
  111. * @param array &$analyzed_sql_results the analyzed query results
  112. *
  113. * @return string limit clause appended SQL query
  114. */
  115. private function getSqlWithLimitClause(array &$analyzed_sql_results)
  116. {
  117. return Query::replaceClause(
  118. $analyzed_sql_results['statement'],
  119. $analyzed_sql_results['parser']->list,
  120. 'LIMIT ' . $_SESSION['tmpval']['pos'] . ', '
  121. . $_SESSION['tmpval']['max_rows']
  122. );
  123. }
  124. /**
  125. * Verify whether the result set has columns from just one table
  126. *
  127. * @param array $fields_meta meta fields
  128. *
  129. * @return boolean whether the result set has columns from just one table
  130. */
  131. private function resultSetHasJustOneTable(array $fields_meta)
  132. {
  133. $just_one_table = true;
  134. $prev_table = '';
  135. foreach ($fields_meta as $one_field_meta) {
  136. if ($one_field_meta->table != ''
  137. && $prev_table != ''
  138. && $one_field_meta->table != $prev_table
  139. ) {
  140. $just_one_table = false;
  141. }
  142. if ($one_field_meta->table != '') {
  143. $prev_table = $one_field_meta->table;
  144. }
  145. }
  146. return $just_one_table && $prev_table != '';
  147. }
  148. /**
  149. * Verify whether the result set contains all the columns
  150. * of at least one unique key
  151. *
  152. * @param string $db database name
  153. * @param string $table table name
  154. * @param array $fields_meta meta fields
  155. *
  156. * @return boolean whether the result set contains a unique key
  157. */
  158. private function resultSetContainsUniqueKey($db, $table, array $fields_meta)
  159. {
  160. $columns = $GLOBALS['dbi']->getColumns($db, $table);
  161. $resultSetColumnNames = array();
  162. foreach ($fields_meta as $oneMeta) {
  163. $resultSetColumnNames[] = $oneMeta->name;
  164. }
  165. foreach (Index::getFromTable($table, $db) as $index) {
  166. if ($index->isUnique()) {
  167. $indexColumns = $index->getColumns();
  168. $numberFound = 0;
  169. foreach ($indexColumns as $indexColumnName => $dummy) {
  170. if (in_array($indexColumnName, $resultSetColumnNames)) {
  171. $numberFound++;
  172. } else if (!in_array($indexColumnName, $columns)) {
  173. $numberFound++;
  174. } else if (strpos($columns[$indexColumnName]['Extra'], 'INVISIBLE') !== false) {
  175. $numberFound++;
  176. }
  177. }
  178. if ($numberFound == count($indexColumns)) {
  179. return true;
  180. }
  181. }
  182. }
  183. return false;
  184. }
  185. /**
  186. * Get the HTML for relational column dropdown
  187. * During grid edit, if we have a relational field, returns the html for the
  188. * dropdown
  189. *
  190. * @param string $db current database
  191. * @param string $table current table
  192. * @param string $column current column
  193. * @param string $curr_value current selected value
  194. *
  195. * @return string $dropdown html for the dropdown
  196. */
  197. private function getHtmlForRelationalColumnDropdown($db, $table, $column, $curr_value)
  198. {
  199. $foreigners = $this->relation->getForeigners($db, $table, $column);
  200. $foreignData = $this->relation->getForeignData($foreigners, $column, false, '', '');
  201. if ($foreignData['disp_row'] == null) {
  202. //Handle the case when number of values
  203. //is more than $cfg['ForeignKeyMaxLimit']
  204. $_url_params = array(
  205. 'db' => $db,
  206. 'table' => $table,
  207. 'field' => $column
  208. );
  209. $dropdown = '<span class="curr_value">'
  210. . htmlspecialchars($_POST['curr_value'])
  211. . '</span>'
  212. . '<a href="browse_foreigners.php" data-post="'
  213. . Url::getCommon($_url_params, '', false) . '"'
  214. . 'class="ajax browse_foreign" ' . '>'
  215. . __('Browse foreign values')
  216. . '</a>';
  217. } else {
  218. $dropdown = $this->relation->foreignDropdown(
  219. $foreignData['disp_row'],
  220. $foreignData['foreign_field'],
  221. $foreignData['foreign_display'],
  222. $curr_value,
  223. $GLOBALS['cfg']['ForeignKeyMaxLimit']
  224. );
  225. $dropdown = '<select>' . $dropdown . '</select>';
  226. }
  227. return $dropdown;
  228. }
  229. /**
  230. * Get the HTML for the profiling table and accompanying chart if profiling is set.
  231. * Otherwise returns null
  232. *
  233. * @param string $url_query url query
  234. * @param string $db current database
  235. * @param array $profiling_results array containing the profiling info
  236. *
  237. * @return string $profiling_table html for the profiling table and chart
  238. */
  239. private function getHtmlForProfilingChart($url_query, $db, $profiling_results)
  240. {
  241. if (! empty($profiling_results)) {
  242. $url_query = isset($url_query)
  243. ? $url_query
  244. : Url::getCommon(array('db' => $db));
  245. $profiling_table = '';
  246. $profiling_table .= '<fieldset><legend>' . __('Profiling')
  247. . '</legend>' . "\n";
  248. $profiling_table .= '<div class="floatleft">';
  249. $profiling_table .= '<h3>' . __('Detailed profile') . '</h3>';
  250. $profiling_table .= '<table id="profiletable"><thead>' . "\n";
  251. $profiling_table .= ' <tr>' . "\n";
  252. $profiling_table .= ' <th>' . __('Order')
  253. . '<div class="sorticon"></div></th>' . "\n";
  254. $profiling_table .= ' <th>' . __('State')
  255. . Util::showMySQLDocu('general-thread-states')
  256. . '<div class="sorticon"></div></th>' . "\n";
  257. $profiling_table .= ' <th>' . __('Time')
  258. . '<div class="sorticon"></div></th>' . "\n";
  259. $profiling_table .= ' </tr></thead><tbody>' . "\n";
  260. list($detailed_table, $chart_json, $profiling_stats)
  261. = $this->analyzeAndGetTableHtmlForProfilingResults($profiling_results);
  262. $profiling_table .= $detailed_table;
  263. $profiling_table .= '</tbody></table>' . "\n";
  264. $profiling_table .= '</div>';
  265. $profiling_table .= '<div class="floatleft">';
  266. $profiling_table .= '<h3>' . __('Summary by state') . '</h3>';
  267. $profiling_table .= '<table id="profilesummarytable"><thead>' . "\n";
  268. $profiling_table .= ' <tr>' . "\n";
  269. $profiling_table .= ' <th>' . __('State')
  270. . Util::showMySQLDocu('general-thread-states')
  271. . '<div class="sorticon"></div></th>' . "\n";
  272. $profiling_table .= ' <th>' . __('Total Time')
  273. . '<div class="sorticon"></div></th>' . "\n";
  274. $profiling_table .= ' <th>' . __('% Time')
  275. . '<div class="sorticon"></div></th>' . "\n";
  276. $profiling_table .= ' <th>' . __('Calls')
  277. . '<div class="sorticon"></div></th>' . "\n";
  278. $profiling_table .= ' <th>' . __('ø Time')
  279. . '<div class="sorticon"></div></th>' . "\n";
  280. $profiling_table .= ' </tr></thead><tbody>' . "\n";
  281. $profiling_table .= $this->getTableHtmlForProfilingSummaryByState(
  282. $profiling_stats
  283. );
  284. $profiling_table .= '</tbody></table>' . "\n";
  285. $profiling_table .= <<<EOT
  286. <script type="text/javascript">
  287. url_query = '$url_query';
  288. </script>
  289. EOT;
  290. $profiling_table .= "</div>";
  291. $profiling_table .= "<div class='clearfloat'></div>";
  292. //require_once 'libraries/chart.lib.php';
  293. $profiling_table .= '<div id="profilingChartData" class="hide">';
  294. $profiling_table .= json_encode($chart_json);
  295. $profiling_table .= '</div>';
  296. $profiling_table .= '<div id="profilingchart" class="hide">';
  297. $profiling_table .= '</div>';
  298. $profiling_table .= '<script type="text/javascript">';
  299. $profiling_table .= "AJAX.registerOnload('sql.js', function () {";
  300. $profiling_table .= 'makeProfilingChart();';
  301. $profiling_table .= 'initProfilingTables();';
  302. $profiling_table .= '});';
  303. $profiling_table .= '</script>';
  304. $profiling_table .= '</fieldset>' . "\n";
  305. } else {
  306. $profiling_table = null;
  307. }
  308. return $profiling_table;
  309. }
  310. /**
  311. * Function to get HTML for detailed profiling results table, profiling stats, and
  312. * $chart_json for displaying the chart.
  313. *
  314. * @param array $profiling_results profiling results
  315. *
  316. * @return mixed
  317. */
  318. private function analyzeAndGetTableHtmlForProfilingResults(
  319. $profiling_results
  320. ) {
  321. $profiling_stats = array(
  322. 'total_time' => 0,
  323. 'states' => array(),
  324. );
  325. $chart_json = Array();
  326. $i = 1;
  327. $table = '';
  328. foreach ($profiling_results as $one_result) {
  329. if (isset($profiling_stats['states'][ucwords($one_result['Status'])])) {
  330. $states = $profiling_stats['states'];
  331. $states[ucwords($one_result['Status'])]['total_time']
  332. += $one_result['Duration'];
  333. $states[ucwords($one_result['Status'])]['calls']++;
  334. } else {
  335. $profiling_stats['states'][ucwords($one_result['Status'])] = array(
  336. 'total_time' => $one_result['Duration'],
  337. 'calls' => 1,
  338. );
  339. }
  340. $profiling_stats['total_time'] += $one_result['Duration'];
  341. $table .= ' <tr>' . "\n";
  342. $table .= '<td>' . $i++ . '</td>' . "\n";
  343. $table .= '<td>' . ucwords($one_result['Status'])
  344. . '</td>' . "\n";
  345. $table .= '<td class="right">'
  346. . (Util::formatNumber($one_result['Duration'], 3, 1))
  347. . 's<span class="rawvalue hide">'
  348. . $one_result['Duration'] . '</span></td>' . "\n";
  349. if (isset($chart_json[ucwords($one_result['Status'])])) {
  350. $chart_json[ucwords($one_result['Status'])]
  351. += $one_result['Duration'];
  352. } else {
  353. $chart_json[ucwords($one_result['Status'])]
  354. = $one_result['Duration'];
  355. }
  356. }
  357. return array($table, $chart_json, $profiling_stats);
  358. }
  359. /**
  360. * Function to get HTML for summary by state table
  361. *
  362. * @param array $profiling_stats profiling stats
  363. *
  364. * @return string $table html for the table
  365. */
  366. private function getTableHtmlForProfilingSummaryByState(array $profiling_stats)
  367. {
  368. $table = '';
  369. foreach ($profiling_stats['states'] as $name => $stats) {
  370. $table .= ' <tr>' . "\n";
  371. $table .= '<td>' . $name . '</td>' . "\n";
  372. $table .= '<td align="right">'
  373. . Util::formatNumber($stats['total_time'], 3, 1)
  374. . 's<span class="rawvalue hide">'
  375. . $stats['total_time'] . '</span></td>' . "\n";
  376. $table .= '<td align="right">'
  377. . Util::formatNumber(
  378. 100 * ($stats['total_time'] / $profiling_stats['total_time']),
  379. 0, 2
  380. )
  381. . '%</td>' . "\n";
  382. $table .= '<td align="right">' . $stats['calls'] . '</td>'
  383. . "\n";
  384. $table .= '<td align="right">'
  385. . Util::formatNumber(
  386. $stats['total_time'] / $stats['calls'], 3, 1
  387. )
  388. . 's<span class="rawvalue hide">'
  389. . number_format($stats['total_time'] / $stats['calls'], 8, '.', '')
  390. . '</span></td>' . "\n";
  391. $table .= ' </tr>' . "\n";
  392. }
  393. return $table;
  394. }
  395. /**
  396. * Get the HTML for the enum column dropdown
  397. * During grid edit, if we have a enum field, returns the html for the
  398. * dropdown
  399. *
  400. * @param string $db current database
  401. * @param string $table current table
  402. * @param string $column current column
  403. * @param string $curr_value currently selected value
  404. *
  405. * @return string $dropdown html for the dropdown
  406. */
  407. private function getHtmlForEnumColumnDropdown($db, $table, $column, $curr_value)
  408. {
  409. $values = $this->getValuesForColumn($db, $table, $column);
  410. $dropdown = '<option value="">&nbsp;</option>';
  411. $dropdown .= $this->getHtmlForOptionsList($values, array($curr_value));
  412. $dropdown = '<select>' . $dropdown . '</select>';
  413. return $dropdown;
  414. }
  415. /**
  416. * Get value of a column for a specific row (marked by $where_clause)
  417. *
  418. * @param string $db current database
  419. * @param string $table current table
  420. * @param string $column current column
  421. * @param string $where_clause where clause to select a particular row
  422. *
  423. * @return string with value
  424. */
  425. private function getFullValuesForSetColumn($db, $table, $column, $where_clause)
  426. {
  427. $result = $GLOBALS['dbi']->fetchSingleRow(
  428. "SELECT `$column` FROM `$db`.`$table` WHERE $where_clause"
  429. );
  430. return $result[$column];
  431. }
  432. /**
  433. * Get the HTML for the set column dropdown
  434. * During grid edit, if we have a set field, returns the html for the
  435. * dropdown
  436. *
  437. * @param string $db current database
  438. * @param string $table current table
  439. * @param string $column current column
  440. * @param string $curr_value currently selected value
  441. *
  442. * @return string $dropdown html for the set column
  443. */
  444. private function getHtmlForSetColumn($db, $table, $column, $curr_value)
  445. {
  446. $values = $this->getValuesForColumn($db, $table, $column);
  447. $dropdown = '';
  448. $full_values =
  449. isset($_POST['get_full_values']) ? $_POST['get_full_values'] : false;
  450. $where_clause =
  451. isset($_POST['where_clause']) ? $_POST['where_clause'] : null;
  452. // If the $curr_value was truncated, we should
  453. // fetch the correct full values from the table
  454. if ($full_values && ! empty($where_clause)) {
  455. $curr_value = $this->getFullValuesForSetColumn(
  456. $db, $table, $column, $where_clause
  457. );
  458. }
  459. //converts characters of $curr_value to HTML entities
  460. $converted_curr_value = htmlentities(
  461. $curr_value, ENT_COMPAT, "UTF-8"
  462. );
  463. $selected_values = explode(',', $converted_curr_value);
  464. $dropdown .= $this->getHtmlForOptionsList($values, $selected_values);
  465. $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
  466. $dropdown = '<select multiple="multiple" size="' . $select_size . '">'
  467. . $dropdown . '</select>';
  468. return $dropdown;
  469. }
  470. /**
  471. * Get all the values for a enum column or set column in a table
  472. *
  473. * @param string $db current database
  474. * @param string $table current table
  475. * @param string $column current column
  476. *
  477. * @return array $values array containing the value list for the column
  478. */
  479. private function getValuesForColumn($db, $table, $column)
  480. {
  481. $field_info_query = $GLOBALS['dbi']->getColumnsSql($db, $table, $column);
  482. $field_info_result = $GLOBALS['dbi']->fetchResult(
  483. $field_info_query,
  484. null,
  485. null,
  486. DatabaseInterface::CONNECT_USER,
  487. DatabaseInterface::QUERY_STORE
  488. );
  489. $values = Util::parseEnumSetValues($field_info_result[0]['Type']);
  490. return $values;
  491. }
  492. /**
  493. * Get HTML for options list
  494. *
  495. * @param array $values set of values
  496. * @param array $selected_values currently selected values
  497. *
  498. * @return string $options HTML for options list
  499. */
  500. private function getHtmlForOptionsList(array $values, array $selected_values)
  501. {
  502. $options = '';
  503. foreach ($values as $value) {
  504. $options .= '<option value="' . $value . '"';
  505. if (in_array($value, $selected_values, true)) {
  506. $options .= ' selected="selected" ';
  507. }
  508. $options .= '>' . $value . '</option>';
  509. }
  510. return $options;
  511. }
  512. /**
  513. * Function to get html for bookmark support if bookmarks are enabled. Else will
  514. * return null
  515. *
  516. * @param array $displayParts the parts to display
  517. * @param array $cfgBookmark configuration setting for bookmarking
  518. * @param string $sql_query sql query
  519. * @param string $db current database
  520. * @param string $table current table
  521. * @param string $complete_query complete query
  522. * @param string $bkm_user bookmarking user
  523. *
  524. * @return string $html
  525. */
  526. public function getHtmlForBookmark(array $displayParts, array $cfgBookmark, $sql_query, $db,
  527. $table, $complete_query, $bkm_user
  528. ) {
  529. if ($displayParts['bkm_form'] == '1'
  530. && (! empty($cfgBookmark) && empty($_GET['id_bookmark']))
  531. && ! empty($sql_query)
  532. ) {
  533. $goto = 'sql.php'
  534. . Url::getCommon(
  535. array(
  536. 'db' => $db,
  537. 'table' => $table,
  538. 'sql_query' => $sql_query,
  539. 'id_bookmark'=> 1,
  540. )
  541. );
  542. $bkm_sql_query = isset($complete_query) ? $complete_query : $sql_query;
  543. $html = '<form action="sql.php" method="post"'
  544. . ' onsubmit="return ! emptyCheckTheField(this,'
  545. . '\'bkm_fields[bkm_label]\');"'
  546. . ' class="bookmarkQueryForm print_ignore">';
  547. $html .= Url::getHiddenInputs();
  548. $html .= '<input type="hidden" name="db"'
  549. . ' value="' . htmlspecialchars($db) . '" />';
  550. $html .= '<input type="hidden" name="goto" value="' . $goto . '" />';
  551. $html .= '<input type="hidden" name="bkm_fields[bkm_database]"'
  552. . ' value="' . htmlspecialchars($db) . '" />';
  553. $html .= '<input type="hidden" name="bkm_fields[bkm_user]"'
  554. . ' value="' . $bkm_user . '" />';
  555. $html .= '<input type="hidden" name="bkm_fields[bkm_sql_query]"'
  556. . ' value="'
  557. . htmlspecialchars($bkm_sql_query)
  558. . '" />';
  559. $html .= '<fieldset>';
  560. $html .= '<legend>';
  561. $html .= Util::getIcon(
  562. 'b_bookmark', __('Bookmark this SQL query'), true
  563. );
  564. $html .= '</legend>';
  565. $html .= '<div class="formelement">';
  566. $html .= '<label>' . __('Label:');
  567. $html .= '<input type="text" name="bkm_fields[bkm_label]" value="" />' .
  568. '</label>';
  569. $html .= '</div>';
  570. $html .= '<div class="formelement">';
  571. $html .= '<label>' .
  572. '<input type="checkbox" name="bkm_all_users" value="true" />';
  573. $html .= __('Let every user access this bookmark') . '</label>';
  574. $html .= '</div>';
  575. $html .= '<div class="clearfloat"></div>';
  576. $html .= '</fieldset>';
  577. $html .= '<fieldset class="tblFooters">';
  578. $html .= '<input type="hidden" name="store_bkm" value="1" />';
  579. $html .= '<input type="submit"'
  580. . ' value="' . __('Bookmark this SQL query') . '" />';
  581. $html .= '</fieldset>';
  582. $html .= '</form>';
  583. } else {
  584. $html = null;
  585. }
  586. return $html;
  587. }
  588. /**
  589. * Function to check whether to remember the sorting order or not
  590. *
  591. * @param array $analyzed_sql_results the analyzed query and other variables set
  592. * after analyzing the query
  593. *
  594. * @return boolean
  595. */
  596. private function isRememberSortingOrder(array $analyzed_sql_results)
  597. {
  598. return $GLOBALS['cfg']['RememberSorting']
  599. && ! ($analyzed_sql_results['is_count']
  600. || $analyzed_sql_results['is_export']
  601. || $analyzed_sql_results['is_func']
  602. || $analyzed_sql_results['is_analyse'])
  603. && $analyzed_sql_results['select_from']
  604. && isset($analyzed_sql_results['select_expr'])
  605. && isset($analyzed_sql_results['select_tables'])
  606. && ((empty($analyzed_sql_results['select_expr']))
  607. || ((count($analyzed_sql_results['select_expr']) == 1)
  608. && ($analyzed_sql_results['select_expr'][0] == '*')))
  609. && count($analyzed_sql_results['select_tables']) == 1;
  610. }
  611. /**
  612. * Function to check whether the LIMIT clause should be appended or not
  613. *
  614. * @param array $analyzed_sql_results the analyzed query and other variables set
  615. * after analyzing the query
  616. *
  617. * @return boolean
  618. */
  619. private function isAppendLimitClause(array $analyzed_sql_results)
  620. {
  621. // Assigning LIMIT clause to an syntactically-wrong query
  622. // is not needed. Also we would want to show the true query
  623. // and the true error message to the query executor
  624. return (isset($analyzed_sql_results['parser'])
  625. && count($analyzed_sql_results['parser']->errors) === 0)
  626. && ($_SESSION['tmpval']['max_rows'] != 'all')
  627. && ! ($analyzed_sql_results['is_export']
  628. || $analyzed_sql_results['is_analyse'])
  629. && ($analyzed_sql_results['select_from']
  630. || $analyzed_sql_results['is_subquery'])
  631. && empty($analyzed_sql_results['limit']);
  632. }
  633. /**
  634. * Function to check whether this query is for just browsing
  635. *
  636. * @param array $analyzed_sql_results the analyzed query and other variables set
  637. * after analyzing the query
  638. * @param boolean $find_real_end whether the real end should be found
  639. *
  640. * @return boolean
  641. */
  642. public function isJustBrowsing(array $analyzed_sql_results, $find_real_end)
  643. {
  644. return ! $analyzed_sql_results['is_group']
  645. && ! $analyzed_sql_results['is_func']
  646. && empty($analyzed_sql_results['union'])
  647. && empty($analyzed_sql_results['distinct'])
  648. && $analyzed_sql_results['select_from']
  649. && (count($analyzed_sql_results['select_tables']) === 1)
  650. && (empty($analyzed_sql_results['statement']->where)
  651. || (count($analyzed_sql_results['statement']->where) == 1
  652. && $analyzed_sql_results['statement']->where[0]->expr ==='1'))
  653. && empty($analyzed_sql_results['group'])
  654. && ! isset($find_real_end)
  655. && ! $analyzed_sql_results['is_subquery']
  656. && ! $analyzed_sql_results['join']
  657. && empty($analyzed_sql_results['having']);
  658. }
  659. /**
  660. * Function to check whether the related transformation information should be deleted
  661. *
  662. * @param array $analyzed_sql_results the analyzed query and other variables set
  663. * after analyzing the query
  664. *
  665. * @return boolean
  666. */
  667. private function isDeleteTransformationInfo(array $analyzed_sql_results)
  668. {
  669. return !empty($analyzed_sql_results['querytype'])
  670. && (($analyzed_sql_results['querytype'] == 'ALTER')
  671. || ($analyzed_sql_results['querytype'] == 'DROP'));
  672. }
  673. /**
  674. * Function to check whether the user has rights to drop the database
  675. *
  676. * @param array $analyzed_sql_results the analyzed query and other variables set
  677. * after analyzing the query
  678. * @param boolean $allowUserDropDatabase whether the user is allowed to drop db
  679. * @param boolean $is_superuser whether this user is a superuser
  680. *
  681. * @return boolean
  682. */
  683. public function hasNoRightsToDropDatabase(array $analyzed_sql_results,
  684. $allowUserDropDatabase, $is_superuser
  685. ) {
  686. return ! $allowUserDropDatabase
  687. && isset($analyzed_sql_results['drop_database'])
  688. && $analyzed_sql_results['drop_database']
  689. && ! $is_superuser;
  690. }
  691. /**
  692. * Function to set a column property
  693. *
  694. * @param Table $pmatable Table instance
  695. * @param string $request_index col_order|col_visib
  696. *
  697. * @return boolean $retval
  698. */
  699. private function setColumnProperty($pmatable, $request_index)
  700. {
  701. $property_value = array_map('intval', explode(',', $_POST[$request_index]));
  702. switch($request_index) {
  703. case 'col_order':
  704. $property_to_set = Table::PROP_COLUMN_ORDER;
  705. break;
  706. case 'col_visib':
  707. $property_to_set = Table::PROP_COLUMN_VISIB;
  708. break;
  709. default:
  710. $property_to_set = '';
  711. }
  712. $retval = $pmatable->setUiProp(
  713. $property_to_set,
  714. $property_value,
  715. isset($_POST['table_create_time']) ? $_POST['table_create_time'] : null
  716. );
  717. if (gettype($retval) != 'boolean') {
  718. $response = Response::getInstance();
  719. $response->setRequestStatus(false);
  720. $response->addJSON('message', $retval->getString());
  721. exit;
  722. }
  723. return $retval;
  724. }
  725. /**
  726. * Function to check the request for setting the column order or visibility
  727. *
  728. * @param string $table the current table
  729. * @param string $db the current database
  730. *
  731. * @return void
  732. */
  733. public function setColumnOrderOrVisibility($table, $db)
  734. {
  735. $pmatable = new Table($table, $db);
  736. $retval = false;
  737. // set column order
  738. if (isset($_POST['col_order'])) {
  739. $retval = $this->setColumnProperty($pmatable, 'col_order');
  740. }
  741. // set column visibility
  742. if ($retval === true && isset($_POST['col_visib'])) {
  743. $retval = $this->setColumnProperty($pmatable, 'col_visib');
  744. }
  745. $response = Response::getInstance();
  746. $response->setRequestStatus($retval == true);
  747. exit;
  748. }
  749. /**
  750. * Function to add a bookmark
  751. *
  752. * @param string $goto goto page URL
  753. *
  754. * @return void
  755. */
  756. public function addBookmark($goto)
  757. {
  758. $bookmark = Bookmark::createBookmark(
  759. $GLOBALS['dbi'],
  760. $GLOBALS['cfg']['Server']['user'],
  761. $_POST['bkm_fields'],
  762. (isset($_POST['bkm_all_users'])
  763. && $_POST['bkm_all_users'] == 'true' ? true : false
  764. )
  765. );
  766. $result = $bookmark->save();
  767. $response = Response::getInstance();
  768. if ($response->isAjax()) {
  769. if ($result) {
  770. $msg = Message::success(__('Bookmark %s has been created.'));
  771. $msg->addParam($_POST['bkm_fields']['bkm_label']);
  772. $response->addJSON('message', $msg);
  773. } else {
  774. $msg = Message::error(__('Bookmark not created!'));
  775. $response->setRequestStatus(false);
  776. $response->addJSON('message', $msg);
  777. }
  778. exit;
  779. } else {
  780. // go back to sql.php to redisplay query; do not use &amp; in this case:
  781. /**
  782. * @todo In which scenario does this happen?
  783. */
  784. Core::sendHeaderLocation(
  785. './' . $goto
  786. . '&label=' . $_POST['bkm_fields']['bkm_label']
  787. );
  788. }
  789. }
  790. /**
  791. * Function to find the real end of rows
  792. *
  793. * @param string $db the current database
  794. * @param string $table the current table
  795. *
  796. * @return mixed the number of rows if "retain" param is true, otherwise true
  797. */
  798. public function findRealEndOfRows($db, $table)
  799. {
  800. $unlim_num_rows = $GLOBALS['dbi']->getTable($db, $table)->countRecords(true);
  801. $_SESSION['tmpval']['pos'] = $this->getStartPosToDisplayRow($unlim_num_rows);
  802. return $unlim_num_rows;
  803. }
  804. /**
  805. * Function to get values for the relational columns
  806. *
  807. * @param string $db the current database
  808. * @param string $table the current table
  809. *
  810. * @return void
  811. */
  812. public function getRelationalValues($db, $table)
  813. {
  814. $column = $_POST['column'];
  815. if ($_SESSION['tmpval']['relational_display'] == 'D'
  816. && isset($_POST['relation_key_or_display_column'])
  817. && $_POST['relation_key_or_display_column']
  818. ) {
  819. $curr_value = $_POST['relation_key_or_display_column'];
  820. } else {
  821. $curr_value = $_POST['curr_value'];
  822. }
  823. $dropdown = $this->getHtmlForRelationalColumnDropdown(
  824. $db, $table, $column, $curr_value
  825. );
  826. $response = Response::getInstance();
  827. $response->addJSON('dropdown', $dropdown);
  828. exit;
  829. }
  830. /**
  831. * Function to get values for Enum or Set Columns
  832. *
  833. * @param string $db the current database
  834. * @param string $table the current table
  835. * @param string $columnType whether enum or set
  836. *
  837. * @return void
  838. */
  839. public function getEnumOrSetValues($db, $table, $columnType)
  840. {
  841. $column = $_POST['column'];
  842. $curr_value = $_POST['curr_value'];
  843. $response = Response::getInstance();
  844. if ($columnType == "enum") {
  845. $dropdown = $this->getHtmlForEnumColumnDropdown(
  846. $db, $table, $column, $curr_value
  847. );
  848. $response->addJSON('dropdown', $dropdown);
  849. } else {
  850. $select = $this->getHtmlForSetColumn(
  851. $db, $table, $column, $curr_value
  852. );
  853. $response->addJSON('select', $select);
  854. }
  855. exit;
  856. }
  857. /**
  858. * Function to get the default sql query for browsing page
  859. *
  860. * @param string $db the current database
  861. * @param string $table the current table
  862. *
  863. * @return string $sql_query the default $sql_query for browse page
  864. */
  865. public function getDefaultSqlQueryForBrowse($db, $table)
  866. {
  867. $bookmark = Bookmark::get(
  868. $GLOBALS['dbi'],
  869. $GLOBALS['cfg']['Server']['user'],
  870. $db,
  871. $table,
  872. 'label',
  873. false,
  874. true
  875. );
  876. if (! empty($bookmark) && ! empty($bookmark->getQuery())) {
  877. $GLOBALS['using_bookmark_message'] = Message::notice(
  878. __('Using bookmark "%s" as default browse query.')
  879. );
  880. $GLOBALS['using_bookmark_message']->addParam($table);
  881. $GLOBALS['using_bookmark_message']->addHtml(
  882. Util::showDocu('faq', 'faq6-22')
  883. );
  884. $sql_query = $bookmark->getQuery();
  885. } else {
  886. $defaultOrderByClause = '';
  887. if (isset($GLOBALS['cfg']['TablePrimaryKeyOrder'])
  888. && ($GLOBALS['cfg']['TablePrimaryKeyOrder'] !== 'NONE')
  889. ) {
  890. $primaryKey = null;
  891. $primary = Index::getPrimary($table, $db);
  892. if ($primary !== false) {
  893. $primarycols = $primary->getColumns();
  894. foreach ($primarycols as $col) {
  895. $primaryKey = $col->getName();
  896. break;
  897. }
  898. if ($primaryKey != null) {
  899. $defaultOrderByClause = ' ORDER BY '
  900. . Util::backquote($table) . '.'
  901. . Util::backquote($primaryKey) . ' '
  902. . $GLOBALS['cfg']['TablePrimaryKeyOrder'];
  903. }
  904. }
  905. }
  906. $sql_query = 'SELECT * FROM ' . Util::backquote($table)
  907. . $defaultOrderByClause;
  908. }
  909. return $sql_query;
  910. }
  911. /**
  912. * Responds an error when an error happens when executing the query
  913. *
  914. * @param boolean $is_gotofile whether goto file or not
  915. * @param string $error error after executing the query
  916. * @param string $full_sql_query full sql query
  917. *
  918. * @return void
  919. */
  920. private function handleQueryExecuteError($is_gotofile, $error, $full_sql_query)
  921. {
  922. if ($is_gotofile) {
  923. $message = Message::rawError($error);
  924. $response = Response::getInstance();
  925. $response->setRequestStatus(false);
  926. $response->addJSON('message', $message);
  927. } else {
  928. Util::mysqlDie($error, $full_sql_query, '', '');
  929. }
  930. exit;
  931. }
  932. /**
  933. * Function to store the query as a bookmark
  934. *
  935. * @param string $db the current database
  936. * @param string $bkm_user the bookmarking user
  937. * @param string $sql_query_for_bookmark the query to be stored in bookmark
  938. * @param string $bkm_label bookmark label
  939. * @param boolean $bkm_replace whether to replace existing bookmarks
  940. *
  941. * @return void
  942. */
  943. public function storeTheQueryAsBookmark($db, $bkm_user, $sql_query_for_bookmark,
  944. $bkm_label, $bkm_replace
  945. ) {
  946. $bfields = array(
  947. 'bkm_database' => $db,
  948. 'bkm_user' => $bkm_user,
  949. 'bkm_sql_query' => $sql_query_for_bookmark,
  950. 'bkm_label' => $bkm_label,
  951. );
  952. // Should we replace bookmark?
  953. if (isset($bkm_replace)) {
  954. $bookmarks = Bookmark::getList(
  955. $GLOBALS['dbi'],
  956. $GLOBALS['cfg']['Server']['user'],
  957. $db
  958. );
  959. foreach ($bookmarks as $bookmark) {
  960. if ($bookmark->getLabel() == $bkm_label) {
  961. $bookmark->delete();
  962. }
  963. }
  964. }
  965. $bookmark = Bookmark::createBookmark(
  966. $GLOBALS['dbi'],
  967. $GLOBALS['cfg']['Server']['user'],
  968. $bfields,
  969. isset($_POST['bkm_all_users'])
  970. );
  971. $bookmark->save();
  972. }
  973. /**
  974. * Executes the SQL query and measures its execution time
  975. *
  976. * @param string $full_sql_query the full sql query
  977. *
  978. * @return array ($result, $querytime)
  979. */
  980. private function executeQueryAndMeasureTime($full_sql_query)
  981. {
  982. // close session in case the query takes too long
  983. session_write_close();
  984. // Measure query time.
  985. $querytime_before = array_sum(explode(' ', microtime()));
  986. $result = @$GLOBALS['dbi']->tryQuery(
  987. $full_sql_query, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_STORE
  988. );
  989. $querytime_after = array_sum(explode(' ', microtime()));
  990. // reopen session
  991. session_start();
  992. return array($result, $querytime_after - $querytime_before);
  993. }
  994. /**
  995. * Function to get the affected or changed number of rows after executing a query
  996. *
  997. * @param boolean $is_affected whether the query affected a table
  998. * @param mixed $result results of executing the query
  999. *
  1000. * @return int $num_rows number of rows affected or changed
  1001. */
  1002. private function getNumberOfRowsAffectedOrChanged($is_affected, $result)
  1003. {
  1004. if (! $is_affected) {
  1005. $num_rows = ($result) ? @$GLOBALS['dbi']->numRows($result) : 0;
  1006. } else {
  1007. $num_rows = @$GLOBALS['dbi']->affectedRows();
  1008. }
  1009. return $num_rows;
  1010. }
  1011. /**
  1012. * Checks if the current database has changed
  1013. * This could happen if the user sends a query like "USE `database`;"
  1014. *
  1015. * @param string $db the database in the query
  1016. *
  1017. * @return int $reload whether to reload the navigation(1) or not(0)
  1018. */
  1019. private function hasCurrentDbChanged($db)
  1020. {
  1021. if (strlen($db) > 0) {
  1022. $current_db = $GLOBALS['dbi']->fetchValue('SELECT DATABASE()');
  1023. // $current_db is false, except when a USE statement was sent
  1024. return ($current_db != false) && ($db !== $current_db);
  1025. }
  1026. return false;
  1027. }
  1028. /**
  1029. * If a table, database or column gets dropped, clean comments.
  1030. *
  1031. * @param string $db current database
  1032. * @param string $table current table
  1033. * @param string $column current column
  1034. * @param bool $purge whether purge set or not
  1035. *
  1036. * @return array $extra_data
  1037. */
  1038. private function cleanupRelations($db, $table, $column, $purge)
  1039. {
  1040. if (! empty($purge) && strlen($db) > 0) {
  1041. if (strlen($table) > 0) {
  1042. if (isset($column) && strlen($column) > 0) {
  1043. RelationCleanup::column($db, $table, $column);
  1044. } else {
  1045. RelationCleanup::table($db, $table);
  1046. }
  1047. } else {
  1048. RelationCleanup::database($db);
  1049. }
  1050. }
  1051. }
  1052. /**
  1053. * Function to count the total number of rows for the same 'SELECT' query without
  1054. * the 'LIMIT' clause that may have been programatically added
  1055. *
  1056. * @param int $num_rows number of rows affected/changed by the query
  1057. * @param bool $justBrowsing whether just browsing or not
  1058. * @param string $db the current database
  1059. * @param string $table the current table
  1060. * @param array $analyzed_sql_results the analyzed query and other variables set
  1061. * after analyzing the query
  1062. *
  1063. * @return int $unlim_num_rows unlimited number of rows
  1064. */
  1065. private function countQueryResults(
  1066. $num_rows, $justBrowsing, $db, $table, array $analyzed_sql_results
  1067. ) {
  1068. /* Shortcut for not analyzed/empty query */
  1069. if (empty($analyzed_sql_results)) {
  1070. return 0;
  1071. }
  1072. if (!$this->isAppendLimitClause($analyzed_sql_results)) {
  1073. // if we did not append a limit, set this to get a correct
  1074. // "Showing rows..." message
  1075. // $_SESSION['tmpval']['max_rows'] = 'all';
  1076. $unlim_num_rows = $num_rows;
  1077. } elseif ($this->isAppendLimitClause($analyzed_sql_results) && $_SESSION['tmpval']['max_rows'] > $num_rows) {
  1078. // When user has not defined a limit in query and total rows in
  1079. // result are less than max_rows to display, there is no need
  1080. // to count total rows for that query again
  1081. $unlim_num_rows = $_SESSION['tmpval']['pos'] + $num_rows;
  1082. } elseif ($analyzed_sql_results['querytype'] == 'SELECT'
  1083. || $analyzed_sql_results['is_subquery']
  1084. ) {
  1085. // c o u n t q u e r y
  1086. // If we are "just browsing", there is only one table (and no join),
  1087. // and no WHERE clause (or just 'WHERE 1 '),
  1088. // we do a quick count (which uses MaxExactCount) because
  1089. // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
  1090. // However, do not count again if we did it previously
  1091. // due to $find_real_end == true
  1092. if ($justBrowsing) {
  1093. // Get row count (is approximate for InnoDB)
  1094. $unlim_num_rows = $GLOBALS['dbi']->getTable($db, $table)->countRecords();
  1095. /**
  1096. * @todo Can we know at this point that this is InnoDB,
  1097. * (in this case there would be no need for getting
  1098. * an exact count)?
  1099. */
  1100. if ($unlim_num_rows < $GLOBALS['cfg']['MaxExactCount']) {
  1101. // Get the exact count if approximate count
  1102. // is less than MaxExactCount
  1103. /**
  1104. * @todo In countRecords(), MaxExactCount is also verified,
  1105. * so can we avoid checking it twice?
  1106. */
  1107. $unlim_num_rows = $GLOBALS['dbi']->getTable($db, $table)
  1108. ->countRecords(true);
  1109. }
  1110. } else {
  1111. // The SQL_CALC_FOUND_ROWS option of the SELECT statement is used.
  1112. // For UNION statements, only a SQL_CALC_FOUND_ROWS is required
  1113. // after the first SELECT.
  1114. $count_query = Query::replaceClause(
  1115. $analyzed_sql_results['statement'],
  1116. $analyzed_sql_results['parser']->list,
  1117. 'SELECT SQL_CALC_FOUND_ROWS',
  1118. null,
  1119. true
  1120. );
  1121. // Another LIMIT clause is added to avoid long delays.
  1122. // A complete result will be returned anyway, but the LIMIT would
  1123. // stop the query as soon as the result that is required has been
  1124. // computed.
  1125. if (empty($analyzed_sql_results['union'])) {
  1126. $count_query .= ' LIMIT 1';
  1127. }
  1128. // Running the count query.
  1129. $GLOBALS['dbi']->tryQuery($count_query);
  1130. $unlim_num_rows = $GLOBALS['dbi']->fetchValue('SELECT FOUND_ROWS()');
  1131. } // end else "just browsing"
  1132. } else {// not $is_select
  1133. $unlim_num_rows = 0;
  1134. }
  1135. return $unlim_num_rows;
  1136. }
  1137. /**
  1138. * Function to handle all aspects relating to executing the query
  1139. *
  1140. * @param array $analyzed_sql_results analyzed sql results
  1141. * @param string $full_sql_query full sql query
  1142. * @param boolean $is_gotofile whether to go to a file
  1143. * @param string $db current database
  1144. * @param string $table current table
  1145. * @param boolean $find_real_end whether to find the real end
  1146. * @param string $sql_query_for_bookmark sql query to be stored as bookmark
  1147. * @param array $extra_data extra data
  1148. *
  1149. * @return mixed
  1150. */
  1151. private function executeTheQuery(array $analyzed_sql_results, $full_sql_query, $is_gotofile,
  1152. $db, $table, $find_real_end, $sql_query_for_bookmark, $extra_data
  1153. ) {
  1154. $response = Response::getInstance();
  1155. $response->getHeader()->getMenu()->setTable($table);
  1156. // Only if we ask to see the php code
  1157. if (isset($GLOBALS['show_as_php'])) {
  1158. $result = null;
  1159. $num_rows = 0;
  1160. $unlim_num_rows = 0;
  1161. } else { // If we don't ask to see the php code
  1162. if (isset($_SESSION['profiling'])
  1163. && Util::profilingSupported()
  1164. ) {
  1165. $GLOBALS['dbi']->query('SET PROFILING=1;');
  1166. }
  1167. list(
  1168. $result,
  1169. $GLOBALS['querytime']
  1170. ) = $this->executeQueryAndMeasureTime($full_sql_query);
  1171. // Displays an error message if required and stop parsing the script
  1172. $error = $GLOBALS['dbi']->getError();
  1173. if ($error && $GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
  1174. $extra_data['error'] = $error;
  1175. } elseif ($error) {
  1176. $this->handleQueryExecuteError($is_gotofile, $error, $full_sql_query);
  1177. }
  1178. // If there are no errors and bookmarklabel was given,
  1179. // store the query as a bookmark
  1180. if (! empty($_POST['bkm_label']) && ! empty($sql_query_for_bookmark)) {
  1181. $cfgBookmark = Bookmark::getParams($GLOBALS['cfg']['Server']['user']);
  1182. $this->storeTheQueryAsBookmark(
  1183. $db, $cfgBookmark['user'],
  1184. $sql_query_for_bookmark, $_POST['bkm_label'],
  1185. isset($_POST['bkm_replace']) ? $_POST['bkm_replace'] : null
  1186. );
  1187. } // end store bookmarks
  1188. // Gets the number of rows affected/returned
  1189. // (This must be done immediately after the query because
  1190. // mysql_affected_rows() reports about the last query done)
  1191. $num_rows = $this->getNumberOfRowsAffectedOrChanged(
  1192. $analyzed_sql_results['is_affected'], $result
  1193. );
  1194. // Grabs the profiling results
  1195. if (isset($_SESSION['profiling'])
  1196. && Util::profilingSupported()
  1197. ) {
  1198. $profiling_results = $GLOBALS['dbi']->fetchResult('SHOW PROFILE;');
  1199. }
  1200. $justBrowsing = $this->isJustBrowsing(
  1201. $analyzed_sql_results, isset($find_real_end) ? $find_real_end : null
  1202. );
  1203. $unlim_num_rows = $this->countQueryResults(
  1204. $num_rows, $justBrowsing, $db, $table, $analyzed_sql_results
  1205. );
  1206. $this->cleanupRelations(
  1207. isset($db) ? $db : '',
  1208. isset($table) ? $table : '',
  1209. isset($_POST['dropped_column']) ? $_POST['dropped_column'] : null,
  1210. isset($_POST['purge']) ? $_POST['purge'] : null
  1211. );
  1212. if (isset($_POST['dropped_column'])
  1213. && strlen($db) > 0
  1214. && strlen($table) > 0
  1215. ) {
  1216. // to refresh the list of indexes (Ajax mode)
  1217. $extra_data['indexes_list'] = Index::getHtmlForIndexes(
  1218. $table,
  1219. $db
  1220. );
  1221. }
  1222. }
  1223. return array($result, $num_rows, $unlim_num_rows,
  1224. isset($profiling_results) ? $profiling_results : null, $extra_data
  1225. );
  1226. }
  1227. /**
  1228. * Delete related transformation information
  1229. *
  1230. * @param string $db current database
  1231. * @param string $table current table
  1232. * @param array $analyzed_sql_results analyzed sql results
  1233. *
  1234. * @return void
  1235. */
  1236. private function deleteTransformationInfo($db, $table, array $analyzed_sql_results)
  1237. {
  1238. if (! isset($analyzed_sql_results['statement'])) {
  1239. return;
  1240. }
  1241. $statement = $analyzed_sql_results['statement'];
  1242. if ($statement instanceof AlterStatement) {
  1243. if (!empty($statement->altered[0])
  1244. && $statement->altered[0]->options->has('DROP')
  1245. ) {
  1246. if (!empty($statement->altered[0]->field->column)) {
  1247. Transformations::clear(
  1248. $db,
  1249. $table,
  1250. $statement->altered[0]->field->column
  1251. );
  1252. }
  1253. }
  1254. } elseif ($statement instanceof DropStatement) {
  1255. Transformations::clear($db, $table);
  1256. }
  1257. }
  1258. /**
  1259. * Function to get the message for the no rows returned case
  1260. *
  1261. * @param string $message_to_show message to show
  1262. * @param array $analyzed_sql_results analyzed sql results
  1263. * @param int $num_rows number of rows
  1264. *
  1265. * @return string $message
  1266. */
  1267. private function getMessageForNoRowsReturned($message_to_show,
  1268. array $analyzed_sql_results, $num_rows
  1269. ) {
  1270. if ($analyzed_sql_results['querytype'] == 'DELETE"') {
  1271. $message = Message::getMessageForDeletedRows($num_rows);
  1272. } elseif ($analyzed_sql_results['is_insert']) {
  1273. if ($analyzed_sql_results['querytype'] == 'REPLACE') {
  1274. // For REPLACE we get DELETED + INSERTED row count,
  1275. // so we have to call it affected
  1276. $message = Message::getMessageForAffectedRows($num_rows);
  1277. } else {
  1278. $message = Message::getMessageForInsertedRows($num_rows);
  1279. }
  1280. $insert_id = $GLOBALS['dbi']->insertId();
  1281. if ($insert_id != 0) {
  1282. // insert_id is id of FIRST record inserted in one insert,
  1283. // so if we inserted multiple rows, we had to increment this
  1284. $message->addText('[br]');
  1285. // need to use a temporary because the Message class
  1286. // currently supports adding parameters only to the first
  1287. // message
  1288. $_inserted = Message::notice(__('Inserted row id: %1$d'));
  1289. $_inserted->addParam($insert_id + $num_rows - 1);
  1290. $message->addMessage($_inserted);
  1291. }
  1292. } elseif ($analyzed_sql_results['is_affected']) {
  1293. $message = Message::getMessageForAffectedRows($num_rows);
  1294. // Ok, here is an explanation for the !$is_select.
  1295. // The form generated by PhpMyAdmin\SqlQueryForm
  1296. // and db_sql.php has many submit buttons
  1297. // on the same form, and some confusion arises from the
  1298. // fact that $message_to_show is sent for every case.
  1299. // The $message_to_show containing a success message and sent with
  1300. // the form should not have priority over errors
  1301. } elseif (! empty($message_to_show)
  1302. && $analyzed_sql_results['querytype'] != 'SELECT'
  1303. ) {
  1304. $message = Message::rawSuccess(htmlspecialchars($message_to_show));
  1305. } elseif (! empty($GLOBALS['show_as_php'])) {
  1306. $message = Message::success(__('Showing as PHP code'));
  1307. } elseif (isset($GLOBALS['show_as_php'])) {
  1308. /* User disable showing as PHP, query is only displayed */
  1309. $message = Message::notice(__('Showing SQL query'));
  1310. } else {
  1311. $message = Message::success(
  1312. __('MySQL returned an empty result set (i.e. zero rows).')
  1313. );
  1314. }
  1315. if (isset($GLOBALS['querytime'])) {
  1316. $_querytime = Message::notice(
  1317. '(' . __('Query took %01.4f seconds.') . ')'
  1318. );
  1319. $_querytime->addParam($GLOBALS['querytime']);
  1320. $message->addMessage($_querytime);
  1321. }
  1322. // In case of ROLLBACK, notify the user.
  1323. if (isset($_POST['rollback_query'])) {
  1324. $message->addText(__('[ROLLBACK occurred.]'));
  1325. }
  1326. return $message;
  1327. }
  1328. /**
  1329. * Function to respond back when the query returns zero rows
  1330. * This method is called
  1331. * 1-> When browsing an empty table
  1332. * 2-> When executing a query on a non empty table which returns zero results
  1333. * 3-> When executing a query on an empty table
  1334. * 4-> When executing an INSERT, UPDATE, DELETE query from the SQL tab
  1335. * 5-> When deleting a row from BROWSE tab
  1336. * 6-> When searching using the SEARCH tab which returns zero results
  1337. * 7-> When changing the structure of the table except change operation
  1338. *
  1339. * @param array $analyzed_sql_results analyzed sql results
  1340. * @param string $db current database
  1341. * @param string $table current table
  1342. * @param string $message_to_show message to show
  1343. * @param int $num_rows number of rows
  1344. * @param DisplayResults $displayResultsObject DisplayResult instance
  1345. * @param array $extra_data extra data
  1346. * @param string $pmaThemeImage uri of the theme image
  1347. * @param array|null $profiling_results profiling results
  1348. * @param object $result executed query results
  1349. * @param string $sql_query sql query
  1350. * @param string $complete_query complete sql query
  1351. *
  1352. * @return string html
  1353. */
  1354. private function getQueryResponseForNoResultsReturned(array $analyzed_sql_results, $db,
  1355. $table, $message_to_show, $num_rows, $displayResultsObject, $extra_data,
  1356. $pmaThemeImage, $profiling_results, $result, $sql_query, $complete_query
  1357. ) {
  1358. if ($this->isDeleteTransformationInfo($analyzed_sql_results)) {
  1359. $this->deleteTransformationInfo($db, $table, $analyzed_sql_results);
  1360. }
  1361. if (isset($extra_data['error'])) {
  1362. $message = Message::rawError($extra_data['error']);
  1363. } else {
  1364. $message = $this->getMessageForNoRowsReturned(
  1365. isset($message_to_show) ? $message_to_show : null,
  1366. $analyzed_sql_results, $num_rows
  1367. );
  1368. }
  1369. $html_output = '';
  1370. $html_message = Util::getMessage(
  1371. $message, $GLOBALS['sql_query'], 'success'
  1372. );
  1373. $html_output .= $html_message;
  1374. if (!isset($GLOBALS['show_as_php'])) {
  1375. if (! empty($GLOBALS['reload'])) {
  1376. $extra_data['reload'] = 1;
  1377. $extra_data['db'] = $GLOBALS['db'];
  1378. }
  1379. // For ajax requests add message and sql_query as JSON
  1380. if (empty($_REQUEST['ajax_page_request'])) {
  1381. $extra_data['message'] = $message;
  1382. if ($GLOBALS['cfg']['ShowSQL']) {
  1383. $extra_data['sql_query'] = $html_message;
  1384. }
  1385. }
  1386. $response = Response::getInstance();
  1387. $response->addJSON(isset($extra_data) ? $extra_data : array());
  1388. if (!empty($analyzed_sql_results['is_select']) &&
  1389. !isset($extra_data['error'])) {
  1390. $url_query = isset($url_query) ? $url_query : null;
  1391. $displayParts = array(
  1392. 'edit_lnk' => null,
  1393. 'del_lnk' => null,
  1394. 'sort_lnk' => '1',
  1395. 'nav_bar' => '0',
  1396. 'bkm_form' => '1',
  1397. 'text_btn' => '1',
  1398. 'pview_lnk' => '1'
  1399. );
  1400. $html_output .= $this->getHtmlForSqlQueryResultsTable(
  1401. $displayResultsObject,
  1402. $pmaThemeImage, $url_query, $displayParts,
  1403. false, 0, $num_rows, true, $result,
  1404. $analyzed_sql_results, true
  1405. );
  1406. if (isset($profiling_results)) {
  1407. $header = $response->getHeader();
  1408. $scripts = $header->getScripts();
  1409. $scripts->addFile('sql.js');
  1410. $html_output .= $this->getHtmlForProfilingChart(
  1411. $url_query,
  1412. $db,
  1413. isset($profiling_results) ? $profiling_results : []
  1414. );
  1415. }
  1416. $html_output .= $displayResultsObject->getCreateViewQueryResultOp(
  1417. $analyzed_sql_results
  1418. );
  1419. $cfgBookmark = Bookmark::getParams($GLOBALS['cfg']['Server']['user']);
  1420. if ($cfgBookmark) {
  1421. $html_output .= $this->getHtmlForBookmark(
  1422. $displayParts,
  1423. $cfgBookmark,
  1424. $sql_query, $db, $table,
  1425. isset($complete_query) ? $complete_query : $sql_query,
  1426. $cfgBookmark['user']
  1427. );
  1428. }
  1429. }
  1430. }
  1431. return $html_output;
  1432. }
  1433. /**
  1434. * Function to send response for ajax grid edit
  1435. *
  1436. * @param object $result result of the executed query
  1437. *
  1438. * @return void
  1439. */
  1440. private function sendResponseForGridEdit($result)
  1441. {
  1442. $row = $GLOBALS['dbi']->fetchRow($result);
  1443. $field_flags = $GLOBALS['dbi']->fieldFlags($result, 0);
  1444. if (stristr($field_flags, DisplayResults::BINARY_FIELD)) {
  1445. $row[0] = bin2hex($row[0]);
  1446. }
  1447. $response = Response::getInstance();
  1448. $response->addJSON('value', $row[0]);
  1449. exit;
  1450. }
  1451. /**
  1452. * Function to get html for the sql query results div
  1453. *
  1454. * @param string $previous_update_query_html html for the previously executed query
  1455. * @param string $profiling_chart_html html for profiling
  1456. * @param Message $missing_unique_column_msg message for the missing unique column
  1457. * @param Message $bookmark_created_msg message for bookmark creation
  1458. * @param string $table_html html for the table for displaying sql
  1459. * results
  1460. * @param string $indexes_problems_html html for displaying errors in indexes
  1461. * @param string $bookmark_support_html html for displaying bookmark form
  1462. *
  1463. * @return string $html_output
  1464. */
  1465. private function getHtmlForSqlQueryResults($previous_update_query_html,
  1466. $profiling_chart_html, $missing_unique_column_msg, $bookmark_created_msg,
  1467. $table_html, $indexes_problems_html, $bookmark_support_html
  1468. ) {
  1469. //begin the sqlqueryresults div here. container div
  1470. $html_output = '<div class="sqlqueryresults ajax">';
  1471. $html_output .= isset($previous_update_query_html)
  1472. ? $previous_update_query_html : '';
  1473. $html_output .= isset($profiling_chart_html) ? $profiling_chart_html : '';
  1474. $html_output .= isset($missing_unique_column_msg)
  1475. ? $missing_unique_column_msg->getDisplay() : '';
  1476. $html_output .= isset($bookmark_created_msg)
  1477. ? $bookmark_created_msg->getDisplay() : '';
  1478. $html_output .= $table_html;
  1479. $html_output .= isset($indexes_problems_html) ? $indexes_problems_html : '';
  1480. $html_output .= isset($bookmark_support_html) ? $bookmark_support_html : '';
  1481. $html_output .= '</div>'; // end sqlqueryresults div
  1482. return $html_output;
  1483. }
  1484. /**
  1485. * Returns a message for successful creation of a bookmark or null if a bookmark
  1486. * was not created
  1487. *
  1488. * @return Message $bookmark_created_msg
  1489. */
  1490. private function getBookmarkCreatedMessage()
  1491. {
  1492. if (isset($_GET['label'])) {
  1493. $bookmark_created_msg = Message::success(
  1494. __('Bookmark %s has been created.')
  1495. );
  1496. $bookmark_created_msg->addParam($_GET['label']);
  1497. } else {
  1498. $bookmark_created_msg = null;
  1499. }
  1500. return $bookmark_created_msg;
  1501. }
  1502. /**
  1503. * Function to get html for the sql query results table
  1504. *
  1505. * @param DisplayResults $displayResultsObject instance of DisplayResult
  1506. * @param string $pmaThemeImage theme image uri
  1507. * @param string $url_query url query
  1508. * @param array $displayParts the parts to display
  1509. * @param bool $editable whether the result table is
  1510. * editable or not
  1511. * @param int $unlim_num_rows unlimited number of rows
  1512. * @param int $num_rows number of rows
  1513. * @param bool $showtable whether to show table or not
  1514. * @param object $result result of the executed query
  1515. * @param array $analyzed_sql_results analyzed sql results
  1516. * @param bool $is_limited_display Show only limited operations or not
  1517. *
  1518. * @return string
  1519. */
  1520. private function getHtmlForSqlQueryResultsTable($displayResultsObject,
  1521. $pmaThemeImage, $url_query, array $displayParts,
  1522. $editable, $unlim_num_rows, $num_rows, $showtable, $result,
  1523. array $analyzed_sql_results, $is_limited_display = false
  1524. ) {
  1525. $printview = isset($_POST['printview']) && $_POST['printview'] == '1' ? '1' : null;
  1526. $table_html = '';
  1527. $browse_dist = ! empty($_POST['is_browse_distinct']);
  1528. if ($analyzed_sql_results['is_procedure']) {
  1529. do {
  1530. if (! isset($result)) {
  1531. $result = $GLOBALS['dbi']->storeResult();
  1532. }
  1533. $num_rows = $GLOBALS['dbi']->numRows($result);
  1534. if ($result !== false && $num_rows > 0) {
  1535. $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
  1536. if (! is_array($fields_meta)) {
  1537. $fields_cnt = 0;
  1538. } else {
  1539. $fields_cnt = count($fields_meta);
  1540. }
  1541. $displayResultsObject->setProperties(
  1542. $num_rows,
  1543. $fields_meta,
  1544. $analyzed_sql_results['is_count'],
  1545. $analyzed_sql_results['is_export'],
  1546. $analyzed_sql_results['is_func'],
  1547. $analyzed_sql_results['is_analyse'],
  1548. $num_rows,
  1549. $fields_cnt,
  1550. $GLOBALS['querytime'],
  1551. $pmaThemeImage,
  1552. $GLOBALS['text_dir'],
  1553. $analyzed_sql_results['is_maint'],
  1554. $analyzed_sql_results['is_explain'],
  1555. $analyzed_sql_results['is_show'],
  1556. $showtable,
  1557. $printview,
  1558. $url_query,
  1559. $editable,
  1560. $browse_dist
  1561. );
  1562. $displayParts = array(
  1563. 'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
  1564. 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
  1565. 'sort_lnk' => '1',
  1566. 'nav_bar' => '1',
  1567. 'bkm_form' => '1',
  1568. 'text_btn' => '1',
  1569. 'pview_lnk' => '1'
  1570. );
  1571. $table_html .= $displayResultsObject->getTable(
  1572. $result,
  1573. $displayParts,
  1574. $analyzed_sql_results,
  1575. $is_limited_display
  1576. );
  1577. }
  1578. $GLOBALS['dbi']->freeResult($result);
  1579. unset($result);
  1580. } while ($GLOBALS['dbi']->moreResults() && $GLOBALS['dbi']->nextResult());
  1581. } else {
  1582. $fields_meta = array();
  1583. if (isset($result) && ! is_bool($result)) {
  1584. $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
  1585. }
  1586. $fields_cnt = count($fields_meta);
  1587. $_SESSION['is_multi_query'] = false;
  1588. $displayResultsObject->setProperties(
  1589. $unlim_num_rows,
  1590. $fields_meta,
  1591. $analyzed_sql_results['is_count'],
  1592. $analyzed_sql_results['is_export'],
  1593. $analyzed_sql_results['is_func'],
  1594. $analyzed_sql_results['is_analyse'],
  1595. $num_rows,
  1596. $fields_cnt, $GLOBALS['querytime'],
  1597. $pmaThemeImage, $GLOBALS['text_dir'],
  1598. $analyzed_sql_results['is_maint'],
  1599. $analyzed_sql_results['is_explain'],
  1600. $analyzed_sql_results['is_show'],
  1601. $showtable,
  1602. $printview,
  1603. $url_query,
  1604. $editable,
  1605. $browse_dist
  1606. );
  1607. if (! is_bool($result)) {
  1608. $table_html .= $displayResultsObject->getTable(
  1609. $result,
  1610. $displayParts,
  1611. $analyzed_sql_results,
  1612. $is_limited_display
  1613. );
  1614. }
  1615. $GLOBALS['dbi']->freeResult($result);
  1616. }
  1617. return $table_html;
  1618. }
  1619. /**
  1620. * Function to get html for the previous query if there is such. If not will return
  1621. * null
  1622. *
  1623. * @param string $disp_query display query
  1624. * @param bool $showSql whether to show sql
  1625. * @param array $sql_data sql data
  1626. * @param string $disp_message display message
  1627. *
  1628. * @return string $previous_update_query_html
  1629. */
  1630. private function getHtmlForPreviousUpdateQuery($disp_query, $showSql, $sql_data,
  1631. $disp_message
  1632. ) {
  1633. // previous update query (from tbl_replace)
  1634. if (isset($disp_query) && ($showSql == true) && empty($sql_data)) {
  1635. $previous_update_query_html = Util::getMessage(
  1636. $disp_message, $disp_query, 'success'
  1637. );
  1638. } else {
  1639. $previous_update_query_html = null;
  1640. }
  1641. return $previous_update_query_html;
  1642. }
  1643. /**
  1644. * To get the message if a column index is missing. If not will return null
  1645. *
  1646. * @param string $table current table
  1647. * @param string $db current database
  1648. * @param boolean $editable whether the results table can be editable or not
  1649. * @param boolean $has_unique whether there is a unique key
  1650. *
  1651. * @return Message $message
  1652. */
  1653. private function getMessageIfMissingColumnIndex($table, $db, $editable, $has_unique)
  1654. {
  1655. if (!empty($table) && ($GLOBALS['dbi']->isSystemSchema($db) || !$editable)) {
  1656. $missing_unique_column_msg = Message::notice(
  1657. sprintf(
  1658. __(
  1659. 'Current selection does not contain a unique column.'
  1660. . ' Grid edit, checkbox, Edit, Copy and Delete features'
  1661. . ' are not available. %s'
  1662. ),
  1663. Util::showDocu(
  1664. 'config',
  1665. 'cfg_RowActionLinksWithoutUnique'
  1666. )
  1667. )
  1668. );
  1669. } elseif (! empty($table) && ! $has_unique) {
  1670. $missing_unique_column_msg = Message::notice(
  1671. sprintf(
  1672. __(
  1673. 'Current selection does not contain a unique column.'
  1674. . ' Grid edit, Edit, Copy and Delete features may result in'
  1675. . ' undesired behavior. %s'
  1676. ),
  1677. Util::showDocu(
  1678. 'config',
  1679. 'cfg_RowActionLinksWithoutUnique'
  1680. )
  1681. )
  1682. );
  1683. } else {
  1684. $missing_unique_column_msg = null;
  1685. }
  1686. return $missing_unique_column_msg;
  1687. }
  1688. /**
  1689. * Function to get html to display problems in indexes
  1690. *
  1691. * @param string $query_type query type
  1692. * @param array|null $selectedTables array of table names selected from the
  1693. * database structure page, for an action
  1694. * like check table, optimize table,
  1695. * analyze table or repair table
  1696. * @param string $db current database
  1697. *
  1698. * @return string
  1699. */
  1700. private function getHtmlForIndexesProblems($query_type, $selectedTables, $db)
  1701. {
  1702. // BEGIN INDEX CHECK See if indexes should be checked.
  1703. if (isset($query_type)
  1704. && $query_type == 'check_tbl'
  1705. && isset($selectedTables)
  1706. && is_array($selectedTables)
  1707. ) {
  1708. $indexes_problems_html = '';
  1709. foreach ($selectedTables as $tbl_name) {
  1710. $check = Index::findDuplicates($tbl_name, $db);
  1711. if (! empty($check)) {
  1712. $indexes_problems_html .= sprintf(
  1713. __('Problems with indexes of table `%s`'), $tbl_name
  1714. );
  1715. $indexes_problems_html .= $check;
  1716. }
  1717. }
  1718. } else {
  1719. $indexes_problems_html = null;
  1720. }
  1721. return $indexes_problems_html;
  1722. }
  1723. /**
  1724. * Function to display results when the executed query returns non empty results
  1725. *
  1726. * @param object $result executed query results
  1727. * @param array $analyzed_sql_results analysed sql results
  1728. * @param string $db current database
  1729. * @param string $table current table
  1730. * @param string $message message to show
  1731. * @param array $sql_data sql data
  1732. * @param DisplayResults $displayResultsObject Instance of DisplayResults
  1733. * @param string $pmaThemeImage uri of the theme image
  1734. * @param int $unlim_num_rows unlimited number of rows
  1735. * @param int $num_rows number of rows
  1736. * @param string $disp_query display query
  1737. * @param string $disp_message display message
  1738. * @param array $profiling_results profiling results
  1739. * @param string $query_type query type
  1740. * @param array|null $selectedTables array of table names selected
  1741. * from the database structure page, for
  1742. * an action like check table,
  1743. * optimize table, analyze table or
  1744. * repair table
  1745. * @param string $sql_query sql query
  1746. * @param string $complete_query complete sql query
  1747. *
  1748. * @return string html
  1749. */
  1750. private function getQueryResponseForResultsReturned($result, array $analyzed_sql_results,
  1751. $db, $table, $message, $sql_data, $displayResultsObject, $pmaThemeImage,
  1752. $unlim_num_rows, $num_rows, $disp_query, $disp_message, $profiling_results,
  1753. $query_type, $selectedTables, $sql_query, $complete_query
  1754. ) {
  1755. // If we are retrieving the full value of a truncated field or the original
  1756. // value of a transformed field, show it here
  1757. if (isset($_POST['grid_edit']) && $_POST['grid_edit'] == true) {
  1758. $this->sendResponseForGridEdit($result);
  1759. // script has exited at this point
  1760. }
  1761. // Gets the list of fields properties
  1762. if (isset($result) && $result) {
  1763. $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
  1764. }
  1765. // Should be initialized these parameters before parsing
  1766. $showtable = isset($showtable) ? $showtable : null;
  1767. $url_query = isset($url_query) ? $url_query : null;
  1768. $response = Response::getInstance();
  1769. $header = $response->getHeader();
  1770. $scripts = $header->getScripts();
  1771. $just_one_table = $this->resultSetHasJustOneTable($fields_meta);
  1772. // hide edit and delete links:
  1773. // - for information_schema
  1774. // - if the result set does not contain all the columns of a unique key
  1775. // (unless this is an updatable view)
  1776. // - if the SELECT query contains a join or a subquery
  1777. $updatableView = false;
  1778. $statement = isset($analyzed_sql_results['statement']) ? $analyzed_sql_results['statement'] : null;
  1779. if ($statement instanceof SelectStatement) {
  1780. if (!empty($statement->expr)) {
  1781. if ($statement->expr[0]->expr === '*') {
  1782. $_table = new Table($table, $db);
  1783. $updatableView = $_table->isUpdatableView();
  1784. }
  1785. }
  1786. if ($analyzed_sql_results['join']
  1787. || $analyzed_sql_results['is_subquery']
  1788. || count($analyzed_sql_results['select_tables']) !== 1
  1789. ) {
  1790. $just_one_table = false;
  1791. }
  1792. }
  1793. $has_unique = $this->resultSetContainsUniqueKey(
  1794. $db, $table, $fields_meta
  1795. );
  1796. $editable = ($has_unique
  1797. || $GLOBALS['cfg']['RowActionLinksWithoutUnique']
  1798. || $updatableView)
  1799. && $just_one_table;
  1800. $_SESSION['tmpval']['possible_as_geometry'] = $editable;
  1801. $displayParts = array(
  1802. 'edit_lnk' => $displayResultsObject::UPDATE_ROW,
  1803. 'del_lnk' => $displayResultsObject::DELETE_ROW,
  1804. 'sort_lnk' => '1',
  1805. 'nav_bar' => '1',
  1806. 'bkm_form' => '1',
  1807. 'text_btn' => '0',
  1808. 'pview_lnk' => '1'
  1809. );
  1810. if ($GLOBALS['dbi']->isSystemSchema($db) || !$editable) {
  1811. $displayParts = array(
  1812. 'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
  1813. 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
  1814. 'sort_lnk' => '1',
  1815. 'nav_bar' => '1',
  1816. 'bkm_form' => '1',
  1817. 'text_btn' => '1',
  1818. 'pview_lnk' => '1'
  1819. );
  1820. }
  1821. if (isset($_POST['printview']) && $_POST['printview'] == '1') {
  1822. $displayParts = array(
  1823. 'edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
  1824. 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE,
  1825. 'sort_lnk' => '0',
  1826. 'nav_bar' => '0',
  1827. 'bkm_form' => '0',
  1828. 'text_btn' => '0',
  1829. 'pview_lnk' => '0'
  1830. );
  1831. }
  1832. if (isset($_POST['table_maintenance'])) {
  1833. $scripts->addFile('makegrid.js');
  1834. $scripts->addFile('sql.js');
  1835. $table_maintenance_html = '';
  1836. if (isset($message)) {
  1837. $message = Message::success($message);
  1838. $table_maintenance_html = Util::getMessage(
  1839. $message, $GLOBALS['sql_query'], 'success'
  1840. );
  1841. }
  1842. $table_maintenance_html .= $this->getHtmlForSqlQueryResultsTable(
  1843. $displayResultsObject,
  1844. $pmaThemeImage, $url_query, $displayParts,
  1845. false, $unlim_num_rows, $num_rows, $showtable, $result,
  1846. $analyzed_sql_results
  1847. );
  1848. if (empty($sql_data) || ($sql_data['valid_queries'] = 1)) {
  1849. $response->addHTML($table_maintenance_html);
  1850. exit();
  1851. }
  1852. }
  1853. if (!isset($_POST['printview']) || $_POST['printview'] != '1') {
  1854. $scripts->addFile('makegrid.js');
  1855. $scripts->addFile('sql.js');
  1856. unset($GLOBALS['message']);
  1857. //we don't need to buffer the output in getMessage here.
  1858. //set a global variable and check against it in the function
  1859. $GLOBALS['buffer_message'] = false;
  1860. }
  1861. $previous_update_query_html = $this->getHtmlForPreviousUpdateQuery(
  1862. isset($disp_query) ? $disp_query : null,
  1863. $GLOBALS['cfg']['ShowSQL'], isset($sql_data) ? $sql_data : null,
  1864. isset($disp_message) ? $disp_message : null
  1865. );
  1866. $profiling_chart_html = $this->getHtmlForProfilingChart(
  1867. $url_query, $db, isset($profiling_results) ? $profiling_results :array()
  1868. );
  1869. $missing_unique_column_msg = $this->getMessageIfMissingColumnIndex(
  1870. $table, $db, $editable, $has_unique
  1871. );
  1872. $bookmark_created_msg = $this->getBookmarkCreatedMessage();
  1873. $table_html = $this->getHtmlForSqlQueryResultsTable(
  1874. $displayResultsObject,
  1875. $pmaThemeImage, $url_query, $displayParts,
  1876. $editable, $unlim_num_rows, $num_rows, $showtable, $result,
  1877. $analyzed_sql_results
  1878. );
  1879. $indexes_problems_html = $this->getHtmlForIndexesProblems(
  1880. isset($query_type) ? $query_type : null,
  1881. isset($selectedTables) ? $selectedTables : null, $db
  1882. );
  1883. $cfgBookmark = Bookmark::getParams($GLOBALS['cfg']['Server']['user']);
  1884. if ($cfgBookmark) {
  1885. $bookmark_support_html = $this->getHtmlForBookmark(
  1886. $displayParts,
  1887. $cfgBookmark,
  1888. $sql_query, $db, $table,
  1889. isset($complete_query) ? $complete_query : $sql_query,
  1890. $cfgBookmark['user']
  1891. );
  1892. } else {
  1893. $bookmark_support_html = '';
  1894. }
  1895. $html_output = isset($table_maintenance_html) ? $table_maintenance_html : '';
  1896. $html_output .= $this->getHtmlForSqlQueryResults(
  1897. $previous_update_query_html, $profiling_chart_html,
  1898. $missing_unique_column_msg, $bookmark_created_msg,
  1899. $table_html, $indexes_problems_html, $bookmark_support_html
  1900. );
  1901. return $html_output;
  1902. }
  1903. /**
  1904. * Function to execute the query and send the response
  1905. *
  1906. * @param array $analyzed_sql_results analysed sql results
  1907. * @param bool $is_gotofile whether goto file or not
  1908. * @param string $db current database
  1909. * @param string $table current table
  1910. * @param bool|null $find_real_end whether to find real end or not
  1911. * @param string $sql_query_for_bookmark the sql query to be stored as bookmark
  1912. * @param array|null $extra_data extra data
  1913. * @param string $message_to_show message to show
  1914. * @param string $message message
  1915. * @param array|null $sql_data sql data
  1916. * @param string $goto goto page url
  1917. * @param string $pmaThemeImage uri of the PMA theme image
  1918. * @param string $disp_query display query
  1919. * @param string $disp_message display message
  1920. * @param string $query_type query type
  1921. * @param string $sql_query sql query
  1922. * @param array|null $selectedTables array of table names selected from the
  1923. * database structure page, for an action
  1924. * like check table, optimize table,
  1925. * analyze table or repair table
  1926. * @param string $complete_query complete query
  1927. *
  1928. * @return void
  1929. */
  1930. public function executeQueryAndSendQueryResponse($analyzed_sql_results,
  1931. $is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark,
  1932. $extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage,
  1933. $disp_query, $disp_message, $query_type, $sql_query, $selectedTables,
  1934. $complete_query
  1935. ) {
  1936. if ($analyzed_sql_results == null) {
  1937. // Parse and analyze the query
  1938. list(
  1939. $analyzed_sql_results,
  1940. $db,
  1941. $table_from_sql
  1942. ) = ParseAnalyze::sqlQuery($sql_query, $db);
  1943. // @todo: possibly refactor
  1944. extract($analyzed_sql_results);
  1945. if ($table != $table_from_sql && !empty($table_from_sql)) {
  1946. $table = $table_from_sql;
  1947. }
  1948. }
  1949. $html_output = $this->executeQueryAndGetQueryResponse(
  1950. $analyzed_sql_results, // analyzed_sql_results
  1951. $is_gotofile, // is_gotofile
  1952. $db, // db
  1953. $table, // table
  1954. $find_real_end, // find_real_end
  1955. $sql_query_for_bookmark, // sql_query_for_bookmark
  1956. $extra_data, // extra_data
  1957. $message_to_show, // message_to_show
  1958. $message, // message
  1959. $sql_data, // sql_data
  1960. $goto, // goto
  1961. $pmaThemeImage, // pmaThemeImage
  1962. $disp_query, // disp_query
  1963. $disp_message, // disp_message
  1964. $query_type, // query_type
  1965. $sql_query, // sql_query
  1966. $selectedTables, // selectedTables
  1967. $complete_query // complete_query
  1968. );
  1969. $response = Response::getInstance();
  1970. $response->addHTML($html_output);
  1971. }
  1972. /**
  1973. * Function to execute the query and send the response
  1974. *
  1975. * @param array $analyzed_sql_results analysed sql results
  1976. * @param bool $is_gotofile whether goto file or not
  1977. * @param string $db current database
  1978. * @param string $table current table
  1979. * @param bool|null $find_real_end whether to find real end or not
  1980. * @param string $sql_query_for_bookmark the sql query to be stored as bookmark
  1981. * @param array|null $extra_data extra data
  1982. * @param string $message_to_show message to show
  1983. * @param string $message message
  1984. * @param array|null $sql_data sql data
  1985. * @param string $goto goto page url
  1986. * @param string $pmaThemeImage uri of the PMA theme image
  1987. * @param string $disp_query display query
  1988. * @param string $disp_message display message
  1989. * @param string $query_type query type
  1990. * @param string $sql_query sql query
  1991. * @param array|null $selectedTables array of table names selected from the
  1992. * database structure page, for an action
  1993. * like check table, optimize table,
  1994. * analyze table or repair table
  1995. * @param string $complete_query complete query
  1996. *
  1997. * @return string html
  1998. */
  1999. public function executeQueryAndGetQueryResponse(array $analyzed_sql_results,
  2000. $is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark,
  2001. $extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage,
  2002. $disp_query, $disp_message, $query_type, $sql_query, $selectedTables,
  2003. $complete_query
  2004. ) {
  2005. // Handle disable/enable foreign key checks
  2006. $default_fk_check = Util::handleDisableFKCheckInit();
  2007. // Handle remembered sorting order, only for single table query.
  2008. // Handling is not required when it's a union query
  2009. // (the parser never sets the 'union' key to 0).
  2010. // Handling is also not required if we came from the "Sort by key"
  2011. // drop-down.
  2012. if (! empty($analyzed_sql_results)
  2013. && $this->isRememberSortingOrder($analyzed_sql_results)
  2014. && empty($analyzed_sql_results['union'])
  2015. && ! isset($_POST['sort_by_key'])
  2016. ) {
  2017. if (! isset($_SESSION['sql_from_query_box'])) {
  2018. $this->handleSortOrder($db, $table, $analyzed_sql_results, $sql_query);
  2019. } else {
  2020. unset($_SESSION['sql_from_query_box']);
  2021. }
  2022. }
  2023. $displayResultsObject = new DisplayResults(
  2024. $GLOBALS['db'], $GLOBALS['table'], $goto, $sql_query
  2025. );
  2026. $displayResultsObject->setConfigParamsForDisplayTable();
  2027. // assign default full_sql_query
  2028. $full_sql_query = $sql_query;
  2029. // Do append a "LIMIT" clause?
  2030. if ($this->isAppendLimitClause($analyzed_sql_results)) {
  2031. $full_sql_query = $this->getSqlWithLimitClause($analyzed_sql_results);
  2032. }
  2033. $GLOBALS['reload'] = $this->hasCurrentDbChanged($db);
  2034. $GLOBALS['dbi']->selectDb($db);
  2035. // Execute the query
  2036. list($result, $num_rows, $unlim_num_rows, $profiling_results, $extra_data)
  2037. = $this->executeTheQuery(
  2038. $analyzed_sql_results,
  2039. $full_sql_query,
  2040. $is_gotofile,
  2041. $db,
  2042. $table,
  2043. isset($find_real_end) ? $find_real_end : null,
  2044. isset($sql_query_for_bookmark) ? $sql_query_for_bookmark : null,
  2045. isset($extra_data) ? $extra_data : null
  2046. );
  2047. if ($GLOBALS['dbi']->moreResults()) {
  2048. $GLOBALS['dbi']->nextResult();
  2049. }
  2050. $operations = new Operations();
  2051. $warning_messages = $operations->getWarningMessagesArray();
  2052. // No rows returned -> move back to the calling page
  2053. if ((0 == $num_rows && 0 == $unlim_num_rows)
  2054. || $analyzed_sql_results['is_affected']
  2055. ) {
  2056. $html_output = $this->getQueryResponseForNoResultsReturned(
  2057. $analyzed_sql_results, $db, $table,
  2058. isset($message_to_show) ? $message_to_show : null,
  2059. $num_rows, $displayResultsObject, $extra_data,
  2060. $pmaThemeImage, $profiling_results, isset($result) ? $result : null,
  2061. $sql_query, isset($complete_query) ? $complete_query : null
  2062. );
  2063. } else {
  2064. // At least one row is returned -> displays a table with results
  2065. $html_output = $this->getQueryResponseForResultsReturned(
  2066. isset($result) ? $result : null,
  2067. $analyzed_sql_results,
  2068. $db,
  2069. $table,
  2070. isset($message) ? $message : null,
  2071. isset($sql_data) ? $sql_data : null,
  2072. $displayResultsObject,
  2073. $pmaThemeImage,
  2074. $unlim_num_rows,
  2075. $num_rows,
  2076. isset($disp_query) ? $disp_query : null,
  2077. isset($disp_message) ? $disp_message : null,
  2078. $profiling_results,
  2079. isset($query_type) ? $query_type : null,
  2080. isset($selectedTables) ? $selectedTables : null,
  2081. $sql_query,
  2082. isset($complete_query) ? $complete_query : null
  2083. );
  2084. }
  2085. // Handle disable/enable foreign key checks
  2086. Util::handleDisableFKCheckCleanup($default_fk_check);
  2087. foreach ($warning_messages as $warning) {
  2088. $message = Message::notice(Message::sanitize($warning));
  2089. $html_output .= $message->getDisplay();
  2090. }
  2091. return $html_output;
  2092. }
  2093. /**
  2094. * Function to define pos to display a row
  2095. *
  2096. * @param int $number_of_line Number of the line to display
  2097. * @param int $max_rows Number of rows by page
  2098. *
  2099. * @return int Start position to display the line
  2100. */
  2101. private function getStartPosToDisplayRow($number_of_line, $max_rows = null)
  2102. {
  2103. if (null === $max_rows) {
  2104. $max_rows = $_SESSION['tmpval']['max_rows'];
  2105. }
  2106. return @((ceil($number_of_line / $max_rows) - 1) * $max_rows);
  2107. }
  2108. /**
  2109. * Function to calculate new pos if pos is higher than number of rows
  2110. * of displayed table
  2111. *
  2112. * @param string $db Database name
  2113. * @param string $table Table name
  2114. * @param int|null $pos Initial position
  2115. *
  2116. * @return int Number of pos to display last page
  2117. */
  2118. public function calculatePosForLastPage($db, $table, $pos)
  2119. {
  2120. if (null === $pos) {
  2121. $pos = $_SESSION['tmpval']['pos'];
  2122. }
  2123. $_table = new Table($table, $db);
  2124. $unlim_num_rows = $_table->countRecords(true);
  2125. //If position is higher than number of rows
  2126. if ($unlim_num_rows <= $pos && 0 != $pos) {
  2127. $pos = $this->getStartPosToDisplayRow($unlim_num_rows);
  2128. }
  2129. return $pos;
  2130. }
  2131. }