Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / DatabaseInterface.php
blob7823c0366872a3f11d3730a42d4116c3fc2fb83e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Main interface for database interactions
6 * @package PhpMyAdmin-DBI
7 */
8 namespace PMA\libraries;
10 use PMA\libraries\dbi\DBIExtension;
11 use PMA\libraries\LanguageManager;
12 use PMA\libraries\URL;
13 use PMA\libraries\Logging;
15 require_once './libraries/util.lib.php';
17 /**
18 * Main interface for database interactions
20 * @package PhpMyAdmin-DBI
22 class DatabaseInterface
24 /**
25 * Force STORE_RESULT method, ignored by classic MySQL.
27 const QUERY_STORE = 1;
28 /**
29 * Do not read whole query.
31 const QUERY_UNBUFFERED = 2;
32 /**
33 * Get session variable.
35 const GETVAR_SESSION = 1;
36 /**
37 * Get global variable.
39 const GETVAR_GLOBAL = 2;
41 /**
42 * User connection.
44 const CONNECT_USER = 0x100;
45 /**
46 * Control user connection.
48 const CONNECT_CONTROL = 0x101;
49 /**
50 * Auxiliary connection.
52 * Used for example for replication setup.
54 const CONNECT_AUXILIARY = 0x102;
56 /**
57 * @var DBIExtension
59 private $_extension;
61 /**
62 * @var array Table data cache
64 private $_table_cache;
66 /**
67 * @var array Current user and host cache
69 private $_current_user;
71 /**
72 * @var null|string lower_case_table_names value cache
74 private $_lower_case_table_names = null;
76 /**
77 * Constructor
79 * @param DBIExtension $ext Object to be used for database queries
81 public function __construct($ext)
83 $this->_extension = $ext;
84 $this->_table_cache = array();
85 $this->_current_user = array();
88 /**
89 * Checks whether database extension is loaded
91 * @param string $extension mysql extension to check
93 * @return bool
95 public static function checkDbExtension($extension = 'mysql')
97 if (function_exists($extension . '_connect')) {
98 return true;
100 return false;
104 * runs a query
106 * @param string $query SQL query to execute
107 * @param mixed $link optional database link to use
108 * @param int $options optional query options
109 * @param bool $cache_affected_rows whether to cache affected rows
111 * @return mixed
113 public function query($query, $link = null, $options = 0,
114 $cache_affected_rows = true
116 $res = $this->tryQuery($query, $link, $options, $cache_affected_rows)
117 or Util::mysqlDie($this->getError($link), $query);
118 return $res;
122 * Get a cached value from table cache.
124 * @param array $contentPath Array of the name of the target value
125 * @param mixed $default Return value on cache miss
127 * @return mixed cached value or default
129 public function getCachedTableContent($contentPath, $default = null)
131 return \PMA\Util\get($this->_table_cache, $contentPath, $default);
135 * Set an item in table cache using dot notation.
137 * @param array $contentPath Array with the target path
138 * @param mixed $value Target value
140 * @return void
142 public function cacheTableContent($contentPath, $value)
144 $loc = &$this->_table_cache;
146 if (!isset($contentPath)) {
147 $loc = $value;
148 return;
151 while (count($contentPath) > 1) {
152 $key = array_shift($contentPath);
154 // If the key doesn't exist at this depth, we will just create an empty
155 // array to hold the next value, allowing us to create the arrays to hold
156 // final values at the correct depth. Then we'll keep digging into the
157 // array.
158 if (!isset($loc[$key]) || !is_array($loc[$key])) {
159 $loc[$key] = array();
161 $loc = &$loc[$key];
164 $loc[array_shift($contentPath)] = $value;
168 * Clear the table cache.
170 * @return void
172 public function clearTableCache()
174 $this->_table_cache = array();
178 * Caches table data so Table does not require to issue
179 * SHOW TABLE STATUS again
181 * @param array $tables information for tables of some databases
182 * @param string $table table name
184 * @return void
186 private function _cacheTableData($tables, $table)
188 // Note: I don't see why we would need array_merge_recursive() here,
189 // as it creates double entries for the same table (for example a double
190 // entry for Comment when changing the storage engine in Operations)
191 // Note 2: Instead of array_merge(), simply use the + operator because
192 // array_merge() renumbers numeric keys starting with 0, therefore
193 // we would lose a db name that consists only of numbers
195 foreach ($tables as $one_database => $its_tables) {
196 if (isset($this->_table_cache[$one_database])) {
197 // the + operator does not do the intended effect
198 // when the cache for one table already exists
199 if ($table
200 && isset($this->_table_cache[$one_database][$table])
202 unset($this->_table_cache[$one_database][$table]);
204 $this->_table_cache[$one_database]
205 = $this->_table_cache[$one_database] + $tables[$one_database];
206 } else {
207 $this->_table_cache[$one_database] = $tables[$one_database];
213 * Stores query data into session data for debugging purposes
215 * @param string $query Query text
216 * @param object $link database link
217 * @param object|boolean $result Query result
218 * @param integer $time Time to execute query
220 * @return void
222 private function _dbgQuery($query, $link, $result, $time)
224 $dbgInfo = array();
225 $error_message = $this->getError($link);
226 if ($result == false && is_string($error_message)) {
227 $dbgInfo['error']
228 = '<span style="color:red">'
229 . htmlspecialchars($error_message) . '</span>';
231 $dbgInfo['query'] = htmlspecialchars($query);
232 $dbgInfo['time'] = $time;
233 // Get and slightly format backtrace, this is used
234 // in the javascript console.
235 // Strip call to _dbgQuery
236 $dbgInfo['trace'] = Error::processBacktrace(
237 array_slice(debug_backtrace(), 1)
239 $dbgInfo['hash'] = md5($query);
241 $_SESSION['debug']['queries'][] = $dbgInfo;
245 * runs a query and returns the result
247 * @param string $query query to run
248 * @param object $link mysql link resource
249 * @param integer $options query options
250 * @param bool $cache_affected_rows whether to cache affected row
252 * @return mixed
254 public function tryQuery($query, $link = null, $options = 0,
255 $cache_affected_rows = true
257 $debug = $GLOBALS['cfg']['DBG']['sql'];
258 $link = $this->getLink($link);
259 if ($link === false) {
260 return false;
263 if ($debug) {
264 $time = microtime(true);
267 $result = $this->_extension->realQuery($query, $link, $options);
269 if ($cache_affected_rows) {
270 $GLOBALS['cached_affected_rows'] = $this->affectedRows($link, false);
273 if ($debug) {
274 $time = microtime(true) - $time;
275 $this->_dbgQuery($query, $link, $result, $time);
276 if ($GLOBALS['cfg']['DBG']['sqllog']) {
277 openlog('phpMyAdmin', LOG_NDELAY | LOG_PID, LOG_USER);
278 syslog(
279 LOG_INFO,
280 'SQL[' . basename($_SERVER['SCRIPT_NAME']) . ']: '
281 . sprintf('%0.3f', $time) . ' > ' . $query
286 if ((!empty($result)) && (Tracker::isActive())) {
287 Tracker::handleQuery($query);
290 return $result;
294 * Run multi query statement and return results
296 * @param string $multi_query multi query statement to execute
297 * @param mysqli $link mysqli object
299 * @return mysqli_result collection | boolean(false)
301 public function tryMultiQuery($multi_query = '', $link = null)
303 $link = $this->getLink($link);
304 if ($link === false) {
305 return false;
308 return $this->_extension->realMultiQuery($link, $multi_query);
312 * returns array with table names for given db
314 * @param string $database name of database
315 * @param mixed $link mysql link resource|object
317 * @return array tables names
319 public function getTables($database, $link = null)
321 return $this->fetchResult(
322 'SHOW TABLES FROM ' . Util::backquote($database) . ';',
323 null,
325 $link,
326 self::QUERY_STORE
331 * returns a segment of the SQL WHERE clause regarding table name and type
333 * @param array|string $table table(s)
334 * @param boolean $tbl_is_group $table is a table group
335 * @param string $table_type whether table or view
337 * @return string a segment of the WHERE clause
339 private function _getTableCondition($table, $tbl_is_group, $table_type)
341 // get table information from information_schema
342 if ($table) {
343 if (is_array($table)) {
344 $sql_where_table = 'AND t.`TABLE_NAME` '
345 . Util::getCollateForIS() . ' IN (\''
346 . implode(
347 '\', \'',
348 array_map(
349 array($this, 'escapeString'),
350 $table
353 . '\')';
354 } elseif (true === $tbl_is_group) {
355 $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
356 . Util::escapeMysqlWildcards(
357 $GLOBALS['dbi']->escapeString($table)
359 . '%\'';
360 } else {
361 $sql_where_table = 'AND t.`TABLE_NAME` '
362 . Util::getCollateForIS() . ' = \''
363 . $GLOBALS['dbi']->escapeString($table) . '\'';
365 } else {
366 $sql_where_table = '';
369 if ($table_type) {
370 if ($table_type == 'view') {
371 $sql_where_table .= " AND t.`TABLE_TYPE` != 'BASE TABLE'";
372 } else if ($table_type == 'table') {
373 $sql_where_table .= " AND t.`TABLE_TYPE` = 'BASE TABLE'";
376 return $sql_where_table;
380 * returns the beginning of the SQL statement to fetch the list of tables
382 * @param string[] $this_databases databases to list
383 * @param string $sql_where_table additional condition
385 * @return string the SQL statement
387 private function _getSqlForTablesFull($this_databases, $sql_where_table)
389 $sql = '
390 SELECT *,
391 `TABLE_SCHEMA` AS `Db`,
392 `TABLE_NAME` AS `Name`,
393 `TABLE_TYPE` AS `TABLE_TYPE`,
394 `ENGINE` AS `Engine`,
395 `ENGINE` AS `Type`,
396 `VERSION` AS `Version`,
397 `ROW_FORMAT` AS `Row_format`,
398 `TABLE_ROWS` AS `Rows`,
399 `AVG_ROW_LENGTH` AS `Avg_row_length`,
400 `DATA_LENGTH` AS `Data_length`,
401 `MAX_DATA_LENGTH` AS `Max_data_length`,
402 `INDEX_LENGTH` AS `Index_length`,
403 `DATA_FREE` AS `Data_free`,
404 `AUTO_INCREMENT` AS `Auto_increment`,
405 `CREATE_TIME` AS `Create_time`,
406 `UPDATE_TIME` AS `Update_time`,
407 `CHECK_TIME` AS `Check_time`,
408 `TABLE_COLLATION` AS `Collation`,
409 `CHECKSUM` AS `Checksum`,
410 `CREATE_OPTIONS` AS `Create_options`,
411 `TABLE_COMMENT` AS `Comment`
412 FROM `information_schema`.`TABLES` t
413 WHERE `TABLE_SCHEMA` ' . Util::getCollateForIS() . '
414 IN (\'' . implode("', '", $this_databases) . '\')
415 ' . $sql_where_table;
417 return $sql;
421 * returns array of all tables in given db or dbs
422 * this function expects unquoted names:
423 * RIGHT: my_database
424 * WRONG: `my_database`
425 * WRONG: my\_database
426 * if $tbl_is_group is true, $table is used as filter for table names
428 * <code>
429 * $GLOBALS['dbi']->getTablesFull('my_database');
430 * $GLOBALS['dbi']->getTablesFull('my_database', 'my_table'));
431 * $GLOBALS['dbi']->getTablesFull('my_database', 'my_tables_', true));
432 * </code>
434 * @param string $database database
435 * @param string|array $table table name(s)
436 * @param boolean $tbl_is_group $table is a table group
437 * @param mixed $link mysql link
438 * @param integer $limit_offset zero-based offset for the count
439 * @param boolean|integer $limit_count number of tables to return
440 * @param string $sort_by table attribute to sort by
441 * @param string $sort_order direction to sort (ASC or DESC)
442 * @param string $table_type whether table or view
444 * @todo move into Table
446 * @return array list of tables in given db(s)
448 public function getTablesFull($database, $table = '',
449 $tbl_is_group = false, $link = null, $limit_offset = 0,
450 $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC',
451 $table_type = null
453 if (true === $limit_count) {
454 $limit_count = $GLOBALS['cfg']['MaxTableList'];
456 // prepare and check parameters
457 if (! is_array($database)) {
458 $databases = array($database);
459 } else {
460 $databases = $database;
463 $tables = array();
465 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
466 $sql_where_table = $this->_getTableCondition(
467 $table, $tbl_is_group, $table_type
470 // for PMA bc:
471 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
473 // on non-Windows servers,
474 // added BINARY in the WHERE clause to force a case sensitive
475 // comparison (if we are looking for the db Aa we don't want
476 // to find the db aa)
477 $this_databases = array_map(
478 array($this, 'escapeString'),
479 $databases
482 $sql = $this->_getSqlForTablesFull($this_databases, $sql_where_table);
484 // Sort the tables
485 $sql .= " ORDER BY $sort_by $sort_order";
487 if ($limit_count) {
488 $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
491 $tables = $this->fetchResult(
492 $sql, array('TABLE_SCHEMA', 'TABLE_NAME'), null, $link
495 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
496 // here, the array's first key is by schema name
497 foreach ($tables as $one_database_name => $one_database_tables) {
498 uksort($one_database_tables, 'strnatcasecmp');
500 if ($sort_order == 'DESC') {
501 $one_database_tables = array_reverse($one_database_tables);
503 $tables[$one_database_name] = $one_database_tables;
505 } elseif ($sort_by == 'Data_length') {
506 // Size = Data_length + Index_length
507 foreach ($tables as $one_database_name => $one_database_tables) {
508 uasort(
509 $one_database_tables,
510 function ($a, $b) {
511 $aLength = $a['Data_length'] + $a['Index_length'];
512 $bLength = $b['Data_length'] + $b['Index_length'];
513 return ($aLength == $bLength)
515 : ($aLength < $bLength) ? -1 : 1;
519 if ($sort_order == 'DESC') {
520 $one_database_tables = array_reverse($one_database_tables);
522 $tables[$one_database_name] = $one_database_tables;
525 } // end (get information from table schema)
527 // If permissions are wrong on even one database directory,
528 // information_schema does not return any table info for any database
529 // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
530 if (empty($tables)) {
531 foreach ($databases as $each_database) {
532 if ($table || (true === $tbl_is_group) || ! empty($table_type)) {
533 $sql = 'SHOW TABLE STATUS FROM '
534 . Util::backquote($each_database)
535 . ' WHERE';
536 $needAnd = false;
537 if ($table || (true === $tbl_is_group)) {
538 if (is_array($table)) {
539 $sql .= ' `Name` IN (\''
540 . implode(
541 '\', \'',
542 array_map(
543 array($this, 'escapeString'),
544 $table,
545 $link
547 ) . '\')';
548 } else {
549 $sql .= " `Name` LIKE '"
550 . Util::escapeMysqlWildcards(
551 $this->escapeString($table, $link)
553 . "%'";
555 $needAnd = true;
557 if (! empty($table_type)) {
558 if ($needAnd) {
559 $sql .= " AND";
561 if ($table_type == 'view') {
562 $sql .= " `Comment` = 'VIEW'";
563 } else if ($table_type == 'table') {
564 $sql .= " `Comment` != 'VIEW'";
567 } else {
568 $sql = 'SHOW TABLE STATUS FROM '
569 . Util::backquote($each_database);
572 $each_tables = $this->fetchResult($sql, 'Name', null, $link);
574 // Sort naturally if the config allows it and we're sorting
575 // the Name column.
576 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
577 uksort($each_tables, 'strnatcasecmp');
579 if ($sort_order == 'DESC') {
580 $each_tables = array_reverse($each_tables);
582 } else {
583 // Prepare to sort by creating array of the selected sort
584 // value to pass to array_multisort
586 // Size = Data_length + Index_length
587 if ($sort_by == 'Data_length') {
588 foreach ($each_tables as $table_name => $table_data) {
589 ${$sort_by}[$table_name] = strtolower(
590 $table_data['Data_length']
591 + $table_data['Index_length']
594 } else {
595 foreach ($each_tables as $table_name => $table_data) {
596 ${$sort_by}[$table_name]
597 = strtolower($table_data[$sort_by]);
601 if (! empty($$sort_by)) {
602 if ($sort_order == 'DESC') {
603 array_multisort($$sort_by, SORT_DESC, $each_tables);
604 } else {
605 array_multisort($$sort_by, SORT_ASC, $each_tables);
609 // cleanup the temporary sort array
610 unset($$sort_by);
613 if ($limit_count) {
614 $each_tables = array_slice(
615 $each_tables, $limit_offset, $limit_count
619 foreach ($each_tables as $table_name => $each_table) {
620 if (! isset($each_tables[$table_name]['Type'])
621 && isset($each_tables[$table_name]['Engine'])
623 // pma BC, same parts of PMA still uses 'Type'
624 $each_tables[$table_name]['Type']
625 =& $each_tables[$table_name]['Engine'];
626 } elseif (! isset($each_tables[$table_name]['Engine'])
627 && isset($each_tables[$table_name]['Type'])
629 // old MySQL reports Type, newer MySQL reports Engine
630 $each_tables[$table_name]['Engine']
631 =& $each_tables[$table_name]['Type'];
634 // Compatibility with INFORMATION_SCHEMA output
635 $each_tables[$table_name]['TABLE_SCHEMA']
636 = $each_database;
637 $each_tables[$table_name]['TABLE_NAME']
638 =& $each_tables[$table_name]['Name'];
639 $each_tables[$table_name]['ENGINE']
640 =& $each_tables[$table_name]['Engine'];
641 $each_tables[$table_name]['VERSION']
642 =& $each_tables[$table_name]['Version'];
643 $each_tables[$table_name]['ROW_FORMAT']
644 =& $each_tables[$table_name]['Row_format'];
645 $each_tables[$table_name]['TABLE_ROWS']
646 =& $each_tables[$table_name]['Rows'];
647 $each_tables[$table_name]['AVG_ROW_LENGTH']
648 =& $each_tables[$table_name]['Avg_row_length'];
649 $each_tables[$table_name]['DATA_LENGTH']
650 =& $each_tables[$table_name]['Data_length'];
651 $each_tables[$table_name]['MAX_DATA_LENGTH']
652 =& $each_tables[$table_name]['Max_data_length'];
653 $each_tables[$table_name]['INDEX_LENGTH']
654 =& $each_tables[$table_name]['Index_length'];
655 $each_tables[$table_name]['DATA_FREE']
656 =& $each_tables[$table_name]['Data_free'];
657 $each_tables[$table_name]['AUTO_INCREMENT']
658 =& $each_tables[$table_name]['Auto_increment'];
659 $each_tables[$table_name]['CREATE_TIME']
660 =& $each_tables[$table_name]['Create_time'];
661 $each_tables[$table_name]['UPDATE_TIME']
662 =& $each_tables[$table_name]['Update_time'];
663 $each_tables[$table_name]['CHECK_TIME']
664 =& $each_tables[$table_name]['Check_time'];
665 $each_tables[$table_name]['TABLE_COLLATION']
666 =& $each_tables[$table_name]['Collation'];
667 $each_tables[$table_name]['CHECKSUM']
668 =& $each_tables[$table_name]['Checksum'];
669 $each_tables[$table_name]['CREATE_OPTIONS']
670 =& $each_tables[$table_name]['Create_options'];
671 $each_tables[$table_name]['TABLE_COMMENT']
672 =& $each_tables[$table_name]['Comment'];
674 if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
675 && $each_tables[$table_name]['Engine'] == null
677 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
678 } elseif ($each_database == 'information_schema') {
679 $each_tables[$table_name]['TABLE_TYPE'] = 'SYSTEM VIEW';
680 } else {
682 * @todo difference between 'TEMPORARY' and 'BASE TABLE'
683 * but how to detect?
685 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
689 $tables[$each_database] = $each_tables;
693 // cache table data
694 // so Table does not require to issue SHOW TABLE STATUS again
695 $this->_cacheTableData($tables, $table);
697 if (is_array($database)) {
698 return $tables;
701 if (isset($tables[$database])) {
702 return $tables[$database];
705 if (isset($tables[mb_strtolower($database)])) {
706 // on windows with lower_case_table_names = 1
707 // MySQL returns
708 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
709 // but information_schema.TABLES gives `test`
710 // bug #2036
711 // https://sourceforge.net/p/phpmyadmin/bugs/2036/
712 return $tables[mb_strtolower($database)];
715 return $tables;
719 * Get VIEWs in a particular database
721 * @param string $db Database name to look in
723 * @return array $views Set of VIEWs inside the database
725 public function getVirtualTables($db)
728 $tables_full = $this->getTablesFull($db);
729 $views = array();
731 foreach ($tables_full as $table=>$tmp) {
733 $_table = $this->getTable($db, $table);
734 if ($_table->isView()) {
735 $views[] = $table;
740 return $views;
746 * returns array with databases containing extended infos about them
748 * @param string $database database
749 * @param boolean $force_stats retrieve stats also for MySQL < 5
750 * @param object $link mysql link
751 * @param string $sort_by column to order by
752 * @param string $sort_order ASC or DESC
753 * @param integer $limit_offset starting offset for LIMIT
754 * @param bool|int $limit_count row count for LIMIT or true
755 * for $GLOBALS['cfg']['MaxDbList']
757 * @todo move into ListDatabase?
759 * @return array $databases
761 public function getDatabasesFull($database = null, $force_stats = false,
762 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
763 $limit_offset = 0, $limit_count = false
765 $sort_order = strtoupper($sort_order);
767 if (true === $limit_count) {
768 $limit_count = $GLOBALS['cfg']['MaxDbList'];
771 $apply_limit_and_order_manual = true;
773 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
775 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
776 * cause MySQL does not support natural ordering,
777 * we have to do it afterward
779 $limit = '';
780 if (! $GLOBALS['cfg']['NaturalOrder']) {
781 if ($limit_count) {
782 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
785 $apply_limit_and_order_manual = false;
788 // get table information from information_schema
789 if (! empty($database)) {
790 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
791 . $this->escapeString($database, $link) . '\'';
792 } else {
793 $sql_where_schema = '';
796 $sql = 'SELECT *,
797 CAST(BIN_NAME AS CHAR CHARACTER SET utf8) AS SCHEMA_NAME
798 FROM (';
799 $sql .= 'SELECT
800 BINARY s.SCHEMA_NAME AS BIN_NAME,
801 s.DEFAULT_COLLATION_NAME';
802 if ($force_stats) {
803 $sql .= ',
804 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
805 SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
806 SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
807 SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
808 SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
809 SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
810 AS SCHEMA_LENGTH,
811 SUM(IF(t.ENGINE <> \'InnoDB\', t.DATA_FREE, 0))
812 AS SCHEMA_DATA_FREE';
814 $sql .= '
815 FROM `information_schema`.SCHEMATA s';
816 if ($force_stats) {
817 $sql .= '
818 LEFT JOIN `information_schema`.TABLES t
819 ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
821 $sql .= $sql_where_schema . '
822 GROUP BY BINARY s.SCHEMA_NAME, s.DEFAULT_COLLATION_NAME
823 ORDER BY ';
824 if ($sort_by == 'SCHEMA_NAME'
825 || $sort_by == 'DEFAULT_COLLATION_NAME'
827 $sql .= 'BINARY ';
829 $sql .= Util::backquote($sort_by)
830 . ' ' . $sort_order
831 . $limit;
832 $sql .= ') a';
834 $databases = $this->fetchResult($sql, 'SCHEMA_NAME', null, $link);
836 $mysql_error = $this->getError($link);
837 if (! count($databases) && $GLOBALS['errno']) {
838 Util::mysqlDie($mysql_error, $sql);
841 // display only databases also in official database list
842 // f.e. to apply hide_db and only_db
843 $drops = array_diff(
844 array_keys($databases), (array) $GLOBALS['dblist']->databases
846 foreach ($drops as $drop) {
847 unset($databases[$drop]);
849 } else {
850 $databases = array();
851 foreach ($GLOBALS['dblist']->databases as $database_name) {
852 // Compatibility with INFORMATION_SCHEMA output
853 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
855 $databases[$database_name]['DEFAULT_COLLATION_NAME']
856 = $this->getDbCollation($database_name);
858 if (!$force_stats) {
859 continue;
862 // get additional info about tables
863 $databases[$database_name]['SCHEMA_TABLES'] = 0;
864 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
865 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
866 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
867 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
868 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
869 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
871 $res = $this->query(
872 'SHOW TABLE STATUS FROM '
873 . Util::backquote($database_name) . ';'
876 if ($res === false) {
877 unset($res);
878 continue;
881 while ($row = $this->fetchAssoc($res)) {
882 $databases[$database_name]['SCHEMA_TABLES']++;
883 $databases[$database_name]['SCHEMA_TABLE_ROWS']
884 += $row['Rows'];
885 $databases[$database_name]['SCHEMA_DATA_LENGTH']
886 += $row['Data_length'];
887 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
888 += $row['Max_data_length'];
889 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
890 += $row['Index_length'];
892 // for InnoDB, this does not contain the number of
893 // overhead bytes but the total free space
894 if ('InnoDB' != $row['Engine']) {
895 $databases[$database_name]['SCHEMA_DATA_FREE']
896 += $row['Data_free'];
898 $databases[$database_name]['SCHEMA_LENGTH']
899 += $row['Data_length'] + $row['Index_length'];
901 $this->freeResult($res);
902 unset($res);
907 * apply limit and order manually now
908 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
910 if ($apply_limit_and_order_manual) {
911 $GLOBALS['callback_sort_order'] = $sort_order;
912 $GLOBALS['callback_sort_by'] = $sort_by;
913 usort(
914 $databases,
915 array('PMA\libraries\DatabaseInterface', '_usortComparisonCallback')
917 unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
920 * now apply limit
922 if ($limit_count) {
923 $databases = array_slice($databases, $limit_offset, $limit_count);
927 return $databases;
931 * usort comparison callback
933 * @param string $a first argument to sort
934 * @param string $b second argument to sort
936 * @return integer a value representing whether $a should be before $b in the
937 * sorted array or not
939 * @access private
941 private static function _usortComparisonCallback($a, $b)
943 if ($GLOBALS['cfg']['NaturalOrder']) {
944 $sorter = 'strnatcasecmp';
945 } else {
946 $sorter = 'strcasecmp';
948 /* No sorting when key is not present */
949 if (! isset($a[$GLOBALS['callback_sort_by']])
950 || ! isset($b[$GLOBALS['callback_sort_by']])
952 return 0;
954 // produces f.e.:
955 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
956 return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter(
957 $a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]
959 } // end of the '_usortComparisonCallback()' method
962 * returns detailed array with all columns for sql
964 * @param string $sql_query target SQL query to get columns
965 * @param array $view_columns alias for columns
967 * @return array
969 public function getColumnMapFromSql($sql_query, $view_columns = array())
971 $result = $this->tryQuery($sql_query);
973 if ($result === false) {
974 return array();
977 $meta = $this->getFieldsMeta(
978 $result
981 $nbFields = count($meta);
982 if ($nbFields <= 0) {
983 return array();
986 $column_map = array();
987 $nbColumns = count($view_columns);
989 for ($i=0; $i < $nbFields; $i++) {
991 $map = array();
992 $map['table_name'] = $meta[$i]->table;
993 $map['refering_column'] = $meta[$i]->name;
995 if ($nbColumns > 1) {
996 $map['real_column'] = $view_columns[$i];
999 $column_map[] = $map;
1002 return $column_map;
1006 * returns detailed array with all columns for given table in database,
1007 * or all tables/databases
1009 * @param string $database name of database
1010 * @param string $table name of table to retrieve columns from
1011 * @param string $column name of specific column
1012 * @param mixed $link mysql link resource
1014 * @return array
1016 public function getColumnsFull($database = null, $table = null,
1017 $column = null, $link = null
1019 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1020 $sql_wheres = array();
1021 $array_keys = array();
1023 // get columns information from information_schema
1024 if (null !== $database) {
1025 $sql_wheres[] = '`TABLE_SCHEMA` = \''
1026 . $this->escapeString($database, $link) . '\' ';
1027 } else {
1028 $array_keys[] = 'TABLE_SCHEMA';
1030 if (null !== $table) {
1031 $sql_wheres[] = '`TABLE_NAME` = \''
1032 . $this->escapeString($table, $link) . '\' ';
1033 } else {
1034 $array_keys[] = 'TABLE_NAME';
1036 if (null !== $column) {
1037 $sql_wheres[] = '`COLUMN_NAME` = \''
1038 . $this->escapeString($column, $link) . '\' ';
1039 } else {
1040 $array_keys[] = 'COLUMN_NAME';
1043 // for PMA bc:
1044 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
1045 $sql = '
1046 SELECT *,
1047 `COLUMN_NAME` AS `Field`,
1048 `COLUMN_TYPE` AS `Type`,
1049 `COLLATION_NAME` AS `Collation`,
1050 `IS_NULLABLE` AS `Null`,
1051 `COLUMN_KEY` AS `Key`,
1052 `COLUMN_DEFAULT` AS `Default`,
1053 `EXTRA` AS `Extra`,
1054 `PRIVILEGES` AS `Privileges`,
1055 `COLUMN_COMMENT` AS `Comment`
1056 FROM `information_schema`.`COLUMNS`';
1058 if (count($sql_wheres)) {
1059 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
1061 return $this->fetchResult($sql, $array_keys, null, $link);
1062 } else {
1063 $columns = array();
1064 if (null === $database) {
1065 foreach ($GLOBALS['dblist']->databases as $database) {
1066 $columns[$database] = $this->getColumnsFull(
1067 $database, null, null, $link
1070 return $columns;
1071 } elseif (null === $table) {
1072 $tables = $this->getTables($database);
1073 foreach ($tables as $table) {
1074 $columns[$table] = $this->getColumnsFull(
1075 $database, $table, null, $link
1078 return $columns;
1080 $sql = 'SHOW FULL COLUMNS FROM '
1081 . Util::backquote($database) . '.' . Util::backquote($table);
1082 if (null !== $column) {
1083 $sql .= " LIKE '" . $this->escapeString($column, $link) . "'";
1086 $columns = $this->fetchResult($sql, 'Field', null, $link);
1087 $ordinal_position = 1;
1088 foreach ($columns as $column_name => $each_column) {
1090 // Compatibility with INFORMATION_SCHEMA output
1091 $columns[$column_name]['COLUMN_NAME']
1092 =& $columns[$column_name]['Field'];
1093 $columns[$column_name]['COLUMN_TYPE']
1094 =& $columns[$column_name]['Type'];
1095 $columns[$column_name]['COLLATION_NAME']
1096 =& $columns[$column_name]['Collation'];
1097 $columns[$column_name]['IS_NULLABLE']
1098 =& $columns[$column_name]['Null'];
1099 $columns[$column_name]['COLUMN_KEY']
1100 =& $columns[$column_name]['Key'];
1101 $columns[$column_name]['COLUMN_DEFAULT']
1102 =& $columns[$column_name]['Default'];
1103 $columns[$column_name]['EXTRA']
1104 =& $columns[$column_name]['Extra'];
1105 $columns[$column_name]['PRIVILEGES']
1106 =& $columns[$column_name]['Privileges'];
1107 $columns[$column_name]['COLUMN_COMMENT']
1108 =& $columns[$column_name]['Comment'];
1110 $columns[$column_name]['TABLE_CATALOG'] = null;
1111 $columns[$column_name]['TABLE_SCHEMA'] = $database;
1112 $columns[$column_name]['TABLE_NAME'] = $table;
1113 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
1114 $columns[$column_name]['DATA_TYPE']
1115 = substr(
1116 $columns[$column_name]['COLUMN_TYPE'],
1118 strpos($columns[$column_name]['COLUMN_TYPE'], '(')
1121 * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
1123 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
1125 * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
1127 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
1128 $columns[$column_name]['NUMERIC_PRECISION'] = null;
1129 $columns[$column_name]['NUMERIC_SCALE'] = null;
1130 $columns[$column_name]['CHARACTER_SET_NAME']
1131 = substr(
1132 $columns[$column_name]['COLLATION_NAME'],
1134 strpos($columns[$column_name]['COLLATION_NAME'], '_')
1137 $ordinal_position++;
1140 if (null !== $column) {
1141 return reset($columns);
1144 return $columns;
1149 * Returns SQL query for fetching columns for a table
1151 * The 'Key' column is not calculated properly, use $GLOBALS['dbi']->getColumns()
1152 * to get correct values.
1154 * @param string $database name of database
1155 * @param string $table name of table to retrieve columns from
1156 * @param string $column name of column, null to show all columns
1157 * @param boolean $full whether to return full info or only column names
1159 * @see getColumns()
1161 * @return string
1163 public function getColumnsSql($database, $table, $column = null, $full = false)
1165 $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS FROM '
1166 . Util::backquote($database) . '.' . Util::backquote($table)
1167 . (($column !== null) ? "LIKE '"
1168 . $GLOBALS['dbi']->escapeString($column) . "'" : '');
1170 return $sql;
1174 * Returns descriptions of columns in given table (all or given by $column)
1176 * @param string $database name of database
1177 * @param string $table name of table to retrieve columns from
1178 * @param string $column name of column, null to show all columns
1179 * @param boolean $full whether to return full info or only column names
1180 * @param mixed $link mysql link resource
1182 * @return array array indexed by column names or,
1183 * if $column is given, flat array description
1185 public function getColumns($database, $table, $column = null, $full = false,
1186 $link = null
1188 $sql = $this->getColumnsSql($database, $table, $column, $full);
1189 $fields = $this->fetchResult($sql, 'Field', null, $link);
1190 if (! is_array($fields) || count($fields) == 0) {
1191 return array();
1193 // Check if column is a part of multiple-column index and set its 'Key'.
1194 $indexes = Index::getFromTable($table, $database);
1195 foreach ($fields as $field => $field_data) {
1196 if (!empty($field_data['Key'])) {
1197 continue;
1200 foreach ($indexes as $index) {
1201 /** @var Index $index */
1202 if (!$index->hasColumn($field)) {
1203 continue;
1206 $index_columns = $index->getColumns();
1207 if ($index_columns[$field]->getSeqInIndex() > 1) {
1208 if ($index->isUnique()) {
1209 $fields[$field]['Key'] = 'UNI';
1210 } else {
1211 $fields[$field]['Key'] = 'MUL';
1217 return ($column != null) ? array_shift($fields) : $fields;
1221 * Returns all column names in given table
1223 * @param string $database name of database
1224 * @param string $table name of table to retrieve columns from
1225 * @param mixed $link mysql link resource
1227 * @return null|array
1229 public function getColumnNames($database, $table, $link = null)
1231 $sql = $this->getColumnsSql($database, $table);
1232 // We only need the 'Field' column which contains the table's column names
1233 $fields = array_keys($this->fetchResult($sql, 'Field', null, $link));
1235 if (! is_array($fields) || count($fields) == 0) {
1236 return null;
1238 return $fields;
1242 * Returns SQL for fetching information on table indexes (SHOW INDEXES)
1244 * @param string $database name of database
1245 * @param string $table name of the table whose indexes are to be retrieved
1246 * @param string $where additional conditions for WHERE
1248 * @return string SQL for getting indexes
1250 public function getTableIndexesSql($database, $table, $where = null)
1252 $sql = 'SHOW INDEXES FROM ' . Util::backquote($database) . '.'
1253 . Util::backquote($table);
1254 if ($where) {
1255 $sql .= ' WHERE (' . $where . ')';
1257 return $sql;
1261 * Returns indexes of a table
1263 * @param string $database name of database
1264 * @param string $table name of the table whose indexes are to be retrieved
1265 * @param mixed $link mysql link resource
1267 * @return array $indexes
1269 public function getTableIndexes($database, $table, $link = null)
1271 $sql = $this->getTableIndexesSql($database, $table);
1272 $indexes = $this->fetchResult($sql, null, null, $link);
1274 if (! is_array($indexes) || count($indexes) < 1) {
1275 return array();
1277 return $indexes;
1281 * returns value of given mysql server variable
1283 * @param string $var mysql server variable name
1284 * @param int $type DatabaseInterface::GETVAR_SESSION |
1285 * DatabaseInterface::GETVAR_GLOBAL
1286 * @param mixed $link mysql link resource|object
1288 * @return mixed value for mysql server variable
1290 public function getVariable(
1291 $var, $type = self::GETVAR_SESSION, $link = null
1293 $link = $this->getLink($link);
1294 if ($link === false) {
1295 return false;
1298 switch ($type) {
1299 case self::GETVAR_SESSION:
1300 $modifier = ' SESSION';
1301 break;
1302 case self::GETVAR_GLOBAL:
1303 $modifier = ' GLOBAL';
1304 break;
1305 default:
1306 $modifier = '';
1308 return $this->fetchValue(
1309 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link
1314 * Sets new value for a variable if it is different from the current value
1316 * @param string $var variable name
1317 * @param string $value value to set
1318 * @param mixed $link mysql link resource|object
1320 * @return bool whether query was a successful
1322 public function setVariable($var, $value, $link = null)
1324 $link = $this->getLink($link);
1325 if ($link === false) {
1326 return false;
1328 $current_value = $this->getVariable(
1329 $var, self::GETVAR_SESSION, $link
1331 if ($current_value == $value) {
1332 return true;
1335 return $this->query("SET " . $var . " = " . $value . ';', $link);
1339 * Function called just after a connection to the MySQL database server has
1340 * been established. It sets the connection collation, and determines the
1341 * version of MySQL which is running.
1343 * @param mixed $link mysql link resource|object
1345 * @return void
1347 public function postConnect($link)
1349 if (! defined('PMA_MYSQL_INT_VERSION')) {
1350 $version = $this->fetchSingleRow(
1351 'SELECT @@version, @@version_comment',
1352 'ASSOC',
1353 $link
1356 if ($version) {
1357 $match = explode('.', $version['@@version']);
1358 define('PMA_MYSQL_MAJOR_VERSION', (int)$match[0]);
1359 define(
1360 'PMA_MYSQL_INT_VERSION',
1361 (int) sprintf(
1362 '%d%02d%02d', $match[0], $match[1], intval($match[2])
1365 define('PMA_MYSQL_STR_VERSION', $version['@@version']);
1366 define(
1367 'PMA_MYSQL_VERSION_COMMENT',
1368 $version['@@version_comment']
1370 } else {
1371 define('PMA_MYSQL_INT_VERSION', 50501);
1372 define('PMA_MYSQL_MAJOR_VERSION', 5);
1373 define('PMA_MYSQL_STR_VERSION', '5.05.01');
1374 define('PMA_MYSQL_VERSION_COMMENT', '');
1376 /* Detect MariaDB */
1377 if (mb_strpos(PMA_MYSQL_STR_VERSION, 'MariaDB') !== false) {
1378 define('PMA_MARIADB', true);
1379 } else {
1380 define('PMA_MARIADB', false);
1384 if (PMA_MYSQL_INT_VERSION > 50503) {
1385 $default_charset = 'utf8mb4';
1386 $default_collation = 'utf8mb4_general_ci';
1387 } else {
1388 $default_charset = 'utf8';
1389 $default_collation = 'utf8_general_ci';
1391 $collation_connection = $GLOBALS['PMA_Config']->get('collation_connection');
1392 if (! empty($collation_connection)) {
1393 $this->query(
1394 "SET CHARACTER SET '$default_charset';",
1395 $link,
1396 self::QUERY_STORE
1398 /* Automatically adjust collation if not supported by server */
1399 if ($default_charset == 'utf8'
1400 && strncmp('utf8mb4_', $collation_connection, 8) == 0
1402 $collation_connection = 'utf8_' . substr($collation_connection, 8);
1404 $result = $this->tryQuery(
1405 "SET collation_connection = '"
1406 . $this->escapeString($collation_connection, $link)
1407 . "';",
1408 $link,
1409 self::QUERY_STORE
1411 if ($result === false) {
1412 trigger_error(
1413 __('Failed to set configured collation connection!'),
1414 E_USER_WARNING
1416 $this->query(
1417 "SET collation_connection = '"
1418 . $this->escapeString($collation_connection, $link)
1419 . "';",
1420 $link,
1421 self::QUERY_STORE
1424 } else {
1425 $this->query(
1426 "SET NAMES '$default_charset' COLLATE '$default_collation';",
1427 $link,
1428 self::QUERY_STORE
1432 /* Locale for messages */
1433 $locale = LanguageManager::getInstance()->getCurrentLanguage()->getMySQLLocale();
1434 if (! empty($locale)) {
1435 $this->query(
1436 "SET lc_messages = '" . $locale . "';",
1437 $link,
1438 self::QUERY_STORE
1444 * returns a single value from the given result or query,
1445 * if the query or the result has more than one row or field
1446 * the first field of the first row is returned
1448 * <code>
1449 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
1450 * $user_name = $GLOBALS['dbi']->fetchValue($sql);
1451 * // produces
1452 * // $user_name = 'John Doe'
1453 * </code>
1455 * @param string $query The query to execute
1456 * @param integer $row_number row to fetch the value from,
1457 * starting at 0, with 0 being default
1458 * @param integer|string $field field to fetch the value from,
1459 * starting at 0, with 0 being default
1460 * @param object $link mysql link
1462 * @return mixed value of first field in first row from result
1463 * or false if not found
1465 public function fetchValue($query, $row_number = 0, $field = 0, $link = null)
1467 $value = false;
1469 $result = $this->tryQuery(
1470 $query,
1471 $link,
1472 self::QUERY_STORE,
1473 false
1475 if ($result === false) {
1476 return false;
1479 // return false if result is empty or false
1480 // or requested row is larger than rows in result
1481 if ($this->numRows($result) < ($row_number + 1)) {
1482 return $value;
1485 // if $field is an integer use non associative mysql fetch function
1486 if (is_int($field)) {
1487 $fetch_function = 'fetchRow';
1488 } else {
1489 $fetch_function = 'fetchAssoc';
1492 // get requested row
1493 for ($i = 0; $i <= $row_number; $i++) {
1494 $row = $this->$fetch_function($result);
1496 $this->freeResult($result);
1498 // return requested field
1499 if (isset($row[$field])) {
1500 $value = $row[$field];
1503 return $value;
1507 * returns only the first row from the result
1509 * <code>
1510 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
1511 * $user = $GLOBALS['dbi']->fetchSingleRow($sql);
1512 * // produces
1513 * // $user = array('id' => 123, 'name' => 'John Doe')
1514 * </code>
1516 * @param string $query The query to execute
1517 * @param string $type NUM|ASSOC|BOTH returned array should either
1518 * numeric associative or both
1519 * @param object $link mysql link
1521 * @return array|boolean first row from result
1522 * or false if result is empty
1524 public function fetchSingleRow($query, $type = 'ASSOC', $link = null)
1526 $result = $this->tryQuery(
1527 $query,
1528 $link,
1529 self::QUERY_STORE,
1530 false
1532 if ($result === false) {
1533 return false;
1536 // return false if result is empty or false
1537 if (! $this->numRows($result)) {
1538 return false;
1541 switch ($type) {
1542 case 'NUM' :
1543 $fetch_function = 'fetchRow';
1544 break;
1545 case 'ASSOC' :
1546 $fetch_function = 'fetchAssoc';
1547 break;
1548 case 'BOTH' :
1549 default :
1550 $fetch_function = 'fetchArray';
1551 break;
1554 $row = $this->$fetch_function($result);
1555 $this->freeResult($result);
1556 return $row;
1560 * Returns row or element of a row
1562 * @param array $row Row to process
1563 * @param string|null $value Which column to return
1565 * @return mixed
1567 private function _fetchValue($row, $value)
1569 if (is_null($value)) {
1570 return $row;
1571 } else {
1572 return $row[$value];
1577 * returns all rows in the resultset in one array
1579 * <code>
1580 * $sql = 'SELECT * FROM `user`';
1581 * $users = $GLOBALS['dbi']->fetchResult($sql);
1582 * // produces
1583 * // $users[] = array('id' => 123, 'name' => 'John Doe')
1585 * $sql = 'SELECT `id`, `name` FROM `user`';
1586 * $users = $GLOBALS['dbi']->fetchResult($sql, 'id');
1587 * // produces
1588 * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
1590 * $sql = 'SELECT `id`, `name` FROM `user`';
1591 * $users = $GLOBALS['dbi']->fetchResult($sql, 0);
1592 * // produces
1593 * // $users['123'] = array(0 => 123, 1 => 'John Doe')
1595 * $sql = 'SELECT `id`, `name` FROM `user`';
1596 * $users = $GLOBALS['dbi']->fetchResult($sql, 'id', 'name');
1597 * // or
1598 * $users = $GLOBALS['dbi']->fetchResult($sql, 0, 1);
1599 * // produces
1600 * // $users['123'] = 'John Doe'
1602 * $sql = 'SELECT `name` FROM `user`';
1603 * $users = $GLOBALS['dbi']->fetchResult($sql);
1604 * // produces
1605 * // $users[] = 'John Doe'
1607 * $sql = 'SELECT `group`, `name` FROM `user`'
1608 * $users = $GLOBALS['dbi']->fetchResult($sql, array('group', null), 'name');
1609 * // produces
1610 * // $users['admin'][] = 'John Doe'
1612 * $sql = 'SELECT `group`, `name` FROM `user`'
1613 * $users = $GLOBALS['dbi']->fetchResult($sql, array('group', 'name'), 'id');
1614 * // produces
1615 * // $users['admin']['John Doe'] = '123'
1616 * </code>
1618 * @param string $query query to execute
1619 * @param string|integer|array $key field-name or offset
1620 * used as key for array
1621 * or array of those
1622 * @param string|integer $value value-name or offset
1623 * used as value for array
1624 * @param object $link mysql link
1625 * @param integer $options query options
1627 * @return array resultrows or values indexed by $key
1629 public function fetchResult($query, $key = null, $value = null,
1630 $link = null, $options = 0
1632 $resultrows = array();
1634 $result = $this->tryQuery($query, $link, $options, false);
1636 // return empty array if result is empty or false
1637 if ($result === false) {
1638 return $resultrows;
1641 $fetch_function = 'fetchAssoc';
1643 // no nested array if only one field is in result
1644 if (null === $key && 1 === $this->numFields($result)) {
1645 $value = 0;
1646 $fetch_function = 'fetchRow';
1649 // if $key is an integer use non associative mysql fetch function
1650 if (is_int($key)) {
1651 $fetch_function = 'fetchRow';
1654 if (null === $key) {
1655 while ($row = $this->$fetch_function($result)) {
1656 $resultrows[] = $this->_fetchValue($row, $value);
1658 } else {
1659 if (is_array($key)) {
1660 while ($row = $this->$fetch_function($result)) {
1661 $result_target =& $resultrows;
1662 foreach ($key as $key_index) {
1663 if (null === $key_index) {
1664 $result_target =& $result_target[];
1665 continue;
1668 if (! isset($result_target[$row[$key_index]])) {
1669 $result_target[$row[$key_index]] = array();
1671 $result_target =& $result_target[$row[$key_index]];
1673 $result_target = $this->_fetchValue($row, $value);
1675 } else {
1676 while ($row = $this->$fetch_function($result)) {
1677 $resultrows[$row[$key]] = $this->_fetchValue($row, $value);
1682 $this->freeResult($result);
1683 return $resultrows;
1687 * Get supported SQL compatibility modes
1689 * @return array supported SQL compatibility modes
1691 public function getCompatibilities()
1693 $compats = array('NONE');
1694 $compats[] = 'ANSI';
1695 $compats[] = 'DB2';
1696 $compats[] = 'MAXDB';
1697 $compats[] = 'MYSQL323';
1698 $compats[] = 'MYSQL40';
1699 $compats[] = 'MSSQL';
1700 $compats[] = 'ORACLE';
1701 // removed; in MySQL 5.0.33, this produces exports that
1702 // can't be read by POSTGRESQL (see our bug #1596328)
1703 //$compats[] = 'POSTGRESQL';
1704 $compats[] = 'TRADITIONAL';
1706 return $compats;
1710 * returns warnings for last query
1712 * @param object $link mysql link resource
1714 * @return array warnings
1716 public function getWarnings($link = null)
1718 $link = $this->getLink($link);
1719 if ($link === false) {
1720 return false;
1723 return $this->fetchResult('SHOW WARNINGS', null, null, $link);
1727 * returns an array of PROCEDURE or FUNCTION names for a db
1729 * @param string $db db name
1730 * @param string $which PROCEDURE | FUNCTION
1731 * @param object $link mysql link
1733 * @return array the procedure names or function names
1735 public function getProceduresOrFunctions($db, $which, $link = null)
1737 $shows = $this->fetchResult(
1738 'SHOW ' . $which . ' STATUS;', null, null, $link
1740 $result = array();
1741 foreach ($shows as $one_show) {
1742 if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
1743 $result[] = $one_show['Name'];
1746 return($result);
1750 * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
1752 * @param string $db db name
1753 * @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
1754 * @param string $name the procedure|function|event|view name
1755 * @param object $link MySQL link
1757 * @return string the definition
1759 public function getDefinition($db, $which, $name, $link = null)
1761 $returned_field = array(
1762 'PROCEDURE' => 'Create Procedure',
1763 'FUNCTION' => 'Create Function',
1764 'EVENT' => 'Create Event',
1765 'VIEW' => 'Create View'
1767 $query = 'SHOW CREATE ' . $which . ' '
1768 . Util::backquote($db) . '.'
1769 . Util::backquote($name);
1770 return($this->fetchValue($query, 0, $returned_field[$which], $link));
1774 * returns details about the PROCEDUREs or FUNCTIONs for a specific database
1775 * or details about a specific routine
1777 * @param string $db db name
1778 * @param string $which PROCEDURE | FUNCTION or null for both
1779 * @param string $name name of the routine (to fetch a specific routine)
1781 * @return array information about ROCEDUREs or FUNCTIONs
1783 public function getRoutines($db, $which = null, $name = '')
1785 $routines = array();
1786 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1787 $query = "SELECT"
1788 . " `ROUTINE_SCHEMA` AS `Db`,"
1789 . " `SPECIFIC_NAME` AS `Name`,"
1790 . " `ROUTINE_TYPE` AS `Type`,"
1791 . " `DEFINER` AS `Definer`,"
1792 . " `LAST_ALTERED` AS `Modified`,"
1793 . " `CREATED` AS `Created`,"
1794 . " `SECURITY_TYPE` AS `Security_type`,"
1795 . " `ROUTINE_COMMENT` AS `Comment`,"
1796 . " `CHARACTER_SET_CLIENT` AS `character_set_client`,"
1797 . " `COLLATION_CONNECTION` AS `collation_connection`,"
1798 . " `DATABASE_COLLATION` AS `Database Collation`,"
1799 . " `DTD_IDENTIFIER`"
1800 . " FROM `information_schema`.`ROUTINES`"
1801 . " WHERE `ROUTINE_SCHEMA` " . Util::getCollateForIS()
1802 . " = '" . $GLOBALS['dbi']->escapeString($db) . "'";
1803 if (PMA_isValid($which, array('FUNCTION','PROCEDURE'))) {
1804 $query .= " AND `ROUTINE_TYPE` = '" . $which . "'";
1806 if (! empty($name)) {
1807 $query .= " AND `SPECIFIC_NAME`"
1808 . " = '" . $GLOBALS['dbi']->escapeString($name) . "'";
1810 $result = $this->fetchResult($query);
1811 if (!empty($result)) {
1812 $routines = $result;
1814 } else {
1815 if ($which == 'FUNCTION' || $which == null) {
1816 $query = "SHOW FUNCTION STATUS"
1817 . " WHERE `Db` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
1818 if (! empty($name)) {
1819 $query .= " AND `Name` = '"
1820 . $GLOBALS['dbi']->escapeString($name) . "'";
1822 $result = $this->fetchResult($query);
1823 if (!empty($result)) {
1824 $routines = array_merge($routines, $result);
1827 if ($which == 'PROCEDURE' || $which == null) {
1828 $query = "SHOW PROCEDURE STATUS"
1829 . " WHERE `Db` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
1830 if (! empty($name)) {
1831 $query .= " AND `Name` = '"
1832 . $GLOBALS['dbi']->escapeString($name) . "'";
1834 $result = $this->fetchResult($query);
1835 if (!empty($result)) {
1836 $routines = array_merge($routines, $result);
1841 $ret = array();
1842 foreach ($routines as $routine) {
1843 $one_result = array();
1844 $one_result['db'] = $routine['Db'];
1845 $one_result['name'] = $routine['Name'];
1846 $one_result['type'] = $routine['Type'];
1847 $one_result['definer'] = $routine['Definer'];
1848 $one_result['returns'] = isset($routine['DTD_IDENTIFIER'])
1849 ? $routine['DTD_IDENTIFIER'] : "";
1850 $ret[] = $one_result;
1853 // Sort results by name
1854 $name = array();
1855 foreach ($ret as $value) {
1856 $name[] = $value['name'];
1858 array_multisort($name, SORT_ASC, $ret);
1860 return($ret);
1864 * returns details about the EVENTs for a specific database
1866 * @param string $db db name
1867 * @param string $name event name
1869 * @return array information about EVENTs
1871 public function getEvents($db, $name = '')
1873 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1874 $query = "SELECT"
1875 . " `EVENT_SCHEMA` AS `Db`,"
1876 . " `EVENT_NAME` AS `Name`,"
1877 . " `DEFINER` AS `Definer`,"
1878 . " `TIME_ZONE` AS `Time zone`,"
1879 . " `EVENT_TYPE` AS `Type`,"
1880 . " `EXECUTE_AT` AS `Execute at`,"
1881 . " `INTERVAL_VALUE` AS `Interval value`,"
1882 . " `INTERVAL_FIELD` AS `Interval field`,"
1883 . " `STARTS` AS `Starts`,"
1884 . " `ENDS` AS `Ends`,"
1885 . " `STATUS` AS `Status`,"
1886 . " `ORIGINATOR` AS `Originator`,"
1887 . " `CHARACTER_SET_CLIENT` AS `character_set_client`,"
1888 . " `COLLATION_CONNECTION` AS `collation_connection`, "
1889 . "`DATABASE_COLLATION` AS `Database Collation`"
1890 . " FROM `information_schema`.`EVENTS`"
1891 . " WHERE `EVENT_SCHEMA` " . Util::getCollateForIS()
1892 . " = '" . $GLOBALS['dbi']->escapeString($db) . "'";
1893 if (! empty($name)) {
1894 $query .= " AND `EVENT_NAME`"
1895 . " = '" . $GLOBALS['dbi']->escapeString($name) . "'";
1897 } else {
1898 $query = "SHOW EVENTS FROM " . Util::backquote($db);
1899 if (! empty($name)) {
1900 $query .= " AND `Name` = '"
1901 . $GLOBALS['dbi']->escapeString($name) . "'";
1905 $result = array();
1906 if ($events = $this->fetchResult($query)) {
1907 foreach ($events as $event) {
1908 $one_result = array();
1909 $one_result['name'] = $event['Name'];
1910 $one_result['type'] = $event['Type'];
1911 $one_result['status'] = $event['Status'];
1912 $result[] = $one_result;
1916 // Sort results by name
1917 $name = array();
1918 foreach ($result as $value) {
1919 $name[] = $value['name'];
1921 array_multisort($name, SORT_ASC, $result);
1923 return $result;
1927 * returns details about the TRIGGERs for a specific table or database
1929 * @param string $db db name
1930 * @param string $table table name
1931 * @param string $delimiter the delimiter to use (may be empty)
1933 * @return array information about triggers (may be empty)
1935 public function getTriggers($db, $table = '', $delimiter = '//')
1937 $result = array();
1938 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1939 $query = 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION'
1940 . ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
1941 . ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
1942 . ' FROM information_schema.TRIGGERS'
1943 . ' WHERE EVENT_OBJECT_SCHEMA ' . Util::getCollateForIS() . '='
1944 . ' \'' . $GLOBALS['dbi']->escapeString($db) . '\'';
1946 if (! empty($table)) {
1947 $query .= " AND EVENT_OBJECT_TABLE " . Util::getCollateForIS()
1948 . " = '" . $GLOBALS['dbi']->escapeString($table) . "';";
1950 } else {
1951 $query = "SHOW TRIGGERS FROM " . Util::backquote($db);
1952 if (! empty($table)) {
1953 $query .= " LIKE '" . $GLOBALS['dbi']->escapeString($table) . "';";
1957 if ($triggers = $this->fetchResult($query)) {
1958 foreach ($triggers as $trigger) {
1959 if ($GLOBALS['cfg']['Server']['DisableIS']) {
1960 $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
1961 $trigger['ACTION_TIMING'] = $trigger['Timing'];
1962 $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
1963 $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
1964 $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
1965 $trigger['DEFINER'] = $trigger['Definer'];
1967 $one_result = array();
1968 $one_result['name'] = $trigger['TRIGGER_NAME'];
1969 $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
1970 $one_result['action_timing'] = $trigger['ACTION_TIMING'];
1971 $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
1972 $one_result['definition'] = $trigger['ACTION_STATEMENT'];
1973 $one_result['definer'] = $trigger['DEFINER'];
1975 // do not prepend the schema name; this way, importing the
1976 // definition into another schema will work
1977 $one_result['full_trigger_name'] = Util::backquote(
1978 $trigger['TRIGGER_NAME']
1980 $one_result['drop'] = 'DROP TRIGGER IF EXISTS '
1981 . $one_result['full_trigger_name'];
1982 $one_result['create'] = 'CREATE TRIGGER '
1983 . $one_result['full_trigger_name'] . ' '
1984 . $trigger['ACTION_TIMING'] . ' '
1985 . $trigger['EVENT_MANIPULATION']
1986 . ' ON ' . Util::backquote($trigger['EVENT_OBJECT_TABLE'])
1987 . "\n" . ' FOR EACH ROW '
1988 . $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";
1990 $result[] = $one_result;
1994 // Sort results by name
1995 $name = array();
1996 foreach ($result as $value) {
1997 $name[] = $value['name'];
1999 array_multisort($name, SORT_ASC, $result);
2001 return($result);
2005 * Formats database error message in a friendly way.
2006 * This is needed because some errors messages cannot
2007 * be obtained by mysql_error().
2009 * @param int $error_number Error code
2010 * @param string $error_message Error message as returned by server
2012 * @return string HML text with error details
2014 public function formatError($error_number, $error_message)
2016 $error_message = htmlspecialchars($error_message);
2018 $error = '#' . ((string) $error_number);
2019 $separator = ' &mdash; ';
2021 if ($error_number == 2002) {
2022 $error .= ' - ' . $error_message;
2023 $error .= $separator;
2024 $error .= __(
2025 'The server is not responding (or the local server\'s socket'
2026 . ' is not correctly configured).'
2028 } elseif ($error_number == 2003) {
2029 $error .= ' - ' . $error_message;
2030 $error .= $separator . __('The server is not responding.');
2031 } elseif ($error_number == 1005) {
2032 if (strpos($error_message, 'errno: 13') !== false) {
2033 $error .= ' - ' . $error_message;
2034 $error .= $separator
2035 . __(
2036 'Please check privileges of directory containing database.'
2038 } else {
2039 /* InnoDB constraints, see
2040 * https://dev.mysql.com/doc/refman/5.0/en/
2041 * innodb-foreign-key-constraints.html
2043 $error .= ' - ' . $error_message .
2044 ' (<a href="server_engines.php' .
2045 URL::getCommon(
2046 array('engine' => 'InnoDB', 'page' => 'Status')
2047 ) . '">' . __('Details…') . '</a>)';
2049 } else {
2050 $error .= ' - ' . $error_message;
2053 return $error;
2057 * gets the current user with host
2059 * @return string the current user i.e. user@host
2061 public function getCurrentUser()
2063 if (Util::cacheExists('mysql_cur_user')) {
2064 return Util::cacheGet('mysql_cur_user');
2066 $user = $this->fetchValue('SELECT CURRENT_USER();');
2067 if ($user !== false) {
2068 Util::cacheSet('mysql_cur_user', $user);
2069 return Util::cacheGet('mysql_cur_user');
2071 return '';
2075 * Checks if current user is superuser
2077 * @return bool Whether user is a superuser
2079 public function isSuperuser()
2081 return self::isUserType('super');
2085 * Checks if current user has global create user/grant privilege
2086 * or is a superuser (i.e. SELECT on mysql.users)
2087 * while caching the result in session.
2089 * @param string $type type of user to check for
2090 * i.e. 'create', 'grant', 'super'
2092 * @return bool Whether user is a given type of user
2094 public function isUserType($type)
2096 if (Util::cacheExists('is_' . $type . 'user')) {
2097 return Util::cacheGet('is_' . $type . 'user');
2100 // when connection failed we don't have a $userlink
2101 if (! isset($GLOBALS['userlink'])) {
2102 Util::cacheSet('is_' . $type . 'user', false);
2103 return Util::cacheGet('is_' . $type . 'user');
2106 if (! $GLOBALS['cfg']['Server']['DisableIS'] || $type === 'super') {
2107 // Prepare query for each user type check
2108 $query = '';
2109 if ($type === 'super') {
2110 $query = 'SELECT 1 FROM mysql.user LIMIT 1';
2111 } elseif ($type === 'create') {
2112 list($user, $host) = $this->getCurrentUserAndHost();
2113 $query = "SELECT 1 FROM `INFORMATION_SCHEMA`.`USER_PRIVILEGES` "
2114 . "WHERE `PRIVILEGE_TYPE` = 'CREATE USER' AND "
2115 . "'''" . $user . "''@''" . $host . "''' LIKE `GRANTEE` LIMIT 1";
2116 } elseif ($type === 'grant') {
2117 list($user, $host) = $this->getCurrentUserAndHost();
2118 $query = "SELECT 1 FROM ("
2119 . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
2120 . "`INFORMATION_SCHEMA`.`COLUMN_PRIVILEGES` UNION "
2121 . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
2122 . "`INFORMATION_SCHEMA`.`TABLE_PRIVILEGES` UNION "
2123 . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
2124 . "`INFORMATION_SCHEMA`.`SCHEMA_PRIVILEGES` UNION "
2125 . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
2126 . "`INFORMATION_SCHEMA`.`USER_PRIVILEGES`) t "
2127 . "WHERE `IS_GRANTABLE` = 'YES' AND "
2128 . "'''" . $user . "''@''" . $host . "''' LIKE `GRANTEE` LIMIT 1";
2131 $is = false;
2132 $result = $this->tryQuery(
2133 $query,
2134 $GLOBALS['userlink'],
2135 self::QUERY_STORE
2137 if ($result) {
2138 $is = (bool) $this->numRows($result);
2140 $this->freeResult($result);
2142 Util::cacheSet('is_' . $type . 'user', $is);
2143 } else {
2144 $is = false;
2145 $grants = $this->fetchResult(
2146 "SHOW GRANTS FOR CURRENT_USER();",
2147 null,
2148 null,
2149 $GLOBALS['userlink'],
2150 self::QUERY_STORE
2152 if ($grants) {
2153 foreach ($grants as $grant) {
2154 if ($type === 'create') {
2155 if (strpos($grant, "ALL PRIVILEGES ON *.*") !== false
2156 || strpos($grant, "CREATE USER") !== false
2158 $is = true;
2159 break;
2161 } elseif ($type === 'grant') {
2162 if (strpos($grant, "WITH GRANT OPTION") !== false) {
2163 $is = true;
2164 break;
2170 Util::cacheSet('is_' . $type . 'user', $is);
2173 return Util::cacheGet('is_' . $type . 'user');
2177 * Get the current user and host
2179 * @return array array of username and hostname
2181 public function getCurrentUserAndHost()
2183 if (count($this->_current_user) == 0) {
2184 $user = $this->getCurrentUser();
2185 $this->_current_user = explode("@", $user);
2187 return $this->_current_user;
2191 * Returns value for lower_case_table_names variable
2193 * @return string
2195 public function getLowerCaseNames()
2197 if (is_null($this->_lower_case_table_names)) {
2198 $this->_lower_case_table_names = $this->fetchValue(
2199 "SELECT @@lower_case_table_names"
2202 return $this->_lower_case_table_names;
2206 * Get the list of system schemas
2208 * @return array list of system schemas
2210 public function getSystemSchemas()
2212 $schemas = array(
2213 'information_schema', 'performance_schema', 'mysql', 'sys'
2215 $systemSchemas = array();
2216 foreach ($schemas as $schema) {
2217 if ($this->isSystemSchema($schema, true)) {
2218 $systemSchemas[] = $schema;
2221 return $systemSchemas;
2225 * Checks whether given schema is a system schema
2227 * @param string $schema_name Name of schema (database) to test
2228 * @param bool $testForMysqlSchema Whether 'mysql' schema should
2229 * be treated the same as IS and DD
2231 * @return bool
2233 public function isSystemSchema($schema_name, $testForMysqlSchema = false)
2235 $schema_name = strtolower($schema_name);
2236 return $schema_name == 'information_schema'
2237 || $schema_name == 'performance_schema'
2238 || ($schema_name == 'mysql' && $testForMysqlSchema)
2239 || $schema_name == 'sys';
2243 * Return connection parameters for the database server
2245 * @param integer $mode Connection mode on of CONNECT_USER, CONNECT_CONTROL
2246 * or CONNECT_AUXILIARY.
2247 * @param array $server Server information like host/port/socket/persistent
2249 * @return array user, host and server settings array
2251 public function getConnectionParams($mode, $server = null)
2253 global $cfg;
2255 $user = null;
2256 $password = null;
2258 if ($mode == DatabaseInterface::CONNECT_USER) {
2259 $user = $cfg['Server']['user'];
2260 $password = $cfg['Server']['password'];
2261 $server = $cfg['Server'];
2262 } elseif ($mode == DatabaseInterface::CONNECT_CONTROL) {
2263 $user = $cfg['Server']['controluser'];
2264 $password = $cfg['Server']['controlpass'];
2266 $server = array();
2268 if (! empty($cfg['Server']['controlhost'])) {
2269 $server['host'] = $cfg['Server']['controlhost'];
2270 } else {
2271 $server['host'] = $cfg['Server']['host'];
2273 // Share the settings if the host is same
2274 if ($server['host'] == $cfg['Server']['host']) {
2275 $shared = array(
2276 'port', 'socket', 'connect_type', 'compress',
2277 'ssl', 'ssl_key', 'ssl_cert', 'ssl_ca',
2278 'ssl_ca_path', 'ssl_ciphers', 'ssl_verify',
2280 foreach ($shared as $item) {
2281 if (isset($cfg['Server'][$item])) {
2282 $server[$item] = $cfg['Server'][$item];
2286 // Set configured port
2287 if (! empty($cfg['Server']['controlport'])) {
2288 $server['port'] = $cfg['Server']['controlport'];
2290 // Set any configuration with control_ prefix
2291 foreach ($cfg['Server'] as $key => $val) {
2292 if (substr($key, 0, 8) === 'control_') {
2293 $server[substr($key, 8)] = $val;
2296 } else {
2297 if (is_null($server)) {
2298 return array(null, null, null);
2300 if (isset($server['user'])) {
2301 $user = $server['user'];
2303 if (isset($server['password'])) {
2304 $password = $server['password'];
2308 // Perform sanity checks on some variables
2309 if (empty($server['port'])) {
2310 $server['port'] = 0;
2311 } else {
2312 $server['port'] = intval($server['port']);
2314 if (empty($server['socket'])) {
2315 $server['socket'] = null;
2317 if (empty($server['host'])) {
2318 $server['host'] = 'localhost';
2320 if (!isset($server['ssl'])) {
2321 $server['ssl'] = false;
2323 if (!isset($server['compress'])) {
2324 $server['compress'] = false;
2327 return array($user, $password, $server);
2331 * connects to the database server
2333 * @param integer $mode Connection mode on of CONNECT_USER, CONNECT_CONTROL
2334 * or CONNECT_AUXILIARY.
2335 * @param array $server Server information like host/port/socket/persistent
2337 * @return mixed false on error or a connection object on success
2339 public function connect($mode, $server = null)
2341 list($user, $password, $server) = $this->getConnectionParams($mode, $server);
2343 if (is_null($user) || is_null($password)) {
2344 trigger_error(
2345 __('Missing connection parameters!'),
2346 E_USER_WARNING
2348 return false;
2351 // Do not show location and backtrace for connection errors
2352 $GLOBALS['error_handler']->setHideLocation(true);
2353 $result = $this->_extension->connect(
2354 $user, $password, $server
2356 $GLOBALS['error_handler']->setHideLocation(false);
2358 if ($result) {
2359 /* Run post connect for user connections */
2360 if ($mode == DatabaseInterface::CONNECT_USER) {
2361 $this->postConnect($result);
2363 return $result;
2366 if ($mode == DatabaseInterface::CONNECT_CONTROL) {
2367 trigger_error(
2369 'Connection for controluser as defined in your '
2370 . 'configuration failed.'
2372 E_USER_WARNING
2374 return false;
2375 } else if ($mode == DatabaseInterface::CONNECT_AUXILIARY) {
2376 // Do not go back to main login if connection failed
2377 // (currently used only in unit testing)
2378 return false;
2381 Logging::logUser($user, 'mysql-denied');
2382 $GLOBALS['auth_plugin']->authFails();
2384 return $result;
2388 * selects given database
2390 * @param string $dbname database name to select
2391 * @param object $link connection object
2393 * @return boolean
2395 public function selectDb($dbname, $link = null)
2397 $link = $this->getLink($link);
2398 if ($link === false) {
2399 return false;
2401 return $this->_extension->selectDb($dbname, $link);
2405 * returns array of rows with associative and numeric keys from $result
2407 * @param object $result result set identifier
2409 * @return array
2411 public function fetchArray($result)
2413 return $this->_extension->fetchArray($result);
2417 * returns array of rows with associative keys from $result
2419 * @param object $result result set identifier
2421 * @return array
2423 public function fetchAssoc($result)
2425 return $this->_extension->fetchAssoc($result);
2429 * returns array of rows with numeric keys from $result
2431 * @param object $result result set identifier
2433 * @return array
2435 public function fetchRow($result)
2437 return $this->_extension->fetchRow($result);
2441 * Adjusts the result pointer to an arbitrary row in the result
2443 * @param object $result database result
2444 * @param integer $offset offset to seek
2446 * @return bool true on success, false on failure
2448 public function dataSeek($result, $offset)
2450 return $this->_extension->dataSeek($result, $offset);
2454 * Frees memory associated with the result
2456 * @param object $result database result
2458 * @return void
2460 public function freeResult($result)
2462 $this->_extension->freeResult($result);
2466 * Check if there are any more query results from a multi query
2468 * @param object $link the connection object
2470 * @return bool true or false
2472 public function moreResults($link = null)
2474 $link = $this->getLink($link);
2475 if ($link === false) {
2476 return false;
2478 return $this->_extension->moreResults($link);
2482 * Prepare next result from multi_query
2484 * @param object $link the connection object
2486 * @return bool true or false
2488 public function nextResult($link = null)
2490 $link = $this->getLink($link);
2491 if ($link === false) {
2492 return false;
2494 return $this->_extension->nextResult($link);
2498 * Store the result returned from multi query
2500 * @param object $link the connection object
2502 * @return mixed false when empty results / result set when not empty
2504 public function storeResult($link = null)
2506 $link = $this->getLink($link);
2507 if ($link === false) {
2508 return false;
2510 return $this->_extension->storeResult($link);
2514 * Returns a string representing the type of connection used
2516 * @param object $link mysql link
2518 * @return string type of connection used
2520 public function getHostInfo($link = null)
2522 $link = $this->getLink($link);
2523 if ($link === false) {
2524 return false;
2526 return $this->_extension->getHostInfo($link);
2530 * Returns the version of the MySQL protocol used
2532 * @param object $link mysql link
2534 * @return integer version of the MySQL protocol used
2536 public function getProtoInfo($link = null)
2538 $link = $this->getLink($link);
2539 if ($link === false) {
2540 return false;
2542 return $this->_extension->getProtoInfo($link);
2546 * returns a string that represents the client library version
2548 * @return string MySQL client library version
2550 public function getClientInfo()
2552 return $this->_extension->getClientInfo();
2556 * returns last error message or false if no errors occurred
2558 * @param object $link connection link
2560 * @return string|bool $error or false
2562 public function getError($link = null)
2564 $link = $this->getLink($link);
2565 return $this->_extension->getError($link);
2569 * returns the number of rows returned by last query
2571 * @param object $result result set identifier
2573 * @return string|int
2575 public function numRows($result)
2577 return $this->_extension->numRows($result);
2581 * returns last inserted auto_increment id for given $link
2582 * or $GLOBALS['userlink']
2584 * @param object $link the connection object
2586 * @return int|boolean
2588 public function insertId($link = null)
2590 $link = $this->getLink($link);
2591 if ($link === false) {
2592 return false;
2594 // If the primary key is BIGINT we get an incorrect result
2595 // (sometimes negative, sometimes positive)
2596 // and in the present function we don't know if the PK is BIGINT
2597 // so better play safe and use LAST_INSERT_ID()
2599 // When no controluser is defined, using mysqli_insert_id($link)
2600 // does not always return the last insert id due to a mixup with
2601 // the tracking mechanism, but this works:
2602 return $this->fetchValue('SELECT LAST_INSERT_ID();', 0, 0, $link);
2606 * returns the number of rows affected by last query
2608 * @param object $link the connection object
2609 * @param bool $get_from_cache whether to retrieve from cache
2611 * @return int|boolean
2613 public function affectedRows($link = null, $get_from_cache = true)
2615 $link = $this->getLink($link);
2616 if ($link === false) {
2617 return false;
2620 if ($get_from_cache) {
2621 return $GLOBALS['cached_affected_rows'];
2622 } else {
2623 return $this->_extension->affectedRows($link);
2628 * returns metainfo for fields in $result
2630 * @param object $result result set identifier
2632 * @return array meta info for fields in $result
2634 public function getFieldsMeta($result)
2636 $result = $this->_extension->getFieldsMeta($result);
2638 if ($this->getLowerCaseNames() === '2') {
2640 * Fixup orgtable for lower_case_table_names = 2
2642 * In this setup MySQL server reports table name lower case
2643 * but we still need to operate on original case to properly
2644 * match existing strings
2646 foreach ($result as $value) {
2647 if (strlen($value->orgtable) !== 0 &&
2648 mb_strtolower($value->orgtable) === mb_strtolower($value->table)) {
2649 $value->orgtable = $value->table;
2654 return $result;
2658 * return number of fields in given $result
2660 * @param object $result result set identifier
2662 * @return int field count
2664 public function numFields($result)
2666 return $this->_extension->numFields($result);
2670 * returns the length of the given field $i in $result
2672 * @param object $result result set identifier
2673 * @param int $i field
2675 * @return int length of field
2677 public function fieldLen($result, $i)
2679 return $this->_extension->fieldLen($result, $i);
2683 * returns name of $i. field in $result
2685 * @param object $result result set identifier
2686 * @param int $i field
2688 * @return string name of $i. field in $result
2690 public function fieldName($result, $i)
2692 return $this->_extension->fieldName($result, $i);
2696 * returns concatenated string of human readable field flags
2698 * @param object $result result set identifier
2699 * @param int $i field
2701 * @return string field flags
2703 public function fieldFlags($result, $i)
2705 return $this->_extension->fieldFlags($result, $i);
2709 * returns properly escaped string for use in MySQL queries
2711 * @param string $str string to be escaped
2712 * @param mixed $link optional database link to use
2714 * @return string a MySQL escaped string
2716 public function escapeString($str, $link = null)
2718 if ($link === null) {
2719 $link = $this->getLink();
2722 if ($this->_extension === null) {
2723 return $str;
2726 return $this->_extension->escapeString($link, $str);
2730 * Gets correct link object.
2732 * @param object $link optional database link to use
2734 * @return object|boolean
2736 public function getLink($link = null)
2738 if (! is_null($link) && $link !== false) {
2739 return $link;
2742 if (isset($GLOBALS['userlink']) && !is_null($GLOBALS['userlink'])) {
2743 return $GLOBALS['userlink'];
2744 } else {
2745 return false;
2750 * Checks if this database server is running on Amazon RDS.
2752 * @return boolean
2754 public function isAmazonRds()
2756 if (Util::cacheExists('is_amazon_rds')) {
2757 return Util::cacheGet('is_amazon_rds');
2759 $sql = 'SELECT @@basedir';
2760 $result = $this->fetchResult($sql);
2761 $rds = ($result[0] == '/rdsdbbin/mysql/');
2762 Util::cacheSet('is_amazon_rds', $rds);
2764 return $rds;
2768 * Gets SQL for killing a process.
2770 * @param int $process Process ID
2772 * @return string
2774 public function getKillQuery($process)
2776 if ($this->isAmazonRds()) {
2777 return 'CALL mysql.rds_kill(' . $process . ');';
2778 } else {
2779 return 'KILL ' . $process . ';';
2784 * Get the phpmyadmin database manager
2786 * @return SystemDatabase
2788 public function getSystemDatabase()
2790 return new SystemDatabase($this);
2794 * Get a table with database name and table name
2796 * @param string $db_name DB name
2797 * @param string $table_name Table name
2799 * @return Table
2801 public function getTable($db_name, $table_name)
2803 return new Table($table_name, $db_name, $this);
2807 * returns collation of given db
2809 * @param string $db name of db
2811 * @return string collation of $db
2813 public function getDbCollation($db)
2815 if ($this->isSystemSchema($db)) {
2816 // We don't have to check the collation of the virtual
2817 // information_schema database: We know it!
2818 return 'utf8_general_ci';
2821 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
2822 // this is slow with thousands of databases
2823 $sql = 'SELECT DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA'
2824 . ' WHERE SCHEMA_NAME = \'' . $this->escapeString($db)
2825 . '\' LIMIT 1';
2826 return $this->fetchValue($sql);
2827 } else {
2828 $this->selectDb($db);
2829 $return = $this->fetchValue('SELECT @@collation_database');
2830 if ($db !== $GLOBALS['db']) {
2831 $this->selectDb($GLOBALS['db']);
2833 return $return;
2838 * returns default server collation from show variables
2840 * @return string $server_collation
2842 function getServerCollation()
2844 return $this->fetchValue('SELECT @@collation_server');