Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / libraries / Table.class.php
bloba1265cb34af826b4c9766920c60e7053db421c26
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\''
373 . preg_replace('/[^01]/', '0', $default_value)
374 . '\'';
375 } elseif ($type == 'BOOLEAN') {
376 if (preg_match('/^1|T|TRUE|YES$/i', $default_value)) {
377 $query .= ' DEFAULT TRUE';
378 } elseif (preg_match('/^0|F|FALSE|NO$/i', $default_value)) {
379 $query .= ' DEFAULT FALSE';
380 } else {
381 // Invalid BOOLEAN value
382 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
384 } else {
385 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
387 break;
388 case 'NULL' :
389 case 'CURRENT_TIMESTAMP' :
390 $query .= ' DEFAULT ' . $default_type;
391 break;
392 case 'NONE' :
393 default :
394 break;
397 if (!empty($extra)) {
398 $query .= ' ' . $extra;
399 // Force an auto_increment field to be part of the primary key
400 // even if user did not tick the PK box;
401 if ($extra == 'AUTO_INCREMENT') {
402 $primary_cnt = count($field_primary);
403 if (1 == $primary_cnt) {
404 for ($j = 0; $j < $primary_cnt; $j++) {
405 if ($field_primary[$j] == $index) {
406 break;
409 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
410 $query .= ' PRIMARY KEY';
411 unset($field_primary[$j]);
413 // but the PK could contain other columns so do not append
414 // a PRIMARY KEY clause, just add a member to $field_primary
415 } else {
416 $found_in_pk = false;
417 for ($j = 0; $j < $primary_cnt; $j++) {
418 if ($field_primary[$j] == $index) {
419 $found_in_pk = true;
420 break;
422 } // end for
423 if (! $found_in_pk) {
424 $field_primary[] = $index;
427 } // end if (auto_increment)
429 if (!empty($comment)) {
430 $query .= " COMMENT '" . PMA_sqlAddSlashes($comment) . "'";
432 return $query;
433 } // end function
436 * Counts and returns (or displays) the number of records in a table
438 * Revision 13 July 2001: Patch for limiting dump size from
439 * vinay@sanisoft.com & girish@sanisoft.com
441 * @param string $db the current database name
442 * @param string $table the current table name
443 * @param bool $force_exact whether to force an exact count
444 * @param bool $is_view
446 * @return mixed the number of records if "retain" param is true,
447 * otherwise true
449 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
451 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
452 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
453 } else {
454 $row_count = false;
456 if (null === $is_view) {
457 $is_view = PMA_Table::isView($db, $table);
460 if (! $force_exact) {
461 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
462 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
463 if (isset($tmp_tables[$table])) {
464 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
467 if (isset(PMA_Table::$cache[$db][$table]['Rows'])) {
468 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
469 } else {
470 $row_count = false;
474 // for a VIEW, $row_count is always false at this point
475 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
476 // Make an exception for views in I_S and D_D schema in Drizzle, as these map to
477 // in-memory data and should execute fast enough
478 if (! $is_view || (PMA_DRIZZLE && (strtolower($db) == 'information_schema' || strtolower($db) == 'data_dictionary'))) {
479 $row_count = PMA_DBI_fetch_value(
480 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
481 . PMA_backquote($table));
482 } else {
483 // For complex views, even trying to get a partial record
484 // count could bring down a server, so we offer an
485 // alternative: setting MaxExactCountViews to 0 will bypass
486 // completely the record counting for views
488 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
489 $row_count = 0;
490 } else {
491 // Counting all rows of a VIEW could be too long, so use
492 // a LIMIT clause.
493 // Use try_query because it can fail (when a VIEW is
494 // based on a table that no longer exists)
495 $result = PMA_DBI_try_query(
496 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
497 . PMA_backquote($table) . ' LIMIT '
498 . $GLOBALS['cfg']['MaxExactCountViews'],
499 null, PMA_DBI_QUERY_STORE);
500 if (!PMA_DBI_getError()) {
501 $row_count = PMA_DBI_num_rows($result);
502 PMA_DBI_free_result($result);
506 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
510 return $row_count;
511 } // end of the 'PMA_Table::countRecords()' function
514 * Generates column specification for ALTER syntax
516 * @see PMA_Table::generateFieldSpec()
517 * @param string $oldcol old column name
518 * @param string $newcol new column name
519 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
520 * @param string $length length ('2', '5,2', '', ...)
521 * @param string $attribute
522 * @param string $collation
523 * @param bool|string $null with 'NULL' or 'NOT NULL'
524 * @param string $default_type whether default is CURRENT_TIMESTAMP,
525 * NULL, NONE, USER_DEFINED
526 * @param string $default_value default value for USER_DEFINED default type
527 * @param string $extra 'AUTO_INCREMENT'
528 * @param string $comment field comment
529 * @param array &$field_primary list of fields for PRIMARY KEY
530 * @param string $index
531 * @param mixed $default_orig
532 * @return string field specification
534 static public function generateAlter($oldcol, $newcol, $type, $length,
535 $attribute, $collation, $null, $default_type, $default_value,
536 $extra, $comment = '', &$field_primary, $index, $default_orig)
538 return PMA_backquote($oldcol) . ' '
539 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
540 $collation, $null, $default_type, $default_value, $extra,
541 $comment, $field_primary, $index, $default_orig);
542 } // end function
545 * Inserts existing entries in a PMA_* table by reading a value from an old entry
547 * @global relation variable
548 * @param string $work The array index, which Relation feature to check ('relwork', 'commwork', ...)
549 * @param string $pma_table The array index, which PMA-table to update ('bookmark', 'relation', ...)
550 * @param array $get_fields Which fields will be SELECT'ed from the old entry
551 * @param array $where_fields Which fields will be used for the WHERE query (array('FIELDNAME' => 'FIELDVALUE'))
552 * @param array $new_fields Which fields will be used as new VALUES. These are the important
553 * keys which differ from the old entry.
554 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
555 * @return int|true
557 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
558 $new_fields)
560 $last_id = -1;
562 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
563 $select_parts = array();
564 $row_fields = array();
565 foreach ($get_fields as $get_field) {
566 $select_parts[] = PMA_backquote($get_field);
567 $row_fields[$get_field] = 'cc';
570 $where_parts = array();
571 foreach ($where_fields as $_where => $_value) {
572 $where_parts[] = PMA_backquote($_where) . ' = \''
573 . PMA_sqlAddSlashes($_value) . '\'';
576 $new_parts = array();
577 $new_value_parts = array();
578 foreach ($new_fields as $_where => $_value) {
579 $new_parts[] = PMA_backquote($_where);
580 $new_value_parts[] = PMA_sqlAddSlashes($_value);
583 $table_copy_query = '
584 SELECT ' . implode(', ', $select_parts) . '
585 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
586 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
587 WHERE ' . implode(' AND ', $where_parts);
589 // must use PMA_DBI_QUERY_STORE here, since we execute another
590 // query inside the loop
591 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
592 PMA_DBI_QUERY_STORE);
594 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
595 $value_parts = array();
596 foreach ($table_copy_row as $_key => $_val) {
597 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
598 $value_parts[] = PMA_sqlAddSlashes($_val);
602 $new_table_query = '
603 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
604 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
605 (' . implode(', ', $select_parts) . ',
606 ' . implode(', ', $new_parts) . ')
607 VALUES
608 (\'' . implode('\', \'', $value_parts) . '\',
609 \'' . implode('\', \'', $new_value_parts) . '\')';
611 PMA_query_as_controluser($new_table_query);
612 $last_id = PMA_DBI_insert_id();
613 } // end while
615 PMA_DBI_free_result($table_copy_rs);
617 return $last_id;
620 return true;
621 } // end of 'PMA_Table::duplicateInfo()' function
625 * Copies or renames table
627 * @param $source_db
628 * @param $source_table
629 * @param $target_db
630 * @param $target_table
631 * @param $what
632 * @param $move
633 * @param $mode
634 * @return bool
636 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
638 global $err_url;
640 /* Try moving table directly */
641 if ($move && $what == 'data') {
642 $tbl = new PMA_Table($source_table, $source_db);
643 $result = $tbl->rename($target_table, $target_db, PMA_Table::isView($source_db, $source_table));
644 if ($result) {
645 $GLOBALS['message'] = $tbl->getLastMessage();
646 return true;
650 // set export settings we need
651 $GLOBALS['sql_backquotes'] = 1;
652 $GLOBALS['asfile'] = 1;
654 // Ensure the target is valid
655 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
656 if (! $GLOBALS['pma']->databases->exists($source_db)) {
657 $GLOBALS['message'] = PMA_Message::rawError('source database `'
658 . htmlspecialchars($source_db) . '` not found');
660 if (! $GLOBALS['pma']->databases->exists($target_db)) {
661 $GLOBALS['message'] = PMA_Message::rawError('target database `'
662 . htmlspecialchars($target_db) . '` not found');
664 return false;
667 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
668 if (! isset($target_db) || ! strlen($target_db)) {
669 $target_db = $source_db;
672 // Doing a select_db could avoid some problems with replicated databases,
673 // when moving table from replicated one to not replicated one
674 PMA_DBI_select_db($target_db);
676 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
678 // do not create the table if dataonly
679 if ($what != 'dataonly') {
680 require_once './libraries/export/sql.php';
682 $no_constraints_comments = true;
683 $GLOBALS['sql_constraints_query'] = '';
685 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
686 unset($no_constraints_comments);
687 $parsed_sql = PMA_SQP_parse($sql_structure);
688 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
689 $i = 0;
690 if (empty($analyzed_sql[0]['create_table_fields'])) {
691 // this is not a CREATE TABLE, so find the first VIEW
692 $target_for_view = PMA_backquote($target_db);
693 while (true) {
694 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
695 break;
697 $i++;
700 unset($analyzed_sql);
701 if (PMA_DRIZZLE) {
702 $table_delimiter = 'quote_backtick';
703 } else {
704 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
705 // ANSI_QUOTES might be a subset of sql_mode, for example
706 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
707 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
708 $table_delimiter = 'quote_double';
709 } else {
710 $table_delimiter = 'quote_backtick';
712 unset($server_sql_mode);
715 /* Find table name in query and replace it */
716 while ($parsed_sql[$i]['type'] != $table_delimiter) {
717 $i++;
720 /* no need to PMA_backquote() */
721 if (isset($target_for_view)) {
722 // this a view definition; we just found the first db name
723 // that follows DEFINER VIEW
724 // so change it for the new db name
725 $parsed_sql[$i]['data'] = $target_for_view;
726 // then we have to find all references to the source db
727 // and change them to the target db, ensuring we stay into
728 // the $parsed_sql limits
729 $last = $parsed_sql['len'] - 1;
730 $backquoted_source_db = PMA_backquote($source_db);
731 for (++$i; $i <= $last; $i++) {
732 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
733 $parsed_sql[$i]['data'] = $target_for_view;
736 unset($last,$backquoted_source_db);
737 } else {
738 $parsed_sql[$i]['data'] = $target;
741 /* Generate query back */
742 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
743 // If table exists, and 'add drop table' is selected: Drop it!
744 $drop_query = '';
745 if (isset($GLOBALS['drop_if_exists'])
746 && $GLOBALS['drop_if_exists'] == 'true') {
747 if (PMA_Table::_isView($target_db,$target_table)) {
748 $drop_query = 'DROP VIEW';
749 } else {
750 $drop_query = 'DROP TABLE';
752 $drop_query .= ' IF EXISTS '
753 . PMA_backquote($target_db) . '.'
754 . PMA_backquote($target_table);
755 PMA_DBI_query($drop_query);
757 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
759 // If an existing table gets deleted, maintain any
760 // entries for the PMA_* tables
761 $maintain_relations = true;
764 @PMA_DBI_query($sql_structure);
765 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
767 if (($move || isset($GLOBALS['add_constraints']))
768 && !empty($GLOBALS['sql_constraints_query'])) {
769 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
770 $i = 0;
772 // find the first $table_delimiter, it must be the source table name
773 while ($parsed_sql[$i]['type'] != $table_delimiter) {
774 $i++;
775 // maybe someday we should guard against going over limit
776 //if ($i == $parsed_sql['len']) {
777 // break;
781 // replace it by the target table name, no need to PMA_backquote()
782 $parsed_sql[$i]['data'] = $target;
784 // now we must remove all $table_delimiter that follow a CONSTRAINT
785 // keyword, because a constraint name must be unique in a db
787 $cnt = $parsed_sql['len'] - 1;
789 for ($j = $i; $j < $cnt; $j++) {
790 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
791 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
792 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
793 $parsed_sql[$j+1]['data'] = '';
798 // Generate query back
799 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
800 'query_only');
801 if ($mode == 'one_table') {
802 PMA_DBI_query($GLOBALS['sql_constraints_query']);
804 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
805 if ($mode == 'one_table') {
806 unset($GLOBALS['sql_constraints_query']);
809 } else {
810 $GLOBALS['sql_query'] = '';
813 // Copy the data unless this is a VIEW
814 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
815 $sql_insert_data =
816 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
817 PMA_DBI_query($sql_insert_data);
818 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
821 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
823 // Drops old table if the user has requested to move it
824 if ($move) {
826 // This could avoid some problems with replicated databases, when
827 // moving table from replicated one to not replicated one
828 PMA_DBI_select_db($source_db);
830 if (PMA_Table::_isView($source_db,$source_table)) {
831 $sql_drop_query = 'DROP VIEW';
832 } else {
833 $sql_drop_query = 'DROP TABLE';
835 $sql_drop_query .= ' ' . $source;
836 PMA_DBI_query($sql_drop_query);
838 // Move old entries from PMA-DBs to new table
839 if ($GLOBALS['cfgRelation']['commwork']) {
840 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
841 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\', '
842 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
843 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
844 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
845 PMA_query_as_controluser($remove_query);
846 unset($remove_query);
849 // updating bookmarks is not possible since only a single table is moved,
850 // and not the whole DB.
852 if ($GLOBALS['cfgRelation']['displaywork']) {
853 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
854 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\', '
855 . ' table_name = \'' . PMA_sqlAddSlashes($target_table) . '\''
856 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
857 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
858 PMA_query_as_controluser($table_query);
859 unset($table_query);
862 if ($GLOBALS['cfgRelation']['relwork']) {
863 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
864 . ' SET foreign_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
865 . ' foreign_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
866 . ' WHERE foreign_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
867 . ' AND foreign_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
868 PMA_query_as_controluser($table_query);
869 unset($table_query);
871 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
872 . ' SET master_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
873 . ' master_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
874 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
875 . ' AND master_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
876 PMA_query_as_controluser($table_query);
877 unset($table_query);
881 * @todo Can't get moving PDFs the right way. The page numbers
882 * always get screwed up independently from duplication because the
883 * numbers do not seem to be stored on a per-database basis. Would
884 * the author of pdf support please have a look at it?
887 if ($GLOBALS['cfgRelation']['pdfwork']) {
888 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
889 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
890 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
891 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
892 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
893 PMA_query_as_controluser($table_query);
894 unset($table_query);
896 $pdf_query = 'SELECT pdf_page_number '
897 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
898 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
899 . ' AND table_name = \'' . PMA_sqlAddSlashes($target_table) . '\'';
900 $pdf_rs = PMA_query_as_controluser($pdf_query);
902 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
903 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
904 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
905 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
906 . ' AND page_nr = \'' . PMA_sqlAddSlashes($pdf_copy_row['pdf_page_number']) . '\'';
907 $tb_rs = PMA_query_as_controluser($table_query);
908 unset($table_query);
909 unset($tb_rs);
914 if ($GLOBALS['cfgRelation']['designerwork']) {
915 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
916 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
917 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
918 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
919 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
920 PMA_query_as_controluser($table_query);
921 unset($table_query);
924 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
925 // end if ($move)
926 } else {
927 // we are copying
928 // Create new entries as duplicates from old PMA DBs
929 if ($what != 'dataonly' && ! isset($maintain_relations)) {
930 if ($GLOBALS['cfgRelation']['commwork']) {
931 // Get all comments and MIME-Types for current table
932 $comments_copy_query = 'SELECT
933 column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
934 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
935 WHERE
936 db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND
937 table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
938 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
940 // Write every comment as new copied entry. [MIME]
941 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
942 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
943 . ' (db_name, table_name, column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
944 . ' VALUES('
945 . '\'' . PMA_sqlAddSlashes($target_db) . '\','
946 . '\'' . PMA_sqlAddSlashes($target_table) . '\','
947 . '\'' . PMA_sqlAddSlashes($comments_copy_row['column_name']) . '\''
948 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddSlashes($comments_copy_row['comment']) . '\','
949 . '\'' . PMA_sqlAddSlashes($comments_copy_row['mimetype']) . '\','
950 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation']) . '\','
951 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
952 . ')';
953 PMA_query_as_controluser($new_comment_query);
954 } // end while
955 PMA_DBI_free_result($comments_copy_rs);
956 unset($comments_copy_rs);
959 // duplicating the bookmarks must not be done here, but
960 // just once per db
962 $get_fields = array('display_field');
963 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
964 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
965 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
969 * @todo revise this code when we support cross-db relations
971 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
972 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
973 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
974 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
977 $get_fields = array('foreign_field', 'master_table', 'master_field');
978 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
979 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
980 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
983 $get_fields = array('x', 'y', 'v', 'h');
984 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
985 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
986 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
989 * @todo Can't get duplicating PDFs the right way. The
990 * page numbers always get screwed up independently from
991 * duplication because the numbers do not seem to be stored on a
992 * per-database basis. Would the author of pdf support please
993 * have a look at it?
995 $get_fields = array('page_descr');
996 $where_fields = array('db_name' => $source_db);
997 $new_fields = array('db_name' => $target_db);
998 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
1000 if (isset($last_id) && $last_id >= 0) {
1001 $get_fields = array('x', 'y');
1002 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
1003 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
1004 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
1009 return true;
1013 * checks if given name is a valid table name,
1014 * currently if not empty, trailing spaces, '.', '/' and '\'
1016 * @todo add check for valid chars in filename on current system/os
1017 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
1018 * @param string $table_name name to check
1019 * @return boolean whether the string is valid or not
1021 function isValidName($table_name)
1023 if ($table_name !== trim($table_name)) {
1024 // trailing spaces
1025 return false;
1028 if (! strlen($table_name)) {
1029 // zero length
1030 return false;
1033 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
1034 // illegal char . / \
1035 return false;
1038 return true;
1042 * renames table
1044 * @param string $new_name new table name
1045 * @param string $new_db new database name
1046 * @param bool $is_view is this for a VIEW rename?
1047 * @return bool success
1049 function rename($new_name, $new_db = null, $is_view = false)
1051 if (null !== $new_db && $new_db !== $this->getDbName()) {
1052 // Ensure the target is valid
1053 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1054 $this->errors[] = __('Invalid database') . ': ' . $new_db;
1055 return false;
1057 } else {
1058 $new_db = $this->getDbName();
1061 $new_table = new PMA_Table($new_name, $new_db);
1063 if ($this->getFullName() === $new_table->getFullName()) {
1064 return true;
1067 if (! PMA_Table::isValidName($new_name)) {
1068 $this->errors[] = __('Invalid table name') . ': ' . $new_table->getFullName();
1069 return false;
1072 if (! $is_view) {
1073 $GLOBALS['sql_query'] = '
1074 RENAME TABLE ' . $this->getFullName(true) . '
1075 TO ' . $new_table->getFullName(true) . ';';
1076 } else {
1077 $GLOBALS['sql_query'] = '
1078 ALTER TABLE ' . $this->getFullName(true) . '
1079 RENAME ' . $new_table->getFullName(true) . ';';
1081 // I don't think a specific error message for views is necessary
1082 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1083 $this->errors[] = sprintf(__('Error renaming table %1$s to %2$s'), $this->getFullName(), $new_table->getFullName());
1084 return false;
1087 $old_name = $this->getName();
1088 $old_db = $this->getDbName();
1089 $this->setName($new_name);
1090 $this->setDbName($new_db);
1093 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1095 // Move old entries from comments to new table
1096 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1097 if ($GLOBALS['cfgRelation']['commwork']) {
1098 $remove_query = '
1099 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1100 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1101 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1102 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1103 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1104 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1105 PMA_query_as_controluser($remove_query);
1106 unset($remove_query);
1109 if ($GLOBALS['cfgRelation']['displaywork']) {
1110 $table_query = '
1111 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1112 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1113 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1114 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1115 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1116 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1117 PMA_query_as_controluser($table_query);
1118 unset($table_query);
1121 if ($GLOBALS['cfgRelation']['relwork']) {
1122 $table_query = '
1123 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1124 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1125 SET `foreign_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1126 `foreign_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1127 WHERE `foreign_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1128 AND `foreign_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1129 PMA_query_as_controluser($table_query);
1131 $table_query = '
1132 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1133 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1134 SET `master_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1135 `master_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1136 WHERE `master_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1137 AND `master_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1138 PMA_query_as_controluser($table_query);
1139 unset($table_query);
1142 if ($GLOBALS['cfgRelation']['pdfwork']) {
1143 $table_query = '
1144 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1145 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1146 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1147 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1148 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1149 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1150 PMA_query_as_controluser($table_query);
1151 unset($table_query);
1154 if ($GLOBALS['cfgRelation']['designerwork']) {
1155 $table_query = '
1156 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1157 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1158 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1159 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1160 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1161 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1162 PMA_query_as_controluser($table_query);
1163 unset($table_query);
1166 $this->messages[] = sprintf(__('Table %s has been renamed to %s'),
1167 htmlspecialchars($old_name), htmlspecialchars($new_name));
1168 return true;
1172 * Get all unique columns
1174 * returns an array with all columns with unqiue content, in fact these are
1175 * all columns being single indexed in PRIMARY or UNIQUE
1177 * e.g.
1178 * - PRIMARY(id) // id
1179 * - UNIQUE(name) // name
1180 * - PRIMARY(fk_id1, fk_id2) // NONE
1181 * - UNIQUE(x,y) // NONE
1184 * @param bool $backquoted whether to quote name with backticks ``
1185 * @return array
1187 public function getUniqueColumns($backquoted = true)
1189 $sql = PMA_DBI_get_table_indexes_sql($this->getDbName(), $this->getName(), 'Non_unique = 0');
1190 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1192 $return = array();
1193 foreach ($uniques as $index) {
1194 if (count($index) > 1) {
1195 continue;
1197 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1200 return $return;
1204 * Get all indexed columns
1206 * returns an array with all columns make use of an index, in fact only
1207 * first columns in an index
1209 * e.g. index(col1, col2) would only return col1
1211 * @param bool $backquoted whether to quote name with backticks ``
1212 * @return array
1214 public function getIndexedColumns($backquoted = true)
1216 $sql = PMA_DBI_get_table_indexes_sql($this->getDbName(), $this->getName(), 'Seq_in_index = 1');
1217 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1219 $return = array();
1220 foreach ($indexed as $column) {
1221 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1224 return $return;
1228 * Get all columns
1230 * returns an array with all columns
1232 * @param bool $backquoted whether to quote name with backticks ``
1233 * @return array
1235 public function getColumns($backquoted = true)
1237 $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
1238 $indexed = PMA_DBI_fetch_result($sql, 'Field', 'Field');
1240 $return = array();
1241 foreach ($indexed as $column) {
1242 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1245 return $return;
1249 * Return UI preferences for this table from phpMyAdmin database.
1252 * @return array
1254 protected function getUiPrefsFromDb()
1256 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1257 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1259 // Read from phpMyAdmin database
1260 $sql_query =
1261 " SELECT `prefs` FROM " . $pma_table .
1262 " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'" .
1263 " AND `db_name` = '" . PMA_sqlAddSlashes($this->db_name) . "'" .
1264 " AND `table_name` = '" . PMA_sqlAddSlashes($this->name) . "'";
1266 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
1267 if (isset($row[0])) {
1268 return json_decode($row[0], true);
1269 } else {
1270 return array();
1275 * Save this table's UI preferences into phpMyAdmin database.
1277 * @return true|PMA_Message
1279 protected function saveUiPrefsToDb()
1281 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1282 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1284 $username = $GLOBALS['cfg']['Server']['user'];
1285 $sql_query =
1286 " REPLACE INTO " . $pma_table .
1287 " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name) . "', '" .
1288 PMA_sqlAddSlashes($this->name) . "', '" .
1289 PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
1291 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1293 if (!$success) {
1294 $message = PMA_Message::error(__('Could not save table UI preferences'));
1295 $message->addMessage('<br /><br />');
1296 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1297 return $message;
1300 // Remove some old rows in table_uiprefs if it exceeds the configured maximum rows
1301 $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
1302 $rows_count = PMA_DBI_fetch_value($sql_query);
1303 $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
1304 if ($rows_count > $max_rows) {
1305 $num_rows_to_delete = $rows_count - $max_rows;
1306 $sql_query =
1307 ' DELETE FROM ' . $pma_table .
1308 ' ORDER BY last_update ASC' .
1309 ' LIMIT ' . $num_rows_to_delete;
1310 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1312 if (!$success) {
1313 $message = PMA_Message::error(sprintf(
1314 __('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
1315 PMA_showDocu('cfg_Servers_MaxTableUiprefs')
1317 $message->addMessage('<br /><br />');
1318 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1319 print_r($message);
1320 return $message;
1324 return true;
1328 * Loads the UI preferences for this table.
1329 * If pmadb and table_uiprefs is set, it will load the UI preferences from
1330 * phpMyAdmin database.
1333 protected function loadUiPrefs()
1335 $server_id = $GLOBALS['server'];
1336 // set session variable if it's still undefined
1337 if (! isset($_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name])) {
1338 $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name] =
1339 // check whether we can get from pmadb
1340 (strlen($GLOBALS['cfg']['Server']['pmadb'])
1341 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) ?
1342 $this->getUiPrefsFromDb() : array();
1344 $this->uiprefs =& $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name];
1348 * Get a property from UI preferences.
1349 * Return false if the property is not found.
1350 * Available property:
1351 * - PROP_SORTED_COLUMN
1352 * - PROP_COLUMN_ORDER
1353 * - PROP_COLUMN_VISIB
1356 * @param string $property
1357 * @return mixed
1359 public function getUiProp($property)
1361 if (! isset($this->uiprefs)) {
1362 $this->loadUiPrefs();
1364 // do checking based on property
1365 if ($property == self::PROP_SORTED_COLUMN) {
1366 if (isset($this->uiprefs[$property])) {
1367 // check if the column name is exist in this table
1368 $tmp = explode(' ', $this->uiprefs[$property]);
1369 $colname = $tmp[0];
1370 $avail_columns = $this->getColumns();
1371 foreach ($avail_columns as $each_col) {
1372 // check if $each_col ends with $colname
1373 if (substr_compare($each_col, $colname,
1374 strlen($each_col) - strlen($colname)) === 0) {
1375 return $this->uiprefs[$property];
1378 // remove the property, since it is not exist anymore in database
1379 $this->removeUiProp(self::PROP_SORTED_COLUMN);
1380 return false;
1381 } else {
1382 return false;
1384 } else if ($property == self::PROP_COLUMN_ORDER ||
1385 $property == self::PROP_COLUMN_VISIB) {
1386 if (! PMA_Table::isView($this->db_name, $this->name) && isset($this->uiprefs[$property])) {
1387 // check if the table has not been modified
1388 if (self::sGetStatusInfo($this->db_name, $this->name, 'Create_time') ==
1389 $this->uiprefs['CREATE_TIME']) {
1390 return $this->uiprefs[$property];
1391 } else {
1392 // remove the property, since the table has been modified
1393 $this->removeUiProp(self::PROP_COLUMN_ORDER);
1394 return false;
1396 } else {
1397 return false;
1400 // default behaviour for other property:
1401 return isset($this->uiprefs[$property]) ? $this->uiprefs[$property] : false;
1405 * Set a property from UI preferences.
1406 * If pmadb and table_uiprefs is set, it will save the UI preferences to
1407 * phpMyAdmin database.
1408 * Available property:
1409 * - PROP_SORTED_COLUMN
1410 * - PROP_COLUMN_ORDER
1411 * - PROP_COLUMN_VISIB
1413 * @param string $property
1414 * @param mixed $value
1415 * @param string $table_create_time Needed for PROP_COLUMN_ORDER and PROP_COLUMN_VISIB
1416 * @return boolean|PMA_Message
1418 public function setUiProp($property, $value, $table_create_time = null)
1420 if (! isset($this->uiprefs)) {
1421 $this->loadUiPrefs();
1423 // we want to save the create time if the property is PROP_COLUMN_ORDER
1424 if (! PMA_Table::isView($this->db_name, $this->name) && ($property == self::PROP_COLUMN_ORDER ||
1425 $property == self::PROP_COLUMN_VISIB)) {
1427 $curr_create_time = self::sGetStatusInfo($this->db_name, $this->name, 'CREATE_TIME');
1428 if (isset($table_create_time) &&
1429 $table_create_time == $curr_create_time) {
1430 $this->uiprefs['CREATE_TIME'] = $curr_create_time;
1431 } else {
1432 // there is no $table_create_time, or
1433 // supplied $table_create_time is older than current create time,
1434 // so don't save
1435 return false;
1438 // save the value
1439 $this->uiprefs[$property] = $value;
1440 // check if pmadb is set
1441 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1442 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) {
1443 return $this->saveUiprefsToDb();
1445 return true;
1449 * Remove a property from UI preferences.
1451 * @param string $property
1452 * @return true|PMA_Message
1454 public function removeUiProp($property)
1456 if (! isset($this->uiprefs)) {
1457 $this->loadUiPrefs();
1459 if (isset($this->uiprefs[$property])) {
1460 unset($this->uiprefs[$property]);
1461 // check if pmadb is set
1462 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1463 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) {
1464 return $this->saveUiprefsToDb();
1467 return true;