/** * This function is called from one of the other functions in this file * and it completes the handling of the export functionality. * * @param string $item_name The name of the item that we are exporting * @param string $export_data The SQL query to create the requested item * * @return void */ function PMA_RTE_handleExport($item_name, $export_data) { global $db; $item_name = htmlspecialchars(PMA_Util::backquote($_GET['item_name'])); if ($export_data !== false) { $export_data = '<textarea cols="40" rows="15" style="width: 100%;">' . htmlspecialchars(trim($export_data)) . '</textarea>'; $title = sprintf(PMA_RTE_getWord('export'), $item_name); if ($GLOBALS['is_ajax_request'] == true) { $response = PMA_Response::getInstance(); $response->addJSON('message', $export_data); $response->addJSON('title', $title); exit; } else { echo "<fieldset>\n" . "<legend>{$title}</legend>\n" . $export_data . "</fieldset>\n"; } } else { $_db = htmlspecialchars(PMA_Util::backquote($db)); $message = __('Error in processing request:') . ' ' . sprintf(PMA_RTE_getWord('not_found'), $item_name, $_db); $response = PMA_message::error($message); if ($GLOBALS['is_ajax_request'] == true) { $response = PMA_Response::getInstance(); $response->isSuccess(false); $response->addJSON('message', $message); exit; } else { $response->display(); } } }
/** * Saves user preferences * * @param array $config_array configuration array * * @return true|PMA_Message */ function PMA_saveUserprefs(array $config_array) { $cfgRelation = PMA_getRelationsParam(); $server = isset($GLOBALS['server']) ? $GLOBALS['server'] : $GLOBALS['cfg']['ServerDefault']; $cache_key = 'server_' . $server; if (!$cfgRelation['userconfigwork']) { // no pmadb table, use session storage $_SESSION['userconfig'] = array('db' => $config_array, 'ts' => time()); if (isset($_SESSION['cache'][$cache_key]['userprefs'])) { unset($_SESSION['cache'][$cache_key]['userprefs']); } return true; } // save configuration to pmadb $query_table = PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['userconfig']); $query = 'SELECT `username` FROM ' . $query_table . ' WHERE `username` = \'' . PMA_Util::sqlAddSlashes($cfgRelation['user']) . '\''; $has_config = $GLOBALS['dbi']->fetchValue($query, 0, 0, $GLOBALS['controllink']); $config_data = json_encode($config_array); if ($has_config) { $query = 'UPDATE ' . $query_table . ' SET `timevalue` = NOW(), `config_data` = \'' . PMA_Util::sqlAddSlashes($config_data) . '\'' . ' WHERE `username` = \'' . PMA_Util::sqlAddSlashes($cfgRelation['user']) . '\''; } else { $query = 'INSERT INTO ' . $query_table . ' (`username`, `timevalue`,`config_data`) ' . 'VALUES (\'' . PMA_Util::sqlAddSlashes($cfgRelation['user']) . '\', NOW(), ' . '\'' . PMA_Util::sqlAddSlashes($config_data) . '\')'; } if (isset($_SESSION['cache'][$cache_key]['userprefs'])) { unset($_SESSION['cache'][$cache_key]['userprefs']); } if (!$GLOBALS['dbi']->tryQuery($query, $GLOBALS['controllink'])) { $message = PMA_Message::error(__('Could not save configuration')); $message->addMessage('<br /><br />'); $message->addMessage(PMA_Message::rawError($GLOBALS['dbi']->getError($GLOBALS['controllink']))); return $message; } return true; }
/** * Send TRI or EVN editor via ajax or by echoing. * * @param string $type TRI or EVN * @param string $mode Editor mode 'add' or 'edit' * @param array $item Data necessary to create the editor * @param string $title Title of the editor * @param string $db Database * @param string $operation Operation 'change' or '' * * @return void */ function PMA_RTE_sendEditor($type, $mode, $item, $title, $db, $operation = null) { if ($item !== false) { // Show form if ($type == 'TRI') { $editor = PMA_TRI_getEditorForm($mode, $item); } else { // EVN $editor = PMA_EVN_getEditorForm($mode, $operation, $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(); } } }
/** * Get SQL query for store new transformation details of a VIEW * * @param mysqli_result $pma_transformation_data Result set of SQL execution * @param array $column_map Details of VIEW columns * @param string $view_name Name of the VIEW * @param string $db Database name of the VIEW * * @return string $new_transformations_sql SQL query for new transformations */ function PMA_getNewTransformationDataSql($pma_transformation_data, $column_map, $view_name, $db) { $cfgRelation = PMA_getRelationsParam(); // Need to store new transformation details for VIEW $new_transformations_sql = 'INSERT INTO ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['column_info']) . ' (`db_name`, `table_name`, `column_name`, `comment`, ' . '`mimetype`, `transformation`, `transformation_options`)' . ' VALUES '; $column_count = 0; $add_comma = false; while ($data_row = $GLOBALS['dbi']->fetchAssoc($pma_transformation_data)) { foreach ($column_map as $column) { if ($data_row['table_name'] == $column['table_name'] && $data_row['column_name'] == $column['refering_column']) { $new_transformations_sql .= $add_comma ? ', ' : ''; $new_transformations_sql .= '(' . '\'' . $db . '\', ' . '\'' . $view_name . '\', ' . '\''; $new_transformations_sql .= isset($column['real_column']) ? $column['real_column'] : $column['refering_column']; $new_transformations_sql .= '\', ' . '\'' . $data_row['comment'] . '\', ' . '\'' . $data_row['mimetype'] . '\', ' . '\'' . $data_row['transformation'] . '\', ' . '\'' . PMA_Util::sqlAddSlashes($data_row['transformation_options']) . '\')'; $add_comma = true; $column_count++; break; } } if ($column_count == count($column_map)) { break; } } return $column_count > 0 ? $new_transformations_sql : ''; }
/** * Test for PMA_getHtmlForActionLinks * * @return void */ public function testPMAGetHtmlForActionLinks() { $current_table = array('TABLE_ROWS' => 3, 'TABLE_NAME' => 'name1', 'TABLE_COMMENT' => 'This is a test comment'); $table_is_view = false; $tbl_url_query = 'tbl_url_query'; $titles = array('Browse' => 'Browse1', 'NoBrowse' => 'NoBrowse1', 'Search' => 'Search1', 'NoSearch' => 'NoSearch1', 'Empty' => 'Empty1', 'NoEmpty' => 'NoEmpty1'); $truename = 'truename'; $db_is_system_schema = null; $url_query = 'url_query'; //$table_is_view = true; list($browse_table, $search_table, $browse_table_label, $empty_table, $tracking_icon) = PMA_getHtmlForActionLinks($current_table, $table_is_view, $tbl_url_query, $titles, $truename, $db_is_system_schema, $url_query); //$browse_table $this->assertContains($titles['Browse'], $browse_table); //$search_table $this->assertContains($titles['Search'], $search_table); $this->assertContains($tbl_url_query, $search_table); //$browse_table_label $this->assertContains($tbl_url_query, $browse_table_label); //$empty_table $this->assertContains($tbl_url_query, $empty_table); $this->assertContains(urlencode('TRUNCATE ' . PMA_Util::backquote($current_table['TABLE_NAME'])), $empty_table); $this->assertContains($titles['Empty'], $empty_table); //$table_is_view = false; $current_table = array('TABLE_ROWS' => 0, 'TABLE_NAME' => 'name1', 'TABLE_COMMENT' => 'This is a test comment'); $table_is_view = false; list($browse_table, $search_table, $browse_table_label, $empty_table, $tracking_icon) = PMA_getHtmlForActionLinks($current_table, $table_is_view, $tbl_url_query, $titles, $truename, $db_is_system_schema, $url_query); //$browse_table $this->assertContains($titles['NoBrowse'], $browse_table); //$search_table $this->assertContains($titles['NoSearch'], $search_table); //$browse_table_label $this->assertContains($tbl_url_query, $browse_table_label); $this->assertContains($titles['NoEmpty'], $empty_table); }
/** * Format a string so it can be a string inside JavaScript code inside an * eventhandler (onclick, onchange, on..., ). * This function is used to displays a javascript confirmation box for * "DROP/DELETE/ALTER" queries. * * @param string $a_string the string to format * @param boolean $add_backquotes whether to add backquotes to the string or not * * @return string the formatted string * * @access public */ function PMA_jsFormat($a_string = '', $add_backquotes = true) { if (is_string($a_string)) { $a_string = htmlspecialchars($a_string); $a_string = PMA_escapeJsString($a_string); // Needed for inline javascript to prevent some browsers // treating it as a anchor $a_string = str_replace('#', '\\#', $a_string); } return $add_backquotes ? PMA_Util::backquote($a_string) : $a_string; }
public function __construct() { if (strlen($GLOBALS['cfg']['Server']['pmadb']) && strlen($GLOBALS['cfg']['Server']['recent'])) { $this->_pmaTable = PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb']) . "." . PMA_Util::backquote($GLOBALS['cfg']['Server']['recent']); } $server_id = $GLOBALS['server']; if (!isset($_SESSION['tmp_user_values']['recent_tables'][$server_id])) { $_SESSION['tmp_user_values']['recent_tables'][$server_id] = isset($this->_pmaTable) ? $this->getFromDb() : array(); } $this->tables =& $_SESSION['tmp_user_values']['recent_tables'][$server_id]; }
/** * Creates a new instance of PMA_RecentFavoriteTable * * @access private * @param string $type the table type */ private function __construct($type) { $this->_tableType = $type; if (strlen($GLOBALS['cfg']['Server']['pmadb']) && strlen($GLOBALS['cfg']['Server'][$this->_tableType])) { $this->_pmaTable = PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb']) . "." . PMA_Util::backquote($GLOBALS['cfg']['Server'][$this->_tableType]); } $server_id = $GLOBALS['server']; if (!isset($_SESSION['tmpval'][$this->_tableType . '_tables'][$server_id])) { $_SESSION['tmpval'][$this->_tableType . '_tables'][$server_id] = isset($this->_pmaTable) ? $this->getFromDb() : array(); } $this->_tables =& $_SESSION['tmpval'][$this->_tableType . '_tables'][$server_id]; }
/** * Returns a modified sql query with only the label column * and spatial column(wrapped with 'ASTEXT()' function). * * @param string $sql_query original sql query * @param array $visualizationSettings settings for the visualization * * @return string the modified sql query. */ function PMA_GIS_modifyQuery($sql_query, $visualizationSettings) { $modified_query = 'SELECT '; // If label column is chosen add it to the query if (!empty($visualizationSettings['labelColumn'])) { $modified_query .= PMA_Util::backquote($visualizationSettings['labelColumn']) . ', '; } // Wrap the spatial column with 'ASTEXT()' function and add it $modified_query .= 'ASTEXT(' . PMA_Util::backquote($visualizationSettings['spatialColumn']) . ') AS ' . PMA_Util::backquote($visualizationSettings['spatialColumn']) . ', '; // Get the SRID $modified_query .= 'SRID(' . PMA_Util::backquote($visualizationSettings['spatialColumn']) . ') AS ' . PMA_Util::backquote('srid') . ' '; // Append the original query as the inner query $modified_query .= 'FROM (' . $sql_query . ') AS ' . PMA_Util::backquote('temp_gis'); return $modified_query; }
/** * Get SQL query for store new transformation details of a VIEW * * @param object $pma_transformation_data Result set of SQL execution * @param array $column_map Details of VIEW columns * @param string $view_name Name of the VIEW * @param string $db Database name of the VIEW * * @return string $new_transformations_sql SQL query for new transformations */ function getNewTransformationDataSql($pma_transformation_data, $column_map, $view_name, $db) { $cfgRelation = \PMA_getRelationsParam(); // Need to store new transformation details for VIEW $new_transformations_sql = sprintf("INSERT INTO %s.%s (" . "`db_name`, `table_name`, `column_name`, " . "`comment`, `mimetype`, `transformation`, " . "`transformation_options`) VALUES", \PMA_Util::backquote($cfgRelation['db']), \PMA_Util::backquote($cfgRelation['column_info'])); $column_count = 0; $add_comma = false; while ($data_row = $this->dbi->fetchAssoc($pma_transformation_data)) { foreach ($column_map as $column) { if ($data_row['table_name'] != $column['table_name'] || $data_row['column_name'] != $column['refering_column']) { continue; } $new_transformations_sql .= sprintf("%s ('%s', '%s', '%s', '%s', '%s', '%s', '%s')", $add_comma ? ', ' : '', $db, $view_name, isset($column['real_column']) ? $column['real_column'] : $column['refering_column'], $data_row['comment'], $data_row['mimetype'], $data_row['transformation'], \PMA_Util::sqlAddSlashes($data_row['transformation_options'])); $add_comma = true; $column_count++; break; } if ($column_count == count($column_map)) { break; } } return $column_count > 0 ? $new_transformations_sql : ''; }
/** * Returns a modified sql query with only the label column * and spatial column(wrapped with 'ASTEXT()' function). * * @param string $sql_query original sql query * @param array $visualizationSettings settings for the visualization * @param integer $rows number of rows * @param integer $pos start position * * @return string the modified sql query. */ function PMA_GIS_modifyQuery($sql_query, $visualizationSettings, $rows = null, $pos = null) { $modified_query = 'SELECT '; // If label column is chosen add it to the query if (!empty($visualizationSettings['labelColumn'])) { $modified_query .= PMA_Util::backquote($visualizationSettings['labelColumn']) . ', '; } // Wrap the spatial column with 'ASTEXT()' function and add it $modified_query .= 'ASTEXT(' . PMA_Util::backquote($visualizationSettings['spatialColumn']) . ') AS ' . PMA_Util::backquote($visualizationSettings['spatialColumn']) . ', '; // Get the SRID $modified_query .= 'SRID(' . PMA_Util::backquote($visualizationSettings['spatialColumn']) . ') AS ' . PMA_Util::backquote('srid') . ' '; // Append the original query as the inner query $modified_query .= 'FROM (' . $sql_query . ') AS ' . PMA_Util::backquote('temp_gis'); // LIMIT clause if (is_numeric($rows) && $rows > 0) { $modified_query .= ' LIMIT '; if (is_numeric($pos) && $pos >= 0) { $modified_query .= $pos . ', ' . $rows; } else { $modified_query .= $rows; } } return $modified_query; }
/** * Function to get update query for updating internal relations * * @param string $multi_edit_columns_name multi edit column names * @param string $master_field_md5 master field md5 * @param string $foreign_db foreign database * @param string $destination_table destination table * @param string $destination_column destination column * @param array $cfgRelation configuration relation * @param string $db current database * @param string $table current table * @param array $existrel db, table, column * * @return string */ function PMA_getQueryForInternalRelationUpdate($multi_edit_columns_name, $master_field_md5, $foreign_db, $destination_table, $destination_column, $cfgRelation, $db, $table, $existrel) { $upd_query = false; // Map the fieldname's md5 back to its real name $master_field = $multi_edit_columns_name[$master_field_md5]; $foreign_table = $destination_table[$master_field_md5]; $foreign_field = $destination_column[$master_field_md5]; if (!empty($foreign_db) && !empty($foreign_table) && !empty($foreign_field)) { if (!isset($existrel[$master_field])) { $upd_query = 'INSERT INTO ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util::backquote($cfgRelation['relation']) . '(master_db, master_table, master_field, foreign_db,' . ' foreign_table, foreign_field)' . ' values(' . '\'' . PMA_Util::sqlAddSlashes($db) . '\', ' . '\'' . PMA_Util::sqlAddSlashes($table) . '\', ' . '\'' . PMA_Util::sqlAddSlashes($master_field) . '\', ' . '\'' . PMA_Util::sqlAddSlashes($foreign_db) . '\', ' . '\'' . PMA_Util::sqlAddSlashes($foreign_table) . '\',' . '\'' . PMA_Util::sqlAddSlashes($foreign_field) . '\')'; } elseif ($existrel[$master_field]['foreign_db'] != $foreign_db || $existrel[$master_field]['foreign_table'] != $foreign_table || $existrel[$master_field]['foreign_field'] != $foreign_field) { $upd_query = 'UPDATE ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util::backquote($cfgRelation['relation']) . ' SET' . ' foreign_db = \'' . PMA_Util::sqlAddSlashes($foreign_db) . '\', ' . ' foreign_table = \'' . PMA_Util::sqlAddSlashes($foreign_table) . '\', ' . ' foreign_field = \'' . PMA_Util::sqlAddSlashes($foreign_field) . '\' ' . ' WHERE master_db = \'' . PMA_Util::sqlAddSlashes($db) . '\'' . ' AND master_table = \'' . PMA_Util::sqlAddSlashes($table) . '\'' . ' AND master_field = \'' . PMA_Util::sqlAddSlashes($master_field) . '\''; } // end if... else.... } elseif (isset($existrel[$master_field])) { $upd_query = 'DELETE FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util::backquote($cfgRelation['relation']) . ' WHERE master_db = \'' . PMA_Util::sqlAddSlashes($db) . '\'' . ' AND master_table = \'' . PMA_Util::sqlAddSlashes($table) . '\'' . ' AND master_field = \'' . PMA_Util::sqlAddSlashes($master_field) . '\''; } // end if... else.... return $upd_query; }
/** * 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 || !empty($real_sql_query) && !$GLOBALS['dbi']->tryQuery($real_sql_query)) { $_REQUEST['createdb-1'] = $_REQUEST['createdb-2'] = $_REQUEST['createdb-3'] = null; $message = PMA_Message::rawError($GLOBALS['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 (!$GLOBALS['dbi']->tryQuery($q)) { $message = PMA_Message::rawError($GLOBALS['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 (!$GLOBALS['dbi']->tryQuery($q)) { $message = PMA_Message::rawError($GLOBALS['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 (!$GLOBALS['dbi']->tryQuery($q)) { $message = PMA_Message::rawError($GLOBALS['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 (!$GLOBALS['dbi']->tryQuery($q)) { $message = PMA_Message::rawError($GLOBALS['dbi']->getError()); } } return array($sql_query, $message); }
/** * Add/update a user group with allowed menu tabs. * * @param string $userGroup user group name * @param boolean $new whether this is a new user group * * @return void */ function PMA_editUserGroup($userGroup, $new = false) { $tabs = PMA_Util::getMenuTabList(); $groupTable = PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb']) . "." . PMA_Util::backquote($GLOBALS['cfg']['Server']['usergroups']); if (!$new) { $sql_query = "DELETE FROM " . $groupTable . " WHERE `usergroup`='" . PMA_Util::sqlAddSlashes($userGroup) . "';"; PMA_queryAsControlUser($sql_query, true); } $sql_query = "INSERT INTO " . $groupTable . "(`usergroup`, `tab`, `allowed`)" . " VALUES "; $first = true; foreach ($tabs as $tabGroupName => $tabGroup) { foreach ($tabs[$tabGroupName] as $tab => $tabName) { if (!$first) { $sql_query .= ", "; } $tabName = $tabGroupName . '_' . $tab; $allowed = isset($_REQUEST[$tabName]) && $_REQUEST[$tabName] == 'Y'; $sql_query .= "('" . $userGroup . "', '" . $tabName . "', '" . ($allowed ? "Y" : "N") . "')"; $first = false; } } $sql_query .= ";"; PMA_queryAsControlUser($sql_query, true); }
/** * get all tables involved or included in page * * @param string $db name of the database * @param integer $pageNumber page no. whose tables will be fetched in an array * * @return Array an array of tables * * @access public */ public function getAllTables($db, $pageNumber) { global $cfgRelation; // Get All tables $tab_sql = 'SELECT table_name FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util::backquote($cfgRelation['table_coords']) . ' WHERE db_name = \'' . PMA_Util::sqlAddSlashes($db) . '\'' . ' AND pdf_page_number = ' . $pageNumber; $tab_rs = PMA_queryAsControlUser($tab_sql, null, PMA_DBI_QUERY_STORE); if (!$tab_rs || !PMA_DBI_num_rows($tab_rs) > 0) { $this->dieSchema('', __('This page does not contain any tables!')); } while ($curr_table = @PMA_DBI_fetch_assoc($tab_rs)) { $alltables[] = PMA_Util::sqlAddSlashes($curr_table['table_name']); } return $alltables; }
/** * 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; } } } } }
/** * Check child table references and foreign key for a table column. * * @param string $db name of master table db. * @param string $table name of master table. * @param string $column name of master table column. * @param array $foreigners_full foreiners array for the whole table. * @param array $child_references_full child references for the whole table. * * @return array $column_status telling about references if foreign key. */ function PMA_checkChildForeignReferences($db, $table, $column, $foreigners_full = null, $child_references_full = null) { $column_status = array(); $column_status['isEditable'] = false; $column_status['isReferenced'] = false; $column_status['isForeignKey'] = false; $column_status['references'] = array(); $foreigners = array(); if ($foreigners_full !== null) { if (isset($foreigners_full[$column])) { $foreigners[$column] = $foreigners_full[$column]; } if (isset($foreigners_full['foreign_keys_data'])) { $foreigners['foreign_keys_data'] = $foreigners_full['foreign_keys_data']; } } else { $foreigners = PMA_getForeigners($db, $table, $column, 'foreign'); } $foreigner = PMA_searchColumnInForeigners($foreigners, $column); $child_references = array(); if ($child_references_full !== null) { if (isset($child_references_full[$column])) { $child_references = $child_references_full[$column]; } } else { $child_references = PMA_getChildReferences($db, $table, $column); } if (sizeof($child_references, 0) > 0 || $foreigner) { if (sizeof($child_references, 0) > 0) { $column_status['isReferenced'] = true; foreach ($child_references as $row => $columns) { array_push($column_status['references'], PMA_Util::backquote($columns['table_schema']) . '.' . PMA_Util::backquote($columns['table_name'])); } } if ($foreigner) { $column_status['isForeignKey'] = true; } } else { $column_status['isEditable'] = true; } return $column_status; }
/** * Returns HTML for show hidden button displayed infront of database node * * @return String HTML for show hidden button */ public function getHtmlForControlButtons() { $ret = ''; $db = $this->real_name; $cfgRelation = PMA_getRelationsParam(); if ($cfgRelation['navwork']) { $navTable = PMA_Util::backquote($cfgRelation['db']) . "." . PMA_Util::backquote($cfgRelation['navigationhiding']); $sqlQuery = "SELECT COUNT(*) FROM " . $navTable . " WHERE `username`='" . PMA_Util::sqlAddSlashes($GLOBALS['cfg']['Server']['user']) . "'" . " AND `db_name`='" . PMA_Util::sqlAddSlashes($db) . "'"; $count = $GLOBALS['dbi']->fetchValue($sqlQuery, 0, 0, $GLOBALS['controllink']); if ($count > 0) { $ret = '<span class="dbItemControls">' . '<a href="navigation.php?' . PMA_URL_getCommon() . '&showUnhideDialog=true' . '&dbName=' . urldecode($db) . '"' . ' class="showUnhide ajax">' . PMA_Util::getImage('lightbulb.png', __('Show hidden items')) . '</a></span>'; } } return $ret; }
/** * Move or copy a table * * @param string $db current database name * @param string $table current table name * * @return void */ function PMA_moveOrCopyTable($db, $table) { /** * Selects the database to work with */ $GLOBALS['dbi']->selectDb($db); /** * $_REQUEST['target_db'] could be empty in case we came from an input field * (when there are many databases, no drop-down) */ if (empty($_REQUEST['target_db'])) { $_REQUEST['target_db'] = $db; } /** * A target table name has been sent to this script -> do the work */ if (PMA_isValid($_REQUEST['new_name'])) { if ($db == $_REQUEST['target_db'] && $table == $_REQUEST['new_name']) { if (isset($_REQUEST['submit_move'])) { $message = PMA_Message::error(__('Can\'t move table to same one!')); } else { $message = PMA_Message::error(__('Can\'t copy table to same one!')); } } else { PMA_Table::moveCopy($db, $table, $_REQUEST['target_db'], $_REQUEST['new_name'], $_REQUEST['what'], isset($_REQUEST['submit_move']), 'one_table'); if (isset($_REQUEST['adjust_privileges']) && !empty($_REQUEST['adjust_privileges'])) { if (isset($_REQUEST['submit_move'])) { PMA_AdjustPrivileges_renameOrMoveTable($db, $table, $_REQUEST['target_db'], $_REQUEST['new_name']); } else { PMA_AdjustPrivileges_copyTable($db, $table, $_REQUEST['target_db'], $_REQUEST['new_name']); } if (isset($_REQUEST['submit_move'])) { $message = PMA_Message::success(__('Table %s has been moved to %s. Privileges have been ' . 'adjusted.')); } else { $message = PMA_Message::success(__('Table %s has been copied to %s. Privileges have been ' . 'adjusted.')); } } else { if (isset($_REQUEST['submit_move'])) { $message = PMA_Message::success(__('Table %s has been moved to %s.')); } else { $message = PMA_Message::success(__('Table %s has been copied to %s.')); } } $old = PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table); $message->addParam($old); $new = PMA_Util::backquote($_REQUEST['target_db']) . '.' . PMA_Util::backquote($_REQUEST['new_name']); $message->addParam($new); /* Check: Work on new table or on old table? */ if (isset($_REQUEST['submit_move']) || PMA_isValid($_REQUEST['switch_to_new'])) { } } } else { /** * No new name for the table! */ $message = PMA_Message::error(__('The table name is empty!')); } if ($GLOBALS['is_ajax_request'] == true) { $response = PMA_Response::getInstance(); $response->addJSON('message', $message); if ($message->isSuccess()) { $response->addJSON('db', $GLOBALS['db']); } else { $response->isSuccess(false); } exit; } }
$is_table = @$GLOBALS['dbi']->numRows($_result); $GLOBALS['dbi']->freeResult($_result); } } else { $is_table = false; } if (!$is_table) { if (!defined('IS_TRANSFORMATION_WRAPPER')) { if (mb_strlen($table)) { // SHOW TABLES doesn't show temporary tables, so try select // (as it can happen just in case temporary table, it should be // fast): /** * @todo should this check really * only happen if IS_TRANSFORMATION_WRAPPER? */ $_result = $GLOBALS['dbi']->tryQuery('SELECT COUNT(*) FROM ' . PMA_Util::backquote($table) . ';', null, PMA_DatabaseInterface::QUERY_STORE); $is_table = $_result && @$GLOBALS['dbi']->numRows($_result); $GLOBALS['dbi']->freeResult($_result); } if (!$is_table) { include './db_sql.php'; exit; } } if (!$is_table) { exit; } } } // end if (ensures table exists)
/** * Prepares the displayable content of a data cell in Browse mode, * taking into account foreign key description field and transformations * * @param string $class css classes for the td element * @param bool $condition_field whether the column is a part of * the where clause * @param array $analyzed_sql the analyzed query * @param object $meta the meta-information about the * field * @param array $map the list of relations * @param string $data data * @param object|string $transformation_plugin transformation plugin. * Can also be the default function: * PMA_mimeDefaultFunction * @param string $default_function default function * @param string $nowrap 'nowrap' if the content should * not be wrapped * @param string $where_comparison data for the where clause * @param array $transform_options options for transformation * @param bool $is_field_truncated whether the field is truncated * * @return string formatted data * * @access private * * @see _getDataCellForNumericColumns(), _getDataCellForGeometryColumns(), * _getDataCellForNonNumericColumns(), * */ private function _getRowData($class, $condition_field, $analyzed_sql, $meta, $map, $data, $transformation_plugin, $default_function, $nowrap, $where_comparison, $transform_options, $is_field_truncated) { $relational_display = $_SESSION['tmpval']['relational_display']; $printview = $this->__get('printview'); $decimals = isset($meta->decimals) ? $meta->decimals : '-1'; $result = '<td data-decimals="' . $decimals . '" data-type="' . $meta->type . '" class="' . $this->_addClass($class, $condition_field, $meta, $nowrap, $is_field_truncated, $transformation_plugin, $default_function) . '">'; if (isset($analyzed_sql[0]['select_expr']) && is_array($analyzed_sql[0]['select_expr'])) { foreach ($analyzed_sql[0]['select_expr'] as $select_expr_position => $select_expr) { $alias = $analyzed_sql[0]['select_expr'][$select_expr_position]['alias']; if (!isset($alias) || !mb_strlen($alias)) { continue; } // end if $true_column = $analyzed_sql[0]['select_expr'][$select_expr_position]['column']; if ($alias == $meta->name) { // this change in the parameter does not matter // outside of the function $meta->name = $true_column; } // end if } // end foreach } // end if if (isset($map[$meta->name])) { // Field to display from the foreign table? if (isset($map[$meta->name][2]) && mb_strlen($map[$meta->name][2])) { $dispsql = 'SELECT ' . PMA_Util::backquote($map[$meta->name][2]) . ' FROM ' . PMA_Util::backquote($map[$meta->name][3]) . '.' . PMA_Util::backquote($map[$meta->name][0]) . ' WHERE ' . PMA_Util::backquote($map[$meta->name][1]) . $where_comparison; $dispresult = $GLOBALS['dbi']->tryQuery($dispsql, null, PMA_DatabaseInterface::QUERY_STORE); if ($dispresult && $GLOBALS['dbi']->numRows($dispresult) > 0) { list($dispval) = $GLOBALS['dbi']->fetchRow($dispresult, 0); } else { $dispval = __('Link not found!'); } @$GLOBALS['dbi']->freeResult($dispresult); } else { $dispval = ''; } // end if... else... if (isset($printview) && $printview == '1') { $result .= ($transformation_plugin != $default_function ? $transformation_plugin->applyTransformation($data, $transform_options, $meta) : $default_function($data)) . ' <code>[->' . $dispval . ']</code>'; } else { if ($relational_display == self::RELATIONAL_KEY) { // user chose "relational key" in the display options, so // the title contains the display field $title = !empty($dispval) ? ' title="' . htmlspecialchars($dispval) . '"' : ''; } else { $title = ' title="' . htmlspecialchars($data) . '"'; } $_url_params = array('db' => $map[$meta->name][3], 'table' => $map[$meta->name][0], 'pos' => '0', 'sql_query' => 'SELECT * FROM ' . PMA_Util::backquote($map[$meta->name][3]) . '.' . PMA_Util::backquote($map[$meta->name][0]) . ' WHERE ' . PMA_Util::backquote($map[$meta->name][1]) . $where_comparison); $result .= '<a class="ajax" href="sql.php' . PMA_URL_getCommon($_url_params) . '"' . $title . '>'; if ($transformation_plugin != $default_function) { // always apply a transformation on the real data, // not on the display field $result .= $transformation_plugin->applyTransformation($data, $transform_options, $meta); } else { if ($relational_display == self::RELATIONAL_DISPLAY_COLUMN && !empty($map[$meta->name][2])) { // user chose "relational display field" in the // display options, so show display field in the cell $result .= $default_function($dispval); } else { // otherwise display data in the cell $result .= $default_function($data); } } $result .= '</a>'; } } else { $result .= $transformation_plugin != $default_function ? $transformation_plugin->applyTransformation($data, $transform_options, $meta) : $default_function($data); } $result .= '</td>' . "\n"; return $result; }
/** * Outputs table's structure * * @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 $export_mode 'create_table','triggers','create_view', * 'stand_in' * @param string $export_type 'server', 'database', 'table' * @param bool $relation whether to include relation comments * @param bool $comments whether to include the pmadb-style column * comments as comments in the structure; this is * deprecated but the parameter is left here * because export.php calls exportStructure() * also for other export types which use this * parameter * @param bool $mime whether to include mime comments * @param bool $dates whether to include creation/update/check dates * * @return bool Whether it succeeded */ public function exportStructure($db, $table, $crlf, $error_url, $export_mode, $export_type, $relation = false, $comments = false, $mime = false, $dates = false) { 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 . '\''; $dump = $this->_possibleCRLF() . $this->_exportComment(str_repeat('-', 56)) . $this->_possibleCRLF() . $this->_exportComment(); switch ($export_mode) { case 'create_table': $dump .= $this->_exportComment(__('Table structure for table') . ' ' . $formatted_table_name); $dump .= $this->_exportComment(); $dump .= $this->getTableDef($db, $table, $crlf, $error_url, $dates); $dump .= $this->_getTableComments($db, $table, $crlf, $relation, $mime); break; case 'triggers': $dump = ''; $triggers = PMA_DBI_get_triggers($db, $table); if ($triggers) { $dump .= $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment(__('Triggers') . ' ' . $formatted_table_name) . $this->_exportComment(); $delimiter = '//'; foreach ($triggers as $trigger) { $dump .= $trigger['drop'] . ';' . $crlf; $dump .= 'DELIMITER ' . $delimiter . $crlf; $dump .= $trigger['create']; $dump .= 'DELIMITER ;' . $crlf; } } break; case 'create_view': $dump .= $this->_exportComment(__('Structure for view') . ' ' . $formatted_table_name) . $this->_exportComment(); // delete the stand-in table previously created (if any) if ($export_type != 'table') { $dump .= 'DROP TABLE IF EXISTS ' . PMA_Util::backquote($table) . ';' . $crlf; } $dump .= $this->getTableDef($db, $table, $crlf, $error_url, $dates, true, true); break; case 'stand_in': $dump .= $this->_exportComment(__('Stand-in structure for view') . ' ' . $formatted_table_name) . $this->_exportComment(); // export a stand-in definition to resolve view dependencies $dump .= $this->getTableDefStandIn($db, $table, $crlf); } // end switch // this one is built by getTableDef() to use in table copy/move // but not in the case of export unset($GLOBALS['sql_constraints_query']); return PMA_exportOutputHandler($dump); }
// In such case we can use the value of port. $server_details['port'] = $cfg['Server']['port']; } // otherwise we leave the $server_details['port'] unset, // allowing it to take default mysql port $controllink = $GLOBALS['dbi']->connect($cfg['Server']['controluser'], $cfg['Server']['controlpass'], true, $server_details); } else { $controllink = $GLOBALS['dbi']->connect($cfg['Server']['controluser'], $cfg['Server']['controlpass'], true); } } // Connects to the server (validates user's login) /** @var PMA_DatabaseInterface $userlink */ $userlink = $GLOBALS['dbi']->connect($cfg['Server']['user'], $cfg['Server']['password'], false); // Set timestamp for the session, if required. if ($cfg['Server']['SessionTimeZone'] != '') { $sql_query_tz = 'SET ' . PMA_Util::backquote('time_zone') . ' = ' . '\'' . PMA_Util::sqlAddSlashes($cfg['Server']['SessionTimeZone']) . '\''; if (!$userlink->query($sql_query_tz)) { $error_message_tz = sprintf(__('Unable to use timezone %1$s for server %2$d. ' . 'Please check your configuration setting for ' . '[em]$cfg[\'Servers\'][%3$d][\'SessionTimeZone\'][/em]. ' . 'phpMyAdmin is currently using the default time zone ' . 'of the database server.'), $cfg['Servers'][$GLOBALS['server']]['SessionTimeZone'], $GLOBALS['server'], $GLOBALS['server']); $GLOBALS['error_handler']->addError($error_message_tz, E_USER_WARNING, '', '', false); } } if (!$controllink) { $controllink = $userlink; } $auth_plugin->storeUserCredentials(); /* Log success */ PMA_logUser($cfg['Server']['user']); if (PMA_MYSQL_INT_VERSION < $cfg['MysqlMinVersion']['internal']) { PMA_fatalError(__('You should upgrade to %s %s or later.'), array('MySQL', $cfg['MysqlMinVersion']['human'])); } /**
/** * Returns the names of children of type $type present inside this container * This method is overridden by the Node_Database and Node_Table classes * * @param string $type The type of item we are looking for * ('tables', 'views', etc) * @param int $pos The offset of the list within the results * @param string $searchClause A string used to filter the results of the query * * @return array */ public function getData($type, $pos, $searchClause = '') { $maxItems = $GLOBALS['cfg']['MaxNavigationItems']; $retval = array(); $db = $this->realParent()->real_name; $table = $this->real_name; switch ($type) { case 'columns': if (!$GLOBALS['cfg']['Server']['DisableIS']) { $db = PMA_Util::sqlAddSlashes($db); $table = PMA_Util::sqlAddSlashes($table); $query = "SELECT `COLUMN_NAME` AS `name` "; $query .= "FROM `INFORMATION_SCHEMA`.`COLUMNS` "; $query .= "WHERE `TABLE_NAME`='{$table}' "; $query .= "AND `TABLE_SCHEMA`='{$db}' "; $query .= "ORDER BY `COLUMN_NAME` ASC "; $query .= "LIMIT " . intval($pos) . ", {$maxItems}"; $retval = $GLOBALS['dbi']->fetchResult($query); break; } $db = PMA_Util::backquote($db); $table = PMA_Util::backquote($table); $query = "SHOW COLUMNS FROM {$table} FROM {$db}"; $handle = $GLOBALS['dbi']->tryQuery($query); if ($handle === false) { break; } $count = 0; if ($GLOBALS['dbi']->dataSeek($handle, $pos)) { while ($arr = $GLOBALS['dbi']->fetchArray($handle)) { if ($count < $maxItems) { $retval[] = $arr['Field']; $count++; } else { break; } } } break; case 'indexes': $db = PMA_Util::backquote($db); $table = PMA_Util::backquote($table); $query = "SHOW INDEXES FROM {$table} FROM {$db}"; $handle = $GLOBALS['dbi']->tryQuery($query); if ($handle === false) { break; } $count = 0; while ($arr = $GLOBALS['dbi']->fetchArray($handle)) { if (in_array($arr['Key_name'], $retval)) { continue; } if ($pos <= 0 && $count < $maxItems) { $retval[] = $arr['Key_name']; $count++; } $pos--; } break; case 'triggers': if (!$GLOBALS['cfg']['Server']['DisableIS']) { $db = PMA_Util::sqlAddSlashes($db); $table = PMA_Util::sqlAddSlashes($table); $query = "SELECT `TRIGGER_NAME` AS `name` "; $query .= "FROM `INFORMATION_SCHEMA`.`TRIGGERS` "; $query .= "WHERE `EVENT_OBJECT_SCHEMA` " . PMA_Util::getCollateForIS() . "='{$db}' "; $query .= "AND `EVENT_OBJECT_TABLE` " . PMA_Util::getCollateForIS() . "='{$table}' "; $query .= "ORDER BY `TRIGGER_NAME` ASC "; $query .= "LIMIT " . intval($pos) . ", {$maxItems}"; $retval = $GLOBALS['dbi']->fetchResult($query); break; } $db = PMA_Util::backquote($db); $table = PMA_Util::sqlAddSlashes($table); $query = "SHOW TRIGGERS FROM {$db} WHERE `Table` = '{$table}'"; $handle = $GLOBALS['dbi']->tryQuery($query); if ($handle === false) { break; } $count = 0; if ($GLOBALS['dbi']->dataSeek($handle, $pos)) { while ($arr = $GLOBALS['dbi']->fetchArray($handle)) { if ($count < $maxItems) { $retval[] = $arr['Trigger']; $count++; } else { break; } } } break; default: break; } return $retval; }
/** * return html for tables' detail * * @param array $the_tables tables list * @param string $db database name * @param array $cfg global config * @param array $cfgRelation config from PMA_getRelationsParam * @param int $cell_align_left cell align left * * @return string */ function PMA_getHtmlForTablesDetail($the_tables, $db, $cfg, $cfgRelation, $cell_align_left) { $html = ''; $tables_cnt = count($the_tables); $multi_tables = count($the_tables) > 1; $counter = 0; foreach ($the_tables as $table) { if ($counter + 1 >= $tables_cnt) { $breakstyle = ''; } else { $breakstyle = ' style="page-break-after: always;"'; } $counter++; $html .= '<div' . $breakstyle . '>' . "\n"; $html .= '<h1>' . htmlspecialchars($table) . '</h1>' . "\n"; /** * Gets table informations */ $showtable = PMA_Table::sGetStatusInfo($db, $table); $num_rows = isset($showtable['Rows']) ? $showtable['Rows'] : 0; $show_comment = isset($showtable['Comment']) ? $showtable['Comment'] : ''; $tbl_is_view = PMA_Table::isView($db, $table); /** * Gets fields properties */ $columns = $GLOBALS['dbi']->getColumns($db, $table); // We need this to correctly learn if a TIMESTAMP is NOT NULL, since // SHOW FULL FIELDS or INFORMATION_SCHEMA incorrectly says NULL // and SHOW CREATE TABLE says NOT NULL (tested // in MySQL 4.0.25 and 5.0.21, http://bugs.mysql.com/20910). $show_create_table = $GLOBALS['dbi']->fetchValue('SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table), 0, 1); $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table)); // Check if we can use Relations // Find which tables are related with the current one and write it in // an array $res_rel = PMA_getForeigners($db, $table); $have_rel = (bool) count($res_rel); /** * Displays the comments of the table if MySQL >= 3.23 */ if (!empty($show_comment)) { $html .= __('Table comments:') . ' ' . htmlspecialchars($show_comment) . '<br /><br />'; } $html .= PMA_getHtmlForTableStructure($have_rel, $tbl_is_view, $columns, $analyzed_sql, $res_rel, $db, $table, $cfgRelation, $cfg, $showtable, $cell_align_left); if ($multi_tables) { unset($num_rows, $show_comment); $html .= '<hr />' . "\n"; } // end if $html .= '</div>' . "\n"; } // end while return $html; }
$response->addHTML(PMA_getHtmlForAddPrefixTable($action, $_url_params)); } else { $response->addHTML(PMA_getHtmlForOtherActions($what, $action, $_url_params, $full_query)); } exit; } elseif (!empty($mult_btn) && $mult_btn == __('Yes')) { /** * Executes the query - dropping rows, columns/fields, tables or dbs */ if ($query_type == 'drop_db' || $query_type == 'drop_tbl' || $query_type == 'drop_fld') { include_once './libraries/relation_cleanup.lib.php'; } if ($query_type == 'primary_fld') { // Gets table primary key $GLOBALS['dbi']->selectDb($db); $result = $GLOBALS['dbi']->query('SHOW KEYS FROM ' . PMA_Util::backquote($table) . ';'); $primary = ''; while ($row = $GLOBALS['dbi']->fetchAssoc($result)) { // Backups the list of primary keys if ($row['Key_name'] == 'PRIMARY') { $primary .= $row['Column_name'] . ', '; } } // end while $GLOBALS['dbi']->freeResult($result); } if ($query_type == 'drop_tbl' || $query_type == 'empty_tbl' || $query_type == 'row_delete') { $default_fk_check_value = PMA_Util::handleDisableFKCheckInit(); } list($result, $rebuild_database_list, $reload_ret, $run_parts, $use_sql, $sql_query, $sql_query_views) = PMA_getQueryStrFromSelected($query_type, $selected, $db, $table, $views, isset($primary) ? $primary : null, isset($from_prefix) ? $from_prefix : null, isset($to_prefix) ? $to_prefix : null); //update the existed variable
/** * Provides where clause for building SQL query * * @param string $table The table name * * @return string The generated where clause */ private function _getWhereClause($table) { // Columns to select $allColumns = $GLOBALS['dbi']->getColumns($GLOBALS['db'], $table); $likeClauses = array(); // Based on search type, decide like/regex & '%'/'' $like_or_regex = $this->_criteriaSearchType == 4 ? 'REGEXP' : 'LIKE'; $automatic_wildcard = $this->_criteriaSearchType < 3 ? '%' : ''; // For "as regular expression" (search option 4), LIKE won't be used // Usage example: If user is searching for a literal $ in a regexp search, // he should enter \$ as the value. $this->_criteriaSearchString = PMA_Util::sqlAddSlashes($this->_criteriaSearchString, $this->_criteriaSearchType == 4 ? false : true); // Extract search words or pattern $search_words = $this->_criteriaSearchType > 2 ? array($this->_criteriaSearchString) : explode(' ', $this->_criteriaSearchString); /** @var PMA_String $pmaString */ $pmaString = $GLOBALS['PMA_String']; foreach ($search_words as $search_word) { // Eliminates empty values if ($pmaString->strlen($search_word) === 0) { continue; } $likeClausesPerColumn = array(); // for each column in the table foreach ($allColumns as $column) { if (!isset($this->_criteriaColumnName) || $pmaString->strlen($this->_criteriaColumnName) == 0 || $column['Field'] == $this->_criteriaColumnName) { // Drizzle has no CONVERT and all text columns are UTF-8 $column = PMA_DRIZZLE ? PMA_Util::backquote($column['Field']) : 'CONVERT(' . PMA_Util::backquote($column['Field']) . ' USING utf8)'; $likeClausesPerColumn[] = $column . ' ' . $like_or_regex . ' ' . "'" . $automatic_wildcard . $search_word . $automatic_wildcard . "'"; } } // end for if (count($likeClausesPerColumn) > 0) { $likeClauses[] = implode(' OR ', $likeClausesPerColumn); } } // end for // Use 'OR' if 'at least one word' is to be searched, else use 'AND' $implode_str = $this->_criteriaSearchType == 1 ? ' OR ' : ' AND '; if (empty($likeClauses)) { // this could happen when the "inside column" does not exist // in any selected tables $where_clause = ' WHERE FALSE'; } else { $where_clause = ' WHERE (' . implode(') ' . $implode_str . ' (', $likeClauses) . ')'; } return $where_clause; }
/** * Function to get the default sql query for browsing page * * @param String $db the current database * @param String $table the current table * * @return String $sql_query the default $sql_query for browse page */ function PMA_getDefaultSqlQueryForBrowse($db, $table) { include_once 'libraries/bookmark.lib.php'; $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA_Util::sqlAddSlashes($table) . '\'', 'label', false, true); if (!empty($book_sql_query)) { $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.')); $GLOBALS['using_bookmark_message']->addParam($table); $GLOBALS['using_bookmark_message']->addMessage(PMA_Util::showDocu('faq', 'faq6-22')); $sql_query = $book_sql_query; } else { $defaultOrderByClause = ''; if (isset($GLOBALS['cfg']['TablePrimaryKeyOrder']) && $GLOBALS['cfg']['TablePrimaryKeyOrder'] !== 'NONE') { $primaryKey = null; $primary = PMA_Index::getPrimary($table, $db); if ($primary !== false) { $primarycols = $primary->getColumns(); foreach ($primarycols as $col) { $primaryKey = $col->getName(); break; } if ($primaryKey != null) { $defaultOrderByClause = ' ORDER BY ' . PMA_Util::backquote($table) . '.' . PMA_Util::backquote($primaryKey) . ' ' . $GLOBALS['cfg']['TablePrimaryKeyOrder']; } } } $sql_query = 'SELECT * FROM ' . PMA_Util::backquote($table) . $defaultOrderByClause; } unset($book_sql_query); return $sql_query; }
/** * returns count of tables in given db * * @param string $db database to count tables for * * @return integer count of tables in $db */ function PMA_getTableCount($db) { $tables = $GLOBALS['dbi']->tryQuery('SHOW TABLES FROM ' . PMA_Util::backquote($db) . ';', null, PMA_DatabaseInterface::QUERY_STORE); if ($tables) { $num_tables = $GLOBALS['dbi']->numRows($tables); $GLOBALS['dbi']->freeResult($tables); } else { $num_tables = 0; } return $num_tables; }
* * @package PhpMyAdmin */ /** * Common functions. */ // we don't want the usual PMA_Response-generated HTML above the column's data define('PMA_BYPASS_GET_INSTANCE', 1); require_once 'libraries/common.inc.php'; require_once 'libraries/mime.lib.php'; /* Check parameters */ PMA_Util::checkParameters(array('db', 'table')); /* Select database */ if (!$GLOBALS['dbi']->selectDb($db)) { PMA_Util::mysqlDie(sprintf(__('\'%s\' database does not exist.'), htmlspecialchars($db)), '', ''); } /* Check if table exists */ if (!$GLOBALS['dbi']->getColumns($db, $table)) { PMA_Util::mysqlDie(__('Invalid table name')); } /* Grab data */ $sql = 'SELECT ' . PMA_Util::backquote($_GET['transform_key']) . ' FROM ' . PMA_Util::backquote($table) . ' WHERE ' . $_GET['where_clause'] . ';'; $result = $GLOBALS['dbi']->fetchValue($sql); /* Check return code */ if ($result === false) { PMA_Util::mysqlDie(__('MySQL returned an empty result set (i.e. zero rows).'), $sql); } /* Avoid corrupting data */ @ini_set('url_rewriter.tags', ''); PMA_downloadHeader($table . '-' . $_GET['transform_key'] . '.bin', PMA_detectMIME($result), strlen($result)); echo $result;