added japanese language
[openemr.git] / phpmyadmin / libraries / Table.class.php
blob676127c913dff3b049be4736a48e3c8809e6350d
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Holds the PMA_Table class
6 * @package PhpMyAdmin
7 */
8 if (! defined('PHPMYADMIN')) {
9 exit;
12 /**
13 * Handles everything related to tables
15 * @todo make use of PMA_Message and PMA_Error
16 * @package PhpMyAdmin
18 class PMA_Table
20 /**
21 * UI preferences properties
23 const PROP_SORTED_COLUMN = 'sorted_col';
24 const PROP_COLUMN_ORDER = 'col_order';
25 const PROP_COLUMN_VISIB = 'col_visib';
27 static $cache = array();
29 /**
30 * @var string table name
32 var $name = '';
34 /**
35 * @var string database name
37 var $db_name = '';
39 /**
40 * @var string engine (innodb, myisam, bdb, ...)
42 var $engine = '';
44 /**
45 * @var string type (view, base table, system view)
47 var $type = '';
49 /**
50 * @var array settings
52 var $settings = array();
54 /**
55 * @var array UI preferences
57 var $uiprefs;
59 /**
60 * @var array errors occurred
62 var $errors = array();
64 /**
65 * @var array messages
67 var $messages = array();
69 /**
70 * Constructor
72 * @param string $table_name table name
73 * @param string $db_name database name
75 function __construct($table_name, $db_name)
77 $this->setName($table_name);
78 $this->setDbName($db_name);
81 /**
82 * returns table name
84 * @see PMA_Table::getName()
85 * @return string table name
87 function __toString()
89 return $this->getName();
92 /**
93 * return the last error
95 * @return string the last error
97 function getLastError()
99 return end($this->errors);
103 * return the last message
105 * @return string the last message
107 function getLastMessage()
109 return end($this->messages);
113 * sets table name
115 * @param string $table_name new table name
117 * @return void
119 function setName($table_name)
121 $this->name = $table_name;
125 * returns table name
127 * @param boolean $backquoted whether to quote name with backticks ``
129 * @return string table name
131 function getName($backquoted = false)
133 if ($backquoted) {
134 return PMA_Util::backquote($this->name);
136 return $this->name;
140 * sets database name for this table
142 * @param string $db_name database name
144 * @return void
146 function setDbName($db_name)
148 $this->db_name = $db_name;
152 * returns database name for this table
154 * @param boolean $backquoted whether to quote name with backticks ``
156 * @return string database name for this table
158 function getDbName($backquoted = false)
160 if ($backquoted) {
161 return PMA_Util::backquote($this->db_name);
163 return $this->db_name;
167 * returns full name for table, including database name
169 * @param boolean $backquoted whether to quote name with backticks ``
171 * @return string
173 function getFullName($backquoted = false)
175 return $this->getDbName($backquoted) . '.'
176 . $this->getName($backquoted);
180 * returns whether the table is actually a view
182 * @param string $db database
183 * @param string $table table
185 * @return boolean whether the given is a view
187 static public function isView($db = null, $table = null)
189 if (empty($db) || empty($table)) {
190 return false;
193 // use cached data or load information with SHOW command
194 if (isset(PMA_Table::$cache[$db][$table])
196 $type = PMA_Table::sGetStatusInfo($db, $table, 'TABLE_TYPE');
197 return $type == 'VIEW';
200 // query information_schema
201 $result = $GLOBALS['dbi']->fetchResult(
202 "SELECT TABLE_NAME
203 FROM information_schema.VIEWS
204 WHERE TABLE_SCHEMA = '" . PMA_Util::sqlAddSlashes($db) . "'
205 AND TABLE_NAME = '" . PMA_Util::sqlAddSlashes($table) . "'"
207 return $result ? true : false;
211 * Returns whether the table is actually an updatable view
213 * @param string $db database
214 * @param string $table table
216 * @return boolean whether the given is an updatable view
218 static public function isUpdatableView($db = null, $table = null)
220 if (empty($db) || empty($table)) {
221 return false;
224 $result = $GLOBALS['dbi']->fetchResult(
225 "SELECT TABLE_NAME
226 FROM information_schema.VIEWS
227 WHERE TABLE_SCHEMA = '" . PMA_Util::sqlAddSlashes($db) . "'
228 AND TABLE_NAME = '" . PMA_Util::sqlAddSlashes($table) . "'
229 AND IS_UPDATABLE = 'YES'"
231 return $result ? true : false;
235 * Returns the analysis of 'SHOW CREATE TABLE' query for the table.
236 * In case of a view, the values are taken from the information_schema.
238 * @param string $db database
239 * @param string $table table
241 * @return array analysis of 'SHOW CREATE TABLE' query for the table
243 static public function analyzeStructure($db = null, $table = null)
245 if (empty($db) || empty($table)) {
246 return false;
249 $analyzed_sql = array();
250 if (self::isView($db, $table)) {
251 // For a view, 'SHOW CREATE TABLE' returns the definition,
252 // but the structure of the view. So, we try to mock
253 // the result of analyzing 'SHOW CREATE TABLE' query.
254 $analyzed_sql[0] = array();
255 $analyzed_sql[0]['create_table_fields'] = array();
257 $results = $GLOBALS['dbi']->fetchResult(
258 "SELECT COLUMN_NAME, DATA_TYPE
259 FROM information_schema.COLUMNS
260 WHERE TABLE_SCHEMA = '" . PMA_Util::sqlAddSlashes($db) . "'
261 AND TABLE_NAME = '" . PMA_Util::sqlAddSlashes($table) . "'"
263 foreach ($results as $result) {
264 $analyzed_sql[0]['create_table_fields'][$result['COLUMN_NAME']]
265 = array('type' => strtoupper($result['DATA_TYPE']));
267 } else {
268 $show_create_table = $GLOBALS['dbi']->fetchValue(
269 'SHOW CREATE TABLE '
270 . PMA_Util::backquote($db)
271 . '.' . PMA_Util::backquote($table),
275 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
277 return $analyzed_sql;
281 * sets given $value for given $param
283 * @param string $param name
284 * @param mixed $value value
286 * @return void
288 function set($param, $value)
290 $this->settings[$param] = $value;
294 * returns value for given setting/param
296 * @param string $param name for value to return
298 * @return mixed value for $param
300 function get($param)
302 if (isset($this->settings[$param])) {
303 return $this->settings[$param];
306 return null;
310 * Checks if this is a merge table
312 * If the ENGINE of the table is MERGE or MRG_MYISAM (alias),
313 * this is a merge table.
315 * @param string $db the database name
316 * @param string $table the table name
318 * @return boolean true if it is a merge table
320 static public function isMerge($db = null, $table = null)
322 $engine = null;
323 // if called static, with parameters
324 if (! empty($db) && ! empty($table)) {
325 $engine = PMA_Table::sGetStatusInfo(
326 $db, $table, 'ENGINE', null, true
330 // did we get engine?
331 if (empty($engine)) {
332 return false;
335 // any of known merge engines?
336 return in_array(strtoupper($engine), array('MERGE', 'MRG_MYISAM'));
340 * Returns full table status info, or specific if $info provided
341 * this info is collected from information_schema
343 * @param string $db database name
344 * @param string $table table name
345 * @param string $info specific information to be fetched
346 * @param boolean $force_read read new rather than serving from cache
347 * @param boolean $disable_error if true, disables error message
349 * @todo DatabaseInterface::getTablesFull needs to be merged
350 * somehow into this class or at least better documented
352 * @return mixed
354 static public function sGetStatusInfo($db, $table, $info = null,
355 $force_read = false, $disable_error = false
357 if (! empty($_SESSION['is_multi_query'])) {
358 $disable_error = true;
361 // sometimes there is only one entry (ExactRows) so
362 // we have to get the table's details
363 if (! isset(PMA_Table::$cache[$db][$table])
364 || $force_read
365 || count(PMA_Table::$cache[$db][$table]) == 1
367 $GLOBALS['dbi']->getTablesFull($db, $table);
370 if (! isset(PMA_Table::$cache[$db][$table])) {
371 // happens when we enter the table creation dialog
372 // or when we really did not get any status info, for example
373 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
374 return '';
377 if (null === $info) {
378 return PMA_Table::$cache[$db][$table];
381 // array_key_exists allows for null values
382 if (!array_key_exists($info, PMA_Table::$cache[$db][$table])) {
383 if (! $disable_error) {
384 trigger_error(
385 __('Unknown table status:') . ' ' . $info,
386 E_USER_WARNING
389 return false;
392 return PMA_Table::$cache[$db][$table][$info];
396 * generates column specification for ALTER or CREATE TABLE syntax
398 * @param string $name name
399 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
400 * @param string $index index
401 * @param string $length length ('2', '5,2', '', ...)
402 * @param string $attribute attribute
403 * @param string $collation collation
404 * @param bool|string $null with 'NULL' or 'NOT NULL'
405 * @param string $default_type whether default is CURRENT_TIMESTAMP,
406 * NULL, NONE, USER_DEFINED
407 * @param string $default_value default value for USER_DEFINED
408 * default type
409 * @param string $extra 'AUTO_INCREMENT'
410 * @param string $comment field comment
411 * @param array &$field_primary list of fields for PRIMARY KEY
412 * @param string $move_to new position for column
414 * @todo move into class PMA_Column
415 * @todo on the interface, some js to clear the default value when the
416 * default current_timestamp is checked
418 * @return string field specification
420 static function generateFieldSpec($name, $type, $index, $length = '',
421 $attribute = '', $collation = '', $null = false,
422 $default_type = 'USER_DEFINED', $default_value = '', $extra = '',
423 $comment = '', &$field_primary = null, $move_to = ''
425 $is_timestamp = strpos(strtoupper($type), 'TIMESTAMP') !== false;
427 $query = PMA_Util::backquote($name) . ' ' . $type;
429 // allow the possibility of a length for TIME, DATETIME and TIMESTAMP
430 // (will work on MySQL >= 5.6.4)
432 // MySQL permits a non-standard syntax for FLOAT and DOUBLE,
433 // see http://dev.mysql.com/doc/refman/5.5/en/floating-point-types.html
435 if ($length != ''
436 && ! preg_match(
437 '@^(DATE|TINYBLOB|TINYTEXT|BLOB|TEXT|'
438 . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN|UUID)$@i',
439 $type
442 $query .= '(' . $length . ')';
445 if ($attribute != '') {
446 $query .= ' ' . $attribute;
449 $matches = preg_match(
450 '@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i',
451 $type
453 if (! empty($collation) && $collation != 'NULL' && $matches) {
454 $query .= PMA_generateCharsetQueryPart($collation);
457 if ($null !== false) {
458 if ($null == 'NULL') {
459 $query .= ' NULL';
460 } else {
461 $query .= ' NOT NULL';
465 switch ($default_type) {
466 case 'USER_DEFINED' :
467 if ($is_timestamp && $default_value === '0') {
468 // a TIMESTAMP does not accept DEFAULT '0'
469 // but DEFAULT 0 works
470 $query .= ' DEFAULT 0';
471 } elseif ($type == 'BIT') {
472 $query .= ' DEFAULT b\''
473 . preg_replace('/[^01]/', '0', $default_value)
474 . '\'';
475 } elseif ($type == 'BOOLEAN') {
476 if (preg_match('/^1|T|TRUE|YES$/i', $default_value)) {
477 $query .= ' DEFAULT TRUE';
478 } elseif (preg_match('/^0|F|FALSE|NO$/i', $default_value)) {
479 $query .= ' DEFAULT FALSE';
480 } else {
481 // Invalid BOOLEAN value
482 $query .= ' DEFAULT \''
483 . PMA_Util::sqlAddSlashes($default_value) . '\'';
485 } else {
486 $query .= ' DEFAULT \''
487 . PMA_Util::sqlAddSlashes($default_value) . '\'';
489 break;
490 case 'NULL' :
491 // If user uncheck null checkbox and not change default value null,
492 // default value will be ignored.
493 if ($null !== false && $null != 'NULL') {
494 break;
496 // otherwise, fall to next case (no break; here)
497 case 'CURRENT_TIMESTAMP' :
498 $query .= ' DEFAULT ' . $default_type;
499 break;
500 case 'NONE' :
501 default :
502 break;
505 if (!empty($extra)) {
506 $query .= ' ' . $extra;
507 // Force an auto_increment field to be part of the primary key
508 // even if user did not tick the PK box;
509 if ($extra == 'AUTO_INCREMENT') {
510 $primary_cnt = count($field_primary);
511 if (1 == $primary_cnt) {
512 for ($j = 0; $j < $primary_cnt; $j++) {
513 if ($field_primary[$j] == $index) {
514 break;
517 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
518 $query .= ' PRIMARY KEY';
519 unset($field_primary[$j]);
521 } else {
522 // but the PK could contain other columns so do not append
523 // a PRIMARY KEY clause, just add a member to $field_primary
524 $found_in_pk = false;
525 for ($j = 0; $j < $primary_cnt; $j++) {
526 if ($field_primary[$j] == $index) {
527 $found_in_pk = true;
528 break;
530 } // end for
531 if (! $found_in_pk) {
532 $field_primary[] = $index;
535 } // end if (auto_increment)
537 if (!empty($comment)) {
538 $query .= " COMMENT '" . PMA_Util::sqlAddSlashes($comment) . "'";
541 // move column
542 if ($move_to == '-first') { // dash can't appear as part of column name
543 $query .= ' FIRST';
544 } elseif ($move_to != '') {
545 $query .= ' AFTER ' . PMA_Util::backquote($move_to);
547 return $query;
548 } // end function
551 * Counts and returns (or displays) the number of records in a table
553 * @param string $db the current database name
554 * @param string $table the current table name
555 * @param bool $force_exact whether to force an exact count
556 * @param bool $is_view whether the table is a view
558 * @return mixed the number of records if "retain" param is true,
559 * otherwise true
561 static public function countRecords($db, $table, $force_exact = false,
562 $is_view = null
564 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
565 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
566 } else {
567 $row_count = false;
569 if (null === $is_view) {
570 $is_view = PMA_Table::isView($db, $table);
573 if (! $force_exact) {
574 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
575 $tmp_tables = $GLOBALS['dbi']->getTablesFull($db, $table);
576 if (isset($tmp_tables[$table])) {
577 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
580 if (isset(PMA_Table::$cache[$db][$table]['Rows'])) {
581 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
582 } else {
583 $row_count = false;
587 // for a VIEW, $row_count is always false at this point
588 if (false === $row_count
589 || $row_count < $GLOBALS['cfg']['MaxExactCount']
591 // Make an exception for views in I_S and D_D schema in
592 // Drizzle, as these map to in-memory data and should execute
593 // fast enough
594 if (! $is_view
595 || (PMA_DRIZZLE && $GLOBALS['dbi']->isSystemSchema($db))
597 $row_count = $GLOBALS['dbi']->fetchValue(
598 'SELECT COUNT(*) FROM ' . PMA_Util::backquote($db) . '.'
599 . PMA_Util::backquote($table)
601 } else {
602 // For complex views, even trying to get a partial record
603 // count could bring down a server, so we offer an
604 // alternative: setting MaxExactCountViews to 0 will bypass
605 // completely the record counting for views
607 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
608 $row_count = 0;
609 } else {
610 // Counting all rows of a VIEW could be too long,
611 // so use a LIMIT clause.
612 // Use try_query because it can fail (when a VIEW is
613 // based on a table that no longer exists)
614 $result = $GLOBALS['dbi']->tryQuery(
615 'SELECT 1 FROM ' . PMA_Util::backquote($db) . '.'
616 . PMA_Util::backquote($table) . ' LIMIT '
617 . $GLOBALS['cfg']['MaxExactCountViews'],
618 null,
619 PMA_DatabaseInterface::QUERY_STORE
621 if (!$GLOBALS['dbi']->getError()) {
622 $row_count = $GLOBALS['dbi']->numRows($result);
623 $GLOBALS['dbi']->freeResult($result);
627 if ($row_count) {
628 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
633 return $row_count;
634 } // end of the 'PMA_Table::countRecords()' function
637 * Generates column specification for ALTER syntax
639 * @param string $oldcol old column name
640 * @param string $newcol new column name
641 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
642 * @param string $length length ('2', '5,2', '', ...)
643 * @param string $attribute attribute
644 * @param string $collation collation
645 * @param bool|string $null with 'NULL' or 'NOT NULL'
646 * @param string $default_type whether default is CURRENT_TIMESTAMP,
647 * NULL, NONE, USER_DEFINED
648 * @param string $default_value default value for USER_DEFINED default
649 * type
650 * @param string $extra 'AUTO_INCREMENT'
651 * @param string $comment field comment
652 * @param array &$field_primary list of fields for PRIMARY KEY
653 * @param string $index index
654 * @param string $move_to new position for column
656 * @see PMA_Table::generateFieldSpec()
658 * @return string field specification
660 static public function generateAlter($oldcol, $newcol, $type, $length,
661 $attribute, $collation, $null, $default_type, $default_value,
662 $extra, $comment, &$field_primary, $index, $move_to
664 return PMA_Util::backquote($oldcol) . ' '
665 . PMA_Table::generateFieldSpec(
666 $newcol, $type, $index, $length, $attribute,
667 $collation, $null, $default_type, $default_value, $extra,
668 $comment, $field_primary, $move_to
670 } // end function
673 * Inserts existing entries in a PMA_* table by reading a value from an old
674 * entry
676 * @param string $work The array index, which Relation feature to
677 * check ('relwork', 'commwork', ...)
678 * @param string $pma_table The array index, which PMA-table to update
679 * ('bookmark', 'relation', ...)
680 * @param array $get_fields Which fields will be SELECT'ed from the old entry
681 * @param array $where_fields Which fields will be used for the WHERE query
682 * (array('FIELDNAME' => 'FIELDVALUE'))
683 * @param array $new_fields Which fields will be used as new VALUES.
684 * These are the important keys which differ
685 * from the old entry
686 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
688 * @global relation variable
690 * @return int|true
692 static public function duplicateInfo($work, $pma_table, $get_fields,
693 $where_fields, $new_fields
695 $last_id = -1;
697 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
698 $select_parts = array();
699 $row_fields = array();
700 foreach ($get_fields as $get_field) {
701 $select_parts[] = PMA_Util::backquote($get_field);
702 $row_fields[$get_field] = 'cc';
705 $where_parts = array();
706 foreach ($where_fields as $_where => $_value) {
707 $where_parts[] = PMA_Util::backquote($_where) . ' = \''
708 . PMA_Util::sqlAddSlashes($_value) . '\'';
711 $new_parts = array();
712 $new_value_parts = array();
713 foreach ($new_fields as $_where => $_value) {
714 $new_parts[] = PMA_Util::backquote($_where);
715 $new_value_parts[] = PMA_Util::sqlAddSlashes($_value);
718 $table_copy_query = '
719 SELECT ' . implode(', ', $select_parts) . '
720 FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
721 . PMA_Util::backquote($GLOBALS['cfgRelation'][$pma_table]) . '
722 WHERE ' . implode(' AND ', $where_parts);
724 // must use PMA_DatabaseInterface::QUERY_STORE here, since we execute
725 // another query inside the loop
726 $table_copy_rs = PMA_queryAsControlUser(
727 $table_copy_query, true, PMA_DatabaseInterface::QUERY_STORE
730 while ($table_copy_row = @$GLOBALS['dbi']->fetchAssoc($table_copy_rs)) {
731 $value_parts = array();
732 foreach ($table_copy_row as $_key => $_val) {
733 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
734 $value_parts[] = PMA_Util::sqlAddSlashes($_val);
738 $new_table_query = 'INSERT IGNORE INTO '
739 . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
740 . '.'
741 . PMA_Util::backquote($GLOBALS['cfgRelation'][$pma_table])
742 . ' (' . implode(', ', $select_parts)
743 . ', ' . implode(', ', $new_parts)
744 . ') VALUES (\''
745 . implode('\', \'', $value_parts) . '\', \''
746 . implode('\', \'', $new_value_parts) . '\')';
748 PMA_queryAsControlUser($new_table_query);
749 $last_id = $GLOBALS['dbi']->insertId();
750 } // end while
752 $GLOBALS['dbi']->freeResult($table_copy_rs);
754 return $last_id;
757 return true;
758 } // end of 'PMA_Table::duplicateInfo()' function
761 * Copies or renames table
763 * @param string $source_db source database
764 * @param string $source_table source table
765 * @param string $target_db target database
766 * @param string $target_table target table
767 * @param string $what what to be moved or copied (data, dataonly)
768 * @param bool $move whether to move
769 * @param string $mode mode
771 * @return bool true if success, false otherwise
773 static public function moveCopy($source_db, $source_table, $target_db,
774 $target_table, $what, $move, $mode
776 global $err_url;
778 /* Try moving table directly */
779 if ($move && $what == 'data') {
780 $tbl = new PMA_Table($source_table, $source_db);
781 $result = $tbl->rename($target_table, $target_db);
782 if ($result) {
783 $GLOBALS['message'] = $tbl->getLastMessage();
784 return true;
788 // set export settings we need
789 $GLOBALS['sql_backquotes'] = 1;
790 $GLOBALS['asfile'] = 1;
792 // Ensure the target is valid
793 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
794 if (! $GLOBALS['pma']->databases->exists($source_db)) {
795 $GLOBALS['message'] = PMA_Message::rawError(
796 sprintf(
797 __('Source database `%s` was not found!'),
798 htmlspecialchars($source_db)
802 if (! $GLOBALS['pma']->databases->exists($target_db)) {
803 $GLOBALS['message'] = PMA_Message::rawError(
804 sprintf(
805 __('Target database `%s` was not found!'),
806 htmlspecialchars($target_db)
810 return false;
813 $source = PMA_Util::backquote($source_db)
814 . '.' . PMA_Util::backquote($source_table);
815 if (! isset($target_db) || ! strlen($target_db)) {
816 $target_db = $source_db;
819 // Doing a select_db could avoid some problems with replicated databases,
820 // when moving table from replicated one to not replicated one
821 $GLOBALS['dbi']->selectDb($target_db);
823 $target = PMA_Util::backquote($target_db)
824 . '.' . PMA_Util::backquote($target_table);
826 // do not create the table if dataonly
827 if ($what != 'dataonly') {
828 include_once "libraries/plugin_interface.lib.php";
829 // get Export SQL instance
830 $export_sql_plugin = PMA_getPlugin(
831 "export",
832 "sql",
833 'libraries/plugins/export/',
834 array(
835 'export_type' => 'table',
836 'single_table' => false,
840 $no_constraints_comments = true;
841 $GLOBALS['sql_constraints_query'] = '';
842 // set the value of global sql_auto_increment variable
843 if (isset($_POST['sql_auto_increment'])) {
844 $GLOBALS['sql_auto_increment'] = $_POST['sql_auto_increment'];
847 $sql_structure = $export_sql_plugin->getTableDef(
848 $source_db, $source_table, "\n", $err_url, false, false
850 unset($no_constraints_comments);
851 $parsed_sql = PMA_SQP_parse($sql_structure);
852 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
853 $i = 0;
854 if (empty($analyzed_sql[0]['create_table_fields'])) {
855 // this is not a CREATE TABLE, so find the first VIEW
856 $target_for_view = PMA_Util::backquote($target_db);
857 while (true) {
858 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord'
859 && $parsed_sql[$i]['data'] == 'VIEW'
861 break;
863 $i++;
866 unset($analyzed_sql);
867 if (PMA_DRIZZLE) {
868 $table_delimiter = 'quote_backtick';
869 } else {
870 $server_sql_mode = $GLOBALS['dbi']->fetchValue(
871 "SHOW VARIABLES LIKE 'sql_mode'",
875 // ANSI_QUOTES might be a subset of sql_mode, for example
876 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
877 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
878 $table_delimiter = 'quote_double';
879 } else {
880 $table_delimiter = 'quote_backtick';
882 unset($server_sql_mode);
885 /* Find table name in query and replace it */
886 while ($parsed_sql[$i]['type'] != $table_delimiter) {
887 $i++;
890 /* no need to backquote() */
891 if (isset($target_for_view)) {
892 // this a view definition; we just found the first db name
893 // that follows DEFINER VIEW
894 // so change it for the new db name
895 $parsed_sql[$i]['data'] = $target_for_view;
896 // then we have to find all references to the source db
897 // and change them to the target db, ensuring we stay into
898 // the $parsed_sql limits
899 $last = $parsed_sql['len'] - 1;
900 $backquoted_source_db = PMA_Util::backquote($source_db);
901 for (++$i; $i <= $last; $i++) {
902 if ($parsed_sql[$i]['type'] == $table_delimiter
903 && $parsed_sql[$i]['data'] == $backquoted_source_db
904 && $parsed_sql[$i - 1]['type'] != 'punct_qualifier'
906 $parsed_sql[$i]['data'] = $target_for_view;
909 unset($last,$backquoted_source_db);
910 } else {
911 $parsed_sql[$i]['data'] = $target;
914 /* Generate query back */
915 $sql_structure = PMA_SQP_format($parsed_sql, 'query_only');
916 // If table exists, and 'add drop table' is selected: Drop it!
917 $drop_query = '';
918 if (isset($_REQUEST['drop_if_exists'])
919 && $_REQUEST['drop_if_exists'] == 'true'
921 if (PMA_Table::isView($target_db, $target_table)) {
922 $drop_query = 'DROP VIEW';
923 } else {
924 $drop_query = 'DROP TABLE';
926 $drop_query .= ' IF EXISTS '
927 . PMA_Util::backquote($target_db) . '.'
928 . PMA_Util::backquote($target_table);
929 $GLOBALS['dbi']->query($drop_query);
931 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
933 // If an existing table gets deleted, maintain any
934 // entries for the PMA_* tables
935 $maintain_relations = true;
938 @$GLOBALS['dbi']->query($sql_structure);
939 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
941 if (($move || isset($GLOBALS['add_constraints']))
942 && !empty($GLOBALS['sql_constraints_query'])
944 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
945 $i = 0;
947 // find the first $table_delimiter, it must be the source
948 // table name
949 while ($parsed_sql[$i]['type'] != $table_delimiter) {
950 $i++;
951 // maybe someday we should guard against going over limit
952 //if ($i == $parsed_sql['len']) {
953 // break;
957 // replace it by the target table name, no need
958 // to backquote()
959 $parsed_sql[$i]['data'] = $target;
961 // now we must remove all $table_delimiter that follow a
962 // CONSTRAINT keyword, because a constraint name must be
963 // unique in a db
965 $cnt = $parsed_sql['len'] - 1;
967 for ($j = $i; $j < $cnt; $j++) {
968 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
969 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT'
971 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
972 $parsed_sql[$j+1]['data'] = '';
977 // Generate query back
978 $GLOBALS['sql_constraints_query'] = PMA_SQP_format(
979 $parsed_sql, 'query_only'
981 if ($mode == 'one_table') {
982 $GLOBALS['dbi']->query($GLOBALS['sql_constraints_query']);
984 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
985 if ($mode == 'one_table') {
986 unset($GLOBALS['sql_constraints_query']);
990 // add indexes to the table
991 if (!empty($GLOBALS['sql_indexes'])) {
992 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_indexes']);
993 $i = 0;
995 while ($parsed_sql[$i]['type'] != $table_delimiter) {
996 $i++;
999 $parsed_sql[$i]['data'] = $target;
1001 $cnt = $parsed_sql['len'] - 1;
1003 for ($j = $i; $j < $cnt; $j++) {
1004 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
1005 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT'
1007 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
1008 $parsed_sql[$j+1]['data'] = '';
1012 $GLOBALS['sql_indexes'] = PMA_SQP_format(
1013 $parsed_sql, 'query_only'
1015 if ($mode == 'one_table' || $mode == 'db_copy') {
1016 $GLOBALS['dbi']->query($GLOBALS['sql_indexes']);
1018 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_indexes'];
1019 if ($mode == 'one_table' || $mode == 'db_copy') {
1020 unset($GLOBALS['sql_indexes']);
1026 * add AUTO_INCREMENT to the table
1028 * @todo refactor with similar code above
1030 if (! empty($GLOBALS['sql_auto_increments'])) {
1031 if ($mode == 'one_table' || $mode == 'db_copy') {
1032 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_auto_increments']);
1033 $i = 0;
1035 // find the first $table_delimiter, it must be the source
1036 // table name
1037 while ($parsed_sql[$i]['type'] != $table_delimiter) {
1038 $i++;
1041 // replace it by the target table name, no need
1042 // to backquote()
1043 $parsed_sql[$i]['data'] = $target;
1045 // Generate query back
1046 $GLOBALS['sql_auto_increments'] = PMA_SQP_format(
1047 $parsed_sql, 'query_only'
1049 $GLOBALS['dbi']->query($GLOBALS['sql_auto_increments']);
1050 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_auto_increments'];
1051 unset($GLOBALS['sql_auto_increments']);
1055 } else {
1056 $GLOBALS['sql_query'] = '';
1059 // Copy the data unless this is a VIEW
1060 if (($what == 'data' || $what == 'dataonly')
1061 && ! PMA_Table::isView($target_db, $target_table)
1063 $sql_set_mode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'";
1064 $GLOBALS['dbi']->query($sql_set_mode);
1065 $GLOBALS['sql_query'] .= "\n\n" . $sql_set_mode . ';';
1067 $sql_insert_data = 'INSERT INTO ' . $target
1068 . ' SELECT * FROM ' . $source;
1069 $GLOBALS['dbi']->query($sql_insert_data);
1070 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
1073 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1075 // Drops old table if the user has requested to move it
1076 if ($move) {
1078 // This could avoid some problems with replicated databases, when
1079 // moving table from replicated one to not replicated one
1080 $GLOBALS['dbi']->selectDb($source_db);
1082 if (PMA_Table::isView($source_db, $source_table)) {
1083 $sql_drop_query = 'DROP VIEW';
1084 } else {
1085 $sql_drop_query = 'DROP TABLE';
1087 $sql_drop_query .= ' ' . $source;
1088 $GLOBALS['dbi']->query($sql_drop_query);
1090 // Renable table in configuration storage
1091 PMA_REL_renameTable(
1092 $source_db, $target_db,
1093 $source_table, $target_table
1096 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
1097 // end if ($move)
1098 } else {
1099 // we are copying
1100 // Create new entries as duplicates from old PMA DBs
1101 if ($what != 'dataonly' && ! isset($maintain_relations)) {
1102 if ($GLOBALS['cfgRelation']['commwork']) {
1103 // Get all comments and MIME-Types for current table
1104 $comments_copy_rs = PMA_queryAsControlUser(
1105 'SELECT column_name, comment'
1106 . ($GLOBALS['cfgRelation']['mimework']
1107 ? ', mimetype, transformation, transformation_options'
1108 : '')
1109 . ' FROM '
1110 . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
1111 . '.'
1112 . PMA_Util::backquote($GLOBALS['cfgRelation']['column_info'])
1113 . ' WHERE '
1114 . ' db_name = \''
1115 . PMA_Util::sqlAddSlashes($source_db) . '\''
1116 . ' AND '
1117 . ' table_name = \''
1118 . PMA_Util::sqlAddSlashes($source_table) . '\''
1121 // Write every comment as new copied entry. [MIME]
1122 while ($comments_copy_row
1123 = $GLOBALS['dbi']->fetchAssoc($comments_copy_rs)) {
1124 $new_comment_query = 'REPLACE INTO '
1125 . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
1126 . '.'
1127 . PMA_Util::backquote(
1128 $GLOBALS['cfgRelation']['column_info']
1130 . ' (db_name, table_name, column_name, comment'
1131 . ($GLOBALS['cfgRelation']['mimework']
1132 ? ', mimetype, transformation, transformation_options'
1133 : '')
1134 . ') '
1135 . ' VALUES('
1136 . '\'' . PMA_Util::sqlAddSlashes($target_db)
1137 . '\','
1138 . '\'' . PMA_Util::sqlAddSlashes($target_table)
1139 . '\','
1140 . '\''
1141 . PMA_Util::sqlAddSlashes(
1142 $comments_copy_row['column_name']
1144 . '\''
1145 . ($GLOBALS['cfgRelation']['mimework']
1146 ? ',\'' . PMA_Util::sqlAddSlashes($comments_copy_row['comment']) . '\','
1147 . '\'' . PMA_Util::sqlAddSlashes($comments_copy_row['mimetype']) . '\','
1148 . '\'' . PMA_Util::sqlAddSlashes($comments_copy_row['transformation']) . '\','
1149 . '\'' . PMA_Util::sqlAddSlashes($comments_copy_row['transformation_options']) . '\''
1150 : '')
1151 . ')';
1152 PMA_queryAsControlUser($new_comment_query);
1153 } // end while
1154 $GLOBALS['dbi']->freeResult($comments_copy_rs);
1155 unset($comments_copy_rs);
1158 // duplicating the bookmarks must not be done here, but
1159 // just once per db
1161 $get_fields = array('display_field');
1162 $where_fields = array(
1163 'db_name' => $source_db,
1164 'table_name' => $source_table
1166 $new_fields = array(
1167 'db_name' => $target_db,
1168 'table_name' => $target_table
1170 PMA_Table::duplicateInfo(
1171 'displaywork',
1172 'table_info',
1173 $get_fields,
1174 $where_fields,
1175 $new_fields
1180 * @todo revise this code when we support cross-db relations
1182 $get_fields = array(
1183 'master_field',
1184 'foreign_table',
1185 'foreign_field'
1187 $where_fields = array(
1188 'master_db' => $source_db,
1189 'master_table' => $source_table
1191 $new_fields = array(
1192 'master_db' => $target_db,
1193 'foreign_db' => $target_db,
1194 'master_table' => $target_table
1196 PMA_Table::duplicateInfo(
1197 'relwork',
1198 'relation',
1199 $get_fields,
1200 $where_fields,
1201 $new_fields
1205 $get_fields = array(
1206 'foreign_field',
1207 'master_table',
1208 'master_field'
1210 $where_fields = array(
1211 'foreign_db' => $source_db,
1212 'foreign_table' => $source_table
1214 $new_fields = array(
1215 'master_db' => $target_db,
1216 'foreign_db' => $target_db,
1217 'foreign_table' => $target_table
1219 PMA_Table::duplicateInfo(
1220 'relwork',
1221 'relation',
1222 $get_fields,
1223 $where_fields,
1224 $new_fields
1228 $get_fields = array('x', 'y', 'v', 'h');
1229 $where_fields = array(
1230 'db_name' => $source_db,
1231 'table_name' => $source_table
1233 $new_fields = array(
1234 'db_name' => $target_db,
1235 'table_name' => $target_table
1237 PMA_Table::duplicateInfo(
1238 'designerwork',
1239 'designer_coords',
1240 $get_fields,
1241 $where_fields,
1242 $new_fields
1246 * @todo Can't get duplicating PDFs the right way. The
1247 * page numbers always get screwed up independently from
1248 * duplication because the numbers do not seem to be stored on a
1249 * per-database basis. Would the author of pdf support please
1250 * have a look at it?
1252 $get_fields = array('page_descr');
1253 $where_fields = array('db_name' => $source_db);
1254 $new_fields = array('db_name' => $target_db);
1255 $last_id = PMA_Table::duplicateInfo(
1256 'pdfwork',
1257 'pdf_pages',
1258 $get_fields,
1259 $where_fields,
1260 $new_fields
1263 if (isset($last_id) && $last_id >= 0) {
1264 $get_fields = array('x', 'y');
1265 $where_fields = array(
1266 'db_name' => $source_db,
1267 'table_name' => $source_table
1269 $new_fields = array(
1270 'db_name' => $target_db,
1271 'table_name' => $target_table,
1272 'pdf_page_number' => $last_id
1274 PMA_Table::duplicateInfo(
1275 'pdfwork',
1276 'table_coords',
1277 $get_fields,
1278 $where_fields,
1279 $new_fields
1285 return true;
1289 * checks if given name is a valid table name,
1290 * currently if not empty, trailing spaces, '.', '/' and '\'
1292 * @param string $table_name name to check
1294 * @todo add check for valid chars in filename on current system/os
1295 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
1297 * @return boolean whether the string is valid or not
1299 static function isValidName($table_name)
1301 if ($table_name !== trim($table_name)) {
1302 // trailing spaces
1303 return false;
1306 if (! strlen($table_name)) {
1307 // zero length
1308 return false;
1311 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
1312 // illegal char . / \
1313 return false;
1316 return true;
1320 * renames table
1322 * @param string $new_name new table name
1323 * @param string $new_db new database name
1325 * @return bool success
1327 function rename($new_name, $new_db = null)
1329 if (null !== $new_db && $new_db !== $this->getDbName()) {
1330 // Ensure the target is valid
1331 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1332 $this->errors[] = __('Invalid database:') . ' ' . $new_db;
1333 return false;
1335 } else {
1336 $new_db = $this->getDbName();
1339 $new_table = new PMA_Table($new_name, $new_db);
1341 if ($this->getFullName() === $new_table->getFullName()) {
1342 return true;
1345 if (! PMA_Table::isValidName($new_name)) {
1346 $this->errors[] = __('Invalid table name:') . ' '
1347 . $new_table->getFullName();
1348 return false;
1351 // If the table is moved to a different database drop its triggers first
1352 $triggers = $GLOBALS['dbi']->getTriggers(
1353 $this->getDbName(), $this->getName(), ''
1355 $handle_triggers = $this->getDbName() != $new_db && $triggers;
1356 if ($handle_triggers) {
1357 foreach ($triggers as $trigger) {
1358 $sql = 'DROP TRIGGER IF EXISTS '
1359 . PMA_Util::backquote($this->getDbName())
1360 . '.' . PMA_Util::backquote($trigger['name']) . ';';
1361 $GLOBALS['dbi']->query($sql);
1366 * tested also for a view, in MySQL 5.0.92, 5.1.55 and 5.5.13
1368 $GLOBALS['sql_query'] = '
1369 RENAME TABLE ' . $this->getFullName(true) . '
1370 TO ' . $new_table->getFullName(true) . ';';
1371 // I don't think a specific error message for views is necessary
1372 if (! $GLOBALS['dbi']->query($GLOBALS['sql_query'])) {
1373 // Restore triggers in the old database
1374 if ($handle_triggers) {
1375 $GLOBALS['dbi']->selectDb($this->getDbName());
1376 foreach ($triggers as $trigger) {
1377 $GLOBALS['dbi']->query($trigger['create']);
1380 $this->errors[] = sprintf(
1381 __('Failed to rename table %1$s to %2$s!'),
1382 $this->getFullName(),
1383 $new_table->getFullName()
1385 return false;
1388 $old_name = $this->getName();
1389 $old_db = $this->getDbName();
1390 $this->setName($new_name);
1391 $this->setDbName($new_db);
1393 // Renable table in configuration storage
1394 PMA_REL_renameTable(
1395 $old_db, $new_db,
1396 $old_name, $new_name
1399 $this->messages[] = sprintf(
1400 __('Table %1$s has been renamed to %2$s.'),
1401 htmlspecialchars($old_name),
1402 htmlspecialchars($new_name)
1404 return true;
1408 * Get all unique columns
1410 * returns an array with all columns with unqiue content, in fact these are
1411 * all columns being single indexed in PRIMARY or UNIQUE
1413 * e.g.
1414 * - PRIMARY(id) // id
1415 * - UNIQUE(name) // name
1416 * - PRIMARY(fk_id1, fk_id2) // NONE
1417 * - UNIQUE(x,y) // NONE
1419 * @param bool $backquoted whether to quote name with backticks ``
1420 * @param bool $fullName whether to include full name of the table as a prefix
1422 * @return array
1424 public function getUniqueColumns($backquoted = true, $fullName = true)
1426 $sql = $GLOBALS['dbi']->getTableIndexesSql(
1427 $this->getDbName(),
1428 $this->getName(),
1429 'Non_unique = 0'
1431 $uniques = $GLOBALS['dbi']->fetchResult(
1432 $sql,
1433 array('Key_name', null),
1434 'Column_name'
1437 $return = array();
1438 foreach ($uniques as $index) {
1439 if (count($index) > 1) {
1440 continue;
1442 $return[] = ($fullName ? $this->getFullName($backquoted) . '.' : '')
1443 . ($backquoted ? PMA_Util::backquote($index[0]) : $index[0]);
1446 return $return;
1450 * Get all indexed columns
1452 * returns an array with all columns make use of an index, in fact only
1453 * first columns in an index
1455 * e.g. index(col1, col2) would only return col1
1457 * @param bool $backquoted whether to quote name with backticks ``
1459 * @return array
1461 public function getIndexedColumns($backquoted = true)
1463 $sql = $GLOBALS['dbi']->getTableIndexesSql(
1464 $this->getDbName(),
1465 $this->getName(),
1466 'Seq_in_index = 1'
1468 $indexed = $GLOBALS['dbi']->fetchResult($sql, 'Column_name', 'Column_name');
1470 $return = array();
1471 foreach ($indexed as $column) {
1472 $return[] = $this->getFullName($backquoted) . '.'
1473 . ($backquoted ? PMA_Util::backquote($column) : $column);
1476 return $return;
1480 * Get all columns
1482 * returns an array with all columns
1484 * @param bool $backquoted whether to quote name with backticks ``
1486 * @return array
1488 public function getColumns($backquoted = true)
1490 $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
1491 $indexed = $GLOBALS['dbi']->fetchResult($sql, 'Field', 'Field');
1493 $return = array();
1494 foreach ($indexed as $column) {
1495 $return[] = $this->getFullName($backquoted) . '.'
1496 . ($backquoted ? PMA_Util::backquote($column) : $column);
1499 return $return;
1503 * Return UI preferences for this table from phpMyAdmin database.
1505 * @return array
1507 protected function getUiPrefsFromDb()
1509 $pma_table = PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
1510 . PMA_Util::backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1512 // Read from phpMyAdmin database
1513 $sql_query = " SELECT `prefs` FROM " . $pma_table
1514 . " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'"
1515 . " AND `db_name` = '" . PMA_Util::sqlAddSlashes($this->db_name) . "'"
1516 . " AND `table_name` = '" . PMA_Util::sqlAddSlashes($this->name) . "'";
1518 $row = $GLOBALS['dbi']->fetchArray(PMA_queryAsControlUser($sql_query));
1519 if (isset($row[0])) {
1520 return json_decode($row[0], true);
1521 } else {
1522 return array();
1527 * Save this table's UI preferences into phpMyAdmin database.
1529 * @return true|PMA_Message
1531 protected function saveUiPrefsToDb()
1533 $pma_table = PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
1534 . PMA_Util::backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1536 $secureDbName = PMA_Util::sqlAddSlashes($this->db_name);
1538 $username = $GLOBALS['cfg']['Server']['user'];
1539 $sql_query = " REPLACE INTO " . $pma_table
1540 . " VALUES ('" . $username . "', '" . $secureDbName
1541 . "', '" . PMA_Util::sqlAddSlashes($this->name) . "', '"
1542 . PMA_Util::sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
1544 $success = $GLOBALS['dbi']->tryQuery($sql_query, $GLOBALS['controllink']);
1546 if (!$success) {
1547 $message = PMA_Message::error(
1548 __('Could not save table UI preferences!')
1550 $message->addMessage('<br /><br />');
1551 $message->addMessage(
1552 PMA_Message::rawError(
1553 $GLOBALS['dbi']->getError($GLOBALS['controllink'])
1556 return $message;
1559 // Remove some old rows in table_uiprefs if it exceeds the configured
1560 // maximum rows
1561 $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
1562 $rows_count = $GLOBALS['dbi']->fetchValue($sql_query);
1563 $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
1564 if ($rows_count > $max_rows) {
1565 $num_rows_to_delete = $rows_count - $max_rows;
1566 $sql_query
1567 = ' DELETE FROM ' . $pma_table .
1568 ' ORDER BY last_update ASC' .
1569 ' LIMIT ' . $num_rows_to_delete;
1570 $success = $GLOBALS['dbi']->tryQuery(
1571 $sql_query, $GLOBALS['controllink']
1574 if (!$success) {
1575 $message = PMA_Message::error(
1576 sprintf(
1577 __('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
1578 PMA_Util::showDocu('config', 'cfg_Servers_MaxTableUiprefs')
1581 $message->addMessage('<br /><br />');
1582 $message->addMessage(
1583 PMA_Message::rawError(
1584 $GLOBALS['dbi']->getError($GLOBALS['controllink'])
1587 print_r($message);
1588 return $message;
1592 return true;
1596 * Loads the UI preferences for this table.
1597 * If pmadb and table_uiprefs is set, it will load the UI preferences from
1598 * phpMyAdmin database.
1600 * @return void
1602 protected function loadUiPrefs()
1604 $server_id = $GLOBALS['server'];
1605 // set session variable if it's still undefined
1606 if (! isset($_SESSION['tmpval']['table_uiprefs'][$server_id][$this->db_name][$this->name])) {
1607 // check whether we can get from pmadb
1608 $_SESSION['tmpval']['table_uiprefs'][$server_id][$this->db_name]
1609 [$this->name]
1610 = (strlen($GLOBALS['cfg']['Server']['pmadb'])
1611 && strlen($GLOBALS['cfg']['Server']['table_uiprefs']))
1612 ? $this->getUiPrefsFromDb()
1613 : array();
1615 $this->uiprefs =& $_SESSION['tmpval']['table_uiprefs'][$server_id]
1616 [$this->db_name][$this->name];
1620 * Get a property from UI preferences.
1621 * Return false if the property is not found.
1622 * Available property:
1623 * - PROP_SORTED_COLUMN
1624 * - PROP_COLUMN_ORDER
1625 * - PROP_COLUMN_VISIB
1627 * @param string $property property
1629 * @return mixed
1631 public function getUiProp($property)
1633 if (! isset($this->uiprefs)) {
1634 $this->loadUiPrefs();
1636 // do checking based on property
1637 if ($property == self::PROP_SORTED_COLUMN) {
1638 if (isset($this->uiprefs[$property])) {
1639 if (isset($_REQUEST['discard_remembered_sort'])) {
1640 $this->removeUiProp(self::PROP_SORTED_COLUMN);
1642 // check if the column name exists in this table
1643 $tmp = explode(' ', $this->uiprefs[$property]);
1644 $colname = $tmp[0];
1645 //remove backquoting from colname
1646 $colname = str_replace('`', '', $colname);
1647 //get the available column name without backquoting
1648 $avail_columns = $this->getColumns(false);
1649 foreach ($avail_columns as $each_col) {
1650 // check if $each_col ends with $colname
1651 if (substr_compare(
1652 $each_col,
1653 $colname,
1654 strlen($each_col) - strlen($colname)
1655 ) === 0) {
1656 return $this->uiprefs[$property];
1659 // remove the property, since it is not exist anymore in database
1660 $this->removeUiProp(self::PROP_SORTED_COLUMN);
1661 return false;
1662 } else {
1663 return false;
1665 } elseif ($property == self::PROP_COLUMN_ORDER
1666 || $property == self::PROP_COLUMN_VISIB
1668 if (! PMA_Table::isView($this->db_name, $this->name)
1669 && isset($this->uiprefs[$property])
1671 // check if the table has not been modified
1672 if (self::sGetStatusInfo(
1673 $this->db_name,
1674 $this->name, 'Create_time'
1675 ) == $this->uiprefs['CREATE_TIME']) {
1676 return $this->uiprefs[$property];
1677 } else {
1678 // remove the property, since the table has been modified
1679 $this->removeUiProp(self::PROP_COLUMN_ORDER);
1680 return false;
1682 } else {
1683 return false;
1686 // default behaviour for other property:
1687 return isset($this->uiprefs[$property]) ? $this->uiprefs[$property] : false;
1691 * Set a property from UI preferences.
1692 * If pmadb and table_uiprefs is set, it will save the UI preferences to
1693 * phpMyAdmin database.
1694 * Available property:
1695 * - PROP_SORTED_COLUMN
1696 * - PROP_COLUMN_ORDER
1697 * - PROP_COLUMN_VISIB
1699 * @param string $property Property
1700 * @param mixed $value Value for the property
1701 * @param string $table_create_time Needed for PROP_COLUMN_ORDER
1702 * and PROP_COLUMN_VISIB
1704 * @return boolean|PMA_Message
1706 public function setUiProp($property, $value, $table_create_time = null)
1708 if (! isset($this->uiprefs)) {
1709 $this->loadUiPrefs();
1711 // we want to save the create time if the property is PROP_COLUMN_ORDER
1712 if (! PMA_Table::isView($this->db_name, $this->name)
1713 && ($property == self::PROP_COLUMN_ORDER
1714 || $property == self::PROP_COLUMN_VISIB)
1716 $curr_create_time = self::sGetStatusInfo(
1717 $this->db_name,
1718 $this->name,
1719 'CREATE_TIME'
1721 if (isset($table_create_time)
1722 && $table_create_time == $curr_create_time
1724 $this->uiprefs['CREATE_TIME'] = $curr_create_time;
1725 } else {
1726 // there is no $table_create_time, or
1727 // supplied $table_create_time is older than current create time,
1728 // so don't save
1729 return PMA_Message::error(
1730 sprintf(
1731 __('Cannot save UI property "%s". The changes made will not be persistent after you refresh this page. Please check if the table structure has been changed.'),
1732 $property
1737 // save the value
1738 $this->uiprefs[$property] = $value;
1739 // check if pmadb is set
1740 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1741 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1743 return $this->saveUiprefsToDb();
1745 return true;
1749 * Remove a property from UI preferences.
1751 * @param string $property the property
1753 * @return true|PMA_Message
1755 public function removeUiProp($property)
1757 if (! isset($this->uiprefs)) {
1758 $this->loadUiPrefs();
1760 if (isset($this->uiprefs[$property])) {
1761 unset($this->uiprefs[$property]);
1762 // check if pmadb is set
1763 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1764 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1766 return $this->saveUiprefsToDb();
1769 return true;
1773 * Get all column names which are MySQL reserved words
1775 * @return array
1776 * @access public
1778 public function getReservedColumnNames()
1780 $columns = $this->getColumns(false);
1781 $return = array();
1782 foreach ($columns as $column) {
1783 $temp = explode('.', $column);
1784 $column_name = $temp[2];
1785 if (PMA_SQP_isKeyWord($column_name)) {
1786 $return[] = $column_name;
1789 return $return;