sql.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * SQL executor
  5. *
  6. * @todo we must handle the case if sql.php is called directly with a query
  7. * that returns 0 rows - to prevent cyclic redirects or includes
  8. * @package PhpMyAdmin
  9. */
  10. /**
  11. * Gets some core libraries
  12. */
  13. require_once 'libraries/common.inc.php';
  14. require_once 'libraries/Table.class.php';
  15. require_once 'libraries/Header.class.php';
  16. require_once 'libraries/check_user_privileges.lib.php';
  17. require_once 'libraries/bookmark.lib.php';
  18. $response = PMA_Response::getInstance();
  19. $header = $response->getHeader();
  20. $scripts = $header->getScripts();
  21. $scripts->addFile('jquery/jquery-ui-timepicker-addon.js');
  22. $scripts->addFile('tbl_change.js');
  23. // the next one needed because sql.php may do a "goto" to tbl_structure.php
  24. $scripts->addFile('tbl_structure.js');
  25. $scripts->addFile('indexes.js');
  26. $scripts->addFile('gis_data_editor.js');
  27. /**
  28. * Set ajax_reload in the response if it was already set
  29. */
  30. if (isset($ajax_reload) && $ajax_reload['reload'] === true) {
  31. $response->addJSON('ajax_reload', $ajax_reload);
  32. }
  33. /**
  34. * Sets globals from $_POST
  35. */
  36. $post_params = array(
  37. 'bkm_all_users',
  38. 'fields',
  39. 'store_bkm'
  40. );
  41. foreach ($post_params as $one_post_param) {
  42. if (isset($_POST[$one_post_param])) {
  43. $GLOBALS[$one_post_param] = $_POST[$one_post_param];
  44. }
  45. }
  46. /**
  47. * Sets globals from $_GET
  48. */
  49. $get_params = array(
  50. 'id_bookmark',
  51. 'label',
  52. 'sql_query'
  53. );
  54. foreach ($get_params as $one_get_param) {
  55. if (isset($_GET[$one_get_param])) {
  56. $GLOBALS[$one_get_param] = $_GET[$one_get_param];
  57. }
  58. }
  59. if (isset($_REQUEST['printview'])) {
  60. $GLOBALS['printview'] = $_REQUEST['printview'];
  61. }
  62. if (!isset($_SESSION['is_multi_query'])) {
  63. $_SESSION['is_multi_query'] = false;
  64. }
  65. /**
  66. * Defines the url to return to in case of error in a sql statement
  67. */
  68. // Security checkings
  69. if (! empty($goto)) {
  70. $is_gotofile = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
  71. if (! @file_exists('' . $is_gotofile)) {
  72. unset($goto);
  73. } else {
  74. $is_gotofile = ($is_gotofile == $goto);
  75. }
  76. } else {
  77. if (empty($table)) {
  78. $goto = $cfg['DefaultTabDatabase'];
  79. } else {
  80. $goto = $cfg['DefaultTabTable'];
  81. }
  82. $is_gotofile = true;
  83. } // end if
  84. if (! isset($err_url)) {
  85. $err_url = (! empty($back) ? $back : $goto)
  86. . '?' . PMA_generate_common_url($db)
  87. . ((strpos(' ' . $goto, 'db_') != 1 && strlen($table))
  88. ? '&amp;table=' . urlencode($table)
  89. : ''
  90. );
  91. } // end if
  92. // Coming from a bookmark dialog
  93. if (isset($fields['query'])) {
  94. $sql_query = $fields['query'];
  95. }
  96. // This one is just to fill $db
  97. if (isset($fields['dbase'])) {
  98. $db = $fields['dbase'];
  99. }
  100. /**
  101. * During grid edit, if we have a relational field, show the dropdown for it
  102. *
  103. * Logic taken from libraries/DisplayResults.class.php
  104. *
  105. * This doesn't seem to be the right place to do this, but I can't think of any
  106. * better place either.
  107. */
  108. if (isset($_REQUEST['get_relational_values'])
  109. && $_REQUEST['get_relational_values'] == true
  110. ) {
  111. $column = $_REQUEST['column'];
  112. $foreigners = PMA_getForeigners($db, $table, $column);
  113. $display_field = PMA_getDisplayField(
  114. $foreigners[$column]['foreign_db'],
  115. $foreigners[$column]['foreign_table']
  116. );
  117. $foreignData = PMA_getForeignData($foreigners, $column, false, '', '');
  118. if ($_SESSION['tmp_user_values']['relational_display'] == 'D'
  119. && isset($display_field)
  120. && strlen($display_field)
  121. && isset($_REQUEST['relation_key_or_display_column'])
  122. && $_REQUEST['relation_key_or_display_column']
  123. ) {
  124. $curr_value = $_REQUEST['relation_key_or_display_column'];
  125. } else {
  126. $curr_value = $_REQUEST['curr_value'];
  127. }
  128. if ($foreignData['disp_row'] == null) {
  129. //Handle the case when number of values
  130. //is more than $cfg['ForeignKeyMaxLimit']
  131. $_url_params = array(
  132. 'db' => $db,
  133. 'table' => $table,
  134. 'field' => $column
  135. );
  136. $dropdown = '<span class="curr_value">'
  137. . htmlspecialchars($_REQUEST['curr_value'])
  138. . '</span>'
  139. . '<a href="browse_foreigners.php'
  140. . PMA_generate_common_url($_url_params) . '"'
  141. . ' target="_blank" class="browse_foreign" ' .'>'
  142. . __('Browse foreign values')
  143. . '</a>';
  144. } else {
  145. $dropdown = PMA_foreignDropdown(
  146. $foreignData['disp_row'],
  147. $foreignData['foreign_field'],
  148. $foreignData['foreign_display'],
  149. $curr_value,
  150. $cfg['ForeignKeyMaxLimit']
  151. );
  152. $dropdown = '<select>' . $dropdown . '</select>';
  153. }
  154. $response = PMA_Response::getInstance();
  155. $response->addJSON('dropdown', $dropdown);
  156. exit;
  157. }
  158. /**
  159. * Just like above, find possible values for enum fields during grid edit.
  160. *
  161. * Logic taken from libraries/DisplayResults.class.php
  162. */
  163. if (isset($_REQUEST['get_enum_values']) && $_REQUEST['get_enum_values'] == true) {
  164. $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
  165. $field_info_result = PMA_DBI_fetch_result(
  166. $field_info_query, null, null, null, PMA_DBI_QUERY_STORE
  167. );
  168. $values = PMA_Util::parseEnumSetValues($field_info_result[0]['Type']);
  169. $dropdown = '<option value="">&nbsp;</option>';
  170. foreach ($values as $value) {
  171. $dropdown .= '<option value="' . $value . '"';
  172. if ($value == $_REQUEST['curr_value']) {
  173. $dropdown .= ' selected="selected"';
  174. }
  175. $dropdown .= '>' . $value . '</option>';
  176. }
  177. $dropdown = '<select>' . $dropdown . '</select>';
  178. $response = PMA_Response::getInstance();
  179. $response->addJSON('dropdown', $dropdown);
  180. exit;
  181. }
  182. /**
  183. * Find possible values for set fields during grid edit.
  184. */
  185. if (isset($_REQUEST['get_set_values']) && $_REQUEST['get_set_values'] == true) {
  186. $field_info_query = PMA_DBI_get_columns_sql($db, $table, $_REQUEST['column']);
  187. $field_info_result = PMA_DBI_fetch_result(
  188. $field_info_query, null, null, null, PMA_DBI_QUERY_STORE
  189. );
  190. $values = PMA_Util::parseEnumSetValues($field_info_result[0]['Type']);
  191. $select = '';
  192. //converts characters of $_REQUEST['curr_value'] to HTML entities
  193. $converted_curr_value = htmlentities(
  194. $_REQUEST['curr_value'], ENT_COMPAT, "UTF-8"
  195. );
  196. $selected_values = explode(',', $converted_curr_value);
  197. foreach ($values as $value) {
  198. $select .= '<option value="' . $value . '"';
  199. if ($value == $converted_curr_value
  200. || in_array($value, $selected_values, true)
  201. ) {
  202. $select .= ' selected="selected" ';
  203. }
  204. $select .= '>' . $value . '</option>';
  205. }
  206. $select_size = (sizeof($values) > 10) ? 10 : sizeof($values);
  207. $select = '<select multiple="multiple" size="' . $select_size . '">'
  208. . $select . '</select>';
  209. $response = PMA_Response::getInstance();
  210. $response->addJSON('select', $select);
  211. exit;
  212. }
  213. /**
  214. * Check ajax request to set the column order
  215. */
  216. if (isset($_REQUEST['set_col_prefs']) && $_REQUEST['set_col_prefs'] == true) {
  217. $pmatable = new PMA_Table($table, $db);
  218. $retval = false;
  219. // set column order
  220. if (isset($_REQUEST['col_order'])) {
  221. $col_order = explode(',', $_REQUEST['col_order']);
  222. $retval = $pmatable->setUiProp(
  223. PMA_Table::PROP_COLUMN_ORDER,
  224. $col_order,
  225. $_REQUEST['table_create_time']
  226. );
  227. if (gettype($retval) != 'boolean') {
  228. $response = PMA_Response::getInstance();
  229. $response->isSuccess(false);
  230. $response->addJSON('message', $retval->getString());
  231. exit;
  232. }
  233. }
  234. // set column visibility
  235. if ($retval === true && isset($_REQUEST['col_visib'])) {
  236. $col_visib = explode(',', $_REQUEST['col_visib']);
  237. $retval = $pmatable->setUiProp(
  238. PMA_Table::PROP_COLUMN_VISIB, $col_visib,
  239. $_REQUEST['table_create_time']
  240. );
  241. if (gettype($retval) != 'boolean') {
  242. $response = PMA_Response::getInstance();
  243. $response->isSuccess(false);
  244. $response->addJSON('message', $retval->getString());
  245. exit;
  246. }
  247. }
  248. $response = PMA_Response::getInstance();
  249. $response->isSuccess($retval == true);
  250. exit;
  251. }
  252. // Default to browse if no query set and we have table
  253. // (needed for browsing from DefaultTabTable)
  254. if (empty($sql_query) && strlen($table) && strlen($db)) {
  255. include_once 'libraries/bookmark.lib.php';
  256. $book_sql_query = PMA_Bookmark_get(
  257. $db,
  258. '\'' . PMA_Util::sqlAddSlashes($table) . '\'',
  259. 'label',
  260. false,
  261. true
  262. );
  263. if (! empty($book_sql_query)) {
  264. $GLOBALS['using_bookmark_message'] = PMA_message::notice(
  265. __('Using bookmark "%s" as default browse query.')
  266. );
  267. $GLOBALS['using_bookmark_message']->addParam($table);
  268. $GLOBALS['using_bookmark_message']->addMessage(
  269. PMA_Util::showDocu('faq', 'faq6-22')
  270. );
  271. $sql_query = $book_sql_query;
  272. } else {
  273. $sql_query = 'SELECT * FROM ' . PMA_Util::backquote($table);
  274. }
  275. unset($book_sql_query);
  276. // set $goto to what will be displayed if query returns 0 rows
  277. $goto = '';
  278. } else {
  279. // Now we can check the parameters
  280. PMA_Util::checkParameters(array('sql_query'));
  281. }
  282. // instead of doing the test twice
  283. $is_drop_database = preg_match(
  284. '/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
  285. $sql_query
  286. );
  287. /**
  288. * Check rights in case of DROP DATABASE
  289. *
  290. * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
  291. * but since a malicious user may pass this variable by url/form, we don't take
  292. * into account this case.
  293. */
  294. if (! defined('PMA_CHK_DROP')
  295. && ! $cfg['AllowUserDropDatabase']
  296. && $is_drop_database
  297. && ! $is_superuser
  298. ) {
  299. PMA_Util::mysqlDie(
  300. __('"DROP DATABASE" statements are disabled.'),
  301. '',
  302. '',
  303. $err_url
  304. );
  305. } // end if
  306. // Include PMA_Index class for use in PMA_DisplayResults class
  307. require_once './libraries/Index.class.php';
  308. require_once 'libraries/DisplayResults.class.php';
  309. $displayResultsObject = new PMA_DisplayResults(
  310. $GLOBALS['db'], $GLOBALS['table'], $GLOBALS['goto'], $GLOBALS['sql_query']
  311. );
  312. $displayResultsObject->setConfigParamsForDisplayTable();
  313. /**
  314. * Need to find the real end of rows?
  315. */
  316. if (isset($find_real_end) && $find_real_end) {
  317. $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
  318. $_SESSION['tmp_user_values']['pos'] = @((ceil(
  319. $unlim_num_rows / $_SESSION['tmp_user_values']['max_rows']
  320. ) - 1) * $_SESSION['tmp_user_values']['max_rows']);
  321. }
  322. /**
  323. * Bookmark add
  324. */
  325. if (isset($store_bkm)) {
  326. $result = PMA_Bookmark_save(
  327. $fields,
  328. (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false)
  329. );
  330. $response = PMA_Response::getInstance();
  331. if ($response->isAjax()) {
  332. if ($result) {
  333. $msg = PMA_message::success(__('Bookmark %s created'));
  334. $msg->addParam($fields['label']);
  335. $response->addJSON('message', $msg);
  336. } else {
  337. $msg = PMA_message::error(__('Bookmark not created'));
  338. $response->isSuccess(false);
  339. $response->addJSON('message', $msg);
  340. }
  341. exit;
  342. } else {
  343. // go back to sql.php to redisplay query; do not use &amp; in this case:
  344. PMA_sendHeaderLocation(
  345. $cfg['PmaAbsoluteUri'] . $goto . '&label=' . $fields['label']
  346. );
  347. }
  348. } // end if
  349. /**
  350. * Parse and analyze the query
  351. */
  352. require_once 'libraries/parse_analyze.lib.php';
  353. /**
  354. * Sets or modifies the $goto variable if required
  355. */
  356. if ($goto == 'sql.php') {
  357. $is_gotofile = false;
  358. $goto = 'sql.php?'
  359. . PMA_generate_common_url($db, $table)
  360. . '&amp;sql_query=' . urlencode($sql_query);
  361. } // end if
  362. /**
  363. * Go back to further page if table should not be dropped
  364. */
  365. if (isset($_REQUEST['btnDrop']) && $_REQUEST['btnDrop'] == __('No')) {
  366. if (! empty($back)) {
  367. $goto = $back;
  368. }
  369. if ($is_gotofile) {
  370. if (strpos($goto, 'db_') === 0 && strlen($table)) {
  371. $table = '';
  372. }
  373. $active_page = $goto;
  374. include '' . PMA_securePath($goto);
  375. } else {
  376. PMA_sendHeaderLocation(
  377. $cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto)
  378. );
  379. }
  380. exit();
  381. } // end if
  382. /**
  383. * Displays the confirm page if required
  384. *
  385. * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
  386. * with js) because possible security issue is not so important here: at most,
  387. * the confirm message isn't displayed.
  388. *
  389. * Also bypassed if only showing php code.or validating a SQL query
  390. */
  391. // if we are coming from a "Create PHP code" or a "Without PHP Code"
  392. // dialog, we won't execute the query anyway, so don't confirm
  393. if (! $cfg['Confirm']
  394. || isset($_REQUEST['is_js_confirmed'])
  395. || isset($_REQUEST['btnDrop'])
  396. || isset($GLOBALS['show_as_php'])
  397. || ! empty($GLOBALS['validatequery'])
  398. ) {
  399. $do_confirm = false;
  400. } else {
  401. $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
  402. }
  403. if ($do_confirm) {
  404. $stripped_sql_query = $sql_query;
  405. $input = '<input type="hidden" name="%s" value="%s" />';
  406. $output = '';
  407. if ($is_drop_database) {
  408. $output .= '<h1 class="error">';
  409. $output .= __('You are about to DESTROY a complete database!');
  410. $output .= '</h1>';
  411. }
  412. $form = '<form class="disableAjax" action="sql.php" method="post">';
  413. $form .= PMA_generate_common_hidden_inputs($db, $table);
  414. $form .= sprintf(
  415. $input, 'sql_query', htmlspecialchars($sql_query)
  416. );
  417. $form .= sprintf(
  418. $input, 'message_to_show',
  419. (isset($message_to_show) ? PMA_sanitize($message_to_show, true) : '')
  420. );
  421. $form .= sprintf(
  422. $input, 'goto', $goto
  423. );
  424. $form .= sprintf(
  425. $input, 'back',
  426. (isset($back) ? PMA_sanitize($back, true) : '')
  427. );
  428. $form .= sprintf(
  429. $input, 'reload',
  430. (isset($reload) ? PMA_sanitize($reload, true) : '')
  431. );
  432. $form .= sprintf(
  433. $input, 'purge',
  434. (isset($purge) ? PMA_sanitize($purge, true) : '')
  435. );
  436. $form .= sprintf(
  437. $input, 'dropped_column',
  438. (isset($dropped_column) ? PMA_sanitize($dropped_column, true) : '')
  439. );
  440. $form .= sprintf(
  441. $input, 'show_query',
  442. (isset($message_to_show) ? PMA_sanitize($show_query, true) : '')
  443. );
  444. $form = str_replace('%', '%%', $form) . '%s</form>';
  445. $output .='<fieldset class="confirmation">'
  446. .'<legend>'
  447. . __('Do you really want to execute the following query?')
  448. . '</legend>'
  449. .'<code>' . htmlspecialchars($stripped_sql_query) . '</code>'
  450. .'</fieldset>'
  451. .'<fieldset class="tblFooters">';
  452. $yes_input = sprintf($input, 'btnDrop', __('Yes'));
  453. $yes_input .= '<input type="submit" value="' . __('Yes') . '" id="buttonYes" />';
  454. $no_input = sprintf($input, 'btnDrop', __('No'));
  455. $no_input .= '<input type="submit" value="' . __('No') . '" id="buttonNo" />';
  456. $output .= sprintf($form, $yes_input);
  457. $output .= sprintf($form, $no_input);
  458. $output .='</fieldset>';
  459. $output .= '';
  460. $message = '';
  461. PMA_Response::getInstance()->addHTML($output);
  462. exit;
  463. } // end if $do_confirm
  464. // Defines some variables
  465. // A table has to be created, renamed, dropped -> navi frame should be reloaded
  466. /**
  467. * @todo use the parser/analyzer
  468. */
  469. if (empty($reload)
  470. && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)
  471. ) {
  472. $reload = 1;
  473. }
  474. // $is_group added for use in calculation of total number of rows.
  475. // $is_count is changed for more correct "LIMIT" clause
  476. // appending in queries like
  477. // "SELECT COUNT(...) FROM ... GROUP BY ..."
  478. /**
  479. * @todo detect all this with the parser, to avoid problems finding
  480. * those strings in comments or backquoted identifiers
  481. */
  482. list($is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain,
  483. $is_delete, $is_affected, $is_insert, $is_replace, $is_show, $is_maint)
  484. = PMA_getDisplayPropertyParams(
  485. $sql_query, $is_select
  486. );
  487. // assign default full_sql_query
  488. $full_sql_query = $sql_query;
  489. // Handle remembered sorting order, only for single table query
  490. if ($GLOBALS['cfg']['RememberSorting']
  491. && ! ($is_count || $is_export || $is_func || $is_analyse)
  492. && isset($analyzed_sql[0]['select_expr'])
  493. && (count($analyzed_sql[0]['select_expr']) == 0)
  494. && isset($analyzed_sql[0]['queryflags']['select_from'])
  495. && count($analyzed_sql[0]['table_ref']) == 1
  496. ) {
  497. PMA_handleSortOrder($db, $table, $analyzed_sql, $full_sql_query);
  498. }
  499. $sql_limit_to_append = '';
  500. // Do append a "LIMIT" clause?
  501. if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
  502. && ! ($is_count || $is_export || $is_func || $is_analyse)
  503. && isset($analyzed_sql[0]['queryflags']['select_from'])
  504. && ! isset($analyzed_sql[0]['queryflags']['offset'])
  505. && empty($analyzed_sql[0]['limit_clause'])
  506. ) {
  507. $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos']
  508. . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
  509. $full_sql_query = PMA_getSqlWithLimitClause(
  510. $full_sql_query,
  511. $analyzed_sql,
  512. $sql_limit_to_append
  513. );
  514. /**
  515. * @todo pretty printing of this modified query
  516. */
  517. if (isset($display_query)) {
  518. // if the analysis of the original query revealed that we found
  519. // a section_after_limit, we now have to analyze $display_query
  520. // to display it correctly
  521. if (! empty($analyzed_sql[0]['section_after_limit'])
  522. && trim($analyzed_sql[0]['section_after_limit']) != ';'
  523. ) {
  524. $analyzed_display_query = PMA_SQP_analyze(
  525. PMA_SQP_parse($display_query)
  526. );
  527. $display_query = $analyzed_display_query[0]['section_before_limit']
  528. . "\n" . $sql_limit_to_append
  529. . $analyzed_display_query[0]['section_after_limit'];
  530. }
  531. }
  532. }
  533. if (strlen($db)) {
  534. PMA_DBI_select_db($db);
  535. }
  536. // E x e c u t e t h e q u e r y
  537. // Only if we didn't ask to see the php code
  538. if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
  539. unset($result);
  540. $num_rows = 0;
  541. $unlim_num_rows = 0;
  542. } else {
  543. if (isset($_SESSION['profiling']) && PMA_Util::profilingSupported()) {
  544. PMA_DBI_query('SET PROFILING=1;');
  545. }
  546. // Measure query time.
  547. $querytime_before = array_sum(explode(' ', microtime()));
  548. $result = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
  549. // If a stored procedure was called, there may be more results that are
  550. // queued up and waiting to be flushed from the buffer. So let's do that.
  551. do {
  552. PMA_DBI_store_result();
  553. if (! PMA_DBI_more_results()) {
  554. break;
  555. }
  556. } while (PMA_DBI_next_result());
  557. $is_procedure = false;
  558. // Since multiple query execution is anyway handled,
  559. // ignore the WHERE clause of the first sql statement
  560. // which might contain a phrase like 'call '
  561. if (preg_match("/\bcall\b/i", $full_sql_query)
  562. && empty($analyzed_sql[0]['where_clause'])
  563. ) {
  564. $is_procedure = true;
  565. }
  566. $querytime_after = array_sum(explode(' ', microtime()));
  567. $GLOBALS['querytime'] = $querytime_after - $querytime_before;
  568. // Displays an error message if required and stop parsing the script
  569. $error = PMA_DBI_getError();
  570. if ($error) {
  571. if ($is_gotofile) {
  572. if (strpos($goto, 'db_') === 0 && strlen($table)) {
  573. $table = '';
  574. }
  575. $active_page = $goto;
  576. $message = PMA_Message::rawError($error);
  577. if ($GLOBALS['is_ajax_request'] == true) {
  578. $response = PMA_Response::getInstance();
  579. $response->isSuccess(false);
  580. $response->addJSON('message', $message);
  581. exit;
  582. }
  583. /**
  584. * Go to target path.
  585. */
  586. include '' . PMA_securePath($goto);
  587. } else {
  588. $full_err_url = $err_url;
  589. if (preg_match('@^(db|tbl)_@', $err_url)) {
  590. $full_err_url .= '&amp;show_query=1&amp;sql_query='
  591. . urlencode($sql_query);
  592. }
  593. PMA_Util::mysqlDie($error, $full_sql_query, '', $full_err_url);
  594. }
  595. exit;
  596. }
  597. unset($error);
  598. // If there are no errors and bookmarklabel was given,
  599. // store the query as a bookmark
  600. if (! empty($bkm_label) && ! empty($import_text)) {
  601. include_once 'libraries/bookmark.lib.php';
  602. $bfields = array(
  603. 'dbase' => $db,
  604. 'user' => $cfg['Bookmark']['user'],
  605. 'query' => urlencode($import_text),
  606. 'label' => $bkm_label
  607. );
  608. // Should we replace bookmark?
  609. if (isset($bkm_replace)) {
  610. $bookmarks = PMA_Bookmark_getList($db);
  611. foreach ($bookmarks as $key => $val) {
  612. if ($val == $bkm_label) {
  613. PMA_Bookmark_delete($db, $key);
  614. }
  615. }
  616. }
  617. PMA_Bookmark_save($bfields, isset($bkm_all_users));
  618. $bookmark_created = true;
  619. } // end store bookmarks
  620. // Gets the number of rows affected/returned
  621. // (This must be done immediately after the query because
  622. // mysql_affected_rows() reports about the last query done)
  623. if (! $is_affected) {
  624. $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
  625. } elseif (! isset($num_rows)) {
  626. $num_rows = @PMA_DBI_affected_rows();
  627. }
  628. // Grabs the profiling results
  629. if (isset($_SESSION['profiling']) && PMA_Util::profilingSupported()) {
  630. $profiling_results = PMA_DBI_fetch_result('SHOW PROFILE;');
  631. }
  632. // Checks if the current database has changed
  633. // This could happen if the user sends a query like "USE `database`;"
  634. /**
  635. * commented out auto-switching to active database - really required?
  636. * bug #2558 win: table list disappears (mixed case db names)
  637. * https://sourceforge.net/p/phpmyadmin/bugs/2558/
  638. * @todo RELEASE test and comit or rollback before release
  639. $current_db = PMA_DBI_fetch_value('SELECT DATABASE()');
  640. if ($db !== $current_db) {
  641. $db = $current_db;
  642. $reload = 1;
  643. }
  644. unset($current_db);
  645. */
  646. // tmpfile remove after convert encoding appended by Y.Kawada
  647. if (function_exists('PMA_kanji_file_conv')
  648. && (isset($textfile) && file_exists($textfile))
  649. ) {
  650. unlink($textfile);
  651. }
  652. // Counts the total number of rows for the same 'SELECT' query without the
  653. // 'LIMIT' clause that may have been programatically added
  654. $justBrowsing = false;
  655. if (empty($sql_limit_to_append)) {
  656. $unlim_num_rows = $num_rows;
  657. // if we did not append a limit, set this to get a correct
  658. // "Showing rows..." message
  659. //$_SESSION['tmp_user_values']['max_rows'] = 'all';
  660. } elseif ($is_select) {
  661. // c o u n t q u e r y
  662. // If we are "just browsing", there is only one table,
  663. // and no WHERE clause (or just 'WHERE 1 '),
  664. // we do a quick count (which uses MaxExactCount) because
  665. // SQL_CALC_FOUND_ROWS is not quick on large InnoDB tables
  666. // However, do not count again if we did it previously
  667. // due to $find_real_end == true
  668. if (! $is_group
  669. && ! isset($analyzed_sql[0]['queryflags']['union'])
  670. && ! isset($analyzed_sql[0]['queryflags']['distinct'])
  671. && ! isset($analyzed_sql[0]['table_ref'][1]['table_name'])
  672. && (empty($analyzed_sql[0]['where_clause'])
  673. || $analyzed_sql[0]['where_clause'] == '1 ')
  674. && ! isset($find_real_end)
  675. ) {
  676. // "j u s t b r o w s i n g"
  677. $justBrowsing = true;
  678. $unlim_num_rows = PMA_Table::countRecords(
  679. $db,
  680. $table,
  681. $force_exact = true
  682. );
  683. } else { // n o t " j u s t b r o w s i n g "
  684. // add select expression after the SQL_CALC_FOUND_ROWS
  685. // for UNION, just adding SQL_CALC_FOUND_ROWS
  686. // after the first SELECT works.
  687. // take the left part, could be:
  688. // SELECT
  689. // (SELECT
  690. $count_query = PMA_SQP_formatHtml(
  691. $parsed_sql,
  692. 'query_only',
  693. 0,
  694. $analyzed_sql[0]['position_of_first_select'] + 1
  695. );
  696. $count_query .= ' SQL_CALC_FOUND_ROWS ';
  697. // add everything that was after the first SELECT
  698. $count_query .= PMA_SQP_formatHtml(
  699. $parsed_sql,
  700. 'query_only',
  701. $analyzed_sql[0]['position_of_first_select'] + 1
  702. );
  703. // ensure there is no semicolon at the end of the
  704. // count query because we'll probably add
  705. // a LIMIT 1 clause after it
  706. $count_query = rtrim($count_query);
  707. $count_query = rtrim($count_query, ';');
  708. // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
  709. // long delays. Returned count will be complete anyway.
  710. // (but a LIMIT would disrupt results in an UNION)
  711. if (! isset($analyzed_sql[0]['queryflags']['union'])) {
  712. $count_query .= ' LIMIT 1';
  713. }
  714. // run the count query
  715. PMA_DBI_try_query($count_query);
  716. // if (mysql_error()) {
  717. // void.
  718. // I tried the case
  719. // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
  720. // UNION (SELECT `User`, `Host`, "%" AS "Db",
  721. // `Select_priv`
  722. // FROM `user`) ORDER BY `User`, `Host`, `Db`;
  723. // and although the generated count_query is wrong
  724. // the SELECT FOUND_ROWS() work! (maybe it gets the
  725. // count from the latest query that worked)
  726. //
  727. // another case where the count_query is wrong:
  728. // SELECT COUNT(*), f1 from t1 group by f1
  729. // and you click to sort on count(*)
  730. // }
  731. $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
  732. } // end else "just browsing"
  733. } else { // not $is_select
  734. $unlim_num_rows = 0;
  735. } // end rows total count
  736. // if a table or database gets dropped, check column comments.
  737. if (isset($purge) && $purge == '1') {
  738. /**
  739. * Cleanup relations.
  740. */
  741. include_once 'libraries/relation_cleanup.lib.php';
  742. if (strlen($table) && strlen($db)) {
  743. PMA_relationsCleanupTable($db, $table);
  744. } elseif (strlen($db)) {
  745. PMA_relationsCleanupDatabase($db);
  746. } else {
  747. // VOID. No DB/Table gets deleted.
  748. } // end if relation-stuff
  749. } // end if ($purge)
  750. // If a column gets dropped, do relation magic.
  751. if (isset($dropped_column)
  752. && strlen($db)
  753. && strlen($table)
  754. && ! empty($dropped_column)
  755. ) {
  756. include_once 'libraries/relation_cleanup.lib.php';
  757. PMA_relationsCleanupColumn($db, $table, $dropped_column);
  758. // to refresh the list of indexes (Ajax mode)
  759. $extra_data['indexes_list'] = PMA_Index::getView($table, $db);
  760. } // end if column was dropped
  761. } // end else "didn't ask to see php code"
  762. // No rows returned -> move back to the calling page
  763. if ((0 == $num_rows && 0 == $unlim_num_rows) || $is_affected) {
  764. // Delete related tranformation information
  765. if (!empty($analyzed_sql[0]['querytype'])
  766. && (($analyzed_sql[0]['querytype'] == 'ALTER')
  767. || ($analyzed_sql[0]['querytype'] == 'DROP'))
  768. ) {
  769. include_once 'libraries/transformations.lib.php';
  770. if ($analyzed_sql[0]['querytype'] == 'ALTER') {
  771. if (stripos($analyzed_sql[0]['unsorted_query'], 'DROP') !== false) {
  772. $drop_column = PMA_getColumnNameInColumnDropSql(
  773. $analyzed_sql[0]['unsorted_query']
  774. );
  775. if ($drop_column != '') {
  776. PMA_clearTransformations($db, $table, $drop_column);
  777. }
  778. }
  779. } else if (($analyzed_sql[0]['querytype'] == 'DROP') && ($table != '')) {
  780. PMA_clearTransformations($db, $table);
  781. }
  782. }
  783. if ($is_delete) {
  784. $message = PMA_Message::getMessageForDeletedRows($num_rows);
  785. } elseif ($is_insert) {
  786. if ($is_replace) {
  787. // For replace we get DELETED + INSERTED row count,
  788. // so we have to call it affected
  789. $message = PMA_Message::getMessageForAffectedRows($num_rows);
  790. } else {
  791. $message = PMA_Message::getMessageForInsertedRows($num_rows);
  792. }
  793. $insert_id = PMA_DBI_insert_id();
  794. if ($insert_id != 0) {
  795. // insert_id is id of FIRST record inserted in one insert,
  796. // so if we inserted multiple rows, we had to increment this
  797. $message->addMessage('[br]');
  798. // need to use a temporary because the Message class
  799. // currently supports adding parameters only to the first
  800. // message
  801. $_inserted = PMA_Message::notice(__('Inserted row id: %1$d'));
  802. $_inserted->addParam($insert_id + $num_rows - 1);
  803. $message->addMessage($_inserted);
  804. }
  805. } elseif ($is_affected) {
  806. $message = PMA_Message::getMessageForAffectedRows($num_rows);
  807. // Ok, here is an explanation for the !$is_select.
  808. // The form generated by sql_query_form.lib.php
  809. // and db_sql.php has many submit buttons
  810. // on the same form, and some confusion arises from the
  811. // fact that $message_to_show is sent for every case.
  812. // The $message_to_show containing a success message and sent with
  813. // the form should not have priority over errors
  814. } elseif (! empty($message_to_show) && ! $is_select) {
  815. $message = PMA_Message::rawSuccess(htmlspecialchars($message_to_show));
  816. } elseif (! empty($GLOBALS['show_as_php'])) {
  817. $message = PMA_Message::success(__('Showing as PHP code'));
  818. } elseif (isset($GLOBALS['show_as_php'])) {
  819. /* User disable showing as PHP, query is only displayed */
  820. $message = PMA_Message::notice(__('Showing SQL query'));
  821. } elseif (! empty($GLOBALS['validatequery'])) {
  822. $message = PMA_Message::notice(__('Validated SQL'));
  823. } else {
  824. $message = PMA_Message::success(
  825. __('MySQL returned an empty result set (i.e. zero rows).')
  826. );
  827. }
  828. if (isset($GLOBALS['querytime'])) {
  829. $_querytime = PMA_Message::notice('(' . __('Query took %01.4f sec') . ')');
  830. $_querytime->addParam($GLOBALS['querytime']);
  831. $message->addMessage($_querytime);
  832. }
  833. if ($GLOBALS['is_ajax_request'] == true) {
  834. if ($cfg['ShowSQL']) {
  835. $extra_data['sql_query'] = PMA_Util::getMessage(
  836. $message, $GLOBALS['sql_query'], 'success'
  837. );
  838. }
  839. if (isset($GLOBALS['reload']) && $GLOBALS['reload'] == 1) {
  840. $extra_data['reload'] = 1;
  841. $extra_data['db'] = $GLOBALS['db'];
  842. }
  843. $response = PMA_Response::getInstance();
  844. $response->isSuccess($message->isSuccess());
  845. // No need to manually send the message
  846. // The Response class will handle that automatically
  847. $response->addJSON(isset($extra_data) ? $extra_data : array());
  848. if (empty($_REQUEST['ajax_page_request'])) {
  849. $response->addJSON('message', $message);
  850. exit;
  851. }
  852. }
  853. if ($is_gotofile) {
  854. $goto = PMA_securePath($goto);
  855. // Checks for a valid target script
  856. $is_db = $is_table = false;
  857. if (isset($_REQUEST['purge']) && $_REQUEST['purge'] == '1') {
  858. $table = '';
  859. unset($url_params['table']);
  860. }
  861. include 'libraries/db_table_exists.lib.php';
  862. if (strpos($goto, 'tbl_') === 0 && ! $is_table) {
  863. if (strlen($table)) {
  864. $table = '';
  865. }
  866. $goto = 'db_sql.php';
  867. }
  868. if (strpos($goto, 'db_') === 0 && ! $is_db) {
  869. if (strlen($db)) {
  870. $db = '';
  871. }
  872. $goto = 'index.php';
  873. }
  874. // Loads to target script
  875. if (strlen($goto) > 0) {
  876. $active_page = $goto;
  877. include '' . $goto;
  878. } else {
  879. // Echo at least one character to prevent showing last page from history
  880. echo " ";
  881. }
  882. } else {
  883. // avoid a redirect loop when last record was deleted
  884. if (0 == $num_rows && 'sql.php' == $cfg['DefaultTabTable']) {
  885. $goto = str_replace('sql.php', 'tbl_structure.php', $goto);
  886. }
  887. PMA_sendHeaderLocation(
  888. $cfg['PmaAbsoluteUri'] . str_replace('&amp;', '&', $goto)
  889. . '&message=' . urlencode($message)
  890. );
  891. } // end else
  892. exit();
  893. // end no rows returned
  894. } else {
  895. // At least one row is returned -> displays a table with results
  896. //If we are retrieving the full value of a truncated field or the original
  897. // value of a transformed field, show it here and exit
  898. if ($GLOBALS['grid_edit'] == true) {
  899. $row = PMA_DBI_fetch_row($result);
  900. $response = PMA_Response::getInstance();
  901. $response->addJSON('value', $row[0]);
  902. exit;
  903. }
  904. if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['table_maintenance'])) {
  905. $response = PMA_Response::getInstance();
  906. $header = $response->getHeader();
  907. $scripts = $header->getScripts();
  908. $scripts->addFile('makegrid.js');
  909. $scripts->addFile('sql.js');
  910. // Gets the list of fields properties
  911. if (isset($result) && $result) {
  912. $fields_meta = PMA_DBI_get_fields_meta($result);
  913. $fields_cnt = count($fields_meta);
  914. }
  915. if (empty($disp_mode)) {
  916. // see the "PMA_setDisplayMode()" function in
  917. // libraries/DisplayResults.class.php
  918. $disp_mode = 'urdr111101';
  919. }
  920. // hide edit and delete links for information_schema
  921. if (PMA_is_system_schema($db)) {
  922. $disp_mode = 'nnnn110111';
  923. }
  924. if (isset($message)) {
  925. $message = PMA_Message::success($message);
  926. echo PMA_Util::getMessage(
  927. $message, $GLOBALS['sql_query'], 'success'
  928. );
  929. }
  930. // Should be initialized these parameters before parsing
  931. $showtable = isset($showtable) ? $showtable : null;
  932. $printview = isset($printview) ? $printview : null;
  933. $url_query = isset($url_query) ? $url_query : null;
  934. if (!empty($sql_data) && ($sql_data['valid_queries'] > 1)) {
  935. $_SESSION['is_multi_query'] = true;
  936. echo getTableHtmlForMultipleQueries(
  937. $displayResultsObject, $db, $sql_data, $goto,
  938. $pmaThemeImage, $text_dir, $printview, $url_query,
  939. $disp_mode, $sql_limit_to_append, false
  940. );
  941. } else {
  942. $_SESSION['is_multi_query'] = false;
  943. $displayResultsObject->setProperties(
  944. $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
  945. $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
  946. $text_dir, $is_maint, $is_explain, $is_show, $showtable,
  947. $printview, $url_query, false
  948. );
  949. echo $displayResultsObject->getTable(
  950. $result, $disp_mode, $analyzed_sql
  951. );
  952. exit();
  953. }
  954. }
  955. // Displays the headers
  956. if (isset($show_query)) {
  957. unset($show_query);
  958. }
  959. if (isset($printview) && $printview == '1') {
  960. PMA_Util::checkParameters(array('db', 'full_sql_query'));
  961. $response = PMA_Response::getInstance();
  962. $header = $response->getHeader();
  963. $header->enablePrintView();
  964. $hostname = '';
  965. if ($cfg['Server']['verbose']) {
  966. $hostname = $cfg['Server']['verbose'];
  967. } else {
  968. $hostname = $cfg['Server']['host'];
  969. if (! empty($cfg['Server']['port'])) {
  970. $hostname .= $cfg['Server']['port'];
  971. }
  972. }
  973. $versions = "phpMyAdmin&nbsp;" . PMA_VERSION;
  974. $versions .= "&nbsp;/&nbsp;";
  975. $versions .= "MySQL&nbsp;" . PMA_MYSQL_STR_VERSION;
  976. echo "<h1>" . __('SQL result') . "</h1>";
  977. echo "<p>";
  978. echo "<strong>" . __('Host') . ":</strong> $hostname<br />";
  979. echo "<strong>" . __('Database') . ":</strong> "
  980. . htmlspecialchars($db) . "<br />";
  981. echo "<strong>" . __('Generation Time') . ":</strong> "
  982. . PMA_Util::localisedDate() . "<br />";
  983. echo "<strong>" . __('Generated by') . ":</strong> $versions<br />";
  984. echo "<strong>" . __('SQL query') . ":</strong> "
  985. . htmlspecialchars($full_sql_query) . ";";
  986. if (isset($num_rows)) {
  987. echo "<br />";
  988. echo "<strong>" . __('Rows') . ":</strong> $num_rows";
  989. }
  990. echo "</p>";
  991. } else {
  992. $response = PMA_Response::getInstance();
  993. $header = $response->getHeader();
  994. $scripts = $header->getScripts();
  995. $scripts->addFile('makegrid.js');
  996. $scripts->addFile('sql.js');
  997. unset($message);
  998. if (! $GLOBALS['is_ajax_request']) {
  999. if (strlen($table)) {
  1000. include 'libraries/tbl_common.inc.php';
  1001. $url_query .= '&amp;goto=tbl_sql.php&amp;back=tbl_sql.php';
  1002. include 'libraries/tbl_info.inc.php';
  1003. } elseif (strlen($db)) {
  1004. include 'libraries/db_common.inc.php';
  1005. include 'libraries/db_info.inc.php';
  1006. } else {
  1007. include 'libraries/server_common.inc.php';
  1008. }
  1009. } else {
  1010. //we don't need to buffer the output in getMessage here.
  1011. //set a global variable and check against it in the function
  1012. $GLOBALS['buffer_message'] = false;
  1013. }
  1014. }
  1015. if (strlen($db)) {
  1016. $cfgRelation = PMA_getRelationsParam();
  1017. }
  1018. // Gets the list of fields properties
  1019. if (isset($result) && $result) {
  1020. $fields_meta = PMA_DBI_get_fields_meta($result);
  1021. $fields_cnt = count($fields_meta);
  1022. }
  1023. //begin the sqlqueryresults div here. container div
  1024. echo '<div id="sqlqueryresults"';
  1025. echo ' class="ajax"';
  1026. echo '>';
  1027. // Display previous update query (from tbl_replace)
  1028. if (isset($disp_query) && ($cfg['ShowSQL'] == true) && empty($sql_data)) {
  1029. echo PMA_Util::getMessage($disp_message, $disp_query, 'success');
  1030. }
  1031. if (isset($profiling_results)) {
  1032. // pma_token/url_query needed for chart export
  1033. echo '<script type="text/javascript">';
  1034. echo 'pma_token = \'' . $_SESSION[' PMA_token '] . '\';';
  1035. echo 'url_query = \''
  1036. . (isset($url_query) ? $url_query : PMA_generate_common_url($db))
  1037. . '\';';
  1038. echo 'AJAX.registerOnload(\'sql.js\',makeProfilingChart);';
  1039. echo '</script>';
  1040. echo '<fieldset><legend>' . __('Profiling') . '</legend>' . "\n";
  1041. echo '<div style="float: left;">';
  1042. echo '<table>' . "\n";
  1043. echo ' <tr>' . "\n";
  1044. echo ' <th>' . __('Status')
  1045. . PMA_Util::showMySQLDocu(
  1046. 'general-thread-states', 'general-thread-states'
  1047. )
  1048. . '</th>' . "\n";
  1049. echo ' <th>' . __('Time') . '</th>' . "\n";
  1050. echo ' </tr>' . "\n";
  1051. $chart_json = Array();
  1052. foreach ($profiling_results as $one_result) {
  1053. echo ' <tr>' . "\n";
  1054. echo '<td>' . ucwords($one_result['Status']) . '</td>' . "\n";
  1055. echo '<td class="right">'
  1056. . (PMA_Util::formatNumber($one_result['Duration'], 3, 1))
  1057. . 's</td>' . "\n";
  1058. if (isset($chart_json[ucwords($one_result['Status'])])) {
  1059. $chart_json[ucwords($one_result['Status'])]
  1060. += $one_result['Duration'];
  1061. } else {
  1062. $chart_json[ucwords($one_result['Status'])]
  1063. = $one_result['Duration'];
  1064. }
  1065. }
  1066. echo '</table>' . "\n";
  1067. echo '</div>';
  1068. //require_once 'libraries/chart.lib.php';
  1069. echo '<div id="profilingChartData" style="display:none;">';
  1070. echo json_encode($chart_json);
  1071. echo '</div>';
  1072. echo '<div id="profilingchart" style="display:none;">';
  1073. echo '</div>';
  1074. echo '<script type="text/javascript">';
  1075. echo 'if($.jqplot !== undefined && $.jqplot.PieRenderer !== undefined) {';
  1076. echo 'makeProfilingChart();';
  1077. echo '}';
  1078. echo '</script>';
  1079. echo '</fieldset>' . "\n";
  1080. }
  1081. // Displays the results in a table
  1082. if (empty($disp_mode)) {
  1083. // see the "PMA_setDisplayMode()" function in
  1084. // libraries/DisplayResults.class.php
  1085. $disp_mode = 'urdr111101';
  1086. }
  1087. $resultSetContainsUniqueKey = PMA_resultSetContainsUniqueKey(
  1088. $db, $table, $fields_meta
  1089. );
  1090. // hide edit and delete links:
  1091. // - for information_schema
  1092. // - if the result set does not contain all the columns of a unique key
  1093. // (unless this is an updatable view)
  1094. $updatableView
  1095. = trim($analyzed_sql[0]['select_expr_clause']) == '*'
  1096. && PMA_Table::isUpdatableView($db, $table);
  1097. $editable = $resultSetContainsUniqueKey || $updatableView;
  1098. if (!empty($table) && (PMA_is_system_schema($db) || !$editable)) {
  1099. $disp_mode = 'nnnn110111';
  1100. $msg = PMA_message::notice(
  1101. __(
  1102. 'This table does not contain a unique column.'
  1103. . ' Grid edit, checkbox, Edit, Copy and Delete features'
  1104. . ' are not available.'
  1105. )
  1106. );
  1107. $msg->display();
  1108. }
  1109. if (isset($label)) {
  1110. $msg = PMA_message::success(__('Bookmark %s created'));
  1111. $msg->addParam($label);
  1112. $msg->display();
  1113. }
  1114. // Should be initialized these parameters before parsing
  1115. $showtable = isset($showtable) ? $showtable : null;
  1116. $printview = isset($printview) ? $printview : null;
  1117. $url_query = isset($url_query) ? $url_query : null;
  1118. if (! empty($sql_data) && ($sql_data['valid_queries'] > 1) || $is_procedure) {
  1119. $_SESSION['is_multi_query'] = true;
  1120. echo getTableHtmlForMultipleQueries(
  1121. $displayResultsObject, $db, $sql_data, $goto,
  1122. $pmaThemeImage, $text_dir, $printview, $url_query,
  1123. $disp_mode, $sql_limit_to_append, $editable
  1124. );
  1125. } else {
  1126. $_SESSION['is_multi_query'] = false;
  1127. $displayResultsObject->setProperties(
  1128. $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
  1129. $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
  1130. $text_dir, $is_maint, $is_explain, $is_show, $showtable,
  1131. $printview, $url_query, $editable
  1132. );
  1133. echo $displayResultsObject->getTable($result, $disp_mode, $analyzed_sql);
  1134. PMA_DBI_free_result($result);
  1135. }
  1136. // BEGIN INDEX CHECK See if indexes should be checked.
  1137. if (isset($query_type)
  1138. && $query_type == 'check_tbl'
  1139. && isset($selected)
  1140. && is_array($selected)
  1141. ) {
  1142. foreach ($selected as $idx => $tbl_name) {
  1143. $check = PMA_Index::findDuplicates($tbl_name, $db);
  1144. if (! empty($check)) {
  1145. printf(__('Problems with indexes of table `%s`'), $tbl_name);
  1146. echo $check;
  1147. }
  1148. }
  1149. } // End INDEX CHECK
  1150. // Bookmark support if required
  1151. if ($disp_mode[7] == '1'
  1152. && (! empty($cfg['Bookmark']) && empty($id_bookmark))
  1153. && ! empty($sql_query)
  1154. ) {
  1155. echo "\n";
  1156. $goto = 'sql.php?'
  1157. . PMA_generate_common_url($db, $table)
  1158. . '&amp;sql_query=' . urlencode($sql_query)
  1159. . '&amp;id_bookmark=1';
  1160. echo '<form action="sql.php" method="post"'
  1161. . ' onsubmit="return ! emptyFormElements(this, \'fields[label]\');"'
  1162. . ' id="bookmarkQueryForm">';
  1163. echo PMA_generate_common_hidden_inputs();
  1164. echo '<input type="hidden" name="goto" value="' . $goto . '" />';
  1165. echo '<input type="hidden" name="fields[dbase]"'
  1166. . ' value="' . htmlspecialchars($db) . '" />';
  1167. echo '<input type="hidden" name="fields[user]"'
  1168. . ' value="' . $cfg['Bookmark']['user'] . '" />';
  1169. echo '<input type="hidden" name="fields[query]"' . ' value="'
  1170. . urlencode(isset($complete_query) ? $complete_query : $sql_query)
  1171. . '" />';
  1172. echo '<fieldset>';
  1173. echo '<legend>';
  1174. echo PMA_Util::getIcon(
  1175. 'b_bookmark.png', __('Bookmark this SQL query'), true
  1176. );
  1177. echo '</legend>';
  1178. echo '<div class="formelement">';
  1179. echo '<label for="fields_label_">' . __('Label') . ':</label>';
  1180. echo '<input type="text" id="fields_label_"'
  1181. . ' name="fields[label]" value="" />';
  1182. echo '</div>';
  1183. echo '<div class="formelement">';
  1184. echo '<input type="checkbox" name="bkm_all_users"'
  1185. . ' id="bkm_all_users" value="true" />';
  1186. echo '<label for="bkm_all_users">'
  1187. . __('Let every user access this bookmark')
  1188. . '</label>';
  1189. echo '</div>';
  1190. echo '<div class="clearfloat"></div>';
  1191. echo '</fieldset>';
  1192. echo '<fieldset class="tblFooters">';
  1193. echo '<input type="hidden" name="store_bkm" value="1" />';
  1194. echo '<input type="submit"'
  1195. . ' value="' . __('Bookmark this SQL query') . '" />';
  1196. echo '</fieldset>';
  1197. echo '</form>';
  1198. } // end bookmark support
  1199. // Do print the page if required
  1200. if (isset($printview) && $printview == '1') {
  1201. echo PMA_Util::getButton();
  1202. } // end print case
  1203. echo '</div>'; // end sqlqueryresults div
  1204. } // end rows returned
  1205. $_SESSION['is_multi_query'] = false;
  1206. /**
  1207. * Displays the footer
  1208. */
  1209. if (! isset($_REQUEST['table_maintenance'])) {
  1210. exit;
  1211. }
  1212. // These functions will need for use set the required parameters for display results
  1213. /**
  1214. * Initialize some parameters needed to display results
  1215. *
  1216. * @param string $sql_query SQL statement
  1217. * @param boolean $is_select select query or not
  1218. *
  1219. * @return array set of parameters
  1220. *
  1221. * @access public
  1222. */
  1223. function PMA_getDisplayPropertyParams($sql_query, $is_select)
  1224. {
  1225. $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = $is_replace = false;
  1226. if ($is_select) {
  1227. $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
  1228. $is_func = ! $is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
  1229. $is_count = ! $is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
  1230. $is_export = preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query);
  1231. $is_analyse = preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query);
  1232. } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
  1233. $is_explain = true;
  1234. } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
  1235. $is_delete = true;
  1236. $is_affected = true;
  1237. } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
  1238. $is_insert = true;
  1239. $is_affected = true;
  1240. if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
  1241. $is_replace = true;
  1242. }
  1243. } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
  1244. $is_affected = true;
  1245. } elseif (preg_match('@^[[:space:]]*SHOW[[:space:]]+@i', $sql_query)) {
  1246. $is_show = true;
  1247. } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
  1248. $is_maint = true;
  1249. }
  1250. return array(
  1251. $is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain,
  1252. $is_delete, $is_affected, $is_insert, $is_replace,$is_show, $is_maint
  1253. );
  1254. }
  1255. /**
  1256. * Get the database name inside a USE query
  1257. *
  1258. * @param string $sql SQL query
  1259. * @param array $databases array with all databases
  1260. *
  1261. * @return strin $db new database name
  1262. */
  1263. function PMA_getNewDatabase($sql, $databases)
  1264. {
  1265. $db = '';
  1266. // loop through all the databases
  1267. foreach ($databases as $database) {
  1268. if (strpos($sql, $database['SCHEMA_NAME']) !== false) {
  1269. $db = $database;
  1270. break;
  1271. }
  1272. }
  1273. return $db;
  1274. }
  1275. /**
  1276. * Get the table name in a sql query
  1277. * If there are several tables in the SQL query,
  1278. * first table wil lreturn
  1279. *
  1280. * @param string $sql SQL query
  1281. * @param array $tables array of names in current database
  1282. *
  1283. * @return string $table table name
  1284. */
  1285. function PMA_getTableNameBySQL($sql, $tables)
  1286. {
  1287. $table = '';
  1288. // loop through all the tables in the database
  1289. foreach ($tables as $tbl) {
  1290. if (strpos($sql, $tbl)) {
  1291. $table .= ' ' . $tbl;
  1292. }
  1293. }
  1294. if (count(explode(' ', trim($table))) > 1) {
  1295. $tmp_array = explode(' ', trim($table));
  1296. return $tmp_array[0];
  1297. }
  1298. return trim($table);
  1299. }
  1300. /**
  1301. * Generate table html when SQL statement have multiple queries
  1302. * which return displayable results
  1303. *
  1304. * @param PMA_DisplayResults $displayResultsObject object
  1305. * @param string $db database name
  1306. * @param array $sql_data information about SQL statement
  1307. * @param string $goto URL to go back in case of errors
  1308. * @param string $pmaThemeImage path for theme images directory
  1309. * @param string $text_dir text direction
  1310. * @param string $printview whether printview is enabled
  1311. * @param string $url_query URL query
  1312. * @param array $disp_mode the display mode
  1313. * @param string $sql_limit_to_append limit clause
  1314. * @param bool $editable whether result set is editable
  1315. *
  1316. * @return string $table_html html content
  1317. */
  1318. function getTableHtmlForMultipleQueries(
  1319. $displayResultsObject, $db, $sql_data, $goto, $pmaThemeImage,
  1320. $text_dir, $printview, $url_query, $disp_mode, $sql_limit_to_append,
  1321. $editable
  1322. ) {
  1323. $table_html = '';
  1324. $tables_array = PMA_DBI_get_tables($db);
  1325. $databases_array = PMA_DBI_get_databases_full();
  1326. $multi_sql = implode(";", $sql_data['valid_sql']);
  1327. $querytime_before = array_sum(explode(' ', microtime()));
  1328. // Assignment for variable is not needed since the results are
  1329. // looiping using the connection
  1330. @PMA_DBI_try_multi_query($multi_sql);
  1331. $querytime_after = array_sum(explode(' ', microtime()));
  1332. $querytime = $querytime_after - $querytime_before;
  1333. $sql_no = 0;
  1334. do {
  1335. $analyzed_sql = array();
  1336. $is_affected = false;
  1337. $result = PMA_DBI_store_result();
  1338. $fields_meta = ($result !== false)
  1339. ? PMA_DBI_get_fields_meta($result)
  1340. : array();
  1341. $fields_cnt = count($fields_meta);
  1342. // Initialize needed params related to each query in multiquery statement
  1343. if (isset($sql_data['valid_sql'][$sql_no])) {
  1344. // 'Use' query can change the database
  1345. if (stripos($sql_data['valid_sql'][$sql_no], "use ")) {
  1346. $db = PMA_getNewDatabase(
  1347. $sql_data['valid_sql'][$sql_no],
  1348. $databases_array
  1349. );
  1350. }
  1351. $parsed_sql = PMA_SQP_parse($sql_data['valid_sql'][$sql_no]);
  1352. $table = PMA_getTableNameBySQL(
  1353. $sql_data['valid_sql'][$sql_no],
  1354. $tables_array
  1355. );
  1356. $analyzed_sql = PMA_SQP_analyze($parsed_sql);
  1357. $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
  1358. $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
  1359. $showtable = PMA_Table::sGetStatusInfo($db, $table, null, true);
  1360. $url_query = PMA_generate_common_url($db, $table);
  1361. list($is_group, $is_func, $is_count, $is_export, $is_analyse,
  1362. $is_explain, $is_delete, $is_affected, $is_insert, $is_replace,
  1363. $is_show, $is_maint)
  1364. = PMA_getDisplayPropertyParams(
  1365. $sql_data['valid_sql'][$sql_no], $is_select
  1366. );
  1367. // Handle remembered sorting order, only for single table query
  1368. if ($GLOBALS['cfg']['RememberSorting']
  1369. && ! ($is_count || $is_export || $is_func || $is_analyse)
  1370. && isset($analyzed_sql[0]['select_expr'])
  1371. && (count($analyzed_sql[0]['select_expr']) == 0)
  1372. && isset($analyzed_sql[0]['queryflags']['select_from'])
  1373. && count($analyzed_sql[0]['table_ref']) == 1
  1374. ) {
  1375. PMA_handleSortOrder(
  1376. $db,
  1377. $table,
  1378. $analyzed_sql,
  1379. $sql_data['valid_sql'][$sql_no]
  1380. );
  1381. }
  1382. // Do append a "LIMIT" clause?
  1383. if (($_SESSION['tmp_user_values']['max_rows'] != 'all')
  1384. && ! ($is_count || $is_export || $is_func || $is_analyse)
  1385. && isset($analyzed_sql[0]['queryflags']['select_from'])
  1386. && ! isset($analyzed_sql[0]['queryflags']['offset'])
  1387. && empty($analyzed_sql[0]['limit_clause'])
  1388. ) {
  1389. $sql_limit_to_append = ' LIMIT '
  1390. . $_SESSION['tmp_user_values']['pos']
  1391. . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
  1392. $sql_data['valid_sql'][$sql_no] = PMA_getSqlWithLimitClause(
  1393. $sql_data['valid_sql'][$sql_no],
  1394. $analyzed_sql,
  1395. $sql_limit_to_append
  1396. );
  1397. }
  1398. // Set the needed properties related to executing sql query
  1399. $displayResultsObject->__set('db', $db);
  1400. $displayResultsObject->__set('table', $table);
  1401. $displayResultsObject->__set('goto', $goto);
  1402. }
  1403. if (! $is_affected) {
  1404. $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
  1405. } elseif (! isset($num_rows)) {
  1406. $num_rows = @PMA_DBI_affected_rows();
  1407. }
  1408. if (isset($sql_data['valid_sql'][$sql_no])) {
  1409. $displayResultsObject->__set(
  1410. 'sql_query',
  1411. $sql_data['valid_sql'][$sql_no]
  1412. );
  1413. $displayResultsObject->setProperties(
  1414. $unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func,
  1415. $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage,
  1416. $text_dir, $is_maint, $is_explain, $is_show, $showtable,
  1417. $printview, $url_query, $editable
  1418. );
  1419. }
  1420. if ($num_rows == 0) {
  1421. continue;
  1422. }
  1423. // With multiple results, operations are limied
  1424. $disp_mode = 'nnnn000000';
  1425. $is_limited_display = true;
  1426. // Collect the tables
  1427. $table_html .= $displayResultsObject->getTable(
  1428. $result, $disp_mode, $analyzed_sql, $is_limited_display
  1429. );
  1430. // Free the result to save the memory
  1431. PMA_DBI_free_result($result);
  1432. $sql_no++;
  1433. } while (PMA_DBI_more_results() && PMA_DBI_next_result());
  1434. return $table_html;
  1435. }
  1436. /**
  1437. * Handle remembered sorting order, only for single table query
  1438. *
  1439. * @param string $db database name
  1440. * @param string $table table name
  1441. * @param array &$analyzed_sql the analyzed query
  1442. * @param string &$full_sql_query SQL query
  1443. *
  1444. * @return void
  1445. */
  1446. function PMA_handleSortOrder($db, $table, &$analyzed_sql, &$full_sql_query)
  1447. {
  1448. $pmatable = new PMA_Table($table, $db);
  1449. if (empty($analyzed_sql[0]['order_by_clause'])) {
  1450. $sorted_col = $pmatable->getUiProp(PMA_Table::PROP_SORTED_COLUMN);
  1451. if ($sorted_col) {
  1452. // retrieve the remembered sorting order for current table
  1453. $sql_order_to_append = ' ORDER BY ' . $sorted_col . ' ';
  1454. $full_sql_query = $analyzed_sql[0]['section_before_limit']
  1455. . $sql_order_to_append . $analyzed_sql[0]['limit_clause']
  1456. . ' ' . $analyzed_sql[0]['section_after_limit'];
  1457. // update the $analyzed_sql
  1458. $analyzed_sql[0]['section_before_limit'] .= $sql_order_to_append;
  1459. $analyzed_sql[0]['order_by_clause'] = $sorted_col;
  1460. }
  1461. } else {
  1462. // store the remembered table into session
  1463. $pmatable->setUiProp(
  1464. PMA_Table::PROP_SORTED_COLUMN,
  1465. $analyzed_sql[0]['order_by_clause']
  1466. );
  1467. }
  1468. }
  1469. /**
  1470. * Append limit clause to SQL query
  1471. *
  1472. * @param string $full_sql_query SQL query
  1473. * @param array $analyzed_sql the analyzed query
  1474. * @param string $sql_limit_to_append clause to append
  1475. *
  1476. * @return string limit clause appended SQL query
  1477. */
  1478. function PMA_getSqlWithLimitClause($full_sql_query, $analyzed_sql,
  1479. $sql_limit_to_append
  1480. ) {
  1481. return $analyzed_sql[0]['section_before_limit'] . "\n"
  1482. . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
  1483. }
  1484. /**
  1485. * Get column name from a drop SQL statement
  1486. *
  1487. * @param string $sql SQL query
  1488. *
  1489. * @return string $drop_column Name of the column
  1490. */
  1491. function PMA_getColumnNameInColumnDropSql($sql)
  1492. {
  1493. $tmpArray1 = explode('DROP', $sql);
  1494. $str_to_check = trim($tmpArray1[1]);
  1495. if (stripos($str_to_check, 'COLUMN') !== false) {
  1496. $tmpArray2 = explode('COLUMN', $str_to_check);
  1497. $str_to_check = trim($tmpArray2[1]);
  1498. }
  1499. $tmpArray3 = explode(' ', $str_to_check);
  1500. $str_to_check = trim($tmpArray3[0]);
  1501. $drop_column = str_replace(';', '', trim($str_to_check));
  1502. $drop_column = str_replace('`', '', $drop_column);
  1503. return $drop_column;
  1504. }
  1505. /**
  1506. * Verify whether the result set contains all the columns
  1507. * of at least one unique key
  1508. *
  1509. * @param string $db database name
  1510. * @param string $table table name
  1511. * @param string $fields_meta meta fields
  1512. *
  1513. * @return boolean whether the result set contains a unique key
  1514. */
  1515. function PMA_resultSetContainsUniqueKey($db, $table, $fields_meta)
  1516. {
  1517. $resultSetColumnNames = array();
  1518. foreach ($fields_meta as $oneMeta) {
  1519. $resultSetColumnNames[] = $oneMeta->name;
  1520. }
  1521. foreach (PMA_Index::getFromTable($table, $db) as $index) {
  1522. if ($index->isUnique()) {
  1523. $indexColumns = $index->getColumns();
  1524. $numberFound = 0;
  1525. foreach ($indexColumns as $indexColumnName => $dummy) {
  1526. if (in_array($indexColumnName, $resultSetColumnNames)) {
  1527. $numberFound++;
  1528. }
  1529. }
  1530. if ($numberFound == count($indexColumns)) {
  1531. return true;
  1532. }
  1533. }
  1534. }
  1535. return false;
  1536. }
  1537. ?>