Coding style improvements
[phpmyadmin/crack.git] / libraries / Table.class.php
blob46ebb91171549b8ace940d8187708510038242de
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 /**
87 * return the last error
89 * @return the last error
91 function getLastError()
93 return end($this->errors);
96 /**
97 * return the last message
99 * @return the last message
101 function getLastMessage()
103 return end($this->messages);
107 * sets table name
109 * @param string $table_name new table name
111 * @return nothing
113 function setName($table_name)
115 $this->name = $table_name;
119 * returns table name
121 * @param boolean $backquoted whether to quote name with backticks ``
123 * @return string table name
125 function getName($backquoted = false)
127 if ($backquoted) {
128 return PMA_backquote($this->name);
130 return $this->name;
134 * sets database name for this table
136 * @param string $db_name database name
138 * @return nothing
140 function setDbName($db_name)
142 $this->db_name = $db_name;
146 * returns database name for this table
148 * @param boolean $backquoted whether to quote name with backticks ``
150 * @return string database name for this table
152 function getDbName($backquoted = false)
154 if ($backquoted) {
155 return PMA_backquote($this->db_name);
157 return $this->db_name;
161 * returns full name for table, including database name
163 * @param boolean $backquoted whether to quote name with backticks ``
165 * @return string
167 function getFullName($backquoted = false)
169 return $this->getDbName($backquoted) . '.' . $this->getName($backquoted);
173 * returns whether the table is actually a view
175 * @param string $db database
176 * @param string $table table
178 * @return whether the given is a view
180 static public function isView($db = null, $table = null)
182 if (strlen($db) && strlen($table)) {
183 return PMA_Table::_isView($db, $table);
186 return false;
190 * sets given $value for given $param
192 * @param string $param name
193 * @param mixed $value value
195 * @return nothing
197 function set($param, $value)
199 $this->settings[$param] = $value;
203 * returns value for given setting/param
205 * @param string $param name for value to return
207 * @return mixed value for $param
209 function get($param)
211 if (isset($this->settings[$param])) {
212 return $this->settings[$param];
215 return null;
219 * loads structure data
220 * (this function is work in progress? not yet used)
222 * @return boolean
224 function loadStructure()
226 $table_info = PMA_DBI_get_tables_full($this->getDbName(), $this->getName());
228 if (false === $table_info) {
229 return false;
232 $this->settings = $table_info;
234 if ($this->get('TABLE_ROWS') === null) {
235 $this->set(
236 'TABLE_ROWS',
237 PMA_Table::countRecords($this->getDbName(), $this->getName(), true)
241 $create_options = explode(' ', $this->get('TABLE_ROWS'));
243 // export create options by its name as variables into gloabel namespace
244 // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
245 foreach ($create_options as $each_create_option) {
246 $each_create_option = explode('=', $each_create_option);
247 if (isset($each_create_option[1])) {
248 $this->set($$each_create_option[0], $each_create_option[1]);
251 return true;
255 * Checks if this "table" is a view
257 * @param string $db the database name
258 * @param string $table the table name
260 * @deprecated
261 * @todo see what we could do with the possible existence of $table_is_view
263 * @return boolean whether this is a view
265 static protected function _isView($db, $table)
267 // maybe we already know if the table is a view
268 if (isset($GLOBALS['tbl_is_view']) && $GLOBALS['tbl_is_view']) {
269 return true;
272 // Since phpMyAdmin 3.2 the field TABLE_TYPE is properly filled by
273 // PMA_DBI_get_tables_full()
274 $type = PMA_Table::sGetStatusInfo($db, $table, 'TABLE_TYPE');
275 return $type == 'VIEW';
279 * Checks if this is a merge table
281 * If the ENGINE of the table is MERGE or MRG_MYISAM (alias),
282 * this is a merge table.
284 * @param string $db the database name
285 * @param string $table the table name
287 * @return boolean true if it is a merge table
289 static public function isMerge($db = null, $table = null)
291 $engine = null;
292 // if called static, with parameters
293 if (! empty($db) && ! empty($table)) {
294 $engine = PMA_Table::sGetStatusInfo($db, $table, 'ENGINE', null, true);
297 return (! empty($engine) && ((strtoupper($engine) == 'MERGE') || (strtoupper($engine) == 'MRG_MYISAM')));
300 static public function sGetToolTip($db, $table)
302 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
303 . ' (' . PMA_Table::countRecords($db, $table) . ')';
307 * Returns full table status info, or specific if $info provided
308 * this info is collected from information_schema
310 * @param string $db database name
311 * @param string $table table name
312 * @param string $info
313 * @param boolean $force_read read new rather than serving from cache
314 * @param boolean $disable_error if true, disables error message
316 * @todo PMA_DBI_get_tables_full needs to be merged somehow into this class
317 * or at least better documented
319 * @return mixed
321 static public function sGetStatusInfo($db, $table, $info = null, $force_read = false, $disable_error = false)
323 if (! isset(PMA_Table::$cache[$db][$table]) || $force_read) {
324 PMA_DBI_get_tables_full($db, $table);
327 if (! isset(PMA_Table::$cache[$db][$table])) {
328 // happens when we enter the table creation dialog
329 // or when we really did not get any status info, for example
330 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
331 return '';
334 if (null === $info) {
335 return PMA_Table::$cache[$db][$table];
338 if (! isset(PMA_Table::$cache[$db][$table][$info])) {
339 if (! $disable_error) {
340 trigger_error(__('unknown table status: ') . $info, E_USER_WARNING);
342 return false;
345 return PMA_Table::$cache[$db][$table][$info];
349 * generates column specification for ALTER or CREATE TABLE syntax
351 * @param string $name name
352 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
353 * @param string $length length ('2', '5,2', '', ...)
354 * @param string $attribute attribute
355 * @param string $collation collation
356 * @param bool|string $null with 'NULL' or 'NOT NULL'
357 * @param string $default_type whether default is CURRENT_TIMESTAMP,
358 * NULL, NONE, USER_DEFINED
359 * @param string $default_value default value for USER_DEFINED default type
360 * @param string $extra 'AUTO_INCREMENT'
361 * @param string $comment field comment
362 * @param array &$field_primary list of fields for PRIMARY KEY
363 * @param string $index
365 * @todo move into class PMA_Column
366 * @todo on the interface, some js to clear the default value when the default
367 * current_timestamp is checked
369 * @return string field specification
371 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
372 $collation = '', $null = false, $default_type = 'USER_DEFINED',
373 $default_value = '', $extra = '', $comment = '',
374 &$field_primary, $index)
377 $is_timestamp = strpos(strtoupper($type), 'TIMESTAMP') !== false;
379 $query = PMA_backquote($name) . ' ' . $type;
381 if ($length != ''
382 && ! preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|'
383 . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN)$@i', $type)
385 $query .= '(' . $length . ')';
388 if ($attribute != '') {
389 $query .= ' ' . $attribute;
392 if (! empty($collation) && $collation != 'NULL'
393 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)
395 $query .= PMA_generateCharsetQueryPart($collation);
398 if ($null !== false) {
399 if ($null == 'NULL') {
400 $query .= ' NULL';
401 } else {
402 $query .= ' NOT NULL';
406 switch ($default_type) {
407 case 'USER_DEFINED' :
408 if ($is_timestamp && $default_value === '0') {
409 // a TIMESTAMP does not accept DEFAULT '0'
410 // but DEFAULT 0 works
411 $query .= ' DEFAULT 0';
412 } elseif ($type == 'BIT') {
413 $query .= ' DEFAULT b\''
414 . preg_replace('/[^01]/', '0', $default_value)
415 . '\'';
416 } else {
417 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
419 break;
420 case 'NULL' :
421 case 'CURRENT_TIMESTAMP' :
422 $query .= ' DEFAULT ' . $default_type;
423 break;
424 case 'NONE' :
425 default :
426 break;
429 if (!empty($extra)) {
430 $query .= ' ' . $extra;
431 // Force an auto_increment field to be part of the primary key
432 // even if user did not tick the PK box;
433 if ($extra == 'AUTO_INCREMENT') {
434 $primary_cnt = count($field_primary);
435 if (1 == $primary_cnt) {
436 for ($j = 0; $j < $primary_cnt; $j++) {
437 if ($field_primary[$j] == $index) {
438 break;
441 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
442 $query .= ' PRIMARY KEY';
443 unset($field_primary[$j]);
445 } else {
446 // but the PK could contain other columns so do not append
447 // a PRIMARY KEY clause, just add a member to $field_primary
448 $found_in_pk = false;
449 for ($j = 0; $j < $primary_cnt; $j++) {
450 if ($field_primary[$j] == $index) {
451 $found_in_pk = true;
452 break;
454 } // end for
455 if (! $found_in_pk) {
456 $field_primary[] = $index;
459 } // end if (auto_increment)
461 if (!empty($comment)) {
462 $query .= " COMMENT '" . PMA_sqlAddSlashes($comment) . "'";
464 return $query;
465 } // end function
468 * Counts and returns (or displays) the number of records in a table
470 * Revision 13 July 2001: Patch for limiting dump size from
471 * vinay@sanisoft.com & girish@sanisoft.com
473 * @param string $db the current database name
474 * @param string $table the current table name
475 * @param bool $force_exact whether to force an exact count
476 * @param bool $is_view whether the table is a view
478 * @return mixed the number of records if "retain" param is true,
479 * otherwise true
481 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
483 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
484 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
485 } else {
486 $row_count = false;
488 if (null === $is_view) {
489 $is_view = PMA_Table::isView($db, $table);
492 if (! $force_exact) {
493 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
494 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
495 if (isset($tmp_tables[$table])) {
496 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
499 if (isset(PMA_Table::$cache[$db][$table]['Rows'])) {
500 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
501 } else {
502 $row_count = false;
506 // for a VIEW, $row_count is always false at this point
507 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
508 if (! $is_view) {
509 $row_count = PMA_DBI_fetch_value(
510 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
511 . PMA_backquote($table)
513 } else {
514 // For complex views, even trying to get a partial record
515 // count could bring down a server, so we offer an
516 // alternative: setting MaxExactCountViews to 0 will bypass
517 // completely the record counting for views
519 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
520 $row_count = 0;
521 } else {
522 // Counting all rows of a VIEW could be too long, so use
523 // a LIMIT clause.
524 // Use try_query because it can fail (when a VIEW is
525 // based on a table that no longer exists)
526 $result = PMA_DBI_try_query(
527 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
528 . PMA_backquote($table) . ' LIMIT '
529 . $GLOBALS['cfg']['MaxExactCountViews'],
530 null,
531 PMA_DBI_QUERY_STORE
533 if (!PMA_DBI_getError()) {
534 $row_count = PMA_DBI_num_rows($result);
535 PMA_DBI_free_result($result);
539 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
543 return $row_count;
544 } // end of the 'PMA_Table::countRecords()' function
547 * Generates column specification for ALTER syntax
549 * @param string $oldcol old column name
550 * @param string $newcol new column name
551 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
552 * @param string $length length ('2', '5,2', '', ...)
553 * @param string $attribute attribute
554 * @param string $collation collation
555 * @param bool|string $null with 'NULL' or 'NOT NULL'
556 * @param string $default_type whether default is CURRENT_TIMESTAMP,
557 * NULL, NONE, USER_DEFINED
558 * @param string $default_value default value for USER_DEFINED default type
559 * @param string $extra 'AUTO_INCREMENT'
560 * @param string $comment field comment
561 * @param array &$field_primary list of fields for PRIMARY KEY
562 * @param string $index
563 * @param mixed $default_orig
565 * @see PMA_Table::generateFieldSpec()
567 * @return string field specification
569 static public function generateAlter($oldcol, $newcol, $type, $length,
570 $attribute, $collation, $null, $default_type, $default_value,
571 $extra, $comment = '', &$field_primary, $index, $default_orig)
573 return PMA_backquote($oldcol) . ' '
574 . PMA_Table::generateFieldSpec(
575 $newcol, $type, $length, $attribute,
576 $collation, $null, $default_type, $default_value, $extra,
577 $comment, $field_primary, $index, $default_orig
579 } // end function
582 * Inserts existing entries in a PMA_* table by reading a value from an old entry
584 * @param string $work The array index, which Relation feature to check
585 * ('relwork', 'commwork', ...)
586 * @param string $pma_table The array index, which PMA-table to update
587 * ('bookmark', 'relation', ...)
588 * @param array $get_fields Which fields will be SELECT'ed from the old entry
589 * @param array $where_fields Which fields will be used for the WHERE query
590 * (array('FIELDNAME' => 'FIELDVALUE'))
591 * @param array $new_fields Which fields will be used as new VALUES. These are
592 * the important keys which differ from the old entry
593 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
595 * @global relation variable
597 * @return int|true
599 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields, $new_fields)
601 $last_id = -1;
603 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
604 $select_parts = array();
605 $row_fields = array();
606 foreach ($get_fields as $get_field) {
607 $select_parts[] = PMA_backquote($get_field);
608 $row_fields[$get_field] = 'cc';
611 $where_parts = array();
612 foreach ($where_fields as $_where => $_value) {
613 $where_parts[] = PMA_backquote($_where) . ' = \''
614 . PMA_sqlAddSlashes($_value) . '\'';
617 $new_parts = array();
618 $new_value_parts = array();
619 foreach ($new_fields as $_where => $_value) {
620 $new_parts[] = PMA_backquote($_where);
621 $new_value_parts[] = PMA_sqlAddSlashes($_value);
624 $table_copy_query = '
625 SELECT ' . implode(', ', $select_parts) . '
626 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
627 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
628 WHERE ' . implode(' AND ', $where_parts);
630 // must use PMA_DBI_QUERY_STORE here, since we execute another
631 // query inside the loop
632 $table_copy_rs = PMA_query_as_controluser(
633 $table_copy_query, true, PMA_DBI_QUERY_STORE
636 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
637 $value_parts = array();
638 foreach ($table_copy_row as $_key => $_val) {
639 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
640 $value_parts[] = PMA_sqlAddSlashes($_val);
644 $new_table_query = 'INSERT IGNORE INTO '
645 . PMA_backquote($GLOBALS['cfgRelation']['db'])
646 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
647 (' . implode(', ', $select_parts) . ',
648 ' . implode(', ', $new_parts) . ')
649 VALUES
650 (\'' . implode('\', \'', $value_parts) . '\',
651 \'' . implode('\', \'', $new_value_parts) . '\')';
653 PMA_query_as_controluser($new_table_query);
654 $last_id = PMA_DBI_insert_id();
655 } // end while
657 PMA_DBI_free_result($table_copy_rs);
659 return $last_id;
662 return true;
663 } // end of 'PMA_Table::duplicateInfo()' function
667 * Copies or renames table
669 * @param string $source_db source database
670 * @param string $source_table source table
671 * @param string $target_db target database
672 * @param string $target_table target table
673 * @param string $what what to be moved or copied (data, dataonly)
674 * @param bool $move whether to move
675 * @param string $mode mode
677 * @return bool true if success, false otherwise
679 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
681 global $err_url;
683 /* Try moving table directly */
684 if ($move && $what == 'data') {
685 $tbl = new PMA_Table($source_table, $source_db);
686 $result = $tbl->rename(
687 $target_table, $target_db,
688 PMA_Table::isView($source_db, $source_table)
690 if ($result) {
691 $GLOBALS['message'] = $tbl->getLastMessage();
692 return true;
696 // set export settings we need
697 $GLOBALS['sql_backquotes'] = 1;
698 $GLOBALS['asfile'] = 1;
700 // Ensure the target is valid
701 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
702 if (! $GLOBALS['pma']->databases->exists($source_db)) {
703 $GLOBALS['message'] = PMA_Message::rawError(
704 'source database `' . htmlspecialchars($source_db) . '` not found'
707 if (! $GLOBALS['pma']->databases->exists($target_db)) {
708 $GLOBALS['message'] = PMA_Message::rawError(
709 'target database `' . htmlspecialchars($target_db) . '` not found'
712 return false;
715 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
716 if (! isset($target_db) || ! strlen($target_db)) {
717 $target_db = $source_db;
720 // Doing a select_db could avoid some problems with replicated databases,
721 // when moving table from replicated one to not replicated one
722 PMA_DBI_select_db($target_db);
724 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
726 // do not create the table if dataonly
727 if ($what != 'dataonly') {
728 include_once './libraries/export/sql.php';
730 $no_constraints_comments = true;
731 $GLOBALS['sql_constraints_query'] = '';
733 $sql_structure = PMA_getTableDef(
734 $source_db, $source_table, "\n", $err_url, false, false
736 unset($no_constraints_comments);
737 $parsed_sql = PMA_SQP_parse($sql_structure);
738 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
739 $i = 0;
740 if (empty($analyzed_sql[0]['create_table_fields'])) {
741 // this is not a CREATE TABLE, so find the first VIEW
742 $target_for_view = PMA_backquote($target_db);
743 while (true) {
744 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord'
745 && $parsed_sql[$i]['data'] == 'VIEW'
747 break;
749 $i++;
752 unset($analyzed_sql);
753 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
754 // ANSI_QUOTES might be a subset of sql_mode, for example
755 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
756 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
757 $table_delimiter = 'quote_double';
758 } else {
759 $table_delimiter = 'quote_backtick';
761 unset($server_sql_mode);
763 /* Find table name in query and replace it */
764 while ($parsed_sql[$i]['type'] != $table_delimiter) {
765 $i++;
768 /* no need to PMA_backquote() */
769 if (isset($target_for_view)) {
770 // this a view definition; we just found the first db name
771 // that follows DEFINER VIEW
772 // so change it for the new db name
773 $parsed_sql[$i]['data'] = $target_for_view;
774 // then we have to find all references to the source db
775 // and change them to the target db, ensuring we stay into
776 // the $parsed_sql limits
777 $last = $parsed_sql['len'] - 1;
778 $backquoted_source_db = PMA_backquote($source_db);
779 for (++$i; $i <= $last; $i++) {
780 if ($parsed_sql[$i]['type'] == $table_delimiter
781 && $parsed_sql[$i]['data'] == $backquoted_source_db
783 $parsed_sql[$i]['data'] = $target_for_view;
786 unset($last,$backquoted_source_db);
787 } else {
788 $parsed_sql[$i]['data'] = $target;
791 /* Generate query back */
792 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
793 // If table exists, and 'add drop table' is selected: Drop it!
794 $drop_query = '';
795 if (isset($GLOBALS['drop_if_exists'])
796 && $GLOBALS['drop_if_exists'] == 'true'
798 if (PMA_Table::_isView($target_db, $target_table)) {
799 $drop_query = 'DROP VIEW';
800 } else {
801 $drop_query = 'DROP TABLE';
803 $drop_query .= ' IF EXISTS '
804 . PMA_backquote($target_db) . '.'
805 . PMA_backquote($target_table);
806 PMA_DBI_query($drop_query);
808 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
810 // If an existing table gets deleted, maintain any
811 // entries for the PMA_* tables
812 $maintain_relations = true;
815 @PMA_DBI_query($sql_structure);
816 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
818 if (($move || isset($GLOBALS['add_constraints']))
819 && !empty($GLOBALS['sql_constraints_query'])
821 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
822 $i = 0;
824 // find the first $table_delimiter, it must be the source table name
825 while ($parsed_sql[$i]['type'] != $table_delimiter) {
826 $i++;
827 // maybe someday we should guard against going over limit
828 //if ($i == $parsed_sql['len']) {
829 // break;
833 // replace it by the target table name, no need to PMA_backquote()
834 $parsed_sql[$i]['data'] = $target;
836 // now we must remove all $table_delimiter that follow a CONSTRAINT
837 // keyword, because a constraint name must be unique in a db
839 $cnt = $parsed_sql['len'] - 1;
841 for ($j = $i; $j < $cnt; $j++) {
842 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
843 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT'
845 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
846 $parsed_sql[$j+1]['data'] = '';
851 // Generate query back
852 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml(
853 $parsed_sql, 'query_only'
855 if ($mode == 'one_table') {
856 PMA_DBI_query($GLOBALS['sql_constraints_query']);
858 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
859 if ($mode == 'one_table') {
860 unset($GLOBALS['sql_constraints_query']);
863 } else {
864 $GLOBALS['sql_query'] = '';
867 // Copy the data unless this is a VIEW
868 if (($what == 'data' || $what == 'dataonly')
869 && ! PMA_Table::_isView($target_db, $target_table)
871 $sql_insert_data = 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
872 PMA_DBI_query($sql_insert_data);
873 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
876 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
878 // Drops old table if the user has requested to move it
879 if ($move) {
881 // This could avoid some problems with replicated databases, when
882 // moving table from replicated one to not replicated one
883 PMA_DBI_select_db($source_db);
885 if (PMA_Table::_isView($source_db, $source_table)) {
886 $sql_drop_query = 'DROP VIEW';
887 } else {
888 $sql_drop_query = 'DROP TABLE';
890 $sql_drop_query .= ' ' . $source;
891 PMA_DBI_query($sql_drop_query);
893 // Move old entries from PMA-DBs to new table
894 if ($GLOBALS['cfgRelation']['commwork']) {
895 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
896 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\', '
897 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
898 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
899 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
900 PMA_query_as_controluser($remove_query);
901 unset($remove_query);
904 // updating bookmarks is not possible since only a single table is moved,
905 // and not the whole DB.
907 if ($GLOBALS['cfgRelation']['displaywork']) {
908 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
909 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\', '
910 . ' table_name = \'' . PMA_sqlAddSlashes($target_table) . '\''
911 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
912 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
913 PMA_query_as_controluser($table_query);
914 unset($table_query);
917 if ($GLOBALS['cfgRelation']['relwork']) {
918 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
919 . ' SET foreign_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
920 . ' foreign_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
921 . ' WHERE foreign_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
922 . ' AND foreign_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
923 PMA_query_as_controluser($table_query);
924 unset($table_query);
926 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
927 . ' SET master_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
928 . ' master_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
929 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
930 . ' AND master_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
931 PMA_query_as_controluser($table_query);
932 unset($table_query);
936 * @todo Can't get moving PDFs the right way. The page numbers
937 * always get screwed up independently from duplication because the
938 * numbers do not seem to be stored on a per-database basis. Would
939 * the author of pdf support please have a look at it?
942 if ($GLOBALS['cfgRelation']['pdfwork']) {
943 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
944 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
945 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
946 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
947 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
948 PMA_query_as_controluser($table_query);
949 unset($table_query);
951 $pdf_query = 'SELECT pdf_page_number '
952 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
953 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
954 . ' AND table_name = \'' . PMA_sqlAddSlashes($target_table) . '\'';
955 $pdf_rs = PMA_query_as_controluser($pdf_query);
957 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
958 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
959 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
960 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
961 . ' AND page_nr = \'' . PMA_sqlAddSlashes($pdf_copy_row['pdf_page_number']) . '\'';
962 $tb_rs = PMA_query_as_controluser($table_query);
963 unset($table_query);
964 unset($tb_rs);
969 if ($GLOBALS['cfgRelation']['designerwork']) {
970 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
971 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
972 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
973 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
974 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
975 PMA_query_as_controluser($table_query);
976 unset($table_query);
979 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
980 // end if ($move)
981 } else {
982 // we are copying
983 // Create new entries as duplicates from old PMA DBs
984 if ($what != 'dataonly' && ! isset($maintain_relations)) {
985 if ($GLOBALS['cfgRelation']['commwork']) {
986 // Get all comments and MIME-Types for current table
987 $comments_copy_query = 'SELECT
988 column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
989 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
990 WHERE
991 db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND
992 table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
993 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
995 // Write every comment as new copied entry. [MIME]
996 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
997 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
998 . ' (db_name, table_name, column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
999 . ' VALUES('
1000 . '\'' . PMA_sqlAddSlashes($target_db) . '\','
1001 . '\'' . PMA_sqlAddSlashes($target_table) . '\','
1002 . '\'' . PMA_sqlAddSlashes($comments_copy_row['column_name']) . '\''
1003 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddSlashes($comments_copy_row['comment']) . '\','
1004 . '\'' . PMA_sqlAddSlashes($comments_copy_row['mimetype']) . '\','
1005 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation']) . '\','
1006 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
1007 . ')';
1008 PMA_query_as_controluser($new_comment_query);
1009 } // end while
1010 PMA_DBI_free_result($comments_copy_rs);
1011 unset($comments_copy_rs);
1014 // duplicating the bookmarks must not be done here, but
1015 // just once per db
1017 $get_fields = array('display_field');
1018 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
1019 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
1020 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
1024 * @todo revise this code when we support cross-db relations
1026 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
1027 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
1028 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
1029 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
1032 $get_fields = array('foreign_field', 'master_table', 'master_field');
1033 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
1034 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
1035 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
1038 $get_fields = array('x', 'y', 'v', 'h');
1039 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
1040 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
1041 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
1044 * @todo Can't get duplicating PDFs the right way. The
1045 * page numbers always get screwed up independently from
1046 * duplication because the numbers do not seem to be stored on a
1047 * per-database basis. Would the author of pdf support please
1048 * have a look at it?
1050 $get_fields = array('page_descr');
1051 $where_fields = array('db_name' => $source_db);
1052 $new_fields = array('db_name' => $target_db);
1053 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
1055 if (isset($last_id) && $last_id >= 0) {
1056 $get_fields = array('x', 'y');
1057 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
1058 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
1059 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
1064 return true;
1068 * checks if given name is a valid table name,
1069 * currently if not empty, trailing spaces, '.', '/' and '\'
1071 * @param string $table_name name to check
1073 * @todo add check for valid chars in filename on current system/os
1074 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
1076 * @return boolean whether the string is valid or not
1078 function isValidName($table_name)
1080 if ($table_name !== trim($table_name)) {
1081 // trailing spaces
1082 return false;
1085 if (! strlen($table_name)) {
1086 // zero length
1087 return false;
1090 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
1091 // illegal char . / \
1092 return false;
1095 return true;
1099 * renames table
1101 * @param string $new_name new table name
1102 * @param string $new_db new database name
1103 * @param bool $is_view is this for a VIEW rename?
1105 * @return bool success
1107 function rename($new_name, $new_db = null, $is_view = false)
1109 if (null !== $new_db && $new_db !== $this->getDbName()) {
1110 // Ensure the target is valid
1111 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1112 $this->errors[] = __('Invalid database') . ': ' . $new_db;
1113 return false;
1115 } else {
1116 $new_db = $this->getDbName();
1119 $new_table = new PMA_Table($new_name, $new_db);
1121 if ($this->getFullName() === $new_table->getFullName()) {
1122 return true;
1125 if (! PMA_Table::isValidName($new_name)) {
1126 $this->errors[] = __('Invalid table name') . ': ' . $new_table->getFullName();
1127 return false;
1130 if (! $is_view) {
1131 $GLOBALS['sql_query'] = '
1132 RENAME TABLE ' . $this->getFullName(true) . '
1133 TO ' . $new_table->getFullName(true) . ';';
1134 } else {
1135 $GLOBALS['sql_query'] = '
1136 ALTER TABLE ' . $this->getFullName(true) . '
1137 RENAME ' . $new_table->getFullName(true) . ';';
1139 // I don't think a specific error message for views is necessary
1140 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1141 $this->errors[] = sprintf(
1142 __('Error renaming table %1$s to %2$s'),
1143 $this->getFullName(),
1144 $new_table->getFullName()
1146 return false;
1149 $old_name = $this->getName();
1150 $old_db = $this->getDbName();
1151 $this->setName($new_name);
1152 $this->setDbName($new_db);
1155 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1157 // Move old entries from comments to new table
1158 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1159 if ($GLOBALS['cfgRelation']['commwork']) {
1160 $remove_query = '
1161 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1162 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1163 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1164 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1165 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1166 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1167 PMA_query_as_controluser($remove_query);
1168 unset($remove_query);
1171 if ($GLOBALS['cfgRelation']['displaywork']) {
1172 $table_query = '
1173 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1174 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1175 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1176 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1177 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1178 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1179 PMA_query_as_controluser($table_query);
1180 unset($table_query);
1183 if ($GLOBALS['cfgRelation']['relwork']) {
1184 $table_query = '
1185 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1186 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1187 SET `foreign_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1188 `foreign_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1189 WHERE `foreign_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1190 AND `foreign_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1191 PMA_query_as_controluser($table_query);
1193 $table_query = '
1194 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1195 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1196 SET `master_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1197 `master_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1198 WHERE `master_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1199 AND `master_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1200 PMA_query_as_controluser($table_query);
1201 unset($table_query);
1204 if ($GLOBALS['cfgRelation']['pdfwork']) {
1205 $table_query = '
1206 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1207 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1208 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1209 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1210 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1211 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1212 PMA_query_as_controluser($table_query);
1213 unset($table_query);
1216 if ($GLOBALS['cfgRelation']['designerwork']) {
1217 $table_query = '
1218 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1219 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1220 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1221 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1222 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1223 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1224 PMA_query_as_controluser($table_query);
1225 unset($table_query);
1228 $this->messages[] = sprintf(
1229 __('Table %s has been renamed to %s'),
1230 htmlspecialchars($old_name),
1231 htmlspecialchars($new_name)
1233 return true;
1237 * Get all unique columns
1239 * returns an array with all columns with unqiue content, in fact these are
1240 * all columns being single indexed in PRIMARY or UNIQUE
1242 * e.g.
1243 * - PRIMARY(id) // id
1244 * - UNIQUE(name) // name
1245 * - PRIMARY(fk_id1, fk_id2) // NONE
1246 * - UNIQUE(x,y) // NONE
1248 * @param bool $backquoted whether to quote name with backticks ``
1250 * @return array
1252 public function getUniqueColumns($backquoted = true)
1254 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1255 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1257 $return = array();
1258 foreach ($uniques as $index) {
1259 if (count($index) > 1) {
1260 continue;
1262 $return[] = $this->getFullName($backquoted) . '.'
1263 . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1266 return $return;
1270 * Get all indexed columns
1272 * returns an array with all columns make use of an index, in fact only
1273 * first columns in an index
1275 * e.g. index(col1, col2) would only return col1
1277 * @param bool $backquoted whether to quote name with backticks ``
1279 * @return array
1281 public function getIndexedColumns($backquoted = true)
1283 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1284 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1286 $return = array();
1287 foreach ($indexed as $column) {
1288 $return[] = $this->getFullName($backquoted) . '.'
1289 . ($backquoted ? PMA_backquote($column) : $column);
1292 return $return;
1296 * Get all columns
1298 * returns an array with all columns
1300 * @param bool $backquoted whether to quote name with backticks ``
1302 * @return array
1304 public function getColumns($backquoted = true)
1306 $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
1307 $indexed = PMA_DBI_fetch_result($sql, 'Field', 'Field');
1309 $return = array();
1310 foreach ($indexed as $column) {
1311 $return[] = $this->getFullName($backquoted) . '.'
1312 . ($backquoted ? PMA_backquote($column) : $column);
1315 return $return;
1319 * Return UI preferences for this table from phpMyAdmin database.
1321 * @return array
1323 protected function getUiPrefsFromDb()
1325 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1326 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1328 // Read from phpMyAdmin database
1329 $sql_query = " SELECT `prefs` FROM " . $pma_table
1330 . " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'"
1331 . " AND `db_name` = '" . PMA_sqlAddSlashes($this->db_name) . "'"
1332 . " AND `table_name` = '" . PMA_sqlAddSlashes($this->name) . "'";
1334 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
1335 if (isset($row[0])) {
1336 return json_decode($row[0], true);
1337 } else {
1338 return array();
1343 * Save this table's UI preferences into phpMyAdmin database.
1345 * @return true|PMA_Message
1347 protected function saveUiPrefsToDb()
1349 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
1350 . PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1352 $username = $GLOBALS['cfg']['Server']['user'];
1353 $sql_query = " REPLACE INTO " . $pma_table
1354 . " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name)
1355 . "', '" . PMA_sqlAddSlashes($this->name) . "', '"
1356 . PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
1358 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1360 if (!$success) {
1361 $message = PMA_Message::error(__('Could not save table UI preferences'));
1362 $message->addMessage('<br /><br />');
1363 $message->addMessage(
1364 PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink']))
1366 return $message;
1369 // Remove some old rows in table_uiprefs if it exceeds the configured maximum rows
1370 $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
1371 $rows_count = PMA_DBI_fetch_value($sql_query);
1372 $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
1373 if ($rows_count > $max_rows) {
1374 $num_rows_to_delete = $rows_count - $max_rows;
1375 $sql_query =
1376 ' DELETE FROM ' . $pma_table .
1377 ' ORDER BY last_update ASC' .
1378 ' LIMIT ' . $num_rows_to_delete;
1379 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1381 if (!$success) {
1382 $message = PMA_Message::error(
1383 sprintf(
1384 __('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
1385 PMA_showDocu('cfg_Servers_MaxTableUiprefs')
1388 $message->addMessage('<br /><br />');
1389 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1390 print_r($message);
1391 return $message;
1395 return true;
1399 * Loads the UI preferences for this table.
1400 * If pmadb and table_uiprefs is set, it will load the UI preferences from
1401 * phpMyAdmin database.
1403 * @return nothing
1405 protected function loadUiPrefs()
1407 $server_id = $GLOBALS['server'];
1408 // set session variable if it's still undefined
1409 if (! isset($_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name])) {
1410 $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name] =
1411 // check whether we can get from pmadb
1412 (strlen($GLOBALS['cfg']['Server']['pmadb'])
1413 && strlen($GLOBALS['cfg']['Server']['table_uiprefs']))
1414 ? $this->getUiPrefsFromDb()
1415 : array();
1417 $this->uiprefs =& $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name];
1421 * Get a property from UI preferences.
1422 * Return false if the property is not found.
1423 * Available property:
1424 * - PROP_SORTED_COLUMN
1425 * - PROP_COLUMN_ORDER
1426 * - PROP_COLUMN_VISIB
1428 * @param string $property property
1430 * @return mixed
1432 public function getUiProp($property)
1434 if (! isset($this->uiprefs)) {
1435 $this->loadUiPrefs();
1437 // do checking based on property
1438 if ($property == self::PROP_SORTED_COLUMN) {
1439 if (isset($this->uiprefs[$property])) {
1440 // check if the column name is exist in this table
1441 $tmp = explode(' ', $this->uiprefs[$property]);
1442 $colname = $tmp[0];
1443 $avail_columns = $this->getColumns();
1444 foreach ($avail_columns as $each_col) {
1445 // check if $each_col ends with $colname
1446 if (substr_compare($each_col, $colname, strlen($each_col) - strlen($colname)) === 0) {
1447 return $this->uiprefs[$property];
1450 // remove the property, since it is not exist anymore in database
1451 $this->removeUiProp(self::PROP_SORTED_COLUMN);
1452 return false;
1453 } else {
1454 return false;
1456 } elseif ($property == self::PROP_COLUMN_ORDER
1457 || $property == self::PROP_COLUMN_VISIB
1459 if (! PMA_Table::isView($this->db_name, $this->name) && isset($this->uiprefs[$property])) {
1460 // check if the table has not been modified
1461 if (self::sGetStatusInfo($this->db_name, $this->name, 'Create_time') == $this->uiprefs['CREATE_TIME']) {
1462 return $this->uiprefs[$property];
1463 } else {
1464 // remove the property, since the table has been modified
1465 $this->removeUiProp(self::PROP_COLUMN_ORDER);
1466 return false;
1468 } else {
1469 return false;
1472 // default behaviour for other property:
1473 return isset($this->uiprefs[$property]) ? $this->uiprefs[$property] : false;
1477 * Set a property from UI preferences.
1478 * If pmadb and table_uiprefs is set, it will save the UI preferences to
1479 * phpMyAdmin database.
1480 * Available property:
1481 * - PROP_SORTED_COLUMN
1482 * - PROP_COLUMN_ORDER
1483 * - PROP_COLUMN_VISIB
1485 * @param string $property Property
1486 * @param mixed $value Value for the property
1487 * @param string $table_create_time Needed for PROP_COLUMN_ORDER and PROP_COLUMN_VISIB
1489 * @return boolean|PMA_Message
1491 public function setUiProp($property, $value, $table_create_time = null)
1493 if (! isset($this->uiprefs)) {
1494 $this->loadUiPrefs();
1496 // we want to save the create time if the property is PROP_COLUMN_ORDER
1497 if (! PMA_Table::isView($this->db_name, $this->name)
1498 && ($property == self::PROP_COLUMN_ORDER || $property == self::PROP_COLUMN_VISIB)
1500 $curr_create_time = self::sGetStatusInfo($this->db_name, $this->name, 'CREATE_TIME');
1501 if (isset($table_create_time)
1502 && $table_create_time == $curr_create_time
1504 $this->uiprefs['CREATE_TIME'] = $curr_create_time;
1505 } else {
1506 // there is no $table_create_time, or
1507 // supplied $table_create_time is older than current create time,
1508 // so don't save
1509 return false;
1512 // save the value
1513 $this->uiprefs[$property] = $value;
1514 // check if pmadb is set
1515 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1516 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1518 return $this->saveUiprefsToDb();
1520 return true;
1524 * Remove a property from UI preferences.
1526 * @param string $property the property
1528 * @return true|PMA_Message
1530 public function removeUiProp($property)
1532 if (! isset($this->uiprefs)) {
1533 $this->loadUiPrefs();
1535 if (isset($this->uiprefs[$property])) {
1536 unset($this->uiprefs[$property]);
1537 // check if pmadb is set
1538 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1539 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1541 return $this->saveUiprefsToDb();
1544 return true;