Translation update done using Pootle.
[phpmyadmin/ammaryasirr.git] / libraries / Table.class.php
blobcdc3224ad9e75c00867360936b35dc1b8c36e152
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 if (! isset(PMA_Table::$cache[$db][$table][$info])) {
302 if (! $disable_error) {
303 trigger_error(__('unknown table status: ') . $info, E_USER_WARNING);
305 return false;
308 return PMA_Table::$cache[$db][$table][$info];
312 * generates column specification for ALTER or CREATE TABLE syntax
314 * @todo move into class PMA_Column
315 * @todo on the interface, some js to clear the default value when the default current_timestamp is checked
316 * @param string $name name
317 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
318 * @param string $length length ('2', '5,2', '', ...)
319 * @param string $attribute
320 * @param string $collation
321 * @param bool|string $null with 'NULL' or 'NOT NULL'
322 * @param string $default_type whether default is CURRENT_TIMESTAMP,
323 * NULL, NONE, USER_DEFINED
324 * @param string $default_value default value for USER_DEFINED default type
325 * @param string $extra 'AUTO_INCREMENT'
326 * @param string $comment field comment
327 * @param array &$field_primary list of fields for PRIMARY KEY
328 * @param string $index
329 * @return string field specification
331 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
332 $collation = '', $null = false, $default_type = 'USER_DEFINED',
333 $default_value = '', $extra = '', $comment = '',
334 &$field_primary, $index)
337 $is_timestamp = strpos(strtoupper($type), 'TIMESTAMP') !== false;
339 $query = PMA_backquote($name) . ' ' . $type;
341 if ($length != ''
342 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT'
343 . '|SERIAL|BOOLEAN)$@i', $type)) {
344 $query .= '(' . $length . ')';
347 if ($attribute != '') {
348 $query .= ' ' . $attribute;
351 if (!empty($collation) && $collation != 'NULL'
352 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)) {
353 $query .= PMA_generateCharsetQueryPart($collation);
356 if ($null !== false) {
357 if ($null == 'NULL') {
358 $query .= ' NULL';
359 } else {
360 $query .= ' NOT NULL';
364 switch ($default_type) {
365 case 'USER_DEFINED' :
366 if ($is_timestamp && $default_value === '0') {
367 // a TIMESTAMP does not accept DEFAULT '0'
368 // but DEFAULT 0 works
369 $query .= ' DEFAULT 0';
370 } elseif ($type == 'BIT') {
371 $query .= ' DEFAULT b\''
372 . preg_replace('/[^01]/', '0', $default_value)
373 . '\'';
374 } else {
375 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
377 break;
378 case 'NULL' :
379 case 'CURRENT_TIMESTAMP' :
380 $query .= ' DEFAULT ' . $default_type;
381 break;
382 case 'NONE' :
383 default :
384 break;
387 if (!empty($extra)) {
388 $query .= ' ' . $extra;
389 // Force an auto_increment field to be part of the primary key
390 // even if user did not tick the PK box;
391 if ($extra == 'AUTO_INCREMENT') {
392 $primary_cnt = count($field_primary);
393 if (1 == $primary_cnt) {
394 for ($j = 0; $j < $primary_cnt; $j++) {
395 if ($field_primary[$j] == $index) {
396 break;
399 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
400 $query .= ' PRIMARY KEY';
401 unset($field_primary[$j]);
403 // but the PK could contain other columns so do not append
404 // a PRIMARY KEY clause, just add a member to $field_primary
405 } else {
406 $found_in_pk = false;
407 for ($j = 0; $j < $primary_cnt; $j++) {
408 if ($field_primary[$j] == $index) {
409 $found_in_pk = true;
410 break;
412 } // end for
413 if (! $found_in_pk) {
414 $field_primary[] = $index;
417 } // end if (auto_increment)
419 if (!empty($comment)) {
420 $query .= " COMMENT '" . PMA_sqlAddSlashes($comment) . "'";
422 return $query;
423 } // end function
426 * Counts and returns (or displays) the number of records in a table
428 * Revision 13 July 2001: Patch for limiting dump size from
429 * vinay@sanisoft.com & girish@sanisoft.com
431 * @param string $db the current database name
432 * @param string $table the current table name
433 * @param bool $force_exact whether to force an exact count
434 * @param bool $is_view
436 * @return mixed the number of records if "retain" param is true,
437 * otherwise true
439 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
441 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
442 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
443 } else {
444 $row_count = false;
446 if (null === $is_view) {
447 $is_view = PMA_Table::isView($db, $table);
450 if (! $force_exact) {
451 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
452 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
453 if (isset($tmp_tables[$table])) {
454 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
457 if (isset(PMA_Table::$cache[$db][$table]['Rows'])) {
458 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
459 } else {
460 $row_count = false;
464 // for a VIEW, $row_count is always false at this point
465 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
466 if (! $is_view) {
467 $row_count = PMA_DBI_fetch_value(
468 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
469 . PMA_backquote($table));
470 } else {
471 // For complex views, even trying to get a partial record
472 // count could bring down a server, so we offer an
473 // alternative: setting MaxExactCountViews to 0 will bypass
474 // completely the record counting for views
476 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
477 $row_count = 0;
478 } else {
479 // Counting all rows of a VIEW could be too long, so use
480 // a LIMIT clause.
481 // Use try_query because it can fail (when a VIEW is
482 // based on a table that no longer exists)
483 $result = PMA_DBI_try_query(
484 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
485 . PMA_backquote($table) . ' LIMIT '
486 . $GLOBALS['cfg']['MaxExactCountViews'],
487 null, PMA_DBI_QUERY_STORE);
488 if (!PMA_DBI_getError()) {
489 $row_count = PMA_DBI_num_rows($result);
490 PMA_DBI_free_result($result);
494 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
498 return $row_count;
499 } // end of the 'PMA_Table::countRecords()' function
502 * Generates column specification for ALTER syntax
504 * @see PMA_Table::generateFieldSpec()
505 * @param string $oldcol old column name
506 * @param string $newcol new column name
507 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
508 * @param string $length length ('2', '5,2', '', ...)
509 * @param string $attribute
510 * @param string $collation
511 * @param bool|string $null with 'NULL' or 'NOT NULL'
512 * @param string $default_type whether default is CURRENT_TIMESTAMP,
513 * NULL, NONE, USER_DEFINED
514 * @param string $default_value default value for USER_DEFINED default type
515 * @param string $extra 'AUTO_INCREMENT'
516 * @param string $comment field comment
517 * @param array &$field_primary list of fields for PRIMARY KEY
518 * @param string $index
519 * @param mixed $default_orig
520 * @return string field specification
522 static public function generateAlter($oldcol, $newcol, $type, $length,
523 $attribute, $collation, $null, $default_type, $default_value,
524 $extra, $comment = '', &$field_primary, $index, $default_orig)
526 return PMA_backquote($oldcol) . ' '
527 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
528 $collation, $null, $default_type, $default_value, $extra,
529 $comment, $field_primary, $index, $default_orig);
530 } // end function
533 * Inserts existing entries in a PMA_* table by reading a value from an old entry
535 * @global relation variable
536 * @param string $work The array index, which Relation feature to check ('relwork', 'commwork', ...)
537 * @param string $pma_table The array index, which PMA-table to update ('bookmark', 'relation', ...)
538 * @param array $get_fields Which fields will be SELECT'ed from the old entry
539 * @param array $where_fields Which fields will be used for the WHERE query (array('FIELDNAME' => 'FIELDVALUE'))
540 * @param array $new_fields Which fields will be used as new VALUES. These are the important
541 * keys which differ from the old entry.
542 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
543 * @return int|true
545 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
546 $new_fields)
548 $last_id = -1;
550 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
551 $select_parts = array();
552 $row_fields = array();
553 foreach ($get_fields as $get_field) {
554 $select_parts[] = PMA_backquote($get_field);
555 $row_fields[$get_field] = 'cc';
558 $where_parts = array();
559 foreach ($where_fields as $_where => $_value) {
560 $where_parts[] = PMA_backquote($_where) . ' = \''
561 . PMA_sqlAddSlashes($_value) . '\'';
564 $new_parts = array();
565 $new_value_parts = array();
566 foreach ($new_fields as $_where => $_value) {
567 $new_parts[] = PMA_backquote($_where);
568 $new_value_parts[] = PMA_sqlAddSlashes($_value);
571 $table_copy_query = '
572 SELECT ' . implode(', ', $select_parts) . '
573 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
574 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
575 WHERE ' . implode(' AND ', $where_parts);
577 // must use PMA_DBI_QUERY_STORE here, since we execute another
578 // query inside the loop
579 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
580 PMA_DBI_QUERY_STORE);
582 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
583 $value_parts = array();
584 foreach ($table_copy_row as $_key => $_val) {
585 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
586 $value_parts[] = PMA_sqlAddSlashes($_val);
590 $new_table_query = '
591 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
592 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
593 (' . implode(', ', $select_parts) . ',
594 ' . implode(', ', $new_parts) . ')
595 VALUES
596 (\'' . implode('\', \'', $value_parts) . '\',
597 \'' . implode('\', \'', $new_value_parts) . '\')';
599 PMA_query_as_controluser($new_table_query);
600 $last_id = PMA_DBI_insert_id();
601 } // end while
603 PMA_DBI_free_result($table_copy_rs);
605 return $last_id;
608 return true;
609 } // end of 'PMA_Table::duplicateInfo()' function
613 * Copies or renames table
615 * @param $source_db
616 * @param $source_table
617 * @param $target_db
618 * @param $target_table
619 * @param $what
620 * @param $move
621 * @param $mode
622 * @return bool
624 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
626 global $err_url;
628 /* Try moving table directly */
629 if ($move && $what == 'data') {
630 $tbl = new PMA_Table($source_table, $source_db);
631 $result = $tbl->rename($target_table, $target_db, PMA_Table::isView($source_db, $source_table));
632 if ($result) {
633 $GLOBALS['message'] = $tbl->getLastMessage();
634 return true;
638 // set export settings we need
639 $GLOBALS['sql_backquotes'] = 1;
640 $GLOBALS['asfile'] = 1;
642 // Ensure the target is valid
643 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
644 if (! $GLOBALS['pma']->databases->exists($source_db)) {
645 $GLOBALS['message'] = PMA_Message::rawError('source database `'
646 . htmlspecialchars($source_db) . '` not found');
648 if (! $GLOBALS['pma']->databases->exists($target_db)) {
649 $GLOBALS['message'] = PMA_Message::rawError('target database `'
650 . htmlspecialchars($target_db) . '` not found');
652 return false;
655 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
656 if (! isset($target_db) || ! strlen($target_db)) {
657 $target_db = $source_db;
660 // Doing a select_db could avoid some problems with replicated databases,
661 // when moving table from replicated one to not replicated one
662 PMA_DBI_select_db($target_db);
664 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
666 // do not create the table if dataonly
667 if ($what != 'dataonly') {
668 require_once './libraries/export/sql.php';
670 $no_constraints_comments = true;
671 $GLOBALS['sql_constraints_query'] = '';
673 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
674 unset($no_constraints_comments);
675 $parsed_sql = PMA_SQP_parse($sql_structure);
676 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
677 $i = 0;
678 if (empty($analyzed_sql[0]['create_table_fields'])) {
679 // this is not a CREATE TABLE, so find the first VIEW
680 $target_for_view = PMA_backquote($target_db);
681 while (true) {
682 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
683 break;
685 $i++;
688 unset($analyzed_sql);
689 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
690 // ANSI_QUOTES might be a subset of sql_mode, for example
691 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
692 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
693 $table_delimiter = 'quote_double';
694 } else {
695 $table_delimiter = 'quote_backtick';
697 unset($server_sql_mode);
699 /* Find table name in query and replace it */
700 while ($parsed_sql[$i]['type'] != $table_delimiter) {
701 $i++;
704 /* no need to PMA_backquote() */
705 if (isset($target_for_view)) {
706 // this a view definition; we just found the first db name
707 // that follows DEFINER VIEW
708 // so change it for the new db name
709 $parsed_sql[$i]['data'] = $target_for_view;
710 // then we have to find all references to the source db
711 // and change them to the target db, ensuring we stay into
712 // the $parsed_sql limits
713 $last = $parsed_sql['len'] - 1;
714 $backquoted_source_db = PMA_backquote($source_db);
715 for (++$i; $i <= $last; $i++) {
716 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
717 $parsed_sql[$i]['data'] = $target_for_view;
720 unset($last,$backquoted_source_db);
721 } else {
722 $parsed_sql[$i]['data'] = $target;
725 /* Generate query back */
726 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
727 // If table exists, and 'add drop table' is selected: Drop it!
728 $drop_query = '';
729 if (isset($GLOBALS['drop_if_exists'])
730 && $GLOBALS['drop_if_exists'] == 'true') {
731 if (PMA_Table::_isView($target_db,$target_table)) {
732 $drop_query = 'DROP VIEW';
733 } else {
734 $drop_query = 'DROP TABLE';
736 $drop_query .= ' IF EXISTS '
737 . PMA_backquote($target_db) . '.'
738 . PMA_backquote($target_table);
739 PMA_DBI_query($drop_query);
741 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
743 // If an existing table gets deleted, maintain any
744 // entries for the PMA_* tables
745 $maintain_relations = true;
748 @PMA_DBI_query($sql_structure);
749 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
751 if (($move || isset($GLOBALS['add_constraints']))
752 && !empty($GLOBALS['sql_constraints_query'])) {
753 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
754 $i = 0;
756 // find the first $table_delimiter, it must be the source table name
757 while ($parsed_sql[$i]['type'] != $table_delimiter) {
758 $i++;
759 // maybe someday we should guard against going over limit
760 //if ($i == $parsed_sql['len']) {
761 // break;
765 // replace it by the target table name, no need to PMA_backquote()
766 $parsed_sql[$i]['data'] = $target;
768 // now we must remove all $table_delimiter that follow a CONSTRAINT
769 // keyword, because a constraint name must be unique in a db
771 $cnt = $parsed_sql['len'] - 1;
773 for ($j = $i; $j < $cnt; $j++) {
774 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
775 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
776 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
777 $parsed_sql[$j+1]['data'] = '';
782 // Generate query back
783 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
784 'query_only');
785 if ($mode == 'one_table') {
786 PMA_DBI_query($GLOBALS['sql_constraints_query']);
788 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
789 if ($mode == 'one_table') {
790 unset($GLOBALS['sql_constraints_query']);
793 } else {
794 $GLOBALS['sql_query'] = '';
797 // Copy the data unless this is a VIEW
798 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
799 $sql_insert_data =
800 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
801 PMA_DBI_query($sql_insert_data);
802 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
805 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
807 // Drops old table if the user has requested to move it
808 if ($move) {
810 // This could avoid some problems with replicated databases, when
811 // moving table from replicated one to not replicated one
812 PMA_DBI_select_db($source_db);
814 if (PMA_Table::_isView($source_db,$source_table)) {
815 $sql_drop_query = 'DROP VIEW';
816 } else {
817 $sql_drop_query = 'DROP TABLE';
819 $sql_drop_query .= ' ' . $source;
820 PMA_DBI_query($sql_drop_query);
822 // Move old entries from PMA-DBs to new table
823 if ($GLOBALS['cfgRelation']['commwork']) {
824 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
825 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\', '
826 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
827 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
828 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
829 PMA_query_as_controluser($remove_query);
830 unset($remove_query);
833 // updating bookmarks is not possible since only a single table is moved,
834 // and not the whole DB.
836 if ($GLOBALS['cfgRelation']['displaywork']) {
837 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
838 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\', '
839 . ' table_name = \'' . PMA_sqlAddSlashes($target_table) . '\''
840 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
841 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
842 PMA_query_as_controluser($table_query);
843 unset($table_query);
846 if ($GLOBALS['cfgRelation']['relwork']) {
847 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
848 . ' SET foreign_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
849 . ' foreign_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
850 . ' WHERE foreign_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
851 . ' AND foreign_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
852 PMA_query_as_controluser($table_query);
853 unset($table_query);
855 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
856 . ' SET master_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
857 . ' master_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
858 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
859 . ' AND master_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
860 PMA_query_as_controluser($table_query);
861 unset($table_query);
865 * @todo Can't get moving PDFs the right way. The page numbers
866 * always get screwed up independently from duplication because the
867 * numbers do not seem to be stored on a per-database basis. Would
868 * the author of pdf support please have a look at it?
871 if ($GLOBALS['cfgRelation']['pdfwork']) {
872 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
873 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
874 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
875 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
876 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
877 PMA_query_as_controluser($table_query);
878 unset($table_query);
880 $pdf_query = 'SELECT pdf_page_number '
881 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
882 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
883 . ' AND table_name = \'' . PMA_sqlAddSlashes($target_table) . '\'';
884 $pdf_rs = PMA_query_as_controluser($pdf_query);
886 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
887 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
888 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
889 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
890 . ' AND page_nr = \'' . PMA_sqlAddSlashes($pdf_copy_row['pdf_page_number']) . '\'';
891 $tb_rs = PMA_query_as_controluser($table_query);
892 unset($table_query);
893 unset($tb_rs);
898 if ($GLOBALS['cfgRelation']['designerwork']) {
899 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
900 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
901 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
902 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
903 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
904 PMA_query_as_controluser($table_query);
905 unset($table_query);
908 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
909 // end if ($move)
910 } else {
911 // we are copying
912 // Create new entries as duplicates from old PMA DBs
913 if ($what != 'dataonly' && ! isset($maintain_relations)) {
914 if ($GLOBALS['cfgRelation']['commwork']) {
915 // Get all comments and MIME-Types for current table
916 $comments_copy_query = 'SELECT
917 column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
918 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
919 WHERE
920 db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND
921 table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
922 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
924 // Write every comment as new copied entry. [MIME]
925 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
926 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
927 . ' (db_name, table_name, column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
928 . ' VALUES('
929 . '\'' . PMA_sqlAddSlashes($target_db) . '\','
930 . '\'' . PMA_sqlAddSlashes($target_table) . '\','
931 . '\'' . PMA_sqlAddSlashes($comments_copy_row['column_name']) . '\''
932 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddSlashes($comments_copy_row['comment']) . '\','
933 . '\'' . PMA_sqlAddSlashes($comments_copy_row['mimetype']) . '\','
934 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation']) . '\','
935 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
936 . ')';
937 PMA_query_as_controluser($new_comment_query);
938 } // end while
939 PMA_DBI_free_result($comments_copy_rs);
940 unset($comments_copy_rs);
943 // duplicating the bookmarks must not be done here, but
944 // just once per db
946 $get_fields = array('display_field');
947 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
948 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
949 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
953 * @todo revise this code when we support cross-db relations
955 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
956 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
957 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
958 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
961 $get_fields = array('foreign_field', 'master_table', 'master_field');
962 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
963 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
964 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
967 $get_fields = array('x', 'y', 'v', 'h');
968 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
969 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
970 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
973 * @todo Can't get duplicating PDFs the right way. The
974 * page numbers always get screwed up independently from
975 * duplication because the numbers do not seem to be stored on a
976 * per-database basis. Would the author of pdf support please
977 * have a look at it?
979 $get_fields = array('page_descr');
980 $where_fields = array('db_name' => $source_db);
981 $new_fields = array('db_name' => $target_db);
982 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
984 if (isset($last_id) && $last_id >= 0) {
985 $get_fields = array('x', 'y');
986 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
987 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
988 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
993 return true;
997 * checks if given name is a valid table name,
998 * currently if not empty, trailing spaces, '.', '/' and '\'
1000 * @todo add check for valid chars in filename on current system/os
1001 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
1002 * @param string $table_name name to check
1003 * @return boolean whether the string is valid or not
1005 function isValidName($table_name)
1007 if ($table_name !== trim($table_name)) {
1008 // trailing spaces
1009 return false;
1012 if (! strlen($table_name)) {
1013 // zero length
1014 return false;
1017 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
1018 // illegal char . / \
1019 return false;
1022 return true;
1026 * renames table
1028 * @param string $new_name new table name
1029 * @param string $new_db new database name
1030 * @param bool $is_view is this for a VIEW rename?
1031 * @return bool success
1033 function rename($new_name, $new_db = null, $is_view = false)
1035 if (null !== $new_db && $new_db !== $this->getDbName()) {
1036 // Ensure the target is valid
1037 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1038 $this->errors[] = __('Invalid database') . ': ' . $new_db;
1039 return false;
1041 } else {
1042 $new_db = $this->getDbName();
1045 $new_table = new PMA_Table($new_name, $new_db);
1047 if ($this->getFullName() === $new_table->getFullName()) {
1048 return true;
1051 if (! PMA_Table::isValidName($new_name)) {
1052 $this->errors[] = __('Invalid table name') . ': ' . $new_table->getFullName();
1053 return false;
1056 if (! $is_view) {
1057 $GLOBALS['sql_query'] = '
1058 RENAME TABLE ' . $this->getFullName(true) . '
1059 TO ' . $new_table->getFullName(true) . ';';
1060 } else {
1061 $GLOBALS['sql_query'] = '
1062 ALTER TABLE ' . $this->getFullName(true) . '
1063 RENAME ' . $new_table->getFullName(true) . ';';
1065 // I don't think a specific error message for views is necessary
1066 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1067 $this->errors[] = sprintf(__('Error renaming table %1$s to %2$s'), $this->getFullName(), $new_table->getFullName());
1068 return false;
1071 $old_name = $this->getName();
1072 $old_db = $this->getDbName();
1073 $this->setName($new_name);
1074 $this->setDbName($new_db);
1077 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1079 // Move old entries from comments to new table
1080 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1081 if ($GLOBALS['cfgRelation']['commwork']) {
1082 $remove_query = '
1083 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1084 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1085 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1086 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1087 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1088 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1089 PMA_query_as_controluser($remove_query);
1090 unset($remove_query);
1093 if ($GLOBALS['cfgRelation']['displaywork']) {
1094 $table_query = '
1095 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1096 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1097 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1098 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1099 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1100 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1101 PMA_query_as_controluser($table_query);
1102 unset($table_query);
1105 if ($GLOBALS['cfgRelation']['relwork']) {
1106 $table_query = '
1107 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1108 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1109 SET `foreign_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1110 `foreign_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1111 WHERE `foreign_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1112 AND `foreign_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1113 PMA_query_as_controluser($table_query);
1115 $table_query = '
1116 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1117 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1118 SET `master_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1119 `master_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1120 WHERE `master_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1121 AND `master_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1122 PMA_query_as_controluser($table_query);
1123 unset($table_query);
1126 if ($GLOBALS['cfgRelation']['pdfwork']) {
1127 $table_query = '
1128 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1129 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1130 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1131 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1132 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1133 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1134 PMA_query_as_controluser($table_query);
1135 unset($table_query);
1138 if ($GLOBALS['cfgRelation']['designerwork']) {
1139 $table_query = '
1140 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1141 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1142 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1143 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1144 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1145 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1146 PMA_query_as_controluser($table_query);
1147 unset($table_query);
1150 $this->messages[] = sprintf(__('Table %s has been renamed to %s'),
1151 htmlspecialchars($old_name), htmlspecialchars($new_name));
1152 return true;
1156 * Get all unique columns
1158 * returns an array with all columns with unqiue content, in fact these are
1159 * all columns being single indexed in PRIMARY or UNIQUE
1161 * e.g.
1162 * - PRIMARY(id) // id
1163 * - UNIQUE(name) // name
1164 * - PRIMARY(fk_id1, fk_id2) // NONE
1165 * - UNIQUE(x,y) // NONE
1168 * @param bool $backquoted whether to quote name with backticks ``
1169 * @return array
1171 public function getUniqueColumns($backquoted = true)
1173 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1174 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1176 $return = array();
1177 foreach ($uniques as $index) {
1178 if (count($index) > 1) {
1179 continue;
1181 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1184 return $return;
1188 * Get all indexed columns
1190 * returns an array with all columns make use of an index, in fact only
1191 * first columns in an index
1193 * e.g. index(col1, col2) would only return col1
1195 * @param bool $backquoted whether to quote name with backticks ``
1196 * @return array
1198 public function getIndexedColumns($backquoted = true)
1200 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1201 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1203 $return = array();
1204 foreach ($indexed as $column) {
1205 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1208 return $return;
1212 * Get all columns
1214 * returns an array with all columns
1216 * @param bool $backquoted whether to quote name with backticks ``
1217 * @return array
1219 public function getColumns($backquoted = true)
1221 $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
1222 $indexed = PMA_DBI_fetch_result($sql, 'Field', 'Field');
1224 $return = array();
1225 foreach ($indexed as $column) {
1226 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1229 return $return;
1233 * Return UI preferences for this table from phpMyAdmin database.
1236 * @return array
1238 protected function getUiPrefsFromDb()
1240 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1241 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1243 // Read from phpMyAdmin database
1244 $sql_query =
1245 " SELECT `prefs` FROM " . $pma_table .
1246 " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'" .
1247 " AND `db_name` = '" . PMA_sqlAddSlashes($this->db_name) . "'" .
1248 " AND `table_name` = '" . PMA_sqlAddSlashes($this->name) . "'";
1250 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
1251 if (isset($row[0])) {
1252 return json_decode($row[0], true);
1253 } else {
1254 return array();
1259 * Save this table's UI preferences into phpMyAdmin database.
1261 * @return true|PMA_Message
1263 protected function saveUiPrefsToDb()
1265 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1266 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1268 $username = $GLOBALS['cfg']['Server']['user'];
1269 $sql_query =
1270 " REPLACE INTO " . $pma_table .
1271 " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name) . "', '" .
1272 PMA_sqlAddSlashes($this->name) . "', '" .
1273 PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
1275 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1277 if (!$success) {
1278 $message = PMA_Message::error(__('Could not save table UI preferences'));
1279 $message->addMessage('<br /><br />');
1280 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1281 return $message;
1284 // Remove some old rows in table_uiprefs if it exceeds the configured maximum rows
1285 $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
1286 $rows_count = PMA_DBI_fetch_value($sql_query);
1287 $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
1288 if ($rows_count > $max_rows) {
1289 $num_rows_to_delete = $rows_count - $max_rows;
1290 $sql_query =
1291 ' DELETE FROM ' . $pma_table .
1292 ' ORDER BY last_update ASC' .
1293 ' LIMIT ' . $num_rows_to_delete;
1294 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1296 if (!$success) {
1297 $message = PMA_Message::error(sprintf(
1298 __('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
1299 PMA_showDocu('cfg_Servers_MaxTableUiprefs')
1301 $message->addMessage('<br /><br />');
1302 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1303 print_r($message);
1304 return $message;
1308 return true;
1312 * Loads the UI preferences for this table.
1313 * If pmadb and table_uiprefs is set, it will load the UI preferences from
1314 * phpMyAdmin database.
1317 protected function loadUiPrefs()
1319 $server_id = $GLOBALS['server'];
1320 // set session variable if it's still undefined
1321 if (! isset($_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name])) {
1322 $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name] =
1323 // check whether we can get from pmadb
1324 (strlen($GLOBALS['cfg']['Server']['pmadb'])
1325 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) ?
1326 $this->getUiPrefsFromDb() : array();
1328 $this->uiprefs =& $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name];
1332 * Get a property from UI preferences.
1333 * Return false if the property is not found.
1334 * Available property:
1335 * - PROP_SORTED_COLUMN
1336 * - PROP_COLUMN_ORDER
1337 * - PROP_COLUMN_VISIB
1340 * @param string $property
1341 * @return mixed
1343 public function getUiProp($property)
1345 if (! isset($this->uiprefs)) {
1346 $this->loadUiPrefs();
1348 // do checking based on property
1349 if ($property == self::PROP_SORTED_COLUMN) {
1350 if (isset($this->uiprefs[$property])) {
1351 // check if the column name is exist in this table
1352 $tmp = explode(' ', $this->uiprefs[$property]);
1353 $colname = $tmp[0];
1354 $avail_columns = $this->getColumns();
1355 foreach ($avail_columns as $each_col) {
1356 // check if $each_col ends with $colname
1357 if (substr_compare($each_col, $colname,
1358 strlen($each_col) - strlen($colname)) === 0) {
1359 return $this->uiprefs[$property];
1362 // remove the property, since it is not exist anymore in database
1363 $this->removeUiProp(self::PROP_SORTED_COLUMN);
1364 return false;
1365 } else {
1366 return false;
1368 } else if ($property == self::PROP_COLUMN_ORDER ||
1369 $property == self::PROP_COLUMN_VISIB) {
1370 if (! PMA_Table::isView($this->db_name, $this->name) && isset($this->uiprefs[$property])) {
1371 // check if the table has not been modified
1372 if (self::sGetStatusInfo($this->db_name, $this->name, 'Create_time') ==
1373 $this->uiprefs['CREATE_TIME']) {
1374 return $this->uiprefs[$property];
1375 } else {
1376 // remove the property, since the table has been modified
1377 $this->removeUiProp(self::PROP_COLUMN_ORDER);
1378 return false;
1380 } else {
1381 return false;
1384 // default behaviour for other property:
1385 return isset($this->uiprefs[$property]) ? $this->uiprefs[$property] : false;
1389 * Set a property from UI preferences.
1390 * If pmadb and table_uiprefs is set, it will save the UI preferences to
1391 * phpMyAdmin database.
1392 * Available property:
1393 * - PROP_SORTED_COLUMN
1394 * - PROP_COLUMN_ORDER
1395 * - PROP_COLUMN_VISIB
1397 * @param string $property
1398 * @param mixed $value
1399 * @param string $table_create_time Needed for PROP_COLUMN_ORDER and PROP_COLUMN_VISIB
1400 * @return boolean|PMA_Message
1402 public function setUiProp($property, $value, $table_create_time = null)
1404 if (! isset($this->uiprefs)) {
1405 $this->loadUiPrefs();
1407 // we want to save the create time if the property is PROP_COLUMN_ORDER
1408 if (! PMA_Table::isView($this->db_name, $this->name) && ($property == self::PROP_COLUMN_ORDER ||
1409 $property == self::PROP_COLUMN_VISIB)) {
1411 $curr_create_time = self::sGetStatusInfo($this->db_name, $this->name, 'CREATE_TIME');
1412 if (isset($table_create_time) &&
1413 $table_create_time == $curr_create_time) {
1414 $this->uiprefs['CREATE_TIME'] = $curr_create_time;
1415 } else {
1416 // there is no $table_create_time, or
1417 // supplied $table_create_time is older than current create time,
1418 // so don't save
1419 return false;
1422 // save the value
1423 $this->uiprefs[$property] = $value;
1424 // check if pmadb is set
1425 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1426 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) {
1427 return $this->saveUiprefsToDb();
1429 return true;
1433 * Remove a property from UI preferences.
1435 * @param string $property
1436 * @return true|PMA_Message
1438 public function removeUiProp($property)
1440 if (! isset($this->uiprefs)) {
1441 $this->loadUiPrefs();
1443 if (isset($this->uiprefs[$property])) {
1444 unset($this->uiprefs[$property]);
1445 // check if pmadb is set
1446 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1447 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])) {
1448 return $this->saveUiprefsToDb();
1451 return true;