function PMA_analyseShowGrant($rs_usr, &$is_create_priv, &$db_to_create, &$is_reload_priv) { $re0 = '(^|(\\\\\\\\)+|[^\\])'; // non-escaped wildcards $re1 = '(^|[^\\])(\\\\)+'; // escaped wildcards while ($row = PMA_DBI_fetch_row($rs_usr)) { $show_grants_dbname = substr($row[0], strpos($row[0], ' ON ') + 4, strpos($row[0], '.', strpos($row[0], ' ON ')) - strpos($row[0], ' ON ') - 4); $show_grants_dbname = ereg_replace('^`(.*)`', '\\1', $show_grants_dbname); $show_grants_str = substr($row[0], 6, strpos($row[0], ' ON ') - 6); if ($show_grants_str == 'ALL' || $show_grants_str == 'ALL PRIVILEGES' || $show_grants_str == 'CREATE' || strpos($show_grants_str, 'CREATE')) { if ($show_grants_dbname == '*') { $is_create_priv = TRUE; $is_reload_priv = TRUE; $db_to_create = ''; break; } else { if (ereg($re0 . '%|_', $show_grants_dbname) && !ereg('\\\\%|\\\\_', $show_grants_dbname) || !PMA_DBI_try_query('USE ' . ereg_replace($re1 . '(%|_)', '\\1\\3', $show_grants_dbname)) && substr(PMA_DBI_getError(), 1, 4) != 1044) { $db_to_create = ereg_replace($re0 . '%', '\\1...', ereg_replace($re0 . '_', '\\1?', $show_grants_dbname)); $db_to_create = ereg_replace($re1 . '(%|_)', '\\1\\3', $db_to_create); $is_create_priv = TRUE; break; } } // end elseif } // end if } // end while }
function PMA_analyseShowGrant($rs_usr, &$is_create_db_priv, &$db_to_create, &$is_reload_priv, &$dbs_where_create_table_allowed) { $re0 = '(^|(\\\\\\\\)+|[^\\])'; // non-escaped wildcards $re1 = '(^|[^\\])(\\\\)+'; // escaped wildcards while ($row = PMA_DBI_fetch_row($rs_usr)) { $show_grants_dbname = substr($row[0], strpos($row[0], ' ON ') + 4, strpos($row[0], '.', strpos($row[0], ' ON ')) - strpos($row[0], ' ON ') - 4); $show_grants_dbname = ereg_replace('^`(.*)`', '\\1', $show_grants_dbname); $show_grants_str = substr($row[0], 6, strpos($row[0], ' ON ') - 6); if ($show_grants_str == 'RELOAD') { $is_reload_priv = true; } /** * @todo if we find CREATE VIEW but not CREATE, do not offer * the create database dialog box */ if ($show_grants_str == 'ALL' || $show_grants_str == 'ALL PRIVILEGES' || $show_grants_str == 'CREATE' || strpos($show_grants_str, 'CREATE,') !== false) { if ($show_grants_dbname == '*') { // a global CREATE privilege $is_create_db_priv = true; $is_reload_priv = true; $db_to_create = ''; $dbs_where_create_table_allowed[] = '*'; break; } else { // this array may contain wildcards $dbs_where_create_table_allowed[] = $show_grants_dbname; // before MySQL 4.1.0, we cannot use backquotes around a dbname // for the USE command, so the USE will fail if the dbname contains // a "-" and we cannot detect if such a db already exists; // since 4.1.0, we need to use backquotes if the dbname contains a "-" // in a USE command if (PMA_MYSQL_INT_VERSION > 40100) { $dbname_to_test = PMA_backquote($show_grants_dbname); } else { $dbname_to_test = $show_grants_dbname; } if (ereg($re0 . '%|_', $show_grants_dbname) && !ereg('\\\\%|\\\\_', $show_grants_dbname) || !PMA_DBI_try_query('USE ' . ereg_replace($re1 . '(%|_)', '\\1\\3', $dbname_to_test), null, PMA_DBI_QUERY_STORE) && substr(PMA_DBI_getError(), 1, 4) != 1044) { $db_to_create = ereg_replace($re0 . '%', '\\1...', ereg_replace($re0 . '_', '\\1?', $show_grants_dbname)); $db_to_create = ereg_replace($re1 . '(%|_)', '\\1\\3', $db_to_create); $is_create_db_priv = true; /** * @todo collect $db_to_create into an array, to display a * drop-down in the "Create new database" dialog */ // we don't break, we want all possible databases //break; } // end if } // end elseif } // end if } // end while }
/** * User is not allowed to login to MySQL -> authentication failed * * @global string the MySQL error message PHP returns * @global string the connection type (persistent or not) * @global string the MySQL server port to use * @global string the MySQL socket port to use * @global array the current server settings * @global string the font face to use in case of failure * @global string the default font size to use in case of failure * @global string the big font size to use in case of failure * @global boolean tell the "PMA_mysqlDie()" function headers have been * sent * * @return boolean always true (no return indeed) */ public function authFails() { $conn_error = PMA_DBI_getError(); if (!$conn_error) { $conn_error = __('Cannot connect: invalid settings.'); } /* HTML header */ $response = PMA_Response::getInstance(); $response->getFooter()->setMinimal(); $header = $response->getHeader(); $header->setTitle(__('Access denied')); $header->disableMenu(); echo '<br /><br /> <center> <h1>'; echo sprintf(__('Welcome to %s'), ' phpMyAdmin '); echo '</h1> </center> <br /> <table cellpadding="0" cellspacing="3" style="margin: 0 auto" width="80%"> <tr> <td>'; if (isset($GLOBALS['allowDeny_forbidden']) && $GLOBALS['allowDeny_forbidden']) { trigger_error(__('Access denied'), E_USER_NOTICE); } else { // Check whether user has configured something if ($GLOBALS['PMA_Config']->source_mtime == 0) { echo '<p>' . sprintf(__('You probably did not create a configuration file.' . ' You might want to use the %1$ssetup script%2$s to' . ' create one.'), '<a href="setup/">', '</a>') . '</p>' . "\n"; } elseif (!isset($GLOBALS['errno']) || isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002 && $GLOBALS['errno'] != 2003) { // if we display the "Server not responding" error, do not confuse // users by telling them they have a settings problem // (note: it's true that they could have a badly typed host name, // but anyway the current message tells that the server // rejected the connection, which is not really what happened) // 2002 is the error given by mysqli // 2003 is the error given by mysql trigger_error(__('phpMyAdmin tried to connect to the MySQL server, and the' . ' server rejected the connection. You should check the' . ' host, username and password in your configuration and' . ' make sure that they correspond to the information given' . ' by the administrator of the MySQL server.'), E_USER_WARNING); } PMA_Util::mysqlDie($conn_error, '', true, '', false); } $GLOBALS['error_handler']->dispUserErrors(); echo '</td> </tr>'; if (count($GLOBALS['cfg']['Servers']) > 1) { // offer a chance to login to other servers if the current one failed include_once './libraries/select_server.lib.php'; echo '<tr>' . "\n"; echo ' <td>' . "\n"; PMA_selectServer(true, true); echo ' </td>' . "\n"; echo '</tr>' . "\n"; } echo '</table>' . "\n"; exit; return true; }
/** * returns array with databases containing extended infos about them * * @todo move into PMA_List_Database? * @param string $databases database * @param boolean $force_stats retrieve stats also for MySQL < 5 * @param resource $link mysql link * @param string $sort_by column to order by * @param string $sort_order ASC or DESC * @param integer $limit_offset starting offset for LIMIT * @param bool|int $limit_count row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList'] * @return array $databases */ function PMA_DBI_get_databases_full($database = null, $force_stats = false, $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC', $limit_offset = 0, $limit_count = false) { $sort_order = strtoupper($sort_order); if (true === $limit_count) { $limit_count = $GLOBALS['cfg']['MaxDbList']; } // initialize to avoid errors when there are no databases $databases = array(); $apply_limit_and_order_manual = true; if (!$GLOBALS['cfg']['Server']['DisableIS']) { /** * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT * cause MySQL does not support natural ordering, we have to do it afterward */ if ($GLOBALS['cfg']['NaturalOrder']) { $limit = ''; } else { if ($limit_count) { $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset; } $apply_limit_and_order_manual = false; } // get table information from information_schema if ($database) { $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \'' . addslashes($database) . '\''; } else { $sql_where_schema = ''; } // for PMA bc: // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME` $sql = ' SELECT `information_schema`.`SCHEMATA`.*'; if ($force_stats) { $sql .= ', COUNT(`information_schema`.`TABLES`.`TABLE_SCHEMA`) AS `SCHEMA_TABLES`, SUM(`information_schema`.`TABLES`.`TABLE_ROWS`) AS `SCHEMA_TABLE_ROWS`, SUM(`information_schema`.`TABLES`.`DATA_LENGTH`) AS `SCHEMA_DATA_LENGTH`, SUM(`information_schema`.`TABLES`.`MAX_DATA_LENGTH`) AS `SCHEMA_MAX_DATA_LENGTH`, SUM(`information_schema`.`TABLES`.`INDEX_LENGTH`) AS `SCHEMA_INDEX_LENGTH`, SUM(`information_schema`.`TABLES`.`DATA_LENGTH` + `information_schema`.`TABLES`.`INDEX_LENGTH`) AS `SCHEMA_LENGTH`, SUM(`information_schema`.`TABLES`.`DATA_FREE`) AS `SCHEMA_DATA_FREE`'; } $sql .= ' FROM `information_schema`.`SCHEMATA`'; if ($force_stats) { $sql .= ' LEFT JOIN `information_schema`.`TABLES` ON BINARY `information_schema`.`TABLES`.`TABLE_SCHEMA` = BINARY `information_schema`.`SCHEMATA`.`SCHEMA_NAME`'; } $sql .= ' ' . $sql_where_schema . ' GROUP BY BINARY `information_schema`.`SCHEMATA`.`SCHEMA_NAME` ORDER BY BINARY ' . PMA_backquote($sort_by) . ' ' . $sort_order . $limit; $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link); $mysql_error = PMA_DBI_getError($link); if (!count($databases) && $GLOBALS['errno']) { PMA_mysqlDie($mysql_error, $sql); } // display only databases also in official database list // f.e. to apply hide_db and only_db $drops = array_diff(array_keys($databases), (array) $GLOBALS['pma']->databases); if (count($drops)) { foreach ($drops as $drop) { unset($databases[$drop]); } unset($drop); } unset($sql_where_schema, $sql, $drops); } else { foreach ($GLOBALS['pma']->databases as $database_name) { // MySQL forward compatibility // so pma could use this array as if every server is of version >5.0 $databases[$database_name]['SCHEMA_NAME'] = $database_name; if ($force_stats) { require_once './libraries/mysql_charsets.lib.php'; $databases[$database_name]['DEFAULT_COLLATION_NAME'] = PMA_getDbCollation($database_name); // get additional info about tables $databases[$database_name]['SCHEMA_TABLES'] = 0; $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0; $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0; $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0; $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0; $databases[$database_name]['SCHEMA_LENGTH'] = 0; $databases[$database_name]['SCHEMA_DATA_FREE'] = 0; $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($database_name) . ';'); while ($row = PMA_DBI_fetch_assoc($res)) { $databases[$database_name]['SCHEMA_TABLES']++; $databases[$database_name]['SCHEMA_TABLE_ROWS'] += $row['Rows']; $databases[$database_name]['SCHEMA_DATA_LENGTH'] += $row['Data_length']; $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] += $row['Max_data_length']; $databases[$database_name]['SCHEMA_INDEX_LENGTH'] += $row['Index_length']; // for InnoDB, this does not contain the number of // overhead bytes but the total free space if ('InnoDB' != $row['Engine']) { $databases[$database_name]['SCHEMA_DATA_FREE'] += $row['Data_free']; } $databases[$database_name]['SCHEMA_LENGTH'] += $row['Data_length'] + $row['Index_length']; } PMA_DBI_free_result($res); unset($res); } } } /** * apply limit and order manually now * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder']) */ if ($apply_limit_and_order_manual) { $GLOBALS['callback_sort_order'] = $sort_order; $GLOBALS['callback_sort_by'] = $sort_by; usort($databases, 'PMA_usort_comparison_callback'); unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']); /** * now apply limit */ if ($limit_count) { $databases = array_slice($databases, $limit_offset, $limit_count); } } return $databases; }
/** * retrieves database list from server * * @todo we could also search mysql tables if all fail? * @uses PMA_List_Database::$_show_databases_disabled for not retrying if SHOW DATABASES is disabled * @uses PMA_List_Database::$_db_link * @uses PMA_List_Database::$_db_link_control in case of SHOW DATABASES is disabled for userlink * @uses PMA_DBI_fetch_result() * @uses PMA_DBI_getError() * @uses $GLOBALS['error_showdatabases'] * @uses $GLOBALS['errno'] * @param string $like_db_name usally a db_name containing wildcards */ protected function _retrieve($like_db_name = null) { if ($this->_show_databases_disabled) { return array(); } if (null !== $like_db_name) { $command = "SHOW DATABASES LIKE '" . $like_db_name . "'"; } elseif (null === $this->_command) { $command = str_replace('#user#', $GLOBALS['cfg']['Server']['user'], $GLOBALS['cfg']['Server']['ShowDatabasesCommand']); $this->_command = $command; } else { $command = $this->_command; } $database_list = PMA_DBI_fetch_result($command, null, null, $this->_db_link); PMA_DBI_getError(); if ($GLOBALS['errno'] !== 0) { // failed to get database list, try the control user // (hopefully there is one and he has SHOW DATABASES right) $this->_db_link = $this->_db_link_control; $database_list = PMA_DBI_fetch_result($command, null, null, $this->_db_link); PMA_DBI_getError(); if ($GLOBALS['errno'] !== 0) { // failed! we will display a warning that phpMyAdmin could not safely // retrieve database list, the admin has to setup a control user or // allow SHOW DATABASES $GLOBALS['error_showdatabases'] = true; $this->_show_databases_disabled = true; } } return $database_list; }
/** * Save recent tables into phpMyAdmin database. * * @return true|PMA_Message */ public function saveToDb() { $username = $GLOBALS['cfg']['Server']['user']; $sql_query = " REPLACE INTO " . $this->pma_table . " (`username`, `tables`)" . " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes(json_encode($this->tables)) . "')"; $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']); if (!$success) { $message = PMA_Message::error(__('Could not save recent table')); $message->addMessage('<br /><br />'); $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink']))); return $message; } return true; }
} } } if (empty($_REQUEST['change_copy'])) { if (empty($queries)) { $message = PMA_Message::error(__('No users selected for deleting!')); } else { if ($_REQUEST['mode'] == 3) { $queries[] = '# ' . __('Reloading the privileges') . ' ...'; $queries[] = 'FLUSH PRIVILEGES;'; } $drop_user_error = ''; foreach ($queries as $sql_query) { if ($sql_query{0} != '#') { if (! PMA_DBI_try_query($sql_query, $GLOBALS['userlink'])) { $drop_user_error .= PMA_DBI_getError() . "\n"; } } } // tracking sets this, causing the deleted db to be shown in navi unset($GLOBALS['db']); $sql_query = join("\n", $queries); if (! empty($drop_user_error)) { $message = PMA_Message::rawError($drop_user_error); } else { $message = PMA_Message::success(__('The selected users have been deleted successfully.')); } } unset($queries); }
/** * Save this table's UI preferences into phpMyAdmin database. * * @return true|PMA_Message */ protected function saveUiPrefsToDb() { $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." . PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']); $username = $GLOBALS['cfg']['Server']['user']; $sql_query = " REPLACE INTO " . $pma_table . " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name) . "', '" . PMA_sqlAddSlashes($this->name) . "', '" . PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)"; $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']); if (!$success) { $message = PMA_Message::error(__('Could not save table UI preferences')); $message->addMessage('<br /><br />'); $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink']))); return $message; } // Remove some old rows in table_uiprefs if it exceeds the configured maximum rows $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table; $rows_count = PMA_DBI_fetch_value($sql_query); $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs']; if ($rows_count > $max_rows) { $num_rows_to_delete = $rows_count - $max_rows; $sql_query = ' DELETE FROM ' . $pma_table . ' ORDER BY last_update ASC' . ' LIMIT ' . $num_rows_to_delete; $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']); if (!$success) { $message = PMA_Message::error(sprintf(__('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'), PMA_showDocu('cfg_Servers_MaxTableUiprefs'))); $message->addMessage('<br /><br />'); $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink']))); print_r($message); return $message; } } return true; }
/** * Counts and returns (or displays) the number of records in a table * * Revision 13 July 2001: Patch for limiting dump size from * vinay@sanisoft.com & girish@sanisoft.com * * @param string the current database name * @param string the current table name * @param boolean whether to force an exact count * * @return mixed the number of records if "retain" param is true, * otherwise true * * @access public */ public static function countRecords($db, $table, $force_exact = false, $is_view = null) { if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) { $row_count = PMA_Table::$cache[$db][$table]['ExactRows']; } else { $row_count = false; if (null === $is_view) { $is_view = PMA_Table::isView($db, $table); } if (!$force_exact) { if (!isset(PMA_Table::$cache[$db][$table]['Rows']) && !$is_view) { PMA_Table::$cache[$db][$table] = PMA_DBI_fetch_single_row('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table, true) . '\''); } $row_count = PMA_Table::$cache[$db][$table]['Rows']; } // for a VIEW, $row_count is always false at this point if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) { if (!$is_view) { $row_count = PMA_DBI_fetch_value('SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table)); } else { // For complex views, even trying to get a partial record // count could bring down a server, so we offer an // alternative: setting MaxExactCountViews to 0 will bypass // completely the record counting for views if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) { $row_count = 0; } else { // Counting all rows of a VIEW could be too long, so use // a LIMIT clause. // Use try_query because it can fail (when a VIEW is // based on a table that no longer exists) $result = PMA_DBI_try_query('SELECT 1 FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' LIMIT ' . $GLOBALS['cfg']['MaxExactCountViews'], null, PMA_DBI_QUERY_STORE); if (!PMA_DBI_getError()) { $row_count = PMA_DBI_num_rows($result); PMA_DBI_free_result($result); } } } PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count; } } return $row_count; }
/** * Handles editor requests for adding or editing an item * * @return void */ function PMA_TRI_handleEditor() { global $_REQUEST, $_POST, $errors, $db, $table; if (!empty($_REQUEST['editor_process_add']) || !empty($_REQUEST['editor_process_edit'])) { $sql_query = ''; $item_query = PMA_TRI_getQueryFromRequest(); if (!count($errors)) { // set by PMA_RTN_getQueryFromRequest() // Execute the created query if (!empty($_REQUEST['editor_process_edit'])) { // Backup the old trigger, in case something goes wrong $trigger = PMA_TRI_getDataFromName($_REQUEST['item_original_name']); $create_item = $trigger['create']; $drop_item = $trigger['drop'] . ';'; $result = PMA_DBI_try_query($drop_item); if (!$result) { $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($drop_item)) . '<br />' . __('MySQL said: ') . PMA_DBI_getError(null); } else { $result = PMA_DBI_try_query($item_query); if (!$result) { $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($item_query)) . '<br />' . __('MySQL said: ') . PMA_DBI_getError(null); // We dropped the old item, but were unable to create the new one // Try to restore the backup query $result = PMA_DBI_try_query($create_item); if (!$result) { // OMG, this is really bad! We dropped the query, // failed to create a new one // and now even the backup query does not execute! // This should not happen, but we better handle // this just in case. $errors[] = __('Sorry, we failed to restore the dropped trigger.') . '<br />' . __('The backed up query was:') . "\"" . htmlspecialchars($create_item) . "\"" . '<br />' . __('MySQL said: ') . PMA_DBI_getError(null); } } else { $message = PMA_Message::success(__('Trigger %1$s has been modified.')); $message->addParam(PMA_Util::backquote($_REQUEST['item_name'])); $sql_query = $drop_item . $item_query; } } } else { // 'Add a new item' mode $result = PMA_DBI_try_query($item_query); if (!$result) { $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($item_query)) . '<br /><br />' . __('MySQL said: ') . PMA_DBI_getError(null); } else { $message = PMA_Message::success(__('Trigger %1$s has been created.')); $message->addParam(PMA_Util::backquote($_REQUEST['item_name'])); $sql_query = $item_query; } } } if (count($errors)) { $message = PMA_Message::error(__('<b>One or more errors have occured while processing your request:</b>')); $message->addString('<ul>'); foreach ($errors as $string) { $message->addString('<li>' . $string . '</li>'); } $message->addString('</ul>'); } $output = PMA_Util::getMessage($message, $sql_query); if ($GLOBALS['is_ajax_request']) { $response = PMA_Response::getInstance(); if ($message->isSuccess()) { $items = PMA_DBI_get_triggers($db, $table, ''); $trigger = false; foreach ($items as $value) { if ($value['name'] == $_REQUEST['item_name']) { $trigger = $value; } } $insert = false; if (empty($table) || $trigger !== false && $table == $trigger['table']) { $insert = true; $response->addJSON('new_row', PMA_TRI_getRowForList($trigger)); $response->addJSON('name', htmlspecialchars(strtoupper($_REQUEST['item_name']))); } $response->addJSON('insert', $insert); $response->addJSON('message', $output); } else { $response->addJSON('message', $message); $response->isSuccess(false); } exit; } } /** * Display a form used to add/edit a trigger, if necessary */ if (count($errors) || empty($_REQUEST['editor_process_add']) && empty($_REQUEST['editor_process_edit']) && (!empty($_REQUEST['add_item']) || !empty($_REQUEST['edit_item']))) { // Get the data for the form (if any) if (!empty($_REQUEST['add_item'])) { $title = PMA_RTE_getWord('add'); $item = PMA_TRI_getDataFromRequest(); $mode = 'add'; } else { if (!empty($_REQUEST['edit_item'])) { $title = __("Edit trigger"); if (!empty($_REQUEST['item_name']) && empty($_REQUEST['editor_process_edit'])) { $item = PMA_TRI_getDataFromName($_REQUEST['item_name']); if ($item !== false) { $item['item_original_name'] = $item['item_name']; } } else { $item = PMA_TRI_getDataFromRequest(); } $mode = 'edit'; } } if ($item !== false) { // Show form $editor = PMA_TRI_getEditorForm($mode, $item); if ($GLOBALS['is_ajax_request']) { $response = PMA_Response::getInstance(); $response->addJSON('message', $editor); $response->addJSON('title', $title); } else { echo "\n\n<h2>{$title}</h2>\n\n{$editor}"; unset($_POST); } exit; } else { $message = __('Error in processing request') . ' : '; $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_Util::backquote($db))); $message = PMA_message::error($message); if ($GLOBALS['is_ajax_request']) { $response = PMA_Response::getInstance(); $response->isSuccess(false); $response->addJSON('message', $message); exit; } else { $message->display(); } } } }
/** * sets privilege information extracted from SHOW GRANTS result * * Detection for some CREATE privilege. * * Since MySQL 4.1.2, we can easily detect current user's grants using $userlink * (no control user needed) and we don't have to try any other method for * detection * * @todo fix to get really all privileges, not only explicitly defined for this user * from MySQL manual: (http://dev.mysql.com/doc/refman/5.0/en/show-grants.html) * SHOW GRANTS displays only the privileges granted explicitly to the named * account. Other privileges might be available to the account, but they are not * displayed. For example, if an anonymous account exists, the named account * might be able to use its privileges, but SHOW GRANTS will not display them. * * @uses $_SESSION['is_create_db_priv'] for caching * @uses $_SESSION['is_process_priv'] for caching * @uses $_SESSION['is_reload_priv'] for caching * @uses $_SESSION['db_to_create'] for caching * @uses $_SESSION['dbs_where_create_table_allowed'] for caching * @uses $GLOBALS['is_create_db_priv'] to set it * @uses $GLOBALS['is_process_priv'] to set it * @uses $GLOBALS['is_reload_priv'] to set it * @uses $GLOBALS['db_to_create'] to set it * @uses $GLOBALS['dbs_where_create_table_allowed'] to set it * @uses $GLOBALS['server'] * @uses PMA_DBI_try_query() * @uses PMA_DBI_fetch_row() * @uses PMA_DBI_free_result() * @uses PMA_DBI_getError() * @uses PMA_unQuote() * @uses PMA_backquote() * @uses preg_match() * @uses preg_replace() * @uses substr() * @uses strpos() */ function PMA_analyseShowGrant() { if (PMA_cacheExists('is_create_db_priv', true)) { $GLOBALS['is_create_db_priv'] = PMA_cacheGet('is_create_db_priv', true); $GLOBALS['is_process_priv'] = PMA_cacheGet('is_process_priv', true); $GLOBALS['is_reload_priv'] = PMA_cacheGet('is_reload_priv', true); $GLOBALS['db_to_create'] = PMA_cacheGet('db_to_create', true); $GLOBALS['dbs_where_create_table_allowed'] = PMA_cacheGet('dbs_where_create_table_allowed', true); return; } // defaults $GLOBALS['is_create_db_priv'] = false; $GLOBALS['is_process_priv'] = true; $GLOBALS['is_reload_priv'] = false; $GLOBALS['db_to_create'] = ''; $GLOBALS['dbs_where_create_table_allowed'] = array(); $rs_usr = PMA_DBI_try_query('SHOW GRANTS'); if (!$rs_usr) { return; } $re0 = '(^|(\\\\\\\\)+|[^\\\\])'; // non-escaped wildcards $re1 = '(^|[^\\\\])(\\\\)+'; // escaped wildcards while ($row = PMA_DBI_fetch_row($rs_usr)) { // extract db from GRANT ... ON *.* or GRANT ... ON db.* $db_name_offset = strpos($row[0], ' ON ') + 4; $show_grants_dbname = substr($row[0], $db_name_offset, strpos($row[0], '.', $db_name_offset) - $db_name_offset); $show_grants_dbname = PMA_unQuote($show_grants_dbname, '`'); $show_grants_str = substr($row[0], 6, strpos($row[0], ' ON ') - 6); if ($show_grants_str == 'RELOAD') { $GLOBALS['is_reload_priv'] = true; } /** * @todo if we find CREATE VIEW but not CREATE, do not offer * the create database dialog box */ if ($show_grants_str == 'ALL' || $show_grants_str == 'ALL PRIVILEGES' || $show_grants_str == 'CREATE' || strpos($show_grants_str, 'CREATE,') !== false) { if ($show_grants_dbname == '*') { // a global CREATE privilege $GLOBALS['is_create_db_priv'] = true; $GLOBALS['is_reload_priv'] = true; $GLOBALS['db_to_create'] = ''; $GLOBALS['dbs_where_create_table_allowed'][] = '*'; // @todo we should not break here, cause GRANT ALL *.* // could be revoked by a later rule like GRANT SELECT ON db.* break; } else { // this array may contain wildcards $GLOBALS['dbs_where_create_table_allowed'][] = $show_grants_dbname; $dbname_to_test = PMA_backquote($show_grants_dbname); if ($GLOBALS['is_create_db_priv']) { // no need for any more tests if we already know this continue; } if (preg_match('/' . $re0 . '%|_/', $show_grants_dbname) && !preg_match('/\\\\%|\\\\_/', $show_grants_dbname) || !PMA_DBI_try_query('USE ' . preg_replace('/' . $re1 . '(%|_)/', '\\1\\3', $dbname_to_test)) && substr(PMA_DBI_getError(), 1, 4) != 1044) { if ($GLOBALS['cfg']['SuggestDBName']) { $GLOBALS['db_to_create'] = preg_replace('/' . $re0 . '_/', '\\1?', $show_grants_dbname); $GLOBALS['db_to_create'] = preg_replace('/' . $re0 . '%/', '\\1...', $GLOBALS['db_to_create']); $GLOBALS['db_to_create'] = preg_replace('/' . $re1 . '(%|_)/', '\\1\\3', $GLOBALS['db_to_create']); } $GLOBALS['is_create_db_priv'] = true; /** * @todo collect $GLOBALS['db_to_create'] into an array, to display a * drop-down in the "Create new database" dialog */ // we don't break, we want all possible databases //break; } // end if } // end elseif } // end if } // end while PMA_DBI_free_result($rs_usr); // must also PMA_cacheUnset() them in libraries/auth/cookie.auth.lib.php PMA_cacheSet('is_create_db_priv', $GLOBALS['is_create_db_priv'], true); PMA_cacheSet('is_process_priv', $GLOBALS['is_process_priv'], true); PMA_cacheSet('is_reload_priv', $GLOBALS['is_reload_priv'], true); PMA_cacheSet('db_to_create', $GLOBALS['db_to_create'], true); PMA_cacheSet('dbs_where_create_table_allowed', $GLOBALS['dbs_where_create_table_allowed'], true); }
// If a stored procedure was called, there may be more results that are // queued up and waiting to be flushed from the buffer. So let's do that. while (true) { if (! PMA_DBI_more_results()) { break; } PMA_DBI_next_result(); } $querytime_after = array_sum(explode(' ', microtime())); $GLOBALS['querytime'] = $querytime_after - $querytime_before; // Displays an error message if required and stop parsing the script if ($error = PMA_DBI_getError()) { if ($is_gotofile) { if (strpos($goto, 'db_') === 0 && strlen($table)) { $table = ''; } $active_page = $goto; $message = PMA_Message::rawError($error); if ($GLOBALS['is_ajax_request'] == true) { PMA_ajaxResponse($message, false); } /** * Go to target path. */ include '' . PMA_securePath($goto);
if (count($key_fields)) { $fields = array(); foreach ($key_fields as $each_field) { if (isset($_REQUEST['field_name'][$each_field]) && strlen($_REQUEST['field_name'][$each_field])) { $fields[] = PMA_CommonFunctions::getInstance()->backquote($_REQUEST['field_name'][$each_field]); } } // end for $key_query = ', ADD KEY (' . implode(', ', $fields) . ') '; } */ // To allow replication, we first select the db to use and then run queries // on this db. if (! PMA_DBI_select_db($db)) { $common_functions->mysqlDie( PMA_DBI_getError(), 'USE ' . $common_functions->backquote($db) . ';', '', $err_url ); } $sql_query = 'ALTER TABLE ' . $common_functions->backquote($table) . ' '; $sql_query .= implode(', ', $changes) . $key_query; $sql_query .= ';'; $result = PMA_DBI_try_query($sql_query); if ($result !== false) { $message = PMA_Message::success( __('Table %1$s has been altered successfully') ); $message->addParam($table);
/** * User is not allowed to login to MySQL -> authentication failed * * prepares error message and switches to PMA_auth() which display the error * and the login form * * this function MUST exit/quit the application, * currently doen by call to PMA_auth() * * @access public */ function PMA_auth_fails() { global $conn_error; // Deletes password cookie and displays the login form $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']); if (!empty($GLOBALS['login_without_password_is_forbidden'])) { $conn_error = __('Login without a password is forbidden by configuration (see AllowNoPassword)'); } elseif (!empty($GLOBALS['allowDeny_forbidden'])) { $conn_error = __('Access denied'); } elseif (!empty($GLOBALS['no_activity'])) { $conn_error = sprintf(__('No activity within %s seconds; please log in again'), $GLOBALS['cfg']['LoginCookieValidity']); // Remember where we got timeout to return on same place if (PMA_getenv('SCRIPT_NAME')) { $GLOBALS['target'] = basename(PMA_getenv('SCRIPT_NAME')); // avoid "missing parameter: field" on re-entry if ('tbl_alter.php' == $GLOBALS['target']) { $GLOBALS['target'] = 'tbl_structure.php'; } } } elseif (PMA_DBI_getError()) { $conn_error = '#' . $GLOBALS['errno'] . ' ' . __('Cannot log in to the MySQL server'); } else { $conn_error = __('Cannot log in to the MySQL server'); } // needed for PHP-CGI (not need for FastCGI or mod-php) header('Cache-Control: no-store, no-cache, must-revalidate'); header('Pragma: no-cache'); PMA_auth(); }
/** * Generate the error url and submit the query * * @param string $password * @param array $_url_params * @param string $sql_query * @param string $hashing_function * * @return void */ function PMA_ChangePassUrlParamsAndSubmitQuery($password, $_url_params, $sql_query, $hashing_function) { $common_functions = PMA_CommonFunctions::getInstance(); $err_url = 'user_password.php' . PMA_generate_common_url($_url_params); $local_query = 'SET password = '******'') ? '\'\'' : $hashing_function . '(\'' . $common_functions->sqlAddSlashes($password) . '\')'); $result = @PMA_DBI_try_query($local_query) or $common_functions->mysqlDie(PMA_DBI_getError(), $sql_query, false, $err_url); }
// (but a LIMIT would disrupt results in an UNION) if (PMA_MYSQL_INT_VERSION >= 40000 && !isset($analyzed_sql[0]['queryflags']['union'])) { $count_query .= ' LIMIT 1'; } // run the count query if (PMA_MYSQL_INT_VERSION < 40000) { if ($cnt_all_result = PMA_DBI_try_query($count_query)) { if ($is_group && $count_what == '*') { $unlim_num_rows = @PMA_DBI_num_rows($cnt_all_result); } else { $unlim_num_rows = PMA_DBI_fetch_assoc($cnt_all_result); $unlim_num_rows = $unlim_num_rows['count']; } PMA_DBI_free_result($cnt_all_result); } else { if (PMA_DBI_getError()) { // there are some cases where the generated // count_query (for MySQL 3) is wrong, // so we get here. //TODO: use a big unlimited query to get // the correct number of rows (depending // on a config variable?) $unlim_num_rows = 0; } } } else { PMA_DBI_try_query($count_query); // if (mysql_error()) { // void. // I tried the case // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
/** * Outputs the content of a table in SQL format * * @param string $db database name * @param string $table table name * @param string $crlf the end of line sequence * @param string $error_url the url to go back in case of error * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { global $current_row, $sql_backquotes; if (isset($GLOBALS['sql_compatibility'])) { $compat = $GLOBALS['sql_compatibility']; } else { $compat = 'NONE'; } $formatted_table_name = isset($GLOBALS['sql_backquotes']) ? PMA_Util::backquoteCompat($table, $compat) : '\'' . $table . '\''; // Do not export data for a VIEW // (For a VIEW, this is called only when exporting a single VIEW) if (PMA_Table::isView($db, $table)) { $head = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment('VIEW ' . ' ' . $formatted_table_name) . $this->_exportComment(__('Data') . ': ' . __('None')) . $this->_exportComment() . $this->_possibleCRLF(); if (!PMA_exportOutputHandler($head)) { return false; } return true; } // analyze the query to get the true column names, not the aliases // (this fixes an undefined index, also if Complete inserts // are used, we did not get the true column name in case of aliases) $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query)); $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); // a possible error: the table has crashed $tmp_error = PMA_DBI_getError(); if ($tmp_error) { return PMA_exportOutputHandler($this->_exportComment(__('Error reading data:') . ' (' . $tmp_error . ')')); } if ($result != false) { $fields_cnt = PMA_DBI_num_fields($result); // Get field information $fields_meta = PMA_DBI_get_fields_meta($result); $field_flags = array(); for ($j = 0; $j < $fields_cnt; $j++) { $field_flags[$j] = PMA_DBI_field_flags($result, $j); } for ($j = 0; $j < $fields_cnt; $j++) { if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) { $field_set[$j] = PMA_Util::backquoteCompat($analyzed_sql[0]['select_expr'][$j]['column'], $compat, $sql_backquotes); } else { $field_set[$j] = PMA_Util::backquoteCompat($fields_meta[$j]->name, $compat, $sql_backquotes); } } if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') { // update $schema_insert = 'UPDATE '; if (isset($GLOBALS['sql_ignore'])) { $schema_insert .= 'IGNORE '; } // avoid EOL blank $schema_insert .= PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' SET'; } else { // insert or replace if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') { $sql_command = 'REPLACE'; } else { $sql_command = 'INSERT'; } // delayed inserts? if (isset($GLOBALS['sql_delayed'])) { $insert_delayed = ' DELAYED'; } else { $insert_delayed = ''; } // insert ignore? if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) { $insert_delayed .= ' IGNORE'; } //truncate table before insert if (isset($GLOBALS['sql_truncate']) && $GLOBALS['sql_truncate'] && $sql_command == 'INSERT') { $truncate = 'TRUNCATE TABLE ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ";"; $truncatehead = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment(__('Truncate table before insert') . ' ' . $formatted_table_name) . $this->_exportComment() . $crlf; PMA_exportOutputHandler($truncatehead); PMA_exportOutputHandler($truncate); } else { $truncate = ''; } // scheme for inserting fields if ($GLOBALS['sql_insert_syntax'] == 'complete' || $GLOBALS['sql_insert_syntax'] == 'both') { $fields = implode(', ', $field_set); $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' (' . $fields . ') VALUES'; } else { $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' VALUES'; } } //\x08\\x09, not required $search = array("", "\n", "\r", ""); $replace = array('\\0', '\\n', '\\r', '\\Z'); $current_row = 0; $query_size = 0; if (($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) { $separator = ','; $schema_insert .= $crlf; } else { $separator = ';'; } while ($row = PMA_DBI_fetch_row($result)) { if ($current_row == 0) { $head = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment(__('Dumping data for table') . ' ' . $formatted_table_name) . $this->_exportComment() . $crlf; if (!PMA_exportOutputHandler($head)) { return false; } } // We need to SET IDENTITY_INSERT ON for MSSQL if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'MSSQL' && $current_row == 0) { if (!PMA_exportOutputHandler('SET IDENTITY_INSERT ' . PMA_Util::backquoteCompat($table, $compat) . ' ON ;' . $crlf)) { return false; } } $current_row++; for ($j = 0; $j < $fields_cnt; $j++) { // NULL if (!isset($row[$j]) || is_null($row[$j])) { $values[] = 'NULL'; } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) { // a number // timestamp is numeric on some MySQL 4.1, BLOBs are // sometimes numeric $values[] = $row[$j]; } elseif (stristr($field_flags[$j], 'BINARY') && $fields_meta[$j]->blob && isset($GLOBALS['sql_hex_for_blob'])) { // a true BLOB // - mysqldump only generates hex data when the --hex-blob // option is used, for fields having the binary attribute // no hex is generated // - a TEXT field returns type blob but a real blob // returns also the 'binary' flag // empty blobs need to be different, but '0' is also empty // :-( if (empty($row[$j]) && $row[$j] != '0') { $values[] = '\'\''; } else { $values[] = '0x' . bin2hex($row[$j]); } } elseif ($fields_meta[$j]->type == 'bit') { // detection of 'bit' works only on mysqli extension $values[] = "b'" . PMA_Util::sqlAddSlashes(PMA_Util::printableBitValue($row[$j], $fields_meta[$j]->length)) . "'"; } else { // something else -> treat as a string $values[] = '\'' . str_replace($search, $replace, PMA_Util::sqlAddSlashes($row[$j])) . '\''; } // end if } // end for // should we make update? if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') { $insert_line = $schema_insert; for ($i = 0; $i < $fields_cnt; $i++) { if (0 == $i) { $insert_line .= ' '; } if ($i > 0) { // avoid EOL blank $insert_line .= ','; } $insert_line .= $field_set[$i] . ' = ' . $values[$i]; } list($tmp_unique_condition, $tmp_clause_is_unique) = PMA_Util::getUniqueCondition($result, $fields_cnt, $fields_meta, $row); $insert_line .= ' WHERE ' . $tmp_unique_condition; unset($tmp_unique_condition, $tmp_clause_is_unique); } else { // Extended inserts case if ($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') { if ($current_row == 1) { $insert_line = $schema_insert . '(' . implode(', ', $values) . ')'; } else { $insert_line = '(' . implode(', ', $values) . ')'; $sql_max_size = $GLOBALS['sql_max_query_size']; if (isset($sql_max_size) && $sql_max_size > 0 && $query_size + strlen($insert_line) > $sql_max_size) { if (!PMA_exportOutputHandler(';' . $crlf)) { return false; } $query_size = 0; $current_row = 1; $insert_line = $schema_insert . $insert_line; } } $query_size += strlen($insert_line); // Other inserts case } else { $insert_line = $schema_insert . '(' . implode(', ', $values) . ')'; } } unset($values); if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) { return false; } } // end while if ($current_row > 0) { if (!PMA_exportOutputHandler(';' . $crlf)) { return false; } } // We need to SET IDENTITY_INSERT OFF for MSSQL if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'MSSQL' && $current_row > 0) { $outputSucceeded = PMA_exportOutputHandler($crlf . 'SET IDENTITY_INSERT ' . PMA_Util::backquoteCompat($table, $compat) . ' OFF;' . $crlf); if (!$outputSucceeded) { return false; } } } // end if ($result != false) PMA_DBI_free_result($result); return true; }
/** * returns array with databases containing extended infos about them * * @param string $database database * @param boolean $force_stats retrieve stats also for MySQL < 5 * @param resource $link mysql link * @param string $sort_by column to order by * @param string $sort_order ASC or DESC * @param integer $limit_offset starting offset for LIMIT * @param bool|int $limit_count row count for LIMIT or true * for $GLOBALS['cfg']['MaxDbList'] * * @todo move into PMA_List_Database? * * @return array $databases */ function PMA_DBI_get_databases_full($database = null, $force_stats = false, $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC', $limit_offset = 0, $limit_count = false) { $common_functions = PMA_CommonFunctions::getInstance(); $sort_order = strtoupper($sort_order); if (true === $limit_count) { $limit_count = $GLOBALS['cfg']['MaxDbList']; } // initialize to avoid errors when there are no databases $databases = array(); $apply_limit_and_order_manual = true; if (!$GLOBALS['cfg']['Server']['DisableIS']) { /** * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT * cause MySQL does not support natural ordering, we have to do it afterward */ $limit = ''; if (!$GLOBALS['cfg']['NaturalOrder']) { if ($limit_count) { $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset; } $apply_limit_and_order_manual = false; } // get table information from information_schema if ($database) { $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \'' . $common_functions->sqlAddSlashes($database) . '\''; } else { $sql_where_schema = ''; } if (PMA_DRIZZLE) { // data_dictionary.table_cache may not contain any data for some // tables, it's just a table cache $sql = 'SELECT s.SCHEMA_NAME, s.DEFAULT_COLLATION_NAME'; if ($force_stats) { // no TABLE_CACHE data, stable results are better than // constantly changing $sql .= ', COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES, SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS'; } $sql .= ' FROM data_dictionary.SCHEMAS s'; if ($force_stats) { $engine_info = $common_functions->cacheGet('drizzle_engines', true); $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false"; if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') { $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS" . " stat ON (t.ENGINE = 'InnoDB' AND stat.NAME" . " = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)"; } $sql .= "\n LEFT JOIN data_dictionary.TABLES t\n ON t.TABLE_SCHEMA = s.SCHEMA_NAME\n {$stats_join}"; } $sql .= $sql_where_schema . ' GROUP BY s.SCHEMA_NAME ORDER BY ' . $common_functions->backquote($sort_by) . ' ' . $sort_order . $limit; } else { $sql = 'SELECT s.SCHEMA_NAME, s.DEFAULT_COLLATION_NAME'; if ($force_stats) { $sql .= ', COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES, SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS, SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH, SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH, SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH, SUM(t.DATA_LENGTH + t.INDEX_LENGTH) AS SCHEMA_LENGTH, SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE'; } $sql .= ' FROM `information_schema`.SCHEMATA s'; if ($force_stats) { $sql .= ' LEFT JOIN `information_schema`.TABLES t ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME'; } $sql .= $sql_where_schema . ' GROUP BY BINARY s.SCHEMA_NAME ORDER BY BINARY ' . $common_functions->backquote($sort_by) . ' ' . $sort_order . $limit; } $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link); $mysql_error = PMA_DBI_getError($link); if (!count($databases) && $GLOBALS['errno']) { $common_functions->mysqlDie($mysql_error, $sql); } // display only databases also in official database list // f.e. to apply hide_db and only_db $drops = array_diff(array_keys($databases), (array) $GLOBALS['pma']->databases); if (count($drops)) { foreach ($drops as $drop) { unset($databases[$drop]); } unset($drop); } unset($sql_where_schema, $sql, $drops); } else { foreach ($GLOBALS['pma']->databases as $database_name) { // MySQL forward compatibility // so pma could use this array as if every server is of version >5.0 // todo : remove and check the rest of the code for usage, // MySQL 5.0 or higher is required for current PMA version $databases[$database_name]['SCHEMA_NAME'] = $database_name; if ($force_stats) { include_once './libraries/mysql_charsets.lib.php'; $databases[$database_name]['DEFAULT_COLLATION_NAME'] = PMA_getDbCollation($database_name); // get additional info about tables $databases[$database_name]['SCHEMA_TABLES'] = 0; $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0; $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0; $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0; $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0; $databases[$database_name]['SCHEMA_LENGTH'] = 0; $databases[$database_name]['SCHEMA_DATA_FREE'] = 0; $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . $common_functions->backquote($database_name) . ';'); while ($row = PMA_DBI_fetch_assoc($res)) { $databases[$database_name]['SCHEMA_TABLES']++; $databases[$database_name]['SCHEMA_TABLE_ROWS'] += $row['Rows']; $databases[$database_name]['SCHEMA_DATA_LENGTH'] += $row['Data_length']; $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] += $row['Max_data_length']; $databases[$database_name]['SCHEMA_INDEX_LENGTH'] += $row['Index_length']; // for InnoDB, this does not contain the number of // overhead bytes but the total free space if ('InnoDB' != $row['Engine']) { $databases[$database_name]['SCHEMA_DATA_FREE'] += $row['Data_free']; } $databases[$database_name]['SCHEMA_LENGTH'] += $row['Data_length'] + $row['Index_length']; } PMA_DBI_free_result($res); unset($res); } } } /** * apply limit and order manually now * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder']) */ if ($apply_limit_and_order_manual) { $GLOBALS['callback_sort_order'] = $sort_order; $GLOBALS['callback_sort_by'] = $sort_by; usort($databases, 'PMA_usort_comparison_callback'); unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']); /** * now apply limit */ if ($limit_count) { $databases = array_slice($databases, $limit_offset, $limit_count); } } return $databases; }
/** * User is not allowed to login to MySQL -> authentication failed * * @global string the MySQL error message PHP returns * @global string the connection type (persistent or not) * @global string the MySQL server port to use * @global string the MySQL socket port to use * @global array the current server settings * @global string the font face to use in case of failure * @global string the default font size to use in case of failure * @global string the big font size to use in case of failure * @global boolean tell the "PMA_mysqlDie()" function headers have been * sent * * @return boolean always true (no return indeed) * * @access public */ function PMA_auth_fails() { global $php_errormsg, $cfg; global $right_font_family, $font_size, $font_bigger; if (PMA_DBI_getError()) { $conn_error = PMA_DBI_getError(); } else { if (isset($php_errormsg)) { $conn_error = $php_errormsg; } else { $conn_error = $GLOBALS['strConnectionError']; } } // Defines the charset to be used header('Content-Type: text/html; charset=' . $GLOBALS['charset']); // Defines the theme to be used require_once './libraries/select_theme.lib.php'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $GLOBALS['available_languages'][$GLOBALS['lang']][2]; ?> " lang="<?php echo $GLOBALS['available_languages'][$GLOBALS['lang']][2]; ?> " dir="<?php echo $GLOBALS['text_dir']; ?> "> <head> <title><?php echo $GLOBALS['strAccessDenied']; ?> </title> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $GLOBALS['charset']; ?> " /> <style type="text/css"> <!-- body {font-family: <?php echo $right_font_family; ?> ; font-size: <?php echo $font_size; ?> ; color: #000000} h1 {font-family: <?php echo $right_font_family; ?> ; font-size: <?php echo $font_bigger; ?> ; font-weight: bold} //--> </style> <script language="JavaScript" type="text/javascript"> <!-- /* added 2004-06-10 by Michael Keck * we need this for Backwards-Compatibility and resolving problems * with non DOM browsers, which may have problems with css 2 (like NC 4) */ var isDOM = (typeof(document.getElementsByTagName) != 'undefined' && typeof(document.createElement) != 'undefined') ? 1 : 0; var isIE4 = (typeof(document.all) != 'undefined' && parseInt(navigator.appVersion) >= 4) ? 1 : 0; var isNS4 = (typeof(document.layers) != 'undefined') ? 1 : 0; var capable = (isDOM || isIE4 || isNS4) ? 1 : 0; // Uggly fix for Opera and Konqueror 2.2 that are half DOM compliant if (capable) { if (typeof(window.opera) != 'undefined') { var browserName = ' ' + navigator.userAgent.toLowerCase(); if ((browserName.indexOf('konqueror 7') == 0)) { capable = 0; } } else if (typeof(navigator.userAgent) != 'undefined') { var browserName = ' ' + navigator.userAgent.toLowerCase(); if ((browserName.indexOf('konqueror') > 0) && (browserName.indexOf('konqueror/3') == 0)) { capable = 0; } } // end if... else if... } // end if document.writeln('<link rel="stylesheet" type="text/css" href="<?php echo defined('PMA_PATH_TO_BASEDIR') ? PMA_PATH_TO_BASEDIR : './'; ?> css/phpmyadmin.css.php?lang=<?php echo $GLOBALS['available_languages'][$GLOBALS['lang']][2]; ?> &js_frame=right&js_isDOM=' + isDOM + '" />'); //--> </script> <noscript> <link rel="stylesheet" type="text/css" href="<?php echo defined('PMA_PATH_TO_BASEDIR') ? PMA_PATH_TO_BASEDIR : './'; ?> css/phpmyadmin.css.php?lang=<?php echo $GLOBALS['available_languages'][$GLOBALS['lang']][2]; ?> &js_frame=right" /> </noscript> </head> <body bgcolor="<?php echo $cfg['RightBgColor']; ?> "> <br /><br /> <center> <h1><?php echo sprintf($GLOBALS['strWelcome'], ' phpMyAdmin ' . PMA_VERSION); ?> </h1> </center> <br /> <table border="0" cellpadding="0" cellspacing="3" align="center" width="80%"> <tr> <td> <?php echo "\n"; $GLOBALS['is_header_sent'] = TRUE; //TODO: I have included this div from header.inc.php to work around // an undefined variable in tooltip.js, when the server // is not responding. Work has to be done to merge all code that // starts the page (DOCTYPE and this div) to one place ?> <div id="TooltipContainer" name="TooltipContainer" onmouseover="holdTooltip();" onmouseout="swapTooltip('default');"></div> <?php // if we display the "Server not responding" error, do not confuse users // by telling them they have a settings problem // (note: it's true that they could have a badly typed host name, but // anyway the current $strAccessDeniedExplanation tells that the server // rejected the connection, which is not really what happened) // 2002 is the error given by mysqli // 2003 is the error given by mysql if (isset($GLOBALS['allowDeny_forbidden']) && $GLOBALS['allowDeny_forbidden']) { echo '<p>' . $GLOBALS['strAccessDenied'] . '</p>' . "\n"; } else { if (!isset($GLOBALS['errno']) || isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002 && $GLOBALS['errno'] != 2003) { echo '<p>' . $GLOBALS['strAccessDeniedExplanation'] . '</p>' . "\n"; } PMA_mysqlDie($conn_error, ''); } ?> </td> </tr> </table> <?php require_once './footer.inc.php'; return TRUE; }
/** * Displays a MySQL error message in the right frame. * * @param string the error message * @param string the sql query that failed * @param boolean whether to show a "modify" link or not * @param string the "back" link url (full path is not required) * @param boolean EXIT the page? * * @global array the configuration array * * @access public */ function PMA_mysqlDie($error_message = '', $the_query = '', $is_modify_link = TRUE, $back_url = '', $exit = TRUE) { global $cfg, $table, $db, $sql_query; require_once './header.inc.php'; if (!$error_message) { $error_message = PMA_DBI_getError(); } if (!$the_query && !empty($GLOBALS['sql_query'])) { $the_query = $GLOBALS['sql_query']; } // --- Added to solve bug #641765 // Robbat2 - 12 January 2003, 9:46PM // Revised, Robbat2 - 13 Janurary 2003, 2:59PM if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) { $formatted_sql = htmlspecialchars($the_query); } else { $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query); } // --- echo "\n" . '<!-- PMA-SQL-ERROR -->' . "\n"; echo ' <table border="0" cellpadding="2" cellspacing="1">' . ' <tr>' . "\n" . ' <th class="tblHeadError"><div class="errorhead">' . $GLOBALS['strError'] . '</div></th>' . "\n" . ' </tr>' . "\n" . ' <tr>' . "\n" . ' <td>'; // if the config password is wrong, or the MySQL server does not // respond, do not show the query that would reveal the // username/password if (!empty($the_query) && !strstr($the_query, 'connect')) { // --- Added to solve bug #641765 // Robbat2 - 12 January 2003, 9:46PM // Revised, Robbat2 - 13 Janurary 2003, 2:59PM if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) { echo PMA_SQP_getErrorString(); } // --- // modified to show me the help on sql errors (Michael Keck) echo '<div class="tblWarn"><p>' . "\n"; echo ' <b>' . $GLOBALS['strSQLQuery'] . ':</b>' . "\n"; if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select echo PMA_showMySQLDocu('Reference', 'SELECT'); } if ($is_modify_link && isset($db)) { if (isset($table)) { $doedit_goto = '<a href="tbl_properties.php?' . PMA_generate_common_url($db, $table) . '&sql_query=' . urlencode($the_query) . '&show_query=1">'; } else { $doedit_goto = '<a href="db_details.php?' . PMA_generate_common_url($db) . '&sql_query=' . urlencode($the_query) . '&show_query=1">'; } if ($GLOBALS['cfg']['PropertiesIconic']) { echo $doedit_goto . '<img src=" ' . $GLOBALS['pmaThemeImage'] . 'b_edit.png" width="16" height="16" border="0" hspace="2" align="middle" alt="' . $GLOBALS['strEdit'] . '" />' . '</a>'; } else { echo ' [' . $doedit_goto . $GLOBALS['strEdit'] . '</a>' . ']' . "\n"; } } // end if echo '</p>' . "\n" . '<p>' . "\n" . ' ' . $formatted_sql . "\n" . '</p></div>' . "\n"; } // end if $tmp_mysql_error = ''; // for saving the original $error_message if (!empty($error_message)) { $tmp_mysql_error = strtolower($error_message); // save the original $error_message $error_message = htmlspecialchars($error_message); $error_message = preg_replace("@((\r\n)|(\r)|(\n)){3,}@", "\n\n", $error_message); } // modified to show me the help on error-returns (Michael Keck) echo '<div class="tblWarn"><p>' . "\n" . ' <b>' . $GLOBALS['strMySQLSaid'] . '</b>' . PMA_showMySQLDocu('Error-returns', 'Error-returns') . "\n" . '</p>' . "\n"; // The error message will be displayed within a CODE segment. // To preserve original formatting, but allow wordwrapping, we do a couple of replacements // Replace all non-single blanks with their HTML-counterpart $error_message = str_replace(' ', ' ', $error_message); // Replace TAB-characters with their HTML-counterpart $error_message = str_replace("\t", ' ', $error_message); // Replace linebreaks $error_message = nl2br($error_message); echo '<code>' . "\n" . $error_message . "\n" . '</code><br />' . "\n"; // feature request #1036254: // Add a link by MySQL-Error #1062 - Duplicate entry // 2004-10-20 by mk.keck if (substr($error_message, 1, 4) == '1062') { // TODO: do not assume that the error message is in English // and do not use mysql_result() // explode the entry and the column $arr_mysql_val_key = explode('entry \'', $tmp_mysql_error); $arr_mysql_val_key = explode('\' for key', $arr_mysql_val_key[1]); // get the duplicate value $string_duplicate_val = trim(strtolower($arr_mysql_val_key[0])); // get the field name ... $string_duplicate_key = mysql_result(mysql_query("SHOW FIELDS FROM " . $table), $arr_mysql_val_key[1] - 1, 0); $duplicate_sql_query = "SELECT * FROM " . $table . " WHERE " . $string_duplicate_key . " LIKE '" . $string_duplicate_val . "'"; echo ' <form method="post" action="read_dump.php" style="padding: 0px; margin: 0px">' . "\n" . ' <input type="hidden" name="sql_query" value="' . $duplicate_sql_query . '" />' . "\n" . ' ' . PMA_generate_common_hidden_inputs($db, $table) . "\n" . ' <input type="submit" name="submit" value="' . $GLOBALS['strBrowse'] . '" />' . "\n" . ' </form>' . "\n"; } // end of show duplicate entry echo '</div>'; if (!empty($back_url) && $exit) { $goto_back_url = '<a href="' . (strstr($back_url, '?') ? $back_url . '&no_history=true' : $back_url . '?no_history=true') . '"> '; echo ' </td> ' . "\n" . ' </tr>' . "\n" . ' <tr><td class="tblHeaders" align="center">'; echo '[' . $goto_back_url . $GLOBALS['strBack'] . ' </a>]'; } echo ' </td>' . "\n" . ' </tr>' . "\n" . ' </table>' . "\n\n"; if ($exit) { require_once './footer.inc.php'; } }
/** * Displays a MySQL error message in the right frame. * * @param string $error_message the error message * @param string $the_query the sql query that failed * @param bool $is_modify_link whether to show a "modify" link or not * @param string $back_url the "back" link url (full path is not required) * @param bool $exit EXIT the page? * * @global string the curent table * @global string the current db * * @access public */ function PMA_mysqlDie($error_message = '', $the_query = '', $is_modify_link = true, $back_url = '', $exit = true) { global $table, $db; /** * start http output, display html headers */ include_once './libraries/header.inc.php'; $error_msg_output = ''; if (!$error_message) { $error_message = PMA_DBI_getError(); } if (!$the_query && !empty($GLOBALS['sql_query'])) { $the_query = $GLOBALS['sql_query']; } // --- Added to solve bug #641765 if (!function_exists('PMA_SQP_isError') || PMA_SQP_isError()) { $formatted_sql = htmlspecialchars($the_query); } elseif (empty($the_query) || trim($the_query) == '') { $formatted_sql = ''; } else { if (strlen($the_query) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) { $formatted_sql = htmlspecialchars(substr($the_query, 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'])) . '[...]'; } else { $formatted_sql = PMA_formatSql(PMA_SQP_parse($the_query), $the_query); } } // --- $error_msg_output .= "\n" . '<!-- PMA-SQL-ERROR -->' . "\n"; $error_msg_output .= ' <div class="error"><h1>' . __('Error') . '</h1>' . "\n"; // if the config password is wrong, or the MySQL server does not // respond, do not show the query that would reveal the // username/password if (!empty($the_query) && !strstr($the_query, 'connect')) { // --- Added to solve bug #641765 if (function_exists('PMA_SQP_isError') && PMA_SQP_isError()) { $error_msg_output .= PMA_SQP_getErrorString() . "\n"; $error_msg_output .= '<br />' . "\n"; } // --- // modified to show the help on sql errors $error_msg_output .= ' <p><strong>' . __('SQL query') . ':</strong>' . "\n"; if (strstr(strtolower($formatted_sql), 'select')) { // please show me help to the error on select $error_msg_output .= PMA_showMySQLDocu('SQL-Syntax', 'SELECT'); } if ($is_modify_link) { $_url_params = array('sql_query' => $the_query, 'show_query' => 1); if (strlen($table)) { $_url_params['db'] = $db; $_url_params['table'] = $table; $doedit_goto = '<a href="tbl_sql.php' . PMA_generate_common_url($_url_params) . '">'; } elseif (strlen($db)) { $_url_params['db'] = $db; $doedit_goto = '<a href="db_sql.php' . PMA_generate_common_url($_url_params) . '">'; } else { $doedit_goto = '<a href="server_sql.php' . PMA_generate_common_url($_url_params) . '">'; } $error_msg_output .= $doedit_goto . PMA_getIcon('b_edit.png', __('Edit')) . '</a>'; } // end if $error_msg_output .= ' </p>' . "\n" . ' <p>' . "\n" . ' ' . $formatted_sql . "\n" . ' </p>' . "\n"; } // end if if (!empty($error_message)) { $error_message = preg_replace("@((\r\n)|(\r)|(\n)){3,}@", "\n\n", $error_message); } // modified to show the help on error-returns // (now error-messages-server) $error_msg_output .= '<p>' . "\n" . ' <strong>' . __('MySQL said: ') . '</strong>' . PMA_showMySQLDocu('Error-messages-server', 'Error-messages-server') . "\n" . '</p>' . "\n"; // The error message will be displayed within a CODE segment. // To preserve original formatting, but allow wordwrapping, // we do a couple of replacements // Replace all non-single blanks with their HTML-counterpart $error_message = str_replace(' ', ' ', $error_message); // Replace TAB-characters with their HTML-counterpart $error_message = str_replace("\t", ' ', $error_message); // Replace linebreaks $error_message = nl2br($error_message); $error_msg_output .= '<code>' . "\n" . $error_message . "\n" . '</code><br />' . "\n"; $error_msg_output .= '</div>'; $_SESSION['Import_message']['message'] = $error_msg_output; if ($exit) { /** * If in an Ajax request * - avoid displaying a Back link * - use PMA_ajaxResponse() to transmit the message and exit */ if ($GLOBALS['is_ajax_request'] == true) { PMA_ajaxResponse($error_msg_output, false); } if (!empty($back_url)) { if (strstr($back_url, '?')) { $back_url .= '&no_history=true'; } else { $back_url .= '?no_history=true'; } $_SESSION['Import_message']['go_back_url'] = $back_url; $error_msg_output .= '<fieldset class="tblFooters">'; $error_msg_output .= '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'; $error_msg_output .= '</fieldset>' . "\n\n"; } echo $error_msg_output; /** * display footer and exit */ include './libraries/footer.inc.php'; } else { echo $error_msg_output; } }
/** * User is not allowed to login to MySQL -> authentication failed * * @global string the MySQL error message PHP returns * @global string the connection type (persistent or not) * @global string the MySQL server port to use * @global string the MySQL socket port to use * @global array the current server settings * @global string the font face to use in case of failure * @global string the default font size to use in case of failure * @global string the big font size to use in case of failure * @global boolean tell the "PMA_mysqlDie()" function headers have been * sent * * @return boolean always true (no return indeed) * * @access public */ function PMA_auth_fails() { global $php_errormsg, $cfg; $conn_error = PMA_DBI_getError(); if (!$conn_error) { if (isset($php_errormsg)) { $conn_error = $php_errormsg; } else { $conn_error = $GLOBALS['strConnectionError']; } } // Defines the charset to be used header('Content-Type: text/html; charset=' . $GLOBALS['charset']); /* HTML header */ $page_title = $GLOBALS['strAccessDenied']; require './libraries/header_meta_style.inc.php'; ?> </head> <body> <br /><br /> <center> <h1><?php echo sprintf($GLOBALS['strWelcome'], ' phpMyAdmin ' . PMA_VERSION); ?> </h1> </center> <br /> <table border="0" cellpadding="0" cellspacing="3" align="center" width="80%"> <tr> <td> <?php echo "\n"; $GLOBALS['is_header_sent'] = TRUE; //TODO: I have included this div from libraries/header.inc.php to work around // an undefined variable in tooltip.js, when the server // is not responding. Work has to be done to merge all code that // starts the page (DOCTYPE and this div) to one place ?> <div id="TooltipContainer" onmouseover="holdTooltip();" onmouseout="swapTooltip('default');"></div> <?php if (isset($GLOBALS['allowDeny_forbidden']) && $GLOBALS['allowDeny_forbidden']) { echo '<p>' . $GLOBALS['strAccessDenied'] . '</p>' . "\n"; } else { // Check whether user has configured something if ($_SESSION['PMA_Config']->source_mtime == 0) { echo '<p>' . sprintf($GLOBALS['strAccessDeniedCreateConfig'], '<a href="scripts/setup.php">', '</a>') . '</p>' . "\n"; } elseif (!isset($GLOBALS['errno']) || isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002 && $GLOBALS['errno'] != 2003) { // if we display the "Server not responding" error, do not confuse users // by telling them they have a settings problem // (note: it's true that they could have a badly typed host name, but // anyway the current $strAccessDeniedExplanation tells that the server // rejected the connection, which is not really what happened) // 2002 is the error given by mysqli // 2003 is the error given by mysql echo '<p>' . $GLOBALS['strAccessDeniedExplanation'] . '</p>' . "\n"; } PMA_mysqlDie($conn_error, '', true, '', false); } if (!empty($GLOBALS['PMA_errors']) && is_array($GLOBALS['PMA_errors'])) { foreach ($GLOBALS['PMA_errors'] as $error) { echo '<div class="error">' . $error . '</div>' . "\n"; } } ?> </td> </tr> <?php if (count($GLOBALS['cfg']['Servers']) > 1) { // offer a chance to login to other servers if the current one failed require_once './libraries/select_server.lib.php'; echo '<tr>' . "\n"; echo ' <td>' . "\n"; PMA_select_server(TRUE, TRUE); echo ' </td>' . "\n"; echo '</tr>' . "\n"; } echo '</table>' . "\n"; require_once './libraries/footer.inc.php'; return TRUE; }
/** * Counts and returns (or displays) the number of records in a table * * Revision 13 July 2001: Patch for limiting dump size from * vinay@sanisoft.com & girish@sanisoft.com * * @param string the current database name * @param string the current table name * @param boolean whether to retain or to displays the result * @param boolean whether to force an exact count * * @return mixed the number of records if retain is required, true else * * @access public */ function countRecords($db, $table, $ret = false, $force_exact = false) { $row_count = false; if (!$force_exact) { $row_count = PMA_DBI_fetch_value('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table, true) . '\';', 0, 'Rows'); } $tbl_is_view = PMA_Table::isView($db, $table); // for a VIEW, $row_count is always false at this point if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) { if (!$tbl_is_view) { $row_count = PMA_DBI_fetch_value('SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table)); } else { // For complex views, even trying to get a partial record // count could bring down a server, so we offer an // alternative: setting MaxExactCountViews to 0 will bypass // completely the record counting for views if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) { $row_count = 0; } else { // Counting all rows of a VIEW could be too long, so use // a LIMIT clause. // Use try_query because it can fail (a VIEW is based on // a table that no longer exists) $result = PMA_DBI_try_query('SELECT 1 FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' LIMIT ' . $GLOBALS['cfg']['MaxExactCountViews'], null, PMA_DBI_QUERY_STORE); if (!PMA_DBI_getError()) { $row_count = PMA_DBI_num_rows($result); PMA_DBI_free_result($result); } } } } if ($ret) { return $row_count; } /** * @deprecated at the moment nowhere is $return = false used */ // Note: as of PMA 2.8.0, we no longer seem to be using // PMA_Table::countRecords() in display mode. echo PMA_formatNumber($row_count, 0); if ($tbl_is_view) { echo ' ' . sprintf($GLOBALS['strViewMaxExactCount'], $GLOBALS['cfg']['MaxExactCount'], '[a@./Documentation.html#cfg_MaxExactCount@_blank]', '[/a]'); } }
} $definitions[] = ' ADD UNIQUE (' . implode(', ', $fields) . ') '; unset($fields); } // Builds the fulltext statements and updates the table if (count($field_fulltext)) { $fields = array(); foreach ($field_fulltext as $field_nr) { $fields[] = PMA_Util::backquote($_REQUEST['field_name'][$field_nr]); } $definitions[] = ' ADD FULLTEXT (' . implode(', ', $fields) . ') '; unset($fields); } // To allow replication, we first select the db to use and then run queries // on this db. PMA_DBI_select_db($db) or PMA_Util::mysqlDie(PMA_DBI_getError(), 'USE ' . PMA_Util::backquote($db), '', $err_url); $sql_query = 'ALTER TABLE ' . PMA_Util::backquote($table) . ' ' . implode(', ', $definitions) . ';'; $result = PMA_DBI_try_query($sql_query); if ($result === true) { // If comments were sent, enable relation stuff include_once 'libraries/transformations.lib.php'; // Update comment table for mime types [MIME] if (isset($_REQUEST['field_mimetype']) && is_array($_REQUEST['field_mimetype']) && $cfg['BrowseMIME']) { foreach ($_REQUEST['field_mimetype'] as $fieldindex => $mimetype) { if (isset($_REQUEST['field_name'][$fieldindex]) && strlen($_REQUEST['field_name'][$fieldindex])) { PMA_setMIME($db, $table, $_REQUEST['field_name'][$fieldindex], $mimetype, $_REQUEST['field_transformation'][$fieldindex], $_REQUEST['field_transformation_options'][$fieldindex]); } } } // Go back to the structure sub-page $message = PMA_Message::success(__('Table %1$s has been altered successfully'));
*/ $sql_query = implode(';', $query) . ';'; $total_affected_rows = 0; $last_message = ''; $warning_message = ''; foreach ($query as $query_index => $single_query) { if ($cfg['IgnoreMultiSubmitErrors']) { $result = PMA_DBI_try_query($single_query); } else { $result = PMA_DBI_query($single_query); } if (isset($GLOBALS['warning'])) { $warning_message .= $GLOBALS['warning'] . '[br]'; } if (!$result) { $message .= PMA_DBI_getError(); } else { if (@PMA_DBI_affected_rows()) { $total_affected_rows += @PMA_DBI_affected_rows(); } $insert_id = PMA_DBI_insert_id(); if ($insert_id != 0) { $last_message .= '[br]' . $strInsertedRowId . ' ' . $insert_id; } } // end if PMA_DBI_free_result($result); unset($result); } if ($total_affected_rows != 0) { $message .= $total_affected_rows;
if (!empty($_REQUEST['view']['column_names'])) { $sql_query .= $sep . ' (' . $_REQUEST['view']['column_names'] . ')'; } $sql_query .= $sep . ' AS ' . $_REQUEST['view']['as']; if (isset($_REQUEST['view']['with'])) { $options = array_intersect($_REQUEST['view']['with'], $view_with_options); if (count($options)) { $sql_query .= $sep . ' WITH ' . implode(' ', $options); } } if (PMA_DBI_try_query($sql_query)) { $message = PMA_Message::success(); require './' . $cfg['DefaultTabDatabase']; exit; } else { $message = PMA_Message::rawError(PMA_DBI_getError()); } } // prefill values if not already filled from former submission $view = array('or_replace' => '', 'algorithm' => '', 'name' => '', 'column_names' => '', 'as' => $sql_query, 'with' => array()); if (PMA_isValid($_REQUEST['view'], 'array')) { $view = array_merge($view, $_REQUEST['view']); } /** * Displays top menu links * We use db links because a VIEW is not necessarily on a single table */ $num_tables = 0; require_once './libraries/db_links.inc.php'; $url_params['db'] = $GLOBALS['db']; $url_params['reload'] = 1;
/** * User is not allowed to login to MySQL -> authentication failed * * @return boolean always true (no return indeed) * * @access public */ function PMA_auth_fails() { $error = PMA_DBI_getError(); if ($error && $GLOBALS['errno'] != 1045) { PMA_fatalError($error); } else { PMA_auth(); return true; } }
/** * Handles requests for executing a routine */ function PMA_RTN_handleExecute() { global $_GET, $_POST, $_REQUEST, $GLOBALS, $db, $cfg; /** * Handle all user requests other than the default of listing routines */ if (!empty($_REQUEST['execute_routine']) && !empty($_REQUEST['item_name'])) { // Build the queries $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type'], false); if ($routine !== false) { $queries = array(); $end_query = array(); $args = array(); for ($i = 0; $i < $routine['item_num_params']; $i++) { if (isset($_REQUEST['params'][$routine['item_param_name'][$i]])) { $value = $_REQUEST['params'][$routine['item_param_name'][$i]]; if (is_array($value)) { // is SET type $value = implode(',', $value); } $value = PMA_sqlAddSlashes($value); if (!empty($_REQUEST['funcs'][$routine['item_param_name'][$i]]) && in_array($_REQUEST['funcs'][$routine['item_param_name'][$i]], $cfg['Functions'])) { $queries[] = "SET @p{$i}={$_REQUEST['funcs'][$routine['item_param_name'][$i]]}('{$value}');\n"; } else { $queries[] = "SET @p{$i}='{$value}';\n"; } $args[] = "@p{$i}"; } else { $args[] = "@p{$i}"; } if ($routine['item_type'] == 'PROCEDURE') { if ($routine['item_param_dir'][$i] == 'OUT' || $routine['item_param_dir'][$i] == 'INOUT') { $end_query[] = "@p{$i} AS " . PMA_backquote($routine['item_param_name'][$i]); } } } if ($routine['item_type'] == 'PROCEDURE') { $queries[] = "CALL " . PMA_backquote($routine['item_name']) . "(" . implode(', ', $args) . ");\n"; if (count($end_query)) { $queries[] = "SELECT " . implode(', ', $end_query) . ";\n"; } } else { $queries[] = "SELECT " . PMA_backquote($routine['item_name']) . "(" . implode(', ', $args) . ") " . "AS " . PMA_backquote($routine['item_name']) . ";\n"; } // Execute the queries $affected = 0; $result = null; $outcome = true; foreach ($queries as $query) { $resource = PMA_DBI_try_query($query); if ($resource === false) { $outcome = false; break; } while (true) { if (!PMA_DBI_more_results()) { break; } PMA_DBI_next_result(); } if (substr($query, 0, 6) == 'SELECT') { $result = $resource; } else { if (substr($query, 0, 4) == 'CALL') { $result = $resource ? $resource : $result; $affected = PMA_DBI_affected_rows() - PMA_DBI_num_rows($resource); } } } // Generate output if ($outcome) { $message = __('Your SQL query has been executed successfully'); if ($routine['item_type'] == 'PROCEDURE') { $message .= '<br />'; $message .= sprintf(_ngettext('%d row affected by the last statement inside the procedure', '%d rows affected by the last statement inside the procedure', $affected), $affected); } $message = PMA_message::success($message); // Pass the SQL queries through the "pretty printer" $output = '<code class="sql" style="margin-bottom: 1em;">'; $output .= PMA_SQP_formatHtml(PMA_SQP_parse(implode($queries))); $output .= '</code>'; // Display results if ($result) { $output .= "<fieldset><legend>"; $output .= sprintf(__('Execution results of routine %s'), PMA_backquote(htmlspecialchars($routine['item_name']))); $output .= "</legend>"; $output .= "<table><tr>"; foreach (PMA_DBI_get_fields_meta($result) as $key => $field) { $output .= "<th>"; $output .= htmlspecialchars($field->name); $output .= "</th>"; } $output .= "</tr>"; // Stored routines can only ever return ONE ROW. $data = PMA_DBI_fetch_single_row($result); foreach ($data as $key => $value) { if ($value === null) { $value = '<i>NULL</i>'; } else { $value = htmlspecialchars($value); } $output .= "<td class='odd'>" . $value . "</td>"; } $output .= "</table></fieldset>"; } else { $notice = __('MySQL returned an empty result set (i.e. zero rows).'); $output .= PMA_message::notice($notice)->getDisplay(); } } else { $output = ''; $message = PMA_message::error(sprintf(__('The following query has failed: "%s"'), $query) . '<br /><br />' . __('MySQL said: ') . PMA_DBI_getError(null)); } // Print/send output if ($GLOBALS['is_ajax_request']) { $extra_data = array('dialog' => false); PMA_ajaxResponse($message->getDisplay() . $output, $message->isSuccess(), $extra_data); } else { echo $message->getDisplay() . $output; if ($message->isError()) { // At least one query has failed, so shouldn't // execute any more queries, so we quit. exit; } unset($_POST); // Now deliberately fall through to displaying the routines list } } else { $message = __('Error in processing request') . ' : '; $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_backquote($db))); $message = PMA_message::error($message); if ($GLOBALS['is_ajax_request']) { PMA_ajaxResponse($message, $message->isSuccess()); } else { echo $message->getDisplay(); unset($_POST); } } } else { if (!empty($_GET['execute_dialog']) && !empty($_GET['item_name'])) { /** * Display the execute form for a routine. */ $routine = PMA_RTN_getDataFromName($_GET['item_name'], $_GET['item_type'], true); if ($routine !== false) { $form = PMA_RTN_getExecuteForm($routine); if ($GLOBALS['is_ajax_request'] == true) { $extra_data = array(); $extra_data['dialog'] = true; $extra_data['title'] = __("Execute routine") . " "; $extra_data['title'] .= PMA_backquote(htmlentities($_GET['item_name'], ENT_QUOTES)); PMA_ajaxResponse($form, true, $extra_data); } else { echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n"; echo $form; include './libraries/footer.inc.php'; // exit; } } else { if ($GLOBALS['is_ajax_request'] == true) { $message = __('Error in processing request') . ' : '; $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_backquote($db))); $message = PMA_message::error($message); PMA_ajaxResponse($message, false); } } } } }
/** * Handles requests for executing a routine * * @return Does not return */ function PMA_RTN_handleExecute() { global $_GET, $_POST, $_REQUEST, $GLOBALS, $db; /** * Handle all user requests other than the default of listing routines */ if (!empty($_REQUEST['execute_routine']) && !empty($_REQUEST['item_name'])) { // Build the queries $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type'], false); if ($routine !== false) { $queries = array(); $end_query = array(); $args = array(); $all_functions = $GLOBALS['PMA_Types']->getAllFunctions(); for ($i = 0; $i < $routine['item_num_params']; $i++) { if (isset($_REQUEST['params'][$routine['item_param_name'][$i]])) { $value = $_REQUEST['params'][$routine['item_param_name'][$i]]; if (is_array($value)) { // is SET type $value = implode(',', $value); } $value = PMA_Util::sqlAddSlashes($value); if (!empty($_REQUEST['funcs'][$routine['item_param_name'][$i]]) && in_array($_REQUEST['funcs'][$routine['item_param_name'][$i]], $all_functions)) { $queries[] = "SET @p{$i}={$_REQUEST['funcs'][$routine['item_param_name'][$i]]}('{$value}');\n"; } else { $queries[] = "SET @p{$i}='{$value}';\n"; } $args[] = "@p{$i}"; } else { $args[] = "@p{$i}"; } if ($routine['item_type'] == 'PROCEDURE') { if ($routine['item_param_dir'][$i] == 'OUT' || $routine['item_param_dir'][$i] == 'INOUT') { $end_query[] = "@p{$i} AS " . PMA_Util::backquote($routine['item_param_name'][$i]); } } } if ($routine['item_type'] == 'PROCEDURE') { $queries[] = "CALL " . PMA_Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ");\n"; if (count($end_query)) { $queries[] = "SELECT " . implode(', ', $end_query) . ";\n"; } } else { $queries[] = "SELECT " . PMA_Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ") " . "AS " . PMA_Util::backquote($routine['item_name']) . ";\n"; } // Get all the queries as one SQL statement $multiple_query = implode("", $queries); $outcome = true; $affected = 0; // Execute query if (!PMA_DBI_try_multi_query($multiple_query)) { $outcome = false; } // Generate output if ($outcome) { // Pass the SQL queries through the "pretty printer" $output = '<code class="sql" style="margin-bottom: 1em;">'; $output .= PMA_SQP_formatHtml(PMA_SQP_parse(implode($queries))); $output .= '</code>'; // Display results $output .= "<fieldset><legend>"; $output .= sprintf(__('Execution results of routine %s'), PMA_Util::backquote(htmlspecialchars($routine['item_name']))); $output .= "</legend>"; $num_of_rusults_set_to_display = 0; do { $result = PMA_DBI_store_result(); $num_rows = PMA_DBI_num_rows($result); if ($result !== false && $num_rows > 0) { $output .= "<table><tr>"; foreach (PMA_DBI_get_fields_meta($result) as $key => $field) { $output .= "<th>"; $output .= htmlspecialchars($field->name); $output .= "</th>"; } $output .= "</tr>"; $color_class = 'odd'; while ($row = PMA_DBI_fetch_assoc($result)) { $output .= "<tr>"; foreach ($row as $key => $value) { if ($value === null) { $value = '<i>NULL</i>'; } else { $value = htmlspecialchars($value); } $output .= "<td class='" . $color_class . "'>" . $value . "</td>"; } $output .= "</tr>"; $color_class = $color_class == 'odd' ? 'even' : 'odd'; } $output .= "</table>"; $num_of_rusults_set_to_display++; $affected = $num_rows; } if (!PMA_DBI_more_results()) { break; } $output .= "<br/>"; PMA_DBI_free_result($result); } while (PMA_DBI_next_result()); $output .= "</fieldset>"; $message = __('Your SQL query has been executed successfully'); if ($routine['item_type'] == 'PROCEDURE') { $message .= '<br />'; // TODO : message need to be modified according to the // output from the routine $message .= sprintf(_ngettext('%d row affected by the last statement inside the procedure', '%d rows affected by the last statement inside the procedure', $affected), $affected); } $message = PMA_message::success($message); if ($num_of_rusults_set_to_display == 0) { $notice = __('MySQL returned an empty result set (i.e. zero rows).'); $output .= PMA_message::notice($notice)->getDisplay(); } } else { $output = ''; $message = PMA_message::error(sprintf(__('The following query has failed: "%s"'), htmlspecialchars($query)) . '<br /><br />' . __('MySQL said: ') . PMA_DBI_getError(null)); } // Print/send output if ($GLOBALS['is_ajax_request']) { $response = PMA_Response::getInstance(); $response->isSuccess($message->isSuccess()); $response->addJSON('message', $message->getDisplay() . $output); $response->addJSON('dialog', false); exit; } else { echo $message->getDisplay() . $output; if ($message->isError()) { // At least one query has failed, so shouldn't // execute any more queries, so we quit. exit; } unset($_POST); // Now deliberately fall through to displaying the routines list } } else { $message = __('Error in processing request') . ' : '; $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_Util::backquote($db))); $message = PMA_message::error($message); if ($GLOBALS['is_ajax_request']) { $response = PMA_Response::getInstance(); $response->isSuccess(false); $response->addJSON('message', $message); exit; } else { echo $message->getDisplay(); unset($_POST); } } } else { if (!empty($_GET['execute_dialog']) && !empty($_GET['item_name'])) { /** * Display the execute form for a routine. */ $routine = PMA_RTN_getDataFromName($_GET['item_name'], $_GET['item_type'], true); if ($routine !== false) { $form = PMA_RTN_getExecuteForm($routine); if ($GLOBALS['is_ajax_request'] == true) { $title = __("Execute routine") . " " . PMA_Util::backquote(htmlentities($_GET['item_name'], ENT_QUOTES)); $response = PMA_Response::getInstance(); $response->addJSON('message', $form); $response->addJSON('title', $title); $response->addJSON('dialog', true); } else { echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n"; echo $form; } exit; } else { if ($GLOBALS['is_ajax_request'] == true) { $message = __('Error in processing request') . ' : '; $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_Util::backquote($db))); $message = PMA_message::error($message); $response = PMA_Response::getInstance(); $response->isSuccess(false); $response->addJSON('message', $message); exit; } } } } }
/** * Prepares queries for adding users and * also create database and return query and message * * @param boolean $_error whether user create or not * @param string $real_sql_query SQL query for add a user * @param string $sql_query SQL query to be displayed * @param string $username username * @param string $hostname host name * @param string $dbname database name * * @return array $sql_query, $message */ function PMA_addUserAndCreateDatabase($_error, $real_sql_query, $sql_query, $username, $hostname, $dbname) { if ($_error || !PMA_DBI_try_query($real_sql_query)) { $_REQUEST['createdb-1'] = $_REQUEST['createdb-2'] = $_REQUEST['createdb-3'] = false; $message = PMA_Message::rawError(PMA_DBI_getError()); } else { $message = PMA_Message::success(__('You have added a new user.')); } if (isset($_REQUEST['createdb-1'])) { // Create database with same name and grant all privileges $q = 'CREATE DATABASE IF NOT EXISTS ' . PMA_Util::backquote(PMA_Util::sqlAddSlashes($username)) . ';'; $sql_query .= $q; if (!PMA_DBI_try_query($q)) { $message = PMA_Message::rawError(PMA_DBI_getError()); } /** * Reload the navigation */ $GLOBALS['reload'] = true; $GLOBALS['db'] = $username; $q = 'GRANT ALL PRIVILEGES ON ' . PMA_Util::backquote(PMA_Util::escapeMysqlWildcards(PMA_Util::sqlAddSlashes($username))) . '.* TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';'; $sql_query .= $q; if (!PMA_DBI_try_query($q)) { $message = PMA_Message::rawError(PMA_DBI_getError()); } } if (isset($_REQUEST['createdb-2'])) { // Grant all privileges on wildcard name (username\_%) $q = 'GRANT ALL PRIVILEGES ON ' . PMA_Util::backquote(PMA_Util::sqlAddSlashes($username) . '\\_%') . '.* TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';'; $sql_query .= $q; if (!PMA_DBI_try_query($q)) { $message = PMA_Message::rawError(PMA_DBI_getError()); } } if (isset($_REQUEST['createdb-3'])) { // Grant all privileges on the specified database to the new user $q = 'GRANT ALL PRIVILEGES ON ' . PMA_Util::backquote(PMA_Util::sqlAddSlashes($dbname)) . '.* TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';'; $sql_query .= $q; if (!PMA_DBI_try_query($q)) { $message = PMA_Message::rawError(PMA_DBI_getError()); } } return array($sql_query, $message); }