DatabaseStructureController.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Holds the PhpMyAdmin\Controllers\Database\DatabaseStructureController
  5. *
  6. * @package PhpMyAdmin\Controllers
  7. */
  8. namespace PhpMyAdmin\Controllers\Database;
  9. use PhpMyAdmin\Charsets;
  10. use PhpMyAdmin\Config\PageSettings;
  11. use PhpMyAdmin\Controllers\DatabaseController;
  12. use PhpMyAdmin\Core;
  13. use PhpMyAdmin\Display\CreateTable;
  14. use PhpMyAdmin\Message;
  15. use PhpMyAdmin\RecentFavoriteTable;
  16. use PhpMyAdmin\Relation;
  17. use PhpMyAdmin\Replication;
  18. use PhpMyAdmin\Response;
  19. use PhpMyAdmin\Sanitize;
  20. use PhpMyAdmin\Template;
  21. use PhpMyAdmin\Tracker;
  22. use PhpMyAdmin\Util;
  23. use PhpMyAdmin\Url;
  24. /**
  25. * Handles database structure logic
  26. *
  27. * @package PhpMyAdmin\Controllers
  28. */
  29. class DatabaseStructureController extends DatabaseController
  30. {
  31. /**
  32. * @var int Number of tables
  33. */
  34. protected $_num_tables;
  35. /**
  36. * @var int Current position in the list
  37. */
  38. protected $_pos;
  39. /**
  40. * @var bool DB is information_schema
  41. */
  42. protected $_db_is_system_schema;
  43. /**
  44. * @var int Number of tables
  45. */
  46. protected $_total_num_tables;
  47. /**
  48. * @var array Tables in the database
  49. */
  50. protected $_tables;
  51. /**
  52. * @var bool whether stats show or not
  53. */
  54. protected $_is_show_stats;
  55. /**
  56. * @var Relation $relation
  57. */
  58. private $relation;
  59. /**
  60. * Constructor
  61. */
  62. public function __construct($response, $dbi, $db)
  63. {
  64. parent::__construct($response, $dbi, $db);
  65. $this->relation = new Relation();
  66. }
  67. /**
  68. * Retrieves databse information for further use
  69. *
  70. * @param string $sub_part Page part name
  71. *
  72. * @return void
  73. */
  74. private function _getDbInfo($sub_part)
  75. {
  76. list(
  77. $tables,
  78. $num_tables,
  79. $total_num_tables,
  80. ,
  81. $is_show_stats,
  82. $db_is_system_schema,
  83. ,
  84. ,
  85. $pos
  86. ) = Util::getDbInfo($this->db, $sub_part);
  87. $this->_tables = $tables;
  88. $this->_num_tables = $num_tables;
  89. $this->_pos = $pos;
  90. $this->_db_is_system_schema = $db_is_system_schema;
  91. $this->_total_num_tables = $total_num_tables;
  92. $this->_is_show_stats = $is_show_stats;
  93. }
  94. /**
  95. * Index action
  96. *
  97. * @return void
  98. */
  99. public function indexAction()
  100. {
  101. $response = Response::getInstance();
  102. // Add/Remove favorite tables using Ajax request.
  103. if ($response->isAjax() && !empty($_REQUEST['favorite_table'])) {
  104. $this->addRemoveFavoriteTablesAction();
  105. return;
  106. }
  107. // If there is an Ajax request for real row count of a table.
  108. if ($response->isAjax()
  109. && isset($_REQUEST['real_row_count'])
  110. && $_REQUEST['real_row_count'] == true
  111. ) {
  112. $this->handleRealRowCountRequestAction();
  113. return;
  114. }
  115. // Drops/deletes/etc. multiple tables if required
  116. if ((! empty($_POST['submit_mult']) && isset($_POST['selected_tbl']))
  117. || isset($_POST['mult_btn'])
  118. ) {
  119. $this->multiSubmitAction();
  120. }
  121. $this->response->getHeader()->getScripts()->addFiles(
  122. array(
  123. 'db_structure.js',
  124. 'tbl_change.js',
  125. )
  126. );
  127. // Gets the database structure
  128. $this->_getDbInfo('_structure');
  129. // Checks if there are any tables to be shown on current page.
  130. // If there are no tables, the user is redirected to the last page
  131. // having any.
  132. if ($this->_total_num_tables > 0 && $this->_pos > $this->_total_num_tables) {
  133. $uri = './db_structure.php' . Url::getCommonRaw(array(
  134. 'db' => $this->db,
  135. 'pos' => max(0, $this->_total_num_tables - $GLOBALS['cfg']['MaxTableList']),
  136. 'reload' => 1
  137. ));
  138. Core::sendHeaderLocation($uri);
  139. }
  140. include_once 'libraries/replication.inc.php';
  141. PageSettings::showGroup('DbStructure');
  142. // 1. No tables
  143. if ($this->_num_tables == 0) {
  144. $this->response->addHTML(
  145. Message::notice(__('No tables found in database.'))
  146. );
  147. if (empty($this->_db_is_system_schema)) {
  148. $this->response->addHTML(CreateTable::getHtml($this->db));
  149. }
  150. return;
  151. }
  152. // else
  153. // 2. Shows table information
  154. /**
  155. * Displays the tables list
  156. */
  157. $this->response->addHTML('<div id="tableslistcontainer">');
  158. $_url_params = array(
  159. 'pos' => $this->_pos,
  160. 'db' => $this->db);
  161. // Add the sort options if they exists
  162. if (isset($_REQUEST['sort'])) {
  163. $_url_params['sort'] = $_REQUEST['sort'];
  164. }
  165. if (isset($_REQUEST['sort_order'])) {
  166. $_url_params['sort_order'] = $_REQUEST['sort_order'];
  167. }
  168. $this->response->addHTML(
  169. Util::getListNavigator(
  170. $this->_total_num_tables, $this->_pos, $_url_params,
  171. 'db_structure.php', 'frame_content', $GLOBALS['cfg']['MaxTableList']
  172. )
  173. );
  174. $this->displayTableList();
  175. // display again the table list navigator
  176. $this->response->addHTML(
  177. Util::getListNavigator(
  178. $this->_total_num_tables, $this->_pos, $_url_params,
  179. 'db_structure.php', 'frame_content',
  180. $GLOBALS['cfg']['MaxTableList']
  181. )
  182. );
  183. $this->response->addHTML('</div><hr />');
  184. /**
  185. * Work on the database
  186. */
  187. /* DATABASE WORK */
  188. /* Printable view of a table */
  189. $this->response->addHTML(
  190. Template::get('database/structure/print_view_data_dictionary_link')
  191. ->render(array('url_query' => Url::getCommon(
  192. array(
  193. 'db' => $this->db,
  194. 'goto' => 'db_structure.php',
  195. )
  196. )))
  197. );
  198. if (empty($this->_db_is_system_schema)) {
  199. $this->response->addHTML(CreateTable::getHtml($this->db));
  200. }
  201. }
  202. /**
  203. * Add or remove favorite tables
  204. *
  205. * @return void
  206. */
  207. public function addRemoveFavoriteTablesAction()
  208. {
  209. $fav_instance = RecentFavoriteTable::getInstance('favorite');
  210. if (isset($_REQUEST['favorite_tables'])) {
  211. $favorite_tables = json_decode($_REQUEST['favorite_tables'], true);
  212. } else {
  213. $favorite_tables = array();
  214. }
  215. // Required to keep each user's preferences separate.
  216. $user = sha1($GLOBALS['cfg']['Server']['user']);
  217. // Request for Synchronization of favorite tables.
  218. if (isset($_REQUEST['sync_favorite_tables'])) {
  219. $cfgRelation = $this->relation->getRelationsParam();
  220. if ($cfgRelation['favoritework']) {
  221. $this->synchronizeFavoriteTables($fav_instance, $user, $favorite_tables);
  222. }
  223. return;
  224. }
  225. $changes = true;
  226. $titles = Util::buildActionTitles();
  227. $favorite_table = $_REQUEST['favorite_table'];
  228. $already_favorite = $this->checkFavoriteTable($favorite_table);
  229. if (isset($_REQUEST['remove_favorite'])) {
  230. if ($already_favorite) {
  231. // If already in favorite list, remove it.
  232. $fav_instance->remove($this->db, $favorite_table);
  233. $already_favorite = false; // for favorite_anchor template
  234. }
  235. } elseif (isset($_REQUEST['add_favorite'])) {
  236. if (!$already_favorite) {
  237. $nbTables = count($fav_instance->getTables());
  238. if ($nbTables == $GLOBALS['cfg']['NumFavoriteTables']) {
  239. $changes = false;
  240. } else {
  241. // Otherwise add to favorite list.
  242. $fav_instance->add($this->db, $favorite_table);
  243. $already_favorite = true; // for favorite_anchor template
  244. }
  245. }
  246. }
  247. $favorite_tables[$user] = $fav_instance->getTables();
  248. $this->response->addJSON('changes', $changes);
  249. if (!$changes) {
  250. $this->response->addJSON(
  251. 'message',
  252. Template::get('components/error_message')
  253. ->render(
  254. array(
  255. 'msg' => __("Favorite List is full!")
  256. )
  257. )
  258. );
  259. return;
  260. }
  261. // Check if current table is already in favorite list.
  262. $favParams = array('db' => $this->db,
  263. 'ajax_request' => true,
  264. 'favorite_table' => $favorite_table,
  265. (($already_favorite ? 'remove' : 'add') . '_favorite') => true
  266. );
  267. $this->response->addJSON(
  268. array(
  269. 'user' => $user,
  270. 'favorite_tables' => json_encode($favorite_tables),
  271. 'list' => $fav_instance->getHtmlList(),
  272. 'anchor' => Template::get('database/structure/favorite_anchor')
  273. ->render(
  274. array(
  275. 'table_name_hash' => md5($favorite_table),
  276. 'db_table_name_hash' => md5($this->db . "." . $favorite_table),
  277. 'fav_params' => $favParams,
  278. 'already_favorite' => $already_favorite,
  279. 'titles' => $titles,
  280. )
  281. )
  282. )
  283. );
  284. }
  285. /**
  286. * Handles request for real row count on database level view page.
  287. *
  288. * @return boolean true
  289. */
  290. public function handleRealRowCountRequestAction()
  291. {
  292. $ajax_response = $this->response;
  293. // If there is a request to update all table's row count.
  294. if (!isset($_REQUEST['real_row_count_all'])) {
  295. // Get the real row count for the table.
  296. $real_row_count = $this->dbi
  297. ->getTable($this->db, $_REQUEST['table'])
  298. ->getRealRowCountTable();
  299. // Format the number.
  300. $real_row_count = Util::formatNumber($real_row_count, 0);
  301. $ajax_response->addJSON('real_row_count', $real_row_count);
  302. return;
  303. }
  304. // Array to store the results.
  305. $real_row_count_all = array();
  306. // Iterate over each table and fetch real row count.
  307. foreach ($this->_tables as $table) {
  308. $row_count = $this->dbi
  309. ->getTable($this->db, $table['TABLE_NAME'])
  310. ->getRealRowCountTable();
  311. $real_row_count_all[] = array(
  312. 'table' => $table['TABLE_NAME'],
  313. 'row_count' => $row_count
  314. );
  315. }
  316. $ajax_response->addJSON(
  317. 'real_row_count_all',
  318. json_encode($real_row_count_all)
  319. );
  320. }
  321. /**
  322. * Handles actions related to multiple tables
  323. *
  324. * @return void
  325. */
  326. public function multiSubmitAction()
  327. {
  328. $action = 'db_structure.php';
  329. $err_url = 'db_structure.php' . Url::getCommon(
  330. array('db' => $this->db)
  331. );
  332. // see bug #2794840; in this case, code path is:
  333. // db_structure.php -> libraries/mult_submits.inc.php -> sql.php
  334. // -> db_structure.php and if we got an error on the multi submit,
  335. // we must display it here and not call again mult_submits.inc.php
  336. if (! isset($_POST['error']) || false === $_POST['error']) {
  337. include 'libraries/mult_submits.inc.php';
  338. }
  339. if (empty($_POST['message'])) {
  340. $_POST['message'] = Message::success();
  341. }
  342. }
  343. /**
  344. * Displays the list of tables
  345. *
  346. * @return void
  347. */
  348. protected function displayTableList()
  349. {
  350. // filtering
  351. $this->response->addHTML(
  352. Template::get('filter')->render(['filter_value' => ''])
  353. );
  354. $i = $sum_entries = 0;
  355. $overhead_check = false;
  356. $create_time_all = '';
  357. $update_time_all = '';
  358. $check_time_all = '';
  359. $num_columns = $GLOBALS['cfg']['PropertiesNumColumns'] > 1
  360. ? ceil($this->_num_tables / $GLOBALS['cfg']['PropertiesNumColumns']) + 1
  361. : 0;
  362. $row_count = 0;
  363. $sum_size = 0;
  364. $overhead_size = 0;
  365. $hidden_fields = array();
  366. $overall_approx_rows = false;
  367. $structure_table_rows = [];
  368. foreach ($this->_tables as $keyname => $current_table) {
  369. // Get valid statistics whatever is the table type
  370. $drop_query = '';
  371. $drop_message = '';
  372. $overhead = '';
  373. $input_class = ['checkall'];
  374. $table_is_view = false;
  375. // Sets parameters for links
  376. $tbl_url_query = Url::getCommon(
  377. array('db' => $this->db, 'table' => $current_table['TABLE_NAME'])
  378. );
  379. // do not list the previous table's size info for a view
  380. list($current_table, $formatted_size, $unit, $formatted_overhead,
  381. $overhead_unit, $overhead_size, $table_is_view, $sum_size)
  382. = $this->getStuffForEngineTypeTable(
  383. $current_table, $sum_size, $overhead_size
  384. );
  385. $curTable = $this->dbi
  386. ->getTable($this->db, $current_table['TABLE_NAME']);
  387. if (!$curTable->isMerge()) {
  388. $sum_entries += $current_table['TABLE_ROWS'];
  389. }
  390. if (isset($current_table['Collation'])) {
  391. $collation = '<dfn title="'
  392. . Charsets::getCollationDescr($current_table['Collation']) . '">'
  393. . $current_table['Collation'] . '</dfn>';
  394. } else {
  395. $collation = '---';
  396. }
  397. if ($this->_is_show_stats) {
  398. if ($formatted_overhead != '') {
  399. $overhead = '<a href="tbl_structure.php'
  400. . $tbl_url_query . '#showusage">'
  401. . '<span>' . $formatted_overhead . '</span>&nbsp;'
  402. . '<span class="unit">' . $overhead_unit . '</span>'
  403. . '</a>' . "\n";
  404. $overhead_check = true;
  405. $input_class[] = 'tbl-overhead';
  406. } else {
  407. $overhead = '-';
  408. }
  409. } // end if
  410. if ($GLOBALS['cfg']['ShowDbStructureCharset']) {
  411. if (isset($current_table['Collation'])) {
  412. $charset = mb_substr($collation, 0, mb_strpos($collation, "_"));
  413. } else {
  414. $charset = '';
  415. }
  416. }
  417. if ($GLOBALS['cfg']['ShowDbStructureCreation']) {
  418. $create_time = isset($current_table['Create_time'])
  419. ? $current_table['Create_time'] : '';
  420. if ($create_time
  421. && (!$create_time_all
  422. || $create_time < $create_time_all)
  423. ) {
  424. $create_time_all = $create_time;
  425. }
  426. }
  427. if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) {
  428. $update_time = isset($current_table['Update_time'])
  429. ? $current_table['Update_time'] : '';
  430. if ($update_time
  431. && (!$update_time_all
  432. || $update_time < $update_time_all)
  433. ) {
  434. $update_time_all = $update_time;
  435. }
  436. }
  437. if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) {
  438. $check_time = isset($current_table['Check_time'])
  439. ? $current_table['Check_time'] : '';
  440. if ($check_time
  441. && (!$check_time_all
  442. || $check_time < $check_time_all)
  443. ) {
  444. $check_time_all = $check_time;
  445. }
  446. }
  447. $truename = (!empty($tooltip_truename)
  448. && isset($tooltip_truename[$current_table['TABLE_NAME']]))
  449. ? $tooltip_truename[$current_table['TABLE_NAME']]
  450. : $current_table['TABLE_NAME'];
  451. $i++;
  452. $row_count++;
  453. if ($table_is_view) {
  454. $hidden_fields[] = '<input type="hidden" name="views[]" value="'
  455. . htmlspecialchars($current_table['TABLE_NAME']) . '" />';
  456. }
  457. /*
  458. * Always activate links for Browse, Search and Empty, even if
  459. * the icons are greyed, because
  460. * 1. for views, we don't know the number of rows at this point
  461. * 2. for tables, another source could have populated them since the
  462. * page was generated
  463. *
  464. * I could have used the PHP ternary conditional operator but I find
  465. * the code easier to read without this operator.
  466. */
  467. $may_have_rows = $current_table['TABLE_ROWS'] > 0 || $table_is_view;
  468. $titles = Util::buildActionTitles();
  469. $browse_table = Template::get('database/structure/browse_table')
  470. ->render(
  471. array(
  472. 'tbl_url_query' => $tbl_url_query,
  473. 'title' => $may_have_rows ? $titles['Browse']
  474. : $titles['NoBrowse'],
  475. )
  476. );
  477. $search_table = Template::get('database/structure/search_table')
  478. ->render(
  479. array(
  480. 'tbl_url_query' => $tbl_url_query,
  481. 'title' => $may_have_rows ? $titles['Search']
  482. : $titles['NoSearch'],
  483. )
  484. );
  485. $browse_table_label = Template::get(
  486. 'database/structure/browse_table_label'
  487. )
  488. ->render(
  489. array(
  490. 'tbl_url_query' => $tbl_url_query,
  491. 'title' => htmlspecialchars(
  492. $current_table['TABLE_COMMENT']
  493. ),
  494. 'truename' => $truename,
  495. )
  496. );
  497. $empty_table = '';
  498. if (!$this->_db_is_system_schema) {
  499. $empty_table = '';
  500. if (!$table_is_view) {
  501. $empty_table = Template::get('database/structure/empty_table')
  502. ->render(
  503. array(
  504. 'tbl_url_query' => $tbl_url_query,
  505. 'sql_query' => urlencode(
  506. 'TRUNCATE ' . Util::backquote(
  507. $current_table['TABLE_NAME']
  508. )
  509. ),
  510. 'message_to_show' => urlencode(
  511. sprintf(
  512. __('Table %s has been emptied.'),
  513. htmlspecialchars(
  514. $current_table['TABLE_NAME']
  515. )
  516. )
  517. ),
  518. 'title' => $may_have_rows ? $titles['Empty']
  519. : $titles['NoEmpty'],
  520. )
  521. );
  522. }
  523. $drop_query = sprintf(
  524. 'DROP %s %s',
  525. ($table_is_view || $current_table['ENGINE'] == null) ? 'VIEW'
  526. : 'TABLE',
  527. Util::backquote(
  528. $current_table['TABLE_NAME']
  529. )
  530. );
  531. $drop_message = sprintf(
  532. (($table_is_view || $current_table['ENGINE'] == null)
  533. ? __('View %s has been dropped.')
  534. : __('Table %s has been dropped.')),
  535. str_replace(
  536. ' ', '&nbsp;',
  537. htmlspecialchars($current_table['TABLE_NAME'])
  538. )
  539. );
  540. }
  541. if ($num_columns > 0
  542. && $this->_num_tables > $num_columns
  543. && ($row_count % $num_columns) == 0
  544. ) {
  545. $row_count = 1;
  546. $this->response->addHTML(
  547. Template::get('database/structure/table_header')->render([
  548. 'db' => $this->db,
  549. 'db_is_system_schema' => $this->_db_is_system_schema,
  550. 'replication' => $GLOBALS['replication_info']['slave']['status'],
  551. 'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
  552. 'is_show_stats' => $GLOBALS['is_show_stats'],
  553. 'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
  554. 'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
  555. 'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
  556. 'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
  557. 'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
  558. 'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
  559. 'structure_table_rows' => $structure_table_rows,
  560. ])
  561. );
  562. $structure_table_rows = [];
  563. }
  564. list($approx_rows, $show_superscript) = $this->isRowCountApproximated(
  565. $current_table, $table_is_view
  566. );
  567. list($do, $ignored) = $this->getReplicationStatus($truename);
  568. $structure_table_rows[] = [
  569. 'db' => $this->db,
  570. 'curr' => $i,
  571. 'input_class' => implode(' ', $input_class),
  572. 'table_is_view' => $table_is_view,
  573. 'current_table' => $current_table,
  574. 'browse_table_label' => $browse_table_label,
  575. 'tracking_icon' => $this->getTrackingIcon($truename),
  576. 'server_slave_status' => $GLOBALS['replication_info']['slave']['status'],
  577. 'browse_table' => $browse_table,
  578. 'tbl_url_query' => $tbl_url_query,
  579. 'search_table' => $search_table,
  580. 'db_is_system_schema' => $this->_db_is_system_schema,
  581. 'titles' => $titles,
  582. 'empty_table' => $empty_table,
  583. 'drop_query' => $drop_query,
  584. 'drop_message' => $drop_message,
  585. 'collation' => $collation,
  586. 'formatted_size' => $formatted_size,
  587. 'unit' => $unit,
  588. 'overhead' => $overhead,
  589. 'create_time' => isset($create_time)
  590. ? $create_time : '',
  591. 'update_time' => isset($update_time)
  592. ? $update_time : '',
  593. 'check_time' => isset($check_time)
  594. ? $check_time : '',
  595. 'charset' => isset($charset)
  596. ? $charset : '',
  597. 'is_show_stats' => $this->_is_show_stats,
  598. 'ignored' => $ignored,
  599. 'do' => $do,
  600. 'approx_rows' => $approx_rows,
  601. 'show_superscript' => $show_superscript,
  602. 'already_favorite' => $this->checkFavoriteTable(
  603. $current_table['TABLE_NAME']
  604. ),
  605. 'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
  606. 'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
  607. 'limit_chars' => $GLOBALS['cfg']['LimitChars'],
  608. 'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
  609. 'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
  610. 'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
  611. 'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
  612. 'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
  613. ];
  614. $overall_approx_rows = $overall_approx_rows || $approx_rows;
  615. } // end foreach
  616. $db_collation = $this->dbi->getDbCollation($this->db);
  617. $db_charset = mb_substr($db_collation, 0, mb_strpos($db_collation, "_"));
  618. // table form
  619. $this->response->addHTML(
  620. Template::get('database/structure/table_header')->render([
  621. 'db' => $this->db,
  622. 'db_is_system_schema' => $this->_db_is_system_schema,
  623. 'replication' => $GLOBALS['replication_info']['slave']['status'],
  624. 'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
  625. 'is_show_stats' => $GLOBALS['is_show_stats'],
  626. 'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
  627. 'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
  628. 'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
  629. 'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
  630. 'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
  631. 'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
  632. 'structure_table_rows' => $structure_table_rows,
  633. 'body_for_table_summary' => [
  634. 'num_tables' => $this->_num_tables,
  635. 'server_slave_status' => $GLOBALS['replication_info']['slave']['status'],
  636. 'db_is_system_schema' => $this->_db_is_system_schema,
  637. 'sum_entries' => $sum_entries,
  638. 'db_collation' => $db_collation,
  639. 'is_show_stats' => $this->_is_show_stats,
  640. 'db_charset' => $db_charset,
  641. 'sum_size' => $sum_size,
  642. 'overhead_size' => $overhead_size,
  643. 'create_time_all' => $create_time_all,
  644. 'update_time_all' => $update_time_all,
  645. 'check_time_all' => $check_time_all,
  646. 'approx_rows' => $overall_approx_rows,
  647. 'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
  648. 'db' => $GLOBALS['db'],
  649. 'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
  650. 'dbi' => $GLOBALS['dbi'],
  651. 'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
  652. 'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
  653. 'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
  654. 'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
  655. 'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
  656. ],
  657. 'check_all_tables' => [
  658. 'pma_theme_image' => $GLOBALS['pmaThemeImage'],
  659. 'text_dir' => $GLOBALS['text_dir'],
  660. 'overhead_check' => $overhead_check,
  661. 'db_is_system_schema' => $this->_db_is_system_schema,
  662. 'hidden_fields' => $hidden_fields,
  663. 'disable_multi_table' => $GLOBALS['cfg']['DisableMultiTableMaintenance'],
  664. 'central_columns_work' => $GLOBALS['cfgRelation']['centralcolumnswork'],
  665. ],
  666. ])
  667. );
  668. }
  669. /**
  670. * Returns the tracking icon if the table is tracked
  671. *
  672. * @param string $table table name
  673. *
  674. * @return string HTML for tracking icon
  675. */
  676. protected function getTrackingIcon($table)
  677. {
  678. $tracking_icon = '';
  679. if (Tracker::isActive()) {
  680. $is_tracked = Tracker::isTracked($this->db, $table);
  681. if ($is_tracked
  682. || Tracker::getVersion($this->db, $table) > 0
  683. ) {
  684. $tracking_icon = Template::get(
  685. 'database/structure/tracking_icon'
  686. )
  687. ->render(
  688. array(
  689. 'db' => $this->db,
  690. 'table' => $table,
  691. 'is_tracked' => $is_tracked,
  692. )
  693. );
  694. }
  695. }
  696. return $tracking_icon;
  697. }
  698. /**
  699. * Returns whether the row count is approximated
  700. *
  701. * @param array $current_table array containing details about the table
  702. * @param boolean $table_is_view whether the table is a view
  703. *
  704. * @return array
  705. */
  706. protected function isRowCountApproximated(array $current_table, $table_is_view)
  707. {
  708. $approx_rows = false;
  709. $show_superscript = '';
  710. // there is a null value in the ENGINE
  711. // - when the table needs to be repaired, or
  712. // - when it's a view
  713. // so ensure that we'll display "in use" below for a table
  714. // that needs to be repaired
  715. if (isset($current_table['TABLE_ROWS'])
  716. && ($current_table['ENGINE'] != null || $table_is_view)
  717. ) {
  718. // InnoDB/TokuDB table: we did not get an accurate row count
  719. $approx_rows = !$table_is_view
  720. && in_array($current_table['ENGINE'], array('InnoDB', 'TokuDB'))
  721. && !$current_table['COUNTED'];
  722. if ($table_is_view
  723. && $current_table['TABLE_ROWS'] >= $GLOBALS['cfg']['MaxExactCountViews']
  724. ) {
  725. $approx_rows = true;
  726. $show_superscript = Util::showHint(
  727. Sanitize::sanitize(
  728. sprintf(
  729. __(
  730. 'This view has at least this number of '
  731. . 'rows. Please refer to %sdocumentation%s.'
  732. ),
  733. '[doc@cfg_MaxExactCountViews]', '[/doc]'
  734. )
  735. )
  736. );
  737. }
  738. }
  739. return array($approx_rows, $show_superscript);
  740. }
  741. /**
  742. * Returns the replication status of the table.
  743. *
  744. * @param string $table table name
  745. *
  746. * @return array
  747. */
  748. protected function getReplicationStatus($table)
  749. {
  750. $do = $ignored = false;
  751. if ($GLOBALS['replication_info']['slave']['status']) {
  752. $nbServSlaveDoDb = count(
  753. $GLOBALS['replication_info']['slave']['Do_DB']
  754. );
  755. $nbServSlaveIgnoreDb = count(
  756. $GLOBALS['replication_info']['slave']['Ignore_DB']
  757. );
  758. $searchDoDBInTruename = array_search(
  759. $table, $GLOBALS['replication_info']['slave']['Do_DB']
  760. );
  761. $searchDoDBInDB = array_search(
  762. $this->db, $GLOBALS['replication_info']['slave']['Do_DB']
  763. );
  764. $do = strlen($searchDoDBInTruename) > 0
  765. || strlen($searchDoDBInDB) > 0
  766. || ($nbServSlaveDoDb == 0 && $nbServSlaveIgnoreDb == 0)
  767. || $this->hasTable(
  768. $GLOBALS['replication_info']['slave']['Wild_Do_Table'],
  769. $table
  770. );
  771. $searchDb = array_search(
  772. $this->db,
  773. $GLOBALS['replication_info']['slave']['Ignore_DB']
  774. );
  775. $searchTable = array_search(
  776. $table,
  777. $GLOBALS['replication_info']['slave']['Ignore_Table']
  778. );
  779. $ignored = strlen($searchTable) > 0
  780. || strlen($searchDb) > 0
  781. || $this->hasTable(
  782. $GLOBALS['replication_info']['slave']['Wild_Ignore_Table'],
  783. $table
  784. );
  785. }
  786. return array($do, $ignored);
  787. }
  788. /**
  789. * Synchronize favorite tables
  790. *
  791. *
  792. * @param RecentFavoriteTable $fav_instance Instance of this class
  793. * @param string $user The user hash
  794. * @param array $favorite_tables Existing favorites
  795. *
  796. * @return void
  797. */
  798. protected function synchronizeFavoriteTables(
  799. $fav_instance,
  800. $user,
  801. array $favorite_tables
  802. ) {
  803. $fav_instance_tables = $fav_instance->getTables();
  804. if (empty($fav_instance_tables)
  805. && isset($favorite_tables[$user])
  806. ) {
  807. foreach ($favorite_tables[$user] as $key => $value) {
  808. $fav_instance->add($value['db'], $value['table']);
  809. }
  810. }
  811. $favorite_tables[$user] = $fav_instance->getTables();
  812. $this->response->addJSON(
  813. array(
  814. 'favorite_tables' => json_encode($favorite_tables),
  815. 'list' => $fav_instance->getHtmlList()
  816. )
  817. );
  818. $server_id = $GLOBALS['server'];
  819. // Set flag when localStorage and pmadb(if present) are in sync.
  820. $_SESSION['tmpval']['favorites_synced'][$server_id] = true;
  821. }
  822. /**
  823. * Function to check if a table is already in favorite list.
  824. *
  825. * @param string $current_table current table
  826. *
  827. * @return true|false
  828. */
  829. protected function checkFavoriteTable($current_table)
  830. {
  831. // ensure $_SESSION['tmpval']['favorite_tables'] is initialized
  832. RecentFavoriteTable::getInstance('favorite');
  833. foreach (
  834. $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']] as $value
  835. ) {
  836. if ($value['db'] == $this->db && $value['table'] == $current_table) {
  837. return true;
  838. }
  839. }
  840. return false;
  841. }
  842. /**
  843. * Find table with truename
  844. *
  845. * @param array $db DB to look into
  846. * @param string $truename Table name
  847. *
  848. * @return bool
  849. */
  850. protected function hasTable(array $db, $truename)
  851. {
  852. foreach ($db as $db_table) {
  853. if ($this->db == Replication::extractDbOrTable($db_table)
  854. && preg_match(
  855. "@^" .
  856. preg_quote(mb_substr(Replication::extractDbOrTable($db_table, 'table'), 0, -1)) . "@",
  857. $truename
  858. )
  859. ) {
  860. return true;
  861. }
  862. }
  863. return false;
  864. }
  865. /**
  866. * Get the value set for ENGINE table,
  867. *
  868. * @param array $current_table current table
  869. * @param integer $sum_size total table size
  870. * @param integer $overhead_size overhead size
  871. *
  872. * @return array
  873. * @internal param bool $table_is_view whether table is view or not
  874. */
  875. protected function getStuffForEngineTypeTable(
  876. array $current_table, $sum_size, $overhead_size
  877. ) {
  878. $formatted_size = '-';
  879. $unit = '';
  880. $formatted_overhead = '';
  881. $overhead_unit = '';
  882. $table_is_view = false;
  883. switch ( $current_table['ENGINE']) {
  884. // MyISAM, ISAM or Heap table: Row count, data size and index size
  885. // are accurate; data size is accurate for ARCHIVE
  886. case 'MyISAM' :
  887. case 'ISAM' :
  888. case 'HEAP' :
  889. case 'MEMORY' :
  890. case 'ARCHIVE' :
  891. case 'Aria' :
  892. case 'Maria' :
  893. list($current_table, $formatted_size, $unit, $formatted_overhead,
  894. $overhead_unit, $overhead_size, $sum_size)
  895. = $this->getValuesForAriaTable(
  896. $current_table, $sum_size, $overhead_size,
  897. $formatted_size, $unit, $formatted_overhead, $overhead_unit
  898. );
  899. break;
  900. case 'InnoDB' :
  901. case 'PBMS' :
  902. case 'TokuDB' :
  903. // InnoDB table: Row count is not accurate but data and index sizes are.
  904. // PBMS table in Drizzle: TABLE_ROWS is taken from table cache,
  905. // so it may be unavailable
  906. list($current_table, $formatted_size, $unit, $sum_size)
  907. = $this->getValuesForInnodbTable(
  908. $current_table, $sum_size
  909. );
  910. break;
  911. // Mysql 5.0.x (and lower) uses MRG_MyISAM
  912. // and MySQL 5.1.x (and higher) uses MRG_MYISAM
  913. // Both are aliases for MERGE
  914. case 'MRG_MyISAM' :
  915. case 'MRG_MYISAM' :
  916. case 'MERGE' :
  917. case 'BerkeleyDB' :
  918. // Merge or BerkleyDB table: Only row count is accurate.
  919. if ($this->_is_show_stats) {
  920. $formatted_size = ' - ';
  921. $unit = '';
  922. }
  923. break;
  924. // for a view, the ENGINE is sometimes reported as null,
  925. // or on some servers it's reported as "SYSTEM VIEW"
  926. case null :
  927. case 'SYSTEM VIEW' :
  928. // possibly a view, do nothing
  929. break;
  930. default :
  931. // Unknown table type.
  932. if ($this->_is_show_stats) {
  933. $formatted_size = __('unknown');
  934. $unit = '';
  935. }
  936. } // end switch
  937. if ($current_table['TABLE_TYPE'] == 'VIEW'
  938. || $current_table['TABLE_TYPE'] == 'SYSTEM VIEW'
  939. ) {
  940. // countRecords() takes care of $cfg['MaxExactCountViews']
  941. $current_table['TABLE_ROWS'] = $this->dbi
  942. ->getTable($this->db, $current_table['TABLE_NAME'])
  943. ->countRecords(true);
  944. $table_is_view = true;
  945. }
  946. return array($current_table, $formatted_size, $unit, $formatted_overhead,
  947. $overhead_unit, $overhead_size, $table_is_view, $sum_size
  948. );
  949. }
  950. /**
  951. * Get values for ARIA/MARIA tables
  952. *
  953. * @param array $current_table current table
  954. * @param integer $sum_size sum size
  955. * @param integer $overhead_size overhead size
  956. * @param integer $formatted_size formatted size
  957. * @param string $unit unit
  958. * @param integer $formatted_overhead overhead formatted
  959. * @param string $overhead_unit overhead unit
  960. *
  961. * @return array
  962. */
  963. protected function getValuesForAriaTable(
  964. array $current_table, $sum_size, $overhead_size, $formatted_size, $unit,
  965. $formatted_overhead, $overhead_unit
  966. ) {
  967. if ($this->_db_is_system_schema) {
  968. $current_table['Rows'] = $this->dbi
  969. ->getTable($this->db, $current_table['Name'])
  970. ->countRecords();
  971. }
  972. if ($this->_is_show_stats) {
  973. $tblsize = $current_table['Data_length']
  974. + $current_table['Index_length'];
  975. $sum_size += $tblsize;
  976. list($formatted_size, $unit) = Util::formatByteDown(
  977. $tblsize, 3, ($tblsize > 0) ? 1 : 0
  978. );
  979. if (isset($current_table['Data_free'])
  980. && $current_table['Data_free'] > 0
  981. ) {
  982. list($formatted_overhead, $overhead_unit)
  983. = Util::formatByteDown(
  984. $current_table['Data_free'], 3,
  985. (($current_table['Data_free'] > 0) ? 1 : 0)
  986. );
  987. $overhead_size += $current_table['Data_free'];
  988. }
  989. }
  990. return array($current_table, $formatted_size, $unit, $formatted_overhead,
  991. $overhead_unit, $overhead_size, $sum_size
  992. );
  993. }
  994. /**
  995. * Get values for InnoDB table
  996. *
  997. * @param array $current_table current table
  998. * @param integer $sum_size sum size
  999. *
  1000. * @return array
  1001. */
  1002. protected function getValuesForInnodbTable(
  1003. array $current_table, $sum_size
  1004. ) {
  1005. $formatted_size = $unit = '';
  1006. if ((in_array($current_table['ENGINE'], array('InnoDB', 'TokuDB'))
  1007. && $current_table['TABLE_ROWS'] < $GLOBALS['cfg']['MaxExactCount'])
  1008. || !isset($current_table['TABLE_ROWS'])
  1009. ) {
  1010. $current_table['COUNTED'] = true;
  1011. $current_table['TABLE_ROWS'] = $this->dbi
  1012. ->getTable($this->db, $current_table['TABLE_NAME'])
  1013. ->countRecords(true);
  1014. } else {
  1015. $current_table['COUNTED'] = false;
  1016. }
  1017. if ($this->_is_show_stats) {
  1018. $tblsize = $current_table['Data_length']
  1019. + $current_table['Index_length'];
  1020. $sum_size += $tblsize;
  1021. list($formatted_size, $unit) = Util::formatByteDown(
  1022. $tblsize, 3, (($tblsize > 0) ? 1 : 0)
  1023. );
  1024. }
  1025. return array($current_table, $formatted_size, $unit, $sum_size);
  1026. }
  1027. }