Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / libraries / Table.class.php
blob6e205cf308cad8354e8b25aacc997a279e4a2f1e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
5 * @package phpMyAdmin
6 */
8 /**
9 * @todo make use of PMA_Message and PMA_Error
10 * @package phpMyAdmin
12 class PMA_Table
14 /**
15 * UI preferences properties
17 const PROP_SORTED_COLUMN = 'sorted_col';
18 const PROP_COLUMN_ORDER = 'col_order';
19 const PROP_COLUMN_VISIB = 'col_visib';
21 static $cache = array();
23 /**
24 * @var string table name
26 var $name = '';
28 /**
29 * @var string database name
31 var $db_name = '';
33 /**
34 * @var string engine (innodb, myisam, bdb, ...)
36 var $engine = '';
38 /**
39 * @var string type (view, base table, system view)
41 var $type = '';
43 /**
44 * @var array settings
46 var $settings = array();
48 /**
49 * @var array UI preferences
51 var $uiprefs;
53 /**
54 * @var array errors occured
56 var $errors = array();
58 /**
59 * @var array messages
61 var $messages = array();
63 /**
64 * Constructor
66 * @param string $table_name table name
67 * @param string $db_name database name
69 function __construct($table_name, $db_name)
71 $this->setName($table_name);
72 $this->setDbName($db_name);
75 /**
76 * returns table name
78 * @see PMA_Table::getName()
79 * @return string table name
81 function __toString()
83 return $this->getName();
86 function getLastError()
88 return end($this->errors);
91 function getLastMessage()
93 return end($this->messages);
96 /**
97 * sets table name
99 * @param string $table_name new table name
101 function setName($table_name)
103 $this->name = $table_name;
107 * returns table name
109 * @param boolean $backquoted whether to quote name with backticks ``
110 * @return string table name
112 function getName($backquoted = false)
114 if ($backquoted) {
115 return PMA_backquote($this->name);
117 return $this->name;
121 * sets database name for this table
123 * @param string $db_name
125 function setDbName($db_name)
127 $this->db_name = $db_name;
131 * returns database name for this table
133 * @param boolean $backquoted whether to quote name with backticks ``
134 * @return string database name for this table
136 function getDbName($backquoted = false)
138 if ($backquoted) {
139 return PMA_backquote($this->db_name);
141 return $this->db_name;
145 * returns full name for table, including database name
147 * @param boolean $backquoted whether to quote name with backticks ``
148 * @return string
150 function getFullName($backquoted = false)
152 return $this->getDbName($backquoted) . '.' . $this->getName($backquoted);
155 static public function isView($db = null, $table = null)
157 if (strlen($db) && strlen($table)) {
158 return PMA_Table::_isView($db, $table);
161 return false;
165 * sets given $value for given $param
167 * @param string $param name
168 * @param mixed $value value
170 function set($param, $value)
172 $this->settings[$param] = $value;
176 * returns value for given setting/param
178 * @param string $param name for value to return
179 * @return mixed value for $param
181 function get($param)
183 if (isset($this->settings[$param])) {
184 return $this->settings[$param];
187 return null;
191 * loads structure data
192 * (this function is work in progress? not yet used)
194 * @return boolean
196 function loadStructure()
198 $table_info = PMA_DBI_get_tables_full($this->getDbName(), $this->getName());
200 if (false === $table_info) {
201 return false;
204 $this->settings = $table_info;
206 if ($this->get('TABLE_ROWS') === null) {
207 $this->set('TABLE_ROWS', PMA_Table::countRecords($this->getDbName(),
208 $this->getName(), true));
211 $create_options = explode(' ', $this->get('TABLE_ROWS'));
213 // export create options by its name as variables into gloabel namespace
214 // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
215 foreach ($create_options as $each_create_option) {
216 $each_create_option = explode('=', $each_create_option);
217 if (isset($each_create_option[1])) {
218 $this->set($$each_create_option[0], $each_create_option[1]);
221 return true;
225 * Checks if this "table" is a view
227 * @deprecated
228 * @todo see what we could do with the possible existence of $table_is_view
229 * @param string $db the database name
230 * @param string $table the table name
231 * @return boolean whether this is a view
233 static protected function _isView($db, $table)
235 // maybe we already know if the table is a view
236 if (isset($GLOBALS['tbl_is_view']) && $GLOBALS['tbl_is_view']) {
237 return true;
240 // Since phpMyAdmin 3.2 the field TABLE_TYPE is properly filled by PMA_DBI_get_tables_full()
241 $type = PMA_Table::sGetStatusInfo($db, $table, 'TABLE_TYPE');
242 return $type == 'VIEW';
246 * Checks if this is a merge table
248 * If the ENGINE of the table is MERGE or MRG_MYISAM (alias), this is a merge table.
250 * @param string $db the database name
251 * @param string $table the table name
252 * @return boolean true if it is a merge table
254 static public function isMerge($db = null, $table = null)
256 $engine = null;
257 // if called static, with parameters
258 if (! empty($db) && ! empty($table)) {
259 $engine = PMA_Table::sGetStatusInfo($db, $table, 'ENGINE', null, true);
262 return (! empty($engine) && ((strtoupper($engine) == 'MERGE') || (strtoupper($engine) == 'MRG_MYISAM')));
265 static public function sGetToolTip($db, $table)
267 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
268 . ' (' . PMA_Table::countRecords($db, $table) . ')';
272 * Returns full table status info, or specific if $info provided
274 * this info is collected from information_schema
276 * @todo PMA_DBI_get_tables_full needs to be merged somehow into this class or at least better documented
277 * @param string $db
278 * @param string $table
279 * @param string $info
280 * @param boolean $force_read
281 * @param boolean $disable_error if true, disables error message
282 * @return mixed
284 static public function sGetStatusInfo($db, $table, $info = null, $force_read = false, $disable_error = false)
286 if (! isset(PMA_Table::$cache[$db][$table]) || $force_read) {
287 PMA_DBI_get_tables_full($db, $table);
290 if (! isset(PMA_Table::$cache[$db][$table])) {
291 // happens when we enter the table creation dialog
292 // or when we really did not get any status info, for example
293 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
294 return '';
297 if (null === $info) {
298 return PMA_Table::$cache[$db][$table];
301 // array_key_exists allows for null values
302 if (!array_key_exists($info, PMA_Table::$cache[$db][$table])) {
303 if (! $disable_error) {
304 trigger_error(__('unknown table status: ') . $info, E_USER_WARNING);
306 return false;
309 return PMA_Table::$cache[$db][$table][$info];
313 * generates column specification for ALTER or CREATE TABLE syntax
315 * @todo move into class PMA_Column
316 * @todo on the interface, some js to clear the default value when the default current_timestamp is checked
317 * @param string $name name
318 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
319 * @param string $length length ('2', '5,2', '', ...)
320 * @param string $attribute
321 * @param string $collation
322 * @param bool|string $null with 'NULL' or 'NOT NULL'
323 * @param string $default_type whether default is CURRENT_TIMESTAMP,
324 * NULL, NONE, USER_DEFINED
325 * @param string $default_value default value for USER_DEFINED default type
326 * @param string $extra 'AUTO_INCREMENT'
327 * @param string $comment field comment
328 * @param array &$field_primary list of fields for PRIMARY KEY
329 * @param string $index
330 * @return string field specification
332 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
333 $collation = '', $null = false, $default_type = 'USER_DEFINED',
334 $default_value = '', $extra = '', $comment = '',
335 &$field_primary, $index)
338 $is_timestamp = strpos(strtoupper($type), 'TIMESTAMP') !== false;
340 $query = PMA_backquote($name) . ' ' . $type;
342 if ($length != ''
343 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT'
344 . '|SERIAL|BOOLEAN|UUID)$@i', $type)) {
345 $query .= '(' . $length . ')';
348 if ($attribute != '') {
349 $query .= ' ' . $attribute;
352 if (!empty($collation) && $collation != 'NULL'
353 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)) {
354 $query .= PMA_generateCharsetQueryPart($collation);
357 if ($null !== false) {
358 if ($null == 'NULL') {
359 $query .= ' NULL';
360 } else {
361 $query .= ' NOT NULL';
365 switch ($default_type) {
366 case 'USER_DEFINED' :
367 if ($is_timestamp && $default_value === '0') {
368 // a TIMESTAMP does not accept DEFAULT '0'
369 // but DEFAULT 0 works
370 $query .= ' DEFAULT 0';
371 } elseif ($type == 'BIT') {
372 $query .= ' DEFAULT b\'' . preg_replace('/[^01]/', '0', $default_value) . '\'';
373 } elseif ($type == 'BOOLEAN') {
374 if (preg_match('/^1|T|TRUE|YES$/i', $default_value)) {
375 $query .= ' DEFAULT TRUE';
376 } elseif (preg_match('/^0|F|FALSE|NO$/i', $default_value)) {
377 $query .= ' DEFAULT FALSE';
378 } else {
379 // Invalid BOOLEAN value
380 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
382 } else {
383 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
385 break;
386 case 'NULL' :
387 case 'CURRENT_TIMESTAMP' :
388 $query .= ' DEFAULT ' . $default_type;
389 break;
390 case 'NONE' :
391 default :
392 break;
395 if (!empty($extra)) {
396 $query .= ' ' . $extra;
397 // Force an auto_increment field to be part of the primary key
398 // even if user did not tick the PK box;
399 if ($extra == 'AUTO_INCREMENT') {
400 $primary_cnt = count($field_primary);
401 if (1 == $primary_cnt) {
402 for ($j = 0; $j < $primary_cnt && $field_primary[$j] != $index; $j++) {
403 //void
405 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
406 $query .= ' PRIMARY KEY';
407 unset($field_primary[$j]);
409 // but the PK could contain other columns so do not append
410 // a PRIMARY KEY clause, just add a member to $field_primary
411 } else {
412 $found_in_pk = false;
413 for ($j = 0; $j < $primary_cnt; $j++) {
414 if ($field_primary[$j] == $index) {
415 $found_in_pk = true;
416 break;
418 } // end for
419 if (! $found_in_pk) {
420 $field_primary[] = $index;
423 } // end if (auto_increment)
425 if (!empty($comment)) {
426 $query .= " COMMENT '" . PMA_sqlAddSlashes($comment) . "'";
428 return $query;
429 } // end function
432 * Counts and returns (or displays) the number of records in a table
434 * Revision 13 July 2001: Patch for limiting dump size from
435 * vinay@sanisoft.com & girish@sanisoft.com
437 * @param string $db the current database name
438 * @param string $table the current table name
439 * @param bool $force_exact whether to force an exact count
440 * @param bool $is_view
442 * @return mixed the number of records if "retain" param is true,
443 * otherwise true
445 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
447 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
448 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
449 } else {
450 $row_count = false;
452 if (null === $is_view) {
453 $is_view = PMA_Table::isView($db, $table);
456 if (! $force_exact) {
457 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
458 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
459 if (isset($tmp_tables[$table])) {
460 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
463 if (isset(PMA_Table::$cache[$db][$table]['Rows'])) {
464 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
465 } else {
466 $row_count = false;
470 // for a VIEW, $row_count is always false at this point
471 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
472 // Make an exception for views in I_S and D_D schema in Drizzle, as these map to
473 // in-memory data and should execute fast enough
474 if (! $is_view || (PMA_DRIZZLE && (strtolower($db) == 'information_schema' || strtolower($db) == 'data_dictionary'))) {
475 $row_count = PMA_DBI_fetch_value(
476 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
477 . PMA_backquote($table));
478 } else {
479 // For complex views, even trying to get a partial record
480 // count could bring down a server, so we offer an
481 // alternative: setting MaxExactCountViews to 0 will bypass
482 // completely the record counting for views
484 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
485 $row_count = 0;
486 } else {
487 // Counting all rows of a VIEW could be too long, so use
488 // a LIMIT clause.
489 // Use try_query because it can fail (when a VIEW is
490 // based on a table that no longer exists)
491 $result = PMA_DBI_try_query(
492 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
493 . PMA_backquote($table) . ' LIMIT '
494 . $GLOBALS['cfg']['MaxExactCountViews'],
495 null, PMA_DBI_QUERY_STORE);
496 if (!PMA_DBI_getError()) {
497 $row_count = PMA_DBI_num_rows($result);
498 PMA_DBI_free_result($result);
502 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
506 return $row_count;
507 } // end of the 'PMA_Table::countRecords()' function
510 * Generates column specification for ALTER syntax
512 * @see PMA_Table::generateFieldSpec()
513 * @param string $oldcol old column name
514 * @param string $newcol new column name
515 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
516 * @param string $length length ('2', '5,2', '', ...)
517 * @param string $attribute
518 * @param string $collation
519 * @param bool|string $null with 'NULL' or 'NOT NULL'
520 * @param string $default_type whether default is CURRENT_TIMESTAMP,
521 * NULL, NONE, USER_DEFINED
522 * @param string $default_value default value for USER_DEFINED default type
523 * @param string $extra 'AUTO_INCREMENT'
524 * @param string $comment field comment
525 * @param array &$field_primary list of fields for PRIMARY KEY
526 * @param string $index
527 * @param mixed $default_orig
528 * @return string field specification
530 static public function generateAlter($oldcol, $newcol, $type, $length,
531 $attribute, $collation, $null, $default_type, $default_value,
532 $extra, $comment = '', &$field_primary, $index, $default_orig)
534 return PMA_backquote($oldcol) . ' '
535 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
536 $collation, $null, $default_type, $default_value, $extra,
537 $comment, $field_primary, $index, $default_orig);
538 } // end function
541 * Inserts existing entries in a PMA_* table by reading a value from an old entry
543 * @global relation variable
544 * @param string $work The array index, which Relation feature to check ('relwork', 'commwork', ...)
545 * @param string $pma_table The array index, which PMA-table to update ('bookmark', 'relation', ...)
546 * @param array $get_fields Which fields will be SELECT'ed from the old entry
547 * @param array $where_fields Which fields will be used for the WHERE query (array('FIELDNAME' => 'FIELDVALUE'))
548 * @param array $new_fields Which fields will be used as new VALUES. These are the important
549 * keys which differ from the old entry.
550 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
551 * @return int|true
553 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
554 $new_fields)
556 $last_id = -1;
558 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
559 $select_parts = array();
560 $row_fields = array();
561 foreach ($get_fields as $get_field) {
562 $select_parts[] = PMA_backquote($get_field);
563 $row_fields[$get_field] = 'cc';
566 $where_parts = array();
567 foreach ($where_fields as $_where => $_value) {
568 $where_parts[] = PMA_backquote($_where) . ' = \''
569 . PMA_sqlAddSlashes($_value) . '\'';
572 $new_parts = array();
573 $new_value_parts = array();
574 foreach ($new_fields as $_where => $_value) {
575 $new_parts[] = PMA_backquote($_where);
576 $new_value_parts[] = PMA_sqlAddSlashes($_value);
579 $table_copy_query = '
580 SELECT ' . implode(', ', $select_parts) . '
581 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
582 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
583 WHERE ' . implode(' AND ', $where_parts);
585 // must use PMA_DBI_QUERY_STORE here, since we execute another
586 // query inside the loop
587 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
588 PMA_DBI_QUERY_STORE);
590 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
591 $value_parts = array();
592 foreach ($table_copy_row as $_key => $_val) {
593 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
594 $value_parts[] = PMA_sqlAddSlashes($_val);
598 $new_table_query = '
599 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
600 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
601 (' . implode(', ', $select_parts) . ',
602 ' . implode(', ', $new_parts) . ')
603 VALUES
604 (\'' . implode('\', \'', $value_parts) . '\',
605 \'' . implode('\', \'', $new_value_parts) . '\')';
607 PMA_query_as_controluser($new_table_query);
608 $last_id = PMA_DBI_insert_id();
609 } // end while
611 PMA_DBI_free_result($table_copy_rs);
613 return $last_id;
616 return true;
617 } // end of 'PMA_Table::duplicateInfo()' function
621 * Copies or renames table
623 * @param $source_db
624 * @param $source_table
625 * @param $target_db
626 * @param $target_table
627 * @param $what
628 * @param $move
629 * @param $mode
630 * @return bool
632 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
634 global $err_url;
636 /* Try moving table directly */
637 if ($move && $what == 'data') {
638 $tbl = new PMA_Table($source_table, $source_db);
639 $result = $tbl->rename($target_table, $target_db, PMA_Table::isView($source_db, $source_table));
640 if ($result) {
641 $GLOBALS['message'] = $tbl->getLastMessage();
642 return true;
646 // set export settings we need
647 $GLOBALS['sql_backquotes'] = 1;
648 $GLOBALS['asfile'] = 1;
650 // Ensure the target is valid
651 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
652 if (! $GLOBALS['pma']->databases->exists($source_db)) {
653 $GLOBALS['message'] = PMA_Message::rawError('source database `'
654 . htmlspecialchars($source_db) . '` not found');
656 if (! $GLOBALS['pma']->databases->exists($target_db)) {
657 $GLOBALS['message'] = PMA_Message::rawError('target database `'
658 . htmlspecialchars($target_db) . '` not found');
660 return false;
663 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
664 if (! isset($target_db) || ! strlen($target_db)) {
665 $target_db = $source_db;
668 // Doing a select_db could avoid some problems with replicated databases,
669 // when moving table from replicated one to not replicated one
670 PMA_DBI_select_db($target_db);
672 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
674 // do not create the table if dataonly
675 if ($what != 'dataonly') {
676 require_once './libraries/export/sql.php';
678 $no_constraints_comments = true;
679 $GLOBALS['sql_constraints_query'] = '';
681 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
682 unset($no_constraints_comments);
683 $parsed_sql = PMA_SQP_parse($sql_structure);
684 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
685 $i = 0;
686 if (empty($analyzed_sql[0]['create_table_fields'])) {
687 // this is not a CREATE TABLE, so find the first VIEW
688 $target_for_view = PMA_backquote($target_db);
689 while (true) {
690 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
691 break;
693 $i++;
696 unset($analyzed_sql);
697 if (PMA_DRIZZLE) {
698 $table_delimiter = 'quote_backtick';
699 } else {
700 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
701 // ANSI_QUOTES might be a subset of sql_mode, for example
702 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
703 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
704 $table_delimiter = 'quote_double';
705 } else {
706 $table_delimiter = 'quote_backtick';
708 unset($server_sql_mode);
711 /* Find table name in query and replace it */
712 while ($parsed_sql[$i]['type'] != $table_delimiter) {
713 $i++;
716 /* no need to PMA_backquote() */
717 if (isset($target_for_view)) {
718 // this a view definition; we just found the first db name
719 // that follows DEFINER VIEW
720 // so change it for the new db name
721 $parsed_sql[$i]['data'] = $target_for_view;
722 // then we have to find all references to the source db
723 // and change them to the target db, ensuring we stay into
724 // the $parsed_sql limits
725 $last = $parsed_sql['len'] - 1;
726 $backquoted_source_db = PMA_backquote($source_db);
727 for (++$i; $i <= $last; $i++) {
728 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
729 $parsed_sql[$i]['data'] = $target_for_view;
732 unset($last,$backquoted_source_db);
733 } else {
734 $parsed_sql[$i]['data'] = $target;
737 /* Generate query back */
738 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
739 // If table exists, and 'add drop table' is selected: Drop it!
740 $drop_query = '';
741 if (isset($GLOBALS['drop_if_exists'])
742 && $GLOBALS['drop_if_exists'] == 'true') {
743 if (PMA_Table::_isView($target_db,$target_table)) {
744 $drop_query = 'DROP VIEW';
745 } else {
746 $drop_query = 'DROP TABLE';
748 $drop_query .= ' IF EXISTS '
749 . PMA_backquote($target_db) . '.'
750 . PMA_backquote($target_table);
751 PMA_DBI_query($drop_query);
753 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
755 // If an existing table gets deleted, maintain any
756 // entries for the PMA_* tables
757 $maintain_relations = true;
760 @PMA_DBI_query($sql_structure);
761 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
763 if (($move || isset($GLOBALS['add_constraints']))
764 && !empty($GLOBALS['sql_constraints_query'])) {
765 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
766 $i = 0;
768 // find the first $table_delimiter, it must be the source table name
769 while ($parsed_sql[$i]['type'] != $table_delimiter) {
770 $i++;
771 // maybe someday we should guard against going over limit
772 //if ($i == $parsed_sql['len']) {
773 // break;
777 // replace it by the target table name, no need to PMA_backquote()
778 $parsed_sql[$i]['data'] = $target;
780 // now we must remove all $table_delimiter that follow a CONSTRAINT
781 // keyword, because a constraint name must be unique in a db
783 $cnt = $parsed_sql['len'] - 1;
785 for ($j = $i; $j < $cnt; $j++) {
786 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
787 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
788 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
789 $parsed_sql[$j+1]['data'] = '';
794 // Generate query back
795 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
796 'query_only');
797 if ($mode == 'one_table') {
798 PMA_DBI_query($GLOBALS['sql_constraints_query']);
800 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
801 if ($mode == 'one_table') {
802 unset($GLOBALS['sql_constraints_query']);
805 } else {
806 $GLOBALS['sql_query'] = '';
809 // Copy the data unless this is a VIEW
810 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
811 $sql_insert_data =
812 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
813 PMA_DBI_query($sql_insert_data);
814 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
817 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
819 // Drops old table if the user has requested to move it
820 if ($move) {
822 // This could avoid some problems with replicated databases, when
823 // moving table from replicated one to not replicated one
824 PMA_DBI_select_db($source_db);
826 if (PMA_Table::_isView($source_db,$source_table)) {
827 $sql_drop_query = 'DROP VIEW';
828 } else {
829 $sql_drop_query = 'DROP TABLE';
831 $sql_drop_query .= ' ' . $source;
832 PMA_DBI_query($sql_drop_query);
834 // Move old entries from PMA-DBs to new table
835 if ($GLOBALS['cfgRelation']['commwork']) {
836 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
837 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\', '
838 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
839 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
840 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
841 PMA_query_as_controluser($remove_query);
842 unset($remove_query);
845 // updating bookmarks is not possible since only a single table is moved,
846 // and not the whole DB.
848 if ($GLOBALS['cfgRelation']['displaywork']) {
849 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
850 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\', '
851 . ' table_name = \'' . PMA_sqlAddSlashes($target_table) . '\''
852 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
853 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
854 PMA_query_as_controluser($table_query);
855 unset($table_query);
858 if ($GLOBALS['cfgRelation']['relwork']) {
859 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
860 . ' SET foreign_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
861 . ' foreign_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
862 . ' WHERE foreign_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
863 . ' AND foreign_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
864 PMA_query_as_controluser($table_query);
865 unset($table_query);
867 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
868 . ' SET master_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
869 . ' master_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
870 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
871 . ' AND master_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
872 PMA_query_as_controluser($table_query);
873 unset($table_query);
877 * @todo Can't get moving PDFs the right way. The page numbers
878 * always get screwed up independently from duplication because the
879 * numbers do not seem to be stored on a per-database basis. Would
880 * the author of pdf support please have a look at it?
883 if ($GLOBALS['cfgRelation']['pdfwork']) {
884 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
885 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
886 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
887 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
888 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
889 PMA_query_as_controluser($table_query);
890 unset($table_query);
892 $pdf_query = 'SELECT pdf_page_number '
893 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
894 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
895 . ' AND table_name = \'' . PMA_sqlAddSlashes($target_table) . '\'';
896 $pdf_rs = PMA_query_as_controluser($pdf_query);
898 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
899 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
900 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
901 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
902 . ' AND page_nr = \'' . PMA_sqlAddSlashes($pdf_copy_row['pdf_page_number']) . '\'';
903 $tb_rs = PMA_query_as_controluser($table_query);
904 unset($table_query);
905 unset($tb_rs);
910 if ($GLOBALS['cfgRelation']['designerwork']) {
911 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
912 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
913 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
914 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
915 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
916 PMA_query_as_controluser($table_query);
917 unset($table_query);
920 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
921 // end if ($move)
922 } else {
923 // we are copying
924 // Create new entries as duplicates from old PMA DBs
925 if ($what != 'dataonly' && ! isset($maintain_relations)) {
926 if ($GLOBALS['cfgRelation']['commwork']) {
927 // Get all comments and MIME-Types for current table
928 $comments_copy_query = 'SELECT
929 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
930 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
931 WHERE
932 db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND
933 table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
934 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
936 // Write every comment as new copied entry. [MIME]
937 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
938 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
939 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
940 . ' VALUES('
941 . '\'' . PMA_sqlAddSlashes($target_db) . '\','
942 . '\'' . PMA_sqlAddSlashes($target_table) . '\','
943 . '\'' . PMA_sqlAddSlashes($comments_copy_row['column_name']) . '\''
944 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddSlashes($comments_copy_row['comment']) . '\','
945 . '\'' . PMA_sqlAddSlashes($comments_copy_row['mimetype']) . '\','
946 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation']) . '\','
947 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
948 . ')';
949 PMA_query_as_controluser($new_comment_query);
950 } // end while
951 PMA_DBI_free_result($comments_copy_rs);
952 unset($comments_copy_rs);
955 // duplicating the bookmarks must not be done here, but
956 // just once per db
958 $get_fields = array('display_field');
959 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
960 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
961 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
965 * @todo revise this code when we support cross-db relations
967 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
968 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
969 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
970 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
973 $get_fields = array('foreign_field', 'master_table', 'master_field');
974 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
975 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
976 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
979 $get_fields = array('x', 'y', 'v', 'h');
980 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
981 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
982 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
985 * @todo Can't get duplicating PDFs the right way. The
986 * page numbers always get screwed up independently from
987 * duplication because the numbers do not seem to be stored on a
988 * per-database basis. Would the author of pdf support please
989 * have a look at it?
991 $get_fields = array('page_descr');
992 $where_fields = array('db_name' => $source_db);
993 $new_fields = array('db_name' => $target_db);
994 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
996 if (isset($last_id) && $last_id >= 0) {
997 $get_fields = array('x', 'y');
998 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
999 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
1000 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
1005 return true;
1009 * checks if given name is a valid table name,
1010 * currently if not empty, trailing spaces, '.', '/' and '\'
1012 * @todo add check for valid chars in filename on current system/os
1013 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
1014 * @param string $table_name name to check
1015 * @return boolean whether the string is valid or not
1017 function isValidName($table_name)
1019 if ($table_name !== trim($table_name)) {
1020 // trailing spaces
1021 return false;
1024 if (! strlen($table_name)) {
1025 // zero length
1026 return false;
1029 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
1030 // illegal char . / \
1031 return false;
1034 return true;
1038 * renames table
1040 * @param string $new_name new table name
1041 * @param string $new_db new database name
1042 * @param bool $is_view is this for a VIEW rename?
1043 * @return bool success
1045 function rename($new_name, $new_db = null, $is_view = false)
1047 if (null !== $new_db && $new_db !== $this->getDbName()) {
1048 // Ensure the target is valid
1049 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1050 $this->errors[] = __('Invalid database') . ': ' . $new_db;
1051 return false;
1053 } else {
1054 $new_db = $this->getDbName();
1057 $new_table = new PMA_Table($new_name, $new_db);
1059 if ($this->getFullName() === $new_table->getFullName()) {
1060 return true;
1063 if (! PMA_Table::isValidName($new_name)) {
1064 $this->errors[] = __('Invalid table name') . ': ' . $new_table->getFullName();
1065 return false;
1068 if (! $is_view) {
1069 $GLOBALS['sql_query'] = '
1070 RENAME TABLE ' . $this->getFullName(true) . '
1071 TO ' . $new_table->getFullName(true) . ';';
1072 } else {
1073 $GLOBALS['sql_query'] = '
1074 ALTER TABLE ' . $this->getFullName(true) . '
1075 RENAME ' . $new_table->getFullName(true) . ';';
1077 // I don't think a specific error message for views is necessary
1078 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1079 $this->errors[] = sprintf(__('Error renaming table %1$s to %2$s'), $this->getFullName(), $new_table->getFullName());
1080 return false;
1083 $old_name = $this->getName();
1084 $old_db = $this->getDbName();
1085 $this->setName($new_name);
1086 $this->setDbName($new_db);
1089 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1091 // Move old entries from comments to new table
1092 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1093 if ($GLOBALS['cfgRelation']['commwork']) {
1094 $remove_query = '
1095 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1096 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1097 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1098 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1099 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1100 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1101 PMA_query_as_controluser($remove_query);
1102 unset($remove_query);
1105 if ($GLOBALS['cfgRelation']['displaywork']) {
1106 $table_query = '
1107 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1108 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1109 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1110 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1111 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1112 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1113 PMA_query_as_controluser($table_query);
1114 unset($table_query);
1117 if ($GLOBALS['cfgRelation']['relwork']) {
1118 $table_query = '
1119 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1120 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1121 SET `foreign_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1122 `foreign_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1123 WHERE `foreign_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1124 AND `foreign_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1125 PMA_query_as_controluser($table_query);
1127 $table_query = '
1128 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1129 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1130 SET `master_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1131 `master_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1132 WHERE `master_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1133 AND `master_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1134 PMA_query_as_controluser($table_query);
1135 unset($table_query);
1138 if ($GLOBALS['cfgRelation']['pdfwork']) {
1139 $table_query = '
1140 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1141 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1142 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1143 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1144 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1145 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1146 PMA_query_as_controluser($table_query);
1147 unset($table_query);
1150 if ($GLOBALS['cfgRelation']['designerwork']) {
1151 $table_query = '
1152 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1153 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1154 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1155 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1156 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1157 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1158 PMA_query_as_controluser($table_query);
1159 unset($table_query);
1162 $this->messages[] = sprintf(__('Table %s has been renamed to %s'),
1163 htmlspecialchars($old_name), htmlspecialchars($new_name));
1164 return true;
1168 * Get all unique columns
1170 * returns an array with all columns with unqiue content, in fact these are
1171 * all columns being single indexed in PRIMARY or UNIQUE
1173 * e.g.
1174 * - PRIMARY(id) // id
1175 * - UNIQUE(name) // name
1176 * - PRIMARY(fk_id1, fk_id2) // NONE
1177 * - UNIQUE(x,y) // NONE
1180 * @param bool $backquoted whether to quote name with backticks ``
1181 * @return array
1183 public function getUniqueColumns($backquoted = true)
1185 $sql = PMA_DBI_get_table_indexes_sql($this->getDbName(), $this->getName(), 'Non_unique = 0');
1186 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1188 $return = array();
1189 foreach ($uniques as $index) {
1190 if (count($index) > 1) {
1191 continue;
1193 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1196 return $return;
1200 * Get all indexed columns
1202 * returns an array with all columns make use of an index, in fact only
1203 * first columns in an index
1205 * e.g. index(col1, col2) would only return col1
1207 * @param bool $backquoted whether to quote name with backticks ``
1208 * @return array
1210 public function getIndexedColumns($backquoted = true)
1212 $sql = PMA_DBI_get_table_indexes_sql($this->getDbName(), $this->getName(), 'Seq_in_index = 1');
1213 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1215 $return = array();
1216 foreach ($indexed as $column) {
1217 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1220 return $return;
1224 * Get all columns
1226 * returns an array with all columns
1228 * @param bool $backquoted whether to quote name with backticks ``
1229 * @return array
1231 public function getColumns($backquoted = true)
1233 $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
1234 $indexed = PMA_DBI_fetch_result($sql, 'Field', 'Field');
1236 $return = array();
1237 foreach ($indexed as $column) {
1238 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1241 return $return;
1245 * Return UI preferences for this table from phpMyAdmin database.
1248 * @return array
1250 protected function getUiPrefsFromDb()
1252 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1253 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1255 // Read from phpMyAdmin database
1256 $sql_query =
1257 " SELECT `prefs` FROM " . $pma_table .
1258 " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'" .
1259 " AND `db_name` = '" . PMA_sqlAddSlashes($this->db_name) . "'" .
1260 " AND `table_name` = '" . PMA_sqlAddSlashes($this->name) . "'";
1262 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
1263 if (isset($row[0])) {
1264 return json_decode($row[0], true);
1265 } else {
1266 return array();
1271 * Save this table's UI preferences into phpMyAdmin database.
1273 * @return true|PMA_Message
1275 protected function saveUiPrefsToDb()
1277 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1278 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1280 $username = $GLOBALS['cfg']['Server']['user'];
1281 $sql_query =
1282 " REPLACE INTO " . $pma_table .
1283 " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name) . "', '" .
1284 PMA_sqlAddSlashes($this->name) . "', '" .
1285 PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
1287 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1289 if (!$success) {
1290 $message = PMA_Message::error(__('Could not save table UI preferences'));
1291 $message->addMessage('<br /><br />');
1292 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1293 return $message;
1296 // Remove some old rows in table_uiprefs if it exceeds the configured maximum rows
1297 $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
1298 $rows_count = PMA_DBI_fetch_value($sql_query);
1299 $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
1300 if ($rows_count > $max_rows) {
1301 $num_rows_to_delete = $rows_count - $max_rows;
1302 $sql_query =
1303 ' DELETE FROM ' . $pma_table .
1304 ' ORDER BY last_update ASC' .
1305 ' LIMIT ' . $num_rows_to_delete;
1306 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1308 if (!$success) {
1309 $message = PMA_Message::error(sprintf(
1310 __('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
1311 PMA_showDocu('cfg_Servers_MaxTableUiprefs')
1313 $message->addMessage('<br /><br />');
1314 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1315 print_r($message);
1316 return $message;
1320 return true;
1324 * Loads the UI preferences for this table.
1325 * If pmadb and table_uiprefs is set, it will load the UI preferences from
1326 * phpMyAdmin database.
1329 protected function loadUiPrefs()
1331 $server_id = $GLOBALS['server'];
1332 // set session variable if it's still undefined
1333 if (! isset($_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name])) {
1334 $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name] =
1335 // check whether we can get from pmadb
1336 (strlen($GLOBALS['cfg']['Server']['pmadb'])
1337 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) ?
1338 $this->getUiPrefsFromDb() : array();
1340 $this->uiprefs =& $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name];
1344 * Get a property from UI preferences.
1345 * Return false if the property is not found.
1346 * Available property:
1347 * - PROP_SORTED_COLUMN
1348 * - PROP_COLUMN_ORDER
1349 * - PROP_COLUMN_VISIB
1352 * @param string $property
1353 * @return mixed
1355 public function getUiProp($property)
1357 if (! isset($this->uiprefs)) {
1358 $this->loadUiPrefs();
1360 // do checking based on property
1361 if ($property == self::PROP_SORTED_COLUMN) {
1362 if (isset($this->uiprefs[$property])) {
1363 // check if the column name is exist in this table
1364 $tmp = explode(' ', $this->uiprefs[$property]);
1365 $colname = $tmp[0];
1366 $avail_columns = $this->getColumns();
1367 foreach ($avail_columns as $each_col) {
1368 // check if $each_col ends with $colname
1369 if (substr_compare($each_col, $colname,
1370 strlen($each_col) - strlen($colname)) === 0) {
1371 return $this->uiprefs[$property];
1374 // remove the property, since it is not exist anymore in database
1375 $this->removeUiProp(self::PROP_SORTED_COLUMN);
1376 return false;
1377 } else {
1378 return false;
1380 } else if ($property == self::PROP_COLUMN_ORDER ||
1381 $property == self::PROP_COLUMN_VISIB) {
1382 if (! PMA_Table::isView($this->db_name, $this->name) && isset($this->uiprefs[$property])) {
1383 // check if the table has not been modified
1384 if (self::sGetStatusInfo($this->db_name, $this->name, 'Create_time') ==
1385 $this->uiprefs['CREATE_TIME']) {
1386 return $this->uiprefs[$property];
1387 } else {
1388 // remove the property, since the table has been modified
1389 $this->removeUiProp(self::PROP_COLUMN_ORDER);
1390 return false;
1392 } else {
1393 return false;
1396 // default behaviour for other property:
1397 return isset($this->uiprefs[$property]) ? $this->uiprefs[$property] : false;
1401 * Set a property from UI preferences.
1402 * If pmadb and table_uiprefs is set, it will save the UI preferences to
1403 * phpMyAdmin database.
1404 * Available property:
1405 * - PROP_SORTED_COLUMN
1406 * - PROP_COLUMN_ORDER
1407 * - PROP_COLUMN_VISIB
1409 * @param string $property
1410 * @param mixed $value
1411 * @param string $table_create_time Needed for PROP_COLUMN_ORDER and PROP_COLUMN_VISIB
1412 * @return boolean|PMA_Message
1414 public function setUiProp($property, $value, $table_create_time = null)
1416 if (! isset($this->uiprefs)) {
1417 $this->loadUiPrefs();
1419 // we want to save the create time if the property is PROP_COLUMN_ORDER
1420 if (! PMA_Table::isView($this->db_name, $this->name) && ($property == self::PROP_COLUMN_ORDER ||
1421 $property == self::PROP_COLUMN_VISIB)) {
1423 $curr_create_time = self::sGetStatusInfo($this->db_name, $this->name, 'CREATE_TIME');
1424 if (isset($table_create_time) &&
1425 $table_create_time == $curr_create_time) {
1426 $this->uiprefs['CREATE_TIME'] = $curr_create_time;
1427 } else {
1428 // there is no $table_create_time, or
1429 // supplied $table_create_time is older than current create time,
1430 // so don't save
1431 return false;
1434 // save the value
1435 $this->uiprefs[$property] = $value;
1436 // check if pmadb is set
1437 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1438 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) {
1439 return $this->saveUiprefsToDb();
1441 return true;
1445 * Remove a property from UI preferences.
1447 * @param string $property
1448 * @return true|PMA_Message
1450 public function removeUiProp($property)
1452 if (! isset($this->uiprefs)) {
1453 $this->loadUiPrefs();
1455 if (isset($this->uiprefs[$property])) {
1456 unset($this->uiprefs[$property]);
1457 // check if pmadb is set
1458 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1459 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) {
1460 return $this->saveUiprefsToDb();
1463 return true;