/** * Gets all the fields of a table along with their types, collations * and whether null or not. * * @param string $db Selected database * @param string $table Selected table * * @return array Array containing the field list, field types, collations * and null constraint */ function PMA_tbl_getFields($db, $table) { // Gets the list and number of fields $fields = PMA_DBI_get_columns($db, $table, null, true); $fields_list = $fields_null = $fields_type = $fields_collation = array(); $geom_column_present = false; $geom_types = PMA_getGISDatatypes(); foreach ($fields as $key => $row) { $fields_list[] = $row['Field']; $type = $row['Type']; // check whether table contains geometric columns if (in_array($type, $geom_types)) { $geom_column_present = true; } // reformat mysql query output if (strncasecmp($type, 'set', 3) == 0 || strncasecmp($type, 'enum', 4) == 0) { $type = str_replace(',', ', ', $type); } else { // strip the "BINARY" attribute, except if we find "BINARY(" because // this would be a BINARY or VARBINARY field type if (!preg_match('@BINARY[\\(]@i', $type)) { $type = preg_replace('@BINARY@i', '', $type); } $type = preg_replace('@ZEROFILL@i', '', $type); $type = preg_replace('@UNSIGNED@i', '', $type); $type = strtolower($type); } if (empty($type)) { $type = ' '; } $fields_null[] = $row['Null']; $fields_type[] = $type; $fields_collation[] = !empty($row['Collation']) && $row['Collation'] != 'NULL' ? $row['Collation'] : ''; } // end while return array($fields_list, $fields_type, $fields_collation, $fields_null, $geom_column_present); }
require_once 'libraries/Index.class.php'; // 2. Gets table keys and retains them // @todo should be: $server->db($db)->table($table)->primary() $primary = PMA_Index::getPrimary($table, $db); $columns_with_unique_index = array(); foreach (PMA_Index::getFromTable($table, $db) as $index) { if ($index->isUnique() && $index->getChoice() == 'UNIQUE') { $columns = $index->getColumns(); foreach ($columns as $column_name => $dummy) { $columns_with_unique_index[$column_name] = 1; } } } unset($index, $columns, $column_name, $dummy); // 3. Get fields $fields = (array) PMA_DBI_get_columns($db, $table, null, true); // Get more complete field information // For now, this is done just for MySQL 4.1.2+ new TIMESTAMP options // but later, if the analyser returns more information, it // could be executed for any MySQL version and replace // the info given by SHOW FULL COLUMNS FROM. // // We also need this to correctly learn if a TIMESTAMP is NOT NULL, since // SHOW FULL COLUMNS 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 = PMA_DBI_fetch_value('SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table), 0, 1); $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table)); /** * prepare table infos */
/** * Builds the SQL search query * * @param string $table the table name * @param string $field restrict the search to this field * @param string $search_str the string to search * @param integer $search_option type of search * (1 -> 1 word at least, 2 -> all words, * 3 -> exact string, 4 -> regexp) * * @return array 3 SQL querys (for count, display and delete results) * * @todo can we make use of fulltextsearch IN BOOLEAN MODE for this? * PMA_backquote * PMA_DBI_free_result * PMA_DBI_fetch_assoc * $GLOBALS['db'] * explode * count * strlen */ function PMA_getSearchSqls($table, $field, $search_str, $search_option) { // Statement types $sqlstr_select = 'SELECT'; $sqlstr_delete = 'DELETE'; // Fields to select $tblfields = PMA_DBI_get_columns($GLOBALS['db'], $table); // Table to use $sqlstr_from = ' FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($table); $search_words = $search_option > 2 ? array($search_str) : explode(' ', $search_str); $like_or_regex = $search_option == 4 ? 'REGEXP' : 'LIKE'; $automatic_wildcard = $search_option < 3 ? '%' : ''; $fieldslikevalues = array(); foreach ($search_words as $search_word) { // Eliminates empty values if (strlen($search_word) === 0) { continue; } $thefieldlikevalue = array(); foreach ($tblfields as $tblfield) { if (!isset($field) || strlen($field) == 0 || $tblfield['Field'] == $field) { // Drizzle has no CONVERT and all text columns are UTF-8 if (PMA_DRIZZLE) { $thefieldlikevalue[] = PMA_backquote($tblfield['Field']) . ' ' . $like_or_regex . ' ' . "'" . $automatic_wildcard . $search_word . $automatic_wildcard . "'"; } else { $thefieldlikevalue[] = 'CONVERT(' . PMA_backquote($tblfield['Field']) . ' USING utf8)' . ' ' . $like_or_regex . ' ' . "'" . $automatic_wildcard . $search_word . $automatic_wildcard . "'"; } } } // end for if (count($thefieldlikevalue) > 0) { $fieldslikevalues[] = implode(' OR ', $thefieldlikevalue); } } // end for $implode_str = $search_option == 1 ? ' OR ' : ' AND '; if (empty($fieldslikevalues)) { // this could happen when the "inside field" does not exist // in any selected tables $sqlstr_where = ' WHERE FALSE'; } else { $sqlstr_where = ' WHERE (' . implode(') ' . $implode_str . ' (', $fieldslikevalues) . ')'; } unset($fieldslikevalues); // Builds complete queries $sql['select_fields'] = $sqlstr_select . ' * ' . $sqlstr_from . $sqlstr_where; // here, I think we need to still use the COUNT clause, even for // VIEWs, anyway we have a WHERE clause that should limit results $sql['select_count'] = $sqlstr_select . ' COUNT(*) AS `count`' . $sqlstr_from . $sqlstr_where; $sql['delete'] = $sqlstr_delete . $sqlstr_from . $sqlstr_where; return $sql; }
/** * Get username and hostname length * * @return array username length and hostname length */ function PMA_getUsernameAndHostnameLength() { $fields_info = PMA_DBI_get_columns('mysql', 'user', null, true); $username_length = 16; $hostname_length = 41; foreach ($fields_info as $val) { if ($val['Field'] == 'User') { strtok($val['Type'], '()'); $value = strtok('()'); if (is_int($value)) { $username_length = $value; } } elseif ($val['Field'] == 'Host') { strtok($val['Type'], '()'); $value = strtok('()'); if (is_int($value)) { $hostname_length = $value; } } } return array($username_length, $hostname_length); }
/** * PMA_createTargetTables() Create the missing table $uncommon_table in target database * * @param string $src_db name of source database * @param string $trg_db name of target database * @param mixed $src_link connection established with source server * @param mixed $trg_link connection established with target server * @param array &$uncommon_tables names of tables present in source but not in target * @param int $table_index index of table in $uncommon_tables array * @param array &$uncommon_tables_fields field names of the uncommon table * @param bool $display */ function PMA_createTargetTables($src_db, $trg_db, $src_link, $trg_link, &$uncommon_tables, $table_index, &$uncommon_tables_fields, $display) { if (isset($uncommon_tables[$table_index])) { $fields_result = PMA_DBI_get_columns($src_db, $uncommon_tables[$table_index], null, true, $src_link); $fields = array(); foreach ($fields_result as $each_field) { $field_name = $each_field['Field']; $fields[] = $field_name; } $uncommon_tables_fields[$table_index] = $fields; $Create_Query = PMA_DBI_fetch_value("SHOW CREATE TABLE " . PMA_backquote($src_db) . '.' . PMA_backquote($uncommon_tables[$table_index]), 0, 1, $src_link); // Replace the src table name with a `dbname`.`tablename` $Create_Table_Query = preg_replace('/' . preg_quote(PMA_backquote($uncommon_tables[$table_index]), '/') . '/', PMA_backquote($trg_db) . '.' . PMA_backquote($uncommon_tables[$table_index]), $Create_Query, $limit = 1); $is_fk_query = "SELECT * FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '" . $src_db . "'\n AND TABLE_NAME = '" . $uncommon_tables[$table_index] . "' AND TABLE_NAME <> REFERENCED_TABLE_NAME;"; $is_fk_result = PMA_DBI_fetch_result($is_fk_query, null, null, $src_link); if (sizeof($is_fk_result) > 0) { for ($j = 0; $j < sizeof($is_fk_result); $j++) { if (in_array($is_fk_result[$j]['REFERENCED_TABLE_NAME'], $uncommon_tables)) { $table_index = array_keys($uncommon_tables, $is_fk_result[$j]['REFERENCED_TABLE_NAME']); PMA_createTargetTables($src_db, $trg_db, $trg_link, $src_link, $uncommon_tables, $table_index[0], $uncommon_tables_fields, $display); unset($uncommon_tables[$table_index[0]]); } } } $Create_Table_Query .= ';'; if ($display == true) { echo '<p>' . $Create_Table_Query . '</p>'; } PMA_DBI_try_query($Create_Table_Query, $trg_link, 0); } }
/** * Gets the comments for all rows of a table or the db itself * * @param string $db the name of the db to check for * @param string $table the name of the table to check for * * @return array [field_name] = comment * * @access public */ function PMA_getComments($db, $table = '') { $comments = array(); if ($table != '') { // MySQL native column comments $fields = PMA_DBI_get_columns($db, $table, null, true); if ($fields) { foreach ($fields as $field) { if (!empty($field['Comment'])) { $comments[$field['Field']] = $field['Comment']; } } } } else { $comments[] = PMA_getDbComment($db); } return $comments; }
/** * Returns $table's CREATE definition * * @param string $db the database name * @param string $table the table name * @param string $crlf the end of line sequence * @param string $error_url the url to go back in case of error * @param bool $do_relation whether to include relation comments * @param bool $do_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 * PMA_exportStructure() also for other * export types which use this parameter * @param bool $do_mime whether to include mime comments * @param bool $show_dates whether to include creation/update/check dates * @param bool $add_semicolon whether to add semicolon and end-of-line * at the end * @param bool $view whether we're handling a view * * @return string resulting schema */ public function getTableDef($db, $table, $crlf, $error_url, $do_relation, $do_comments, $do_mime, $show_dates = false, $add_semicolon = true, $view = false) { // set $cfgRelation here, because there is a chance that it's modified // since the class initialization global $cfgRelation; $schema_insert = ''; /** * Gets fields properties */ PMA_DBI_select_db($db); // Check if we can use Relations if ($do_relation && !empty($cfgRelation['relation'])) { // Find which tables are related with the current one and write it in // an array $res_rel = PMA_getForeigners($db, $table); if ($res_rel && count($res_rel) > 0) { $have_rel = true; } else { $have_rel = false; } } else { $have_rel = false; } // end if /** * Displays the table structure */ $schema_insert .= '<table class="width100" cellspacing="1">'; $columns_cnt = 4; if ($do_relation && $have_rel) { $columns_cnt++; } if ($do_comments && $cfgRelation['commwork']) { $columns_cnt++; } if ($do_mime && $cfgRelation['mimework']) { $columns_cnt++; } $schema_insert .= '<tr class="print-category">'; $schema_insert .= '<th class="print">' . __('Column') . '</th>'; $schema_insert .= '<td class="print"><strong>' . __('Type') . '</strong></td>'; $schema_insert .= '<td class="print"><strong>' . __('Null') . '</strong></td>'; $schema_insert .= '<td class="print"><strong>' . __('Default') . '</strong></td>'; if ($do_relation && $have_rel) { $schema_insert .= '<td class="print"><strong>' . __('Links to') . '</strong></td>'; } if ($do_comments) { $schema_insert .= '<td class="print"><strong>' . __('Comments') . '</strong></td>'; $comments = PMA_getComments($db, $table); } if ($do_mime && $cfgRelation['mimework']) { $schema_insert .= '<td class="print"><strong>' . htmlspecialchars('MIME') . '</strong></td>'; $mime_map = PMA_getMIME($db, $table, true); } $schema_insert .= '</tr>'; $columns = PMA_DBI_get_columns($db, $table); /** * Get the unique keys in the table */ $unique_keys = array(); $keys = PMA_DBI_get_table_indexes($db, $table); foreach ($keys as $key) { if ($key['Non_unique'] == 0) { $unique_keys[] = $key['Column_name']; } } foreach ($columns as $column) { $schema_insert .= $this->formatOneColumnDefinition($column, $unique_keys); $field_name = $column['Field']; if ($do_relation && $have_rel) { $schema_insert .= '<td class="print">' . (isset($res_rel[$field_name]) ? htmlspecialchars($res_rel[$field_name]['foreign_table'] . ' (' . $res_rel[$field_name]['foreign_field'] . ')') : '') . '</td>'; } if ($do_comments && $cfgRelation['commwork']) { $schema_insert .= '<td class="print">' . (isset($comments[$field_name]) ? htmlspecialchars($comments[$field_name]) : '') . '</td>'; } if ($do_mime && $cfgRelation['mimework']) { $schema_insert .= '<td class="print">' . (isset($mime_map[$field_name]) ? htmlspecialchars(str_replace('_', '/', $mime_map[$field_name]['mimetype'])) : '') . '</td>'; } $schema_insert .= '</tr>'; } // end foreach $schema_insert .= '</table>'; return $schema_insert; }
/** * 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 bool $do_relation whether to include relation comments * @param bool $do_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 PMA_exportStructure() also for other export * types which use this parameter * @param bool $do_mime whether to include mime comments * @param bool $dates whether to include creation/update/check dates * @param string $export_mode 'create_table', 'triggers', 'create_view', 'stand_in' * @param string $export_type 'server', 'database', 'table' * * @return bool Whether it succeeded * * @access public */ function PMA_exportStructure($db, $table, $crlf, $error_url, $do_relation = false, $do_comments = false, $do_mime = false, $dates = false, $export_mode, $export_type) { global $cfgRelation; /* We do not export triggers */ if ($export_mode == 'triggers') { return true; } /** * Get the unique keys in the table */ $unique_keys = array(); $keys = PMA_DBI_get_table_indexes($db, $table); foreach ($keys as $key) { if ($key['Non_unique'] == 0) { $unique_keys[] = $key['Column_name']; } } /** * Gets fields properties */ PMA_DBI_select_db($db); // Check if we can use Relations if ($do_relation && !empty($cfgRelation['relation'])) { // Find which tables are related with the current one and write it in // an array $res_rel = PMA_getForeigners($db, $table); if ($res_rel && count($res_rel) > 0) { $have_rel = true; } else { $have_rel = false; } } else { $have_rel = false; } // end if /** * Displays the table structure */ $buffer = $crlf . '%' . $crlf . '% ' . __('Structure') . ': ' . $table . $crlf . '%' . $crlf . ' \\begin{longtable}{'; if (!PMA_exportOutputHandler($buffer)) { return false; } $columns_cnt = 4; $alignment = '|l|c|c|c|'; if ($do_relation && $have_rel) { $columns_cnt++; $alignment .= 'l|'; } if ($do_comments) { $columns_cnt++; $alignment .= 'l|'; } if ($do_mime && $cfgRelation['mimework']) { $columns_cnt++; $alignment .= 'l|'; } $buffer = $alignment . '} ' . $crlf; $header = ' \\hline '; $header .= '\\multicolumn{1}{|c|}{\\textbf{' . __('Column') . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Type') . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Null') . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Default') . '}}'; if ($do_relation && $have_rel) { $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Links to') . '}}'; } if ($do_comments) { $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Comments') . '}}'; $comments = PMA_getComments($db, $table); } if ($do_mime && $cfgRelation['mimework']) { $header .= ' & \\multicolumn{1}{|c|}{\\textbf{MIME}}'; $mime_map = PMA_getMIME($db, $table, true); } // Table caption for first page and label if (isset($GLOBALS['latex_caption'])) { $buffer .= ' \\caption{' . PMA_expandUserString($GLOBALS['latex_structure_caption'], 'PMA_texEscape', array('table' => $table, 'database' => $db)) . '} \\label{' . PMA_expandUserString($GLOBALS['latex_structure_label'], null, array('table' => $table, 'database' => $db)) . '} \\\\' . $crlf; } $buffer .= $header . ' \\\\ \\hline \\hline' . $crlf . '\\endfirsthead' . $crlf; // Table caption on next pages if (isset($GLOBALS['latex_caption'])) { $buffer .= ' \\caption{' . PMA_expandUserString($GLOBALS['latex_structure_continued_caption'], 'PMA_texEscape', array('table' => $table, 'database' => $db)) . '} \\\\ ' . $crlf; } $buffer .= $header . ' \\\\ \\hline \\hline \\endhead \\endfoot ' . $crlf; if (!PMA_exportOutputHandler($buffer)) { return false; } $fields = PMA_DBI_get_columns($db, $table); foreach ($fields as $row) { $extracted_fieldspec = PMA_extractFieldSpec($row['Type']); $type = $extracted_fieldspec['print_type']; if (empty($type)) { $type = ' '; } if (!isset($row['Default'])) { if ($row['Null'] != 'NO') { $row['Default'] = 'NULL'; } } $field_name = $row['Field']; $local_buffer = $field_name . "" . $type . "" . ($row['Null'] == '' || $row['Null'] == 'NO' ? __('No') : __('Yes')) . "" . (isset($row['Default']) ? $row['Default'] : ''); if ($do_relation && $have_rel) { $local_buffer .= ""; if (isset($res_rel[$field_name])) { $local_buffer .= $res_rel[$field_name]['foreign_table'] . ' (' . $res_rel[$field_name]['foreign_field'] . ')'; } } if ($do_comments && $cfgRelation['commwork']) { $local_buffer .= ""; if (isset($comments[$field_name])) { $local_buffer .= $comments[$field_name]; } } if ($do_mime && $cfgRelation['mimework']) { $local_buffer .= ""; if (isset($mime_map[$field_name])) { $local_buffer .= str_replace('_', '/', $mime_map[$field_name]['mimetype']); } } $local_buffer = PMA_texEscape($local_buffer); if ($row['Key'] == 'PRI') { $pos = strpos($local_buffer, ""); $local_buffer = '\\textit{' . substr($local_buffer, 0, $pos) . '}' . substr($local_buffer, $pos); } if (in_array($field_name, $unique_keys)) { $pos = strpos($local_buffer, ""); $local_buffer = '\\textbf{' . substr($local_buffer, 0, $pos) . '}' . substr($local_buffer, $pos); } $buffer = str_replace("", ' & ', $local_buffer); $buffer .= ' \\\\ \\hline ' . $crlf; if (!PMA_exportOutputHandler($buffer)) { return false; } } // end while $buffer = ' \\end{longtable}' . $crlf; return PMA_exportOutputHandler($buffer); }
/** * 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 bool $do_relation whether to include relation comments * @param bool $do_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 PMA_exportStructure() also for other export * types which use this parameter * @param bool $do_mime whether to include mime comments * @param bool $dates whether to include creation/update/check dates * @param string $export_mode 'create_table', 'triggers', 'create_view', 'stand_in' * @param string $export_type 'server', 'database', 'table' * @return bool Whether it succeeded * * @access public */ function PMA_exportStructure($db, $table, $crlf, $error_url, $do_relation = false, $do_comments = false, $do_mime = false, $dates = false, $export_mode, $export_type) { global $cfgRelation; if (!PMA_exportOutputHandler('<h2>' . __('Table structure for table') . ' ' . htmlspecialchars($table) . '</h2>')) { return false; } /** * Get the unique keys in the table */ $unique_keys = array(); $keys = PMA_DBI_get_table_indexes($db, $table); foreach ($keys as $key) { if ($key['Non_unique'] == 0) { $unique_keys[] = $key['Column_name']; } } /** * Gets fields properties */ PMA_DBI_select_db($db); // Check if we can use Relations if ($do_relation && !empty($cfgRelation['relation'])) { // Find which tables are related with the current one and write it in // an array $res_rel = PMA_getForeigners($db, $table); if ($res_rel && count($res_rel) > 0) { $have_rel = true; } else { $have_rel = false; } } else { $have_rel = false; } // end if /** * Displays the table structure */ if (!PMA_exportOutputHandler('<table class="width100" cellspacing="1">')) { return false; } $columns_cnt = 4; if ($do_relation && $have_rel) { $columns_cnt++; } if ($do_comments && $cfgRelation['commwork']) { $columns_cnt++; } if ($do_mime && $cfgRelation['mimework']) { $columns_cnt++; } $schema_insert = '<tr class="print-category">'; $schema_insert .= '<th class="print">' . __('Column') . '</th>'; $schema_insert .= '<td class="print"><b>' . __('Type') . '</b></td>'; $schema_insert .= '<td class="print"><b>' . __('Null') . '</b></td>'; $schema_insert .= '<td class="print"><b>' . __('Default') . '</b></td>'; if ($do_relation && $have_rel) { $schema_insert .= '<td class="print"><b>' . __('Links to') . '</b></td>'; } if ($do_comments) { $schema_insert .= '<td class="print"><b>' . __('Comments') . '</b></td>'; $comments = PMA_getComments($db, $table); } if ($do_mime && $cfgRelation['mimework']) { $schema_insert .= '<td class="print"><b>' . htmlspecialchars('MIME') . '</b></td>'; $mime_map = PMA_getMIME($db, $table, true); } $schema_insert .= '</tr>'; if (!PMA_exportOutputHandler($schema_insert)) { return false; } $columns = PMA_DBI_get_columns($db, $table); foreach ($columns as $column) { $schema_insert = '<tr class="print-category">'; $extracted_fieldspec = PMA_extractFieldSpec($column['Type']); $type = htmlspecialchars($extracted_fieldspec['print_type']); if (empty($type)) { $type = ' '; } if (!isset($column['Default'])) { if ($column['Null'] != 'NO') { $column['Default'] = 'NULL'; } } $fmt_pre = ''; $fmt_post = ''; if (in_array($column['Field'], $unique_keys)) { $fmt_pre = '<b>' . $fmt_pre; $fmt_post = $fmt_post . '</b>'; } if ($column['Key'] == 'PRI') { $fmt_pre = '<i>' . $fmt_pre; $fmt_post = $fmt_post . '</i>'; } $schema_insert .= '<td class="print">' . $fmt_pre . htmlspecialchars($column['Field']) . $fmt_post . '</td>'; $schema_insert .= '<td class="print">' . htmlspecialchars($type) . '</td>'; $schema_insert .= '<td class="print">' . ($column['Null'] == '' || $column['Null'] == 'NO' ? __('No') : __('Yes')) . '</td>'; $schema_insert .= '<td class="print">' . htmlspecialchars(isset($column['Default']) ? $column['Default'] : '') . '</td>'; $field_name = $column['Field']; if ($do_relation && $have_rel) { $schema_insert .= '<td class="print">' . (isset($res_rel[$field_name]) ? htmlspecialchars($res_rel[$field_name]['foreign_table'] . ' (' . $res_rel[$field_name]['foreign_field'] . ')') : '') . '</td>'; } if ($do_comments && $cfgRelation['commwork']) { $schema_insert .= '<td class="print">' . (isset($comments[$field_name]) ? htmlspecialchars($comments[$field_name]) : '') . '</td>'; } if ($do_mime && $cfgRelation['mimework']) { $schema_insert .= '<td class="print">' . (isset($mime_map[$field_name]) ? htmlspecialchars(str_replace('_', '/', $mime_map[$field_name]['mimetype'])) : '') . '</td>'; } $schema_insert .= '</tr>'; if (!PMA_exportOutputHandler($schema_insert)) { return false; } } // end while return PMA_exportOutputHandler('</table>'); }
/** * Check if there are tables that need to be deleted in dashboard, * if there are, ask the user for allowance * * @param array $array_sh_page array of tables on page * * @return void * @access private */ private function _displayScratchboardTables($array_sh_page) { global $with_field_names, $db; echo '<form method="post" action="schema_edit.php" name="dragdrop">'; echo '<input type="button" name="dragdrop" id="toggle-dragdrop" ' . 'value="' . __('Toggle scratchboard') . '" />'; echo '<input type="button" name="dragdropreset" id="reset-dragdrop" ' . 'value="' . __('Reset') . '" />'; echo '</form>'; echo '<div id="pdflayout" class="pdflayout" style="visibility: hidden;">'; $i = 0; foreach ($array_sh_page as $temp_sh_page) { $drag_x = $temp_sh_page['x']; $drag_y = $temp_sh_page['y']; echo '<div id="table_' . $i . '" ' . 'data-number="' . $i . '" ' . 'data-x="' . $drag_x . '" ' . 'data-y="' . $drag_y . '" ' . 'class="pdflayout_table"' . '>' . '<u>' . htmlspecialchars($temp_sh_page['table_name']) . '</u>'; if (isset($with_field_names)) { $fields = PMA_DBI_get_columns($db, $temp_sh_page['table_name']); // if the table has been dropped from outside phpMyAdmin, // we can no longer obtain its columns list if ($fields) { foreach ($fields as $row) { echo '<br />' . htmlspecialchars($row['Field']) . "\n"; } } } echo '</div>' . "\n"; $i++; } echo '</div>'; }
/** * Gets all the columns of a table along with their types, collations * and whether null or not. * * @return void */ private function _loadTableInfo() { // Gets the list and number of columns $columns = PMA_DBI_get_columns($this->_db, $this->_table, null, true); // Get details about the geometry fucntions $geom_types = PMA_Util::getGISDatatypes(); foreach ($columns as $row) { // set column name $this->_columnNames[] = $row['Field']; $type = $row['Type']; // check whether table contains geometric columns if (in_array($type, $geom_types)) { $this->_geomColumnFlag = true; } // reformat mysql query output if (strncasecmp($type, 'set', 3) == 0 || strncasecmp($type, 'enum', 4) == 0) { $type = str_replace(',', ', ', $type); } else { // strip the "BINARY" attribute, except if we find "BINARY(" because // this would be a BINARY or VARBINARY column type if (!preg_match('@BINARY[\\(]@i', $type)) { $type = preg_replace('@BINARY@i', '', $type); } $type = preg_replace('@ZEROFILL@i', '', $type); $type = preg_replace('@UNSIGNED@i', '', $type); $type = strtolower($type); } if (empty($type)) { $type = ' '; } $this->_columnTypes[] = $type; $this->_columnNullFlags[] = $row['Null']; $this->_columnCollations[] = !empty($row['Collation']) && $row['Collation'] != 'NULL' ? $row['Collation'] : ''; } // end for // Retrieve foreign keys $this->_foreigners = PMA_getForeigners($this->_db, $this->_table); }
/** * Formats user string, expanding @VARIABLES@, accepting strftime format * string. * * @param string $string Text where to do expansion. * @param function $escape Function to call for escaping variable values. * Can also be an array of: * - the escape method name * - the class that contains the method * - location of the class (for inclusion) * @param array $updates Array with overrides for default parameters * (obtained from GLOBALS). * * @return string */ public static function expandUserString($string, $escape = null, $updates = array()) { /* Content */ $vars['http_host'] = PMA_getenv('HTTP_HOST'); $vars['server_name'] = $GLOBALS['cfg']['Server']['host']; $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose']; if (empty($GLOBALS['cfg']['Server']['verbose'])) { $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['host']; } else { $vars['server_verbose_or_name'] = $GLOBALS['cfg']['Server']['verbose']; } $vars['database'] = $GLOBALS['db']; $vars['table'] = $GLOBALS['table']; $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION; /* Update forced variables */ foreach ($updates as $key => $val) { $vars[$key] = $val; } /* Replacement mapping */ /* * The __VAR__ ones are for backward compatibility, because user * might still have it in cookies. */ $replace = array('@HTTP_HOST@' => $vars['http_host'], '@SERVER@' => $vars['server_name'], '__SERVER__' => $vars['server_name'], '@VERBOSE@' => $vars['server_verbose'], '@VSERVER@' => $vars['server_verbose_or_name'], '@DATABASE@' => $vars['database'], '__DB__' => $vars['database'], '@TABLE@' => $vars['table'], '__TABLE__' => $vars['table'], '@PHPMYADMIN@' => $vars['phpmyadmin_version']); /* Optional escaping */ if (!is_null($escape)) { if (is_array($escape)) { include_once $escape[2]; $escape_class = new $escape[1](); $escape_method = $escape[0]; } foreach ($replace as $key => $val) { if (is_array($escape)) { $replace[$key] = $escape_class->{$escape_method}($val); } else { $replace[$key] = $escape == 'backquote' ? self::$escape($val) : $escape($val); } } } /* Backward compatibility in 3.5.x */ if (strpos($string, '@FIELDS@') !== false) { $string = strtr($string, array('@FIELDS@' => '@COLUMNS@')); } /* Fetch columns list if required */ if (strpos($string, '@COLUMNS@') !== false) { $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']); // sometimes the table no longer exists at this point if (!is_null($columns_list)) { $column_names = array(); foreach ($columns_list as $column) { if (!is_null($escape)) { $column_names[] = self::$escape($column['Field']); } else { $column_names[] = $column['Field']; } } $replace['@COLUMNS@'] = implode(',', $column_names); } else { $replace['@COLUMNS@'] = '*'; } } /* Do the replacement */ return strtr(strftime($string), $replace); }
/** * Provides where clause for bulding SQL query * * @param string $table The table name * * @return string The generated where clause */ private function _getWhereClause($table) { $where_clause = ''; // Columns to select $allColumns = PMA_DBI_get_columns($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 seaching 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); foreach ($search_words as $search_word) { // Eliminates empty values if (strlen($search_word) === 0) { continue; } $likeClausesPerColumn = array(); // for each column in the table foreach ($allColumns as $column) { if (!isset($this->_criteriaColumnName) || 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; }
/** * Displays HTML for changing one or more columns * * @param string $db database name * @param string $table table name * @param array $selected the selected columns * @param string $action target script to call * * @return boolean $regenerate true if error occurred * */ function PMA_displayHtmlForColumnChange($db, $table, $selected, $action) { // $selected comes from multi_submits.inc.php if (empty($selected)) { $selected[] = $_REQUEST['field']; $selected_cnt = 1; } else { // from a multiple submit $selected_cnt = count($selected); } /** * @todo optimize in case of multiple fields to modify */ for ($i = 0; $i < $selected_cnt; $i++) { $fields_meta[] = PMA_DBI_get_columns($db, $table, $selected[$i], true); } $num_fields = count($fields_meta); // set these globals because tbl_columns_definition_form.inc.php // verifies them // @todo: refactor tbl_columns_definition_form.inc.php so that it uses // function params $GLOBALS['action'] = 'tbl_structure.php'; $GLOBALS['num_fields'] = $num_fields; // Get more complete field information. // For now, this is done to obtain MySQL 4.1.2+ new TIMESTAMP options // and to know when there is an empty DEFAULT value. // Later, if the analyser returns more information, it // could be executed to replace the info given by SHOW FULL COLUMNS FROM. /** * @todo put this code into a require() * or maybe make it part of PMA_DBI_get_columns(); */ // We also need this to correctly learn if a TIMESTAMP is NOT NULL, since // SHOW FULL COLUMNS says NULL and SHOW CREATE TABLE says NOT NULL (tested // in MySQL 4.0.25). $show_create_table = PMA_DBI_fetch_value('SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table), 0, 1); $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table)); unset($show_create_table); /** * Form for changing properties. */ include 'libraries/tbl_columns_definition_form.inc.php'; }
$disp_query = null; } PMA_showMessage($disp_message, $disp_query); } /** * Get the analysis of SHOW CREATE TABLE for this table * @todo should be handled by class Table */ $show_create_table = PMA_DBI_fetch_value('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), 0, 1); $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table)); unset($show_create_table); /** * Get the list of the fields of the current table */ PMA_DBI_select_db($db); $table_fields = array_values(PMA_DBI_get_columns($db, $table)); $rows = array(); if (isset($where_clause)) { // when in edit mode load all selected rows from table $insert_mode = false; if (is_array($where_clause)) { $where_clause_array = $where_clause; } else { $where_clause_array = array(0 => $where_clause); } $result = array(); $found_unique_key = false; $where_clauses = array(); foreach ($where_clause_array as $key_id => $where_clause) { $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' WHERE ' . $where_clause . ';'; $result[$key_id] = PMA_DBI_query($local_query, null, PMA_DBI_QUERY_STORE);
* Get some core libraries */ require_once './libraries/common.inc.php'; $action = 'tbl_create.php'; require_once './libraries/header.inc.php'; $titles = PMA_buildActionTitles(); // Check parameters PMA_checkParameters(array('db')); /* Check if database name is empty */ if (strlen($db) == 0) { PMA_mysqlDie(__('The database name is empty!'), '', '', 'main.php'); } /** * Defines the url to return to in case of error in a sql statement */ if (PMA_DBI_get_columns($db, $table)) { // table exists already PMA_mysqlDie(sprintf(__('Table %s already exists!'), htmlspecialchars($table)), '', '', 'db_structure.php?' . PMA_generate_common_url($db)); } $err_url = 'tbl_create.php?' . PMA_generate_common_url($db, $table); // check number of fields to be created if (isset($_REQUEST['submit_num_fields'])) { $regenerate = true; // for libraries/tbl_properties.inc.php $num_fields = $_REQUEST['orig_num_fields'] + $_REQUEST['added_fields']; } elseif (isset($_REQUEST['num_fields']) && intval($_REQUEST['num_fields']) > 0) { $num_fields = (int) $_REQUEST['num_fields']; } else { $num_fields = 2; } /**
/** * prints querybox fieldset * * @param string $query query to display in the textarea * @param boolean $is_querywindow if inside querywindow or not * @param string $delimiter default delimiter to use * * @usedby PMA_sqlQueryForm() */ function PMA_sqlQueryFormInsert($query = '', $is_querywindow = false, $delimiter = ';') { // enable auto select text in textarea if ($GLOBALS['cfg']['TextareaAutoSelect']) { $auto_sel = ' onclick="selectContent(this, sql_box_locked, true)"'; } else { $auto_sel = ''; } // enable locking if inside query window if ($is_querywindow) { $locking = ' onkeypress="document.sqlform.elements[\'LockFromUpdate\'].' . 'checked = true;"'; $height = $GLOBALS['cfg']['TextareaRows'] * 1.25; } else { $locking = ''; $height = $GLOBALS['cfg']['TextareaRows'] * 2; } $table = ''; $db = ''; $fields_list = array(); if (!strlen($GLOBALS['db'])) { // prepare for server related $legend = sprintf(__('Run SQL query/queries on server %s'), '"' . htmlspecialchars(!empty($GLOBALS['cfg']['Servers'][$GLOBALS['server']]['verbose']) ? $GLOBALS['cfg']['Servers'][$GLOBALS['server']]['verbose'] : $GLOBALS['cfg']['Servers'][$GLOBALS['server']]['host']) . '"'); } elseif (!strlen($GLOBALS['table'])) { // prepare for db related $db = $GLOBALS['db']; // if you want navigation: $tmp_db_link = '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($db) . '"'; if ($is_querywindow) { $tmp_db_link .= ' target="_self"' . ' onclick="this.target=window.opener.frame_content.name"'; } $tmp_db_link .= '>' . htmlspecialchars($db) . '</a>'; // else use // $tmp_db_link = htmlspecialchars($db); $legend = sprintf(__('Run SQL query/queries on database %s'), $tmp_db_link); if (empty($query)) { $query = PMA_expandUserString($GLOBALS['cfg']['DefaultQueryDatabase'], 'PMA_backquote'); } } else { $table = $GLOBALS['table']; $db = $GLOBALS['db']; // Get the list and number of fields // we do a try_query here, because we could be in the query window, // trying to synchonize and the table has not yet been created $fields_list = PMA_DBI_get_columns($db, $GLOBALS['table'], null, true); $tmp_db_link = '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase'] . '?' . PMA_generate_common_url($db) . '"'; if ($is_querywindow) { $tmp_db_link .= ' target="_self"' . ' onclick="this.target=window.opener.frame_content.name"'; } $tmp_db_link .= '>' . htmlspecialchars($db) . '</a>'; // else use // $tmp_db_link = htmlspecialchars($db); $legend = sprintf(__('Run SQL query/queries on database %s'), $tmp_db_link); if (empty($query)) { $query = PMA_expandUserString($GLOBALS['cfg']['DefaultQueryTable'], 'PMA_backquote'); } } $legend .= ': ' . PMA_showMySQLDocu('SQL-Syntax', 'SELECT'); if (count($fields_list)) { $sqlquerycontainer_id = 'sqlquerycontainer'; } else { $sqlquerycontainer_id = 'sqlquerycontainerfull'; } echo '<a id="querybox"></a>' . "\n" . '<div id="queryboxcontainer">' . "\n" . '<fieldset id="queryboxf">' . "\n"; echo '<legend>' . $legend . '</legend>' . "\n"; echo '<div id="queryfieldscontainer">' . "\n"; echo '<div id="' . $sqlquerycontainer_id . '">' . "\n" . '<textarea tabindex="100" name="sql_query" id="sqlquery"' . ' cols="' . $GLOBALS['cfg']['TextareaCols'] . '"' . ' rows="' . $height . '"' . ' dir="' . $GLOBALS['text_dir'] . '"' . $auto_sel . $locking . '>' . htmlspecialchars($query) . '</textarea>' . "\n"; // Add buttons to generate query easily for select all,single select,insert,update and delete if (count($fields_list)) { echo '<input type="button" value="SELECT *" id="selectall" class="button sqlbutton" />'; echo '<input type="button" value="SELECT" id="select" class="button sqlbutton" />'; echo '<input type="button" value="INSERT" id="insert" class="button sqlbutton" />'; echo '<input type="button" value="UPDATE" id="update" class="button sqlbutton" />'; echo '<input type="button" value="DELETE" id="delete" class="button sqlbutton" />'; } echo '<input type="button" value="' . __('Clear') . '" id="clear" class="button sqlbutton" />'; echo '</div>' . "\n"; if (count($fields_list)) { echo '<div id="tablefieldscontainer">' . "\n" . '<label>' . __('Columns') . '</label>' . "\n" . '<select id="tablefields" name="dummy" ' . 'size="' . ($GLOBALS['cfg']['TextareaRows'] - 2) . '" ' . 'multiple="multiple" ondblclick="insertValueQuery()">' . "\n"; foreach ($fields_list as $field) { echo '<option value="' . PMA_backquote(htmlspecialchars($field['Field'])) . '"'; if (isset($field['Field']) && strlen($field['Field']) && isset($field['Comment'])) { echo ' title="' . htmlspecialchars($field['Comment']) . '"'; } echo '>' . htmlspecialchars($field['Field']) . '</option>' . "\n"; } echo '</select>' . "\n" . '<div id="tablefieldinsertbuttoncontainer">' . "\n"; if ($GLOBALS['cfg']['PropertiesIconic']) { echo '<input type="button" class="button" name="insert" value="<<"' . ' onclick="insertValueQuery()"' . ' title="' . __('Insert') . '" />' . "\n"; } else { echo '<input type="button" class="button" name="insert"' . ' value="' . __('Insert') . '"' . ' onclick="insertValueQuery()" />' . "\n"; } echo '</div>' . "\n" . '</div>' . "\n"; } echo '<div class="clearfloat"></div>' . "\n"; echo '</div>' . "\n"; if (!empty($GLOBALS['cfg']['Bookmark'])) { ?> <div id="bookmarkoptions"> <div class="formelement"> <label for="bkm_label"> <?php echo __('Bookmark this SQL query'); ?> :</label> <input type="text" name="bkm_label" id="bkm_label" tabindex="110" value="" /> </div> <div class="formelement"> <input type="checkbox" name="bkm_all_users" tabindex="111" id="id_bkm_all_users" value="true" /> <label for="id_bkm_all_users"> <?php echo __('Let every user access this bookmark'); ?> </label> </div> <div class="formelement"> <input type="checkbox" name="bkm_replace" tabindex="112" id="id_bkm_replace" value="true" /> <label for="id_bkm_replace"> <?php echo __('Replace existing bookmark of same name'); ?> </label> </div> </div> <?php } echo '<div class="clearfloat"></div>' . "\n"; echo '</fieldset>' . "\n" . '</div>' . "\n"; echo '<fieldset id="queryboxfooter" class="tblFooters">' . "\n"; echo '<div class="formelement">' . "\n"; if ($is_querywindow) { ?> <script type="text/javascript"> //<![CDATA[ document.writeln(' <input type="checkbox" name="LockFromUpdate" checked="checked" tabindex="120" id="checkbox_lock" /> <label for="checkbox_lock"><?php echo __('Do not overwrite this query from outside the window'); ?> </label> '); //]]> </script> <?php } echo '</div>' . "\n"; echo '<div class="formelement">' . "\n"; echo '<label for="id_sql_delimiter">[ ' . __('Delimiter') . '</label>' . "\n"; echo '<input type="text" name="sql_delimiter" tabindex="131" size="3" ' . 'value="' . $delimiter . '" ' . 'id="id_sql_delimiter" /> ]' . "\n"; echo '<input type="checkbox" name="show_query" value="1" ' . 'id="checkbox_show_query" tabindex="132" checked="checked" />' . "\n" . '<label for="checkbox_show_query">' . __('Show this query here again') . '</label>' . "\n"; if (!$is_querywindow) { echo '<input type="checkbox" name="retain_query_box" value="1" ' . 'id="retain_query_box" tabindex="133" ' . ($GLOBALS['cfg']['RetainQueryBox'] === false ? '' : ' checked="checked"') . ' />' . '<label for="retain_query_box">' . __('Retain query box') . '</label>'; } echo '</div>' . "\n"; echo '<input type="submit" id="button_submit_query" name="SQL" tabindex="200" value="' . __('Go') . '" />' . "\n"; echo '<div class="clearfloat"></div>' . "\n"; echo '</fieldset>' . "\n"; }
/** * 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 bool $do_relation whether to include relation comments * @param bool $do_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 PMA_exportStructure() also for other export * types which use this parameter * @param bool $do_mime whether to include mime comments * @param bool $dates whether to include creation/update/check dates * @param string $export_mode 'create_table', 'triggers', 'create_view', 'stand_in' * @param string $export_type 'server', 'database', 'table' * * @return bool Whether it succeeded * * @access public */ function PMA_exportStructure($db, $table, $crlf, $error_url, $do_relation = false, $do_comments = false, $do_mime = false, $dates = false, $export_mode, $export_type) { global $cfgRelation; /* We do not export triggers */ if ($export_mode == 'triggers') { return true; } /* Heading */ $GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2" text:is-list-header="true">' . __('Table structure for table') . ' ' . htmlspecialchars($table) . '</text:h>'; /** * Get the unique keys in the table */ $unique_keys = array(); $keys = PMA_DBI_get_table_indexes($db, $table); foreach ($keys as $key) { if ($key['Non_unique'] == 0) { $unique_keys[] = $key['Column_name']; } } /** * Gets fields properties */ PMA_DBI_select_db($db); // Check if we can use Relations if ($do_relation && !empty($cfgRelation['relation'])) { // Find which tables are related with the current one and write it in // an array $res_rel = PMA_getForeigners($db, $table); if ($res_rel && count($res_rel) > 0) { $have_rel = true; } else { $have_rel = false; } } else { $have_rel = false; } // end if /** * Displays the table structure */ $GLOBALS['odt_buffer'] .= '<table:table table:name="' . htmlspecialchars($table) . '_data">'; $columns_cnt = 4; if ($do_relation && $have_rel) { $columns_cnt++; } if ($do_comments) { $columns_cnt++; } if ($do_mime && $cfgRelation['mimework']) { $columns_cnt++; } $GLOBALS['odt_buffer'] .= '<table:table-column table:number-columns-repeated="' . $columns_cnt . '"/>'; /* Header */ $GLOBALS['odt_buffer'] .= '<table:table-row>'; $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Column') . '</text:p>' . '</table:table-cell>'; $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Type') . '</text:p>' . '</table:table-cell>'; $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Null') . '</text:p>' . '</table:table-cell>'; $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Default') . '</text:p>' . '</table:table-cell>'; if ($do_relation && $have_rel) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Links to') . '</text:p>' . '</table:table-cell>'; } if ($do_comments) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Comments') . '</text:p>' . '</table:table-cell>'; $comments = PMA_getComments($db, $table); } if ($do_mime && $cfgRelation['mimework']) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('MIME type') . '</text:p>' . '</table:table-cell>'; $mime_map = PMA_getMIME($db, $table, true); } $GLOBALS['odt_buffer'] .= '</table:table-row>'; $columns = PMA_DBI_get_columns($db, $table); foreach ($columns as $column) { $field_name = $column['Field']; $GLOBALS['odt_buffer'] .= '<table:table-row>'; $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($field_name) . '</text:p>' . '</table:table-cell>'; $extracted_fieldspec = PMA_extractFieldSpec($column['Type']); $type = htmlspecialchars($extracted_fieldspec['print_type']); if (empty($type)) { $type = ' '; } $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($type) . '</text:p>' . '</table:table-cell>'; if (!isset($column['Default'])) { if ($column['Null'] != 'NO') { $column['Default'] = 'NULL'; } else { $column['Default'] = ''; } } else { $column['Default'] = $column['Default']; } $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . ($column['Null'] == '' || $column['Null'] == 'NO' ? __('No') : __('Yes')) . '</text:p>' . '</table:table-cell>'; $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($column['Default']) . '</text:p>' . '</table:table-cell>'; if ($do_relation && $have_rel) { if (isset($res_rel[$field_name])) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($res_rel[$field_name]['foreign_table'] . ' (' . $res_rel[$field_name]['foreign_field'] . ')') . '</text:p>' . '</table:table-cell>'; } } if ($do_comments) { if (isset($comments[$field_name])) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($comments[$field_name]) . '</text:p>' . '</table:table-cell>'; } else { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p></text:p>' . '</table:table-cell>'; } } if ($do_mime && $cfgRelation['mimework']) { if (isset($mime_map[$field_name])) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars(str_replace('_', '/', $mime_map[$field_name]['mimetype'])) . '</text:p>' . '</table:table-cell>'; } else { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p></text:p>' . '</table:table-cell>'; } } $GLOBALS['odt_buffer'] .= '</table:table-row>'; } // end while $GLOBALS['odt_buffer'] .= '</table:table>'; return true; }
/** * Check if there are tables that need to be deleted in dashboard, * if there are, ask the user for allowance * * @return void * @access private */ private function _displayScratchboardTables($array_sh_page) { global $with_field_names, $db; ?> <script type="text/javascript" src="./js/dom-drag.js"></script> <form method="post" action="schema_edit.php" name="dragdrop"> <input type="button" name="dragdrop" value="<?php echo __('Toggle scratchboard'); ?> " onclick="ToggleDragDrop('pdflayout');" /> <input type="button" name="dragdropreset" value="<?php echo __('Reset'); ?> " onclick="resetDrag();" /> </form> <div id="pdflayout" class="pdflayout" style="visibility: hidden;"> <?php $draginit = ''; $draginit2 = ''; $reset_draginit = ''; $i = 0; foreach ($array_sh_page as $key => $temp_sh_page) { $drag_x = $temp_sh_page['x']; $drag_y = $temp_sh_page['y']; $draginit2 .= ' Drag.init($("#table_' . $i . '")[0], null, 0, parseInt(myid.style.width)-2, 0, parseInt(myid.style.height)-5);' . "\n"; $draginit2 .= ' $("#table_' . $i . '")[0].onDrag = function (x, y) { document.edcoord.elements["c_table_' . $i . '[x]"].value = parseInt(x); document.edcoord.elements["c_table_' . $i . '[y]"].value = parseInt(y) }' . "\n"; $draginit .= ' $("#table_' . $i . '")[0].style.left = "' . $drag_x . 'px";' . "\n"; $draginit .= ' $("#table_' . $i . '")[0].style.top = "' . $drag_y . 'px";' . "\n"; $reset_draginit .= ' $("#table_' . $i . '")[0].style.left = "2px";' . "\n"; $reset_draginit .= ' $("#table_' . $i . '")[0].style.top = "' . 15 * $i . 'px";' . "\n"; $reset_draginit .= ' document.edcoord.elements["c_table_' . $i . '[x]"].value = "2"' . "\n"; $reset_draginit .= ' document.edcoord.elements["c_table_' . $i . '[y]"].value = "' . 15 * $i . '"' . "\n"; echo '<div id="table_' . $i . '" class="pdflayout_table"><u>' . htmlspecialchars($temp_sh_page['table_name']) . '</u>'; if (isset($with_field_names)) { $fields = PMA_DBI_get_columns($db, $temp_sh_page['table_name']); // if the table has been dropped from outside phpMyAdmin, // we can no longer obtain its columns list if ($fields) { foreach ($fields as $row) { echo '<br />' . htmlspecialchars($row['Field']) . "\n"; } } } echo '</div>' . "\n"; $i++; } ?> </div> <script type="text/javascript"> //<![CDATA[ function PDFinit() { refreshLayout(); myid = $('#pdflayout')[0]; <?php echo $draginit; ?> TableDragInit(); } function TableDragInit() { myid = $('#pdflayout')[0]; <?php echo $draginit2; ?> } function resetDrag() { <?php echo $reset_draginit; ?> } //]]> </script> <?php }
/** * Outputs the content of a table in MediaWiki 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 * * @access public */ function PMA_exportData($db, $table, $crlf, $error_url, $sql_query) { $columns = PMA_DBI_get_columns($db, $table); $columns = array_values($columns); $row_cnt = count($columns); $output = "{| cellpadding=\"10\" cellspacing=\"0\" border=\"1\" style=\"text-align:center;\"\n"; $output .= "|+'''" . $table . "'''\n"; $output .= "|- style=\"background:#ffdead;\"\n"; $output .= "! style=\"background:#ffffff\" | \n"; for ($i = 0; $i < $row_cnt; ++$i) { $output .= " | " . $columns[$i]['Field']; if ($i + 1 != $row_cnt) { $output .= "\n"; } } $output .= "\n"; $output .= "|- style=\"background:#f9f9f9;\"\n"; $output .= "! style=\"background:#f2f2f2\" | Type\n"; for ($i = 0; $i < $row_cnt; ++$i) { $output .= " | " . $columns[$i]['Type']; if ($i + 1 != $row_cnt) { $output .= "\n"; } } $output .= "\n"; $output .= "|- style=\"background:#f9f9f9;\"\n"; $output .= "! style=\"background:#f2f2f2\" | Null\n"; for ($i = 0; $i < $row_cnt; ++$i) { $output .= " | " . $columns[$i]['Null']; if ($i + 1 != $row_cnt) { $output .= "\n"; } } $output .= "\n"; $output .= "|- style=\"background:#f9f9f9;\"\n"; $output .= "! style=\"background:#f2f2f2\" | Default\n"; for ($i = 0; $i < $row_cnt; ++$i) { $output .= " | " . $columns[$i]['Default']; if ($i + 1 != $row_cnt) { $output .= "\n"; } } $output .= "\n"; $output .= "|- style=\"background:#f9f9f9;\"\n"; $output .= "! style=\"background:#f2f2f2\" | Extra\n"; for ($i = 0; $i < $row_cnt; ++$i) { $output .= " | " . $columns[$i]['Extra']; if ($i + 1 != $row_cnt) { $output .= "\n"; } } $output .= "\n"; $output .= "|}\n\n\n\n"; return PMA_exportOutputHandler($output); }
$breakstyle = ' style="page-break-after: always;"'; } $counter++; echo '<div' . $breakstyle . '>' . "\n"; echo '<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 = PMA_DBI_get_columns($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 = PMA_DBI_fetch_value('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_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)) {
/** * Handles the whole import logic * * @return void */ public function doImport() { global $db, $csv_terminated, $csv_enclosed, $csv_escaped, $csv_new_line; global $error, $timeout_passed, $finished; $common_functions = PMA_CommonFunctions::getInstance(); $replacements = array('\\n' => "\n", '\\t' => "\t", '\\r' => "\r"); $csv_terminated = strtr($csv_terminated, $replacements); $csv_enclosed = strtr($csv_enclosed, $replacements); $csv_escaped = strtr($csv_escaped, $replacements); $csv_new_line = strtr($csv_new_line, $replacements); $param_error = false; if (strlen($csv_terminated) != 1) { $message = PMA_Message::error(__('Invalid parameter for CSV import: %s')); $message->addParam(__('Columns terminated by'), false); $error = true; $param_error = true; // The default dialog of MS Excel when generating a CSV produces a // semi-colon-separated file with no chance of specifying the // enclosing character. Thus, users who want to import this file // tend to remove the enclosing character on the Import dialog. // I could not find a test case where having no enclosing characters // confuses this script. // But the parser won't work correctly with strings so we allow just // one character. } elseif (strlen($csv_enclosed) > 1) { $message = PMA_Message::error(__('Invalid parameter for CSV import: %s')); $message->addParam(__('Columns enclosed by'), false); $error = true; $param_error = true; } elseif (strlen($csv_escaped) != 1) { $message = PMA_Message::error(__('Invalid parameter for CSV import: %s')); $message->addParam(__('Columns escaped by'), false); $error = true; $param_error = true; } elseif (strlen($csv_new_line) != 1 && $csv_new_line != 'auto') { $message = PMA_Message::error(__('Invalid parameter for CSV import: %s')); $message->addParam(__('Lines terminated by'), false); $error = true; $param_error = true; } // If there is an error in the parameters entered, // indicate that immediately. if ($param_error) { $common_functions->mysqlDie($message->getMessage(), '', '', $err_url); } $buffer = ''; $required_fields = 0; if (!$this->_getAnalyze()) { if (isset($csv_replace)) { $sql_template = 'REPLACE'; } else { $sql_template = 'INSERT'; if (isset($csv_ignore)) { $sql_template .= ' IGNORE'; } } $sql_template .= ' INTO ' . $common_functions->backquote($table); $tmp_fields = PMA_DBI_get_columns($db, $table); if (empty($csv_columns)) { $fields = $tmp_fields; } else { $sql_template .= ' ('; $fields = array(); $tmp = preg_split('/,( ?)/', $csv_columns); foreach ($tmp as $key => $val) { if (count($fields) > 0) { $sql_template .= ', '; } /* Trim also `, if user already included backquoted fields */ $val = trim($val, " \t\r\n\v`"); $found = false; foreach ($tmp_fields as $id => $field) { if ($field['Field'] == $val) { $found = true; break; } } if (!$found) { $message = PMA_Message::error(__('Invalid column (%s) specified! Ensure that columns' . ' names are spelled correctly, separated by commas' . ', and not enclosed in quotes.')); $message->addParam($val); $error = true; break; } $fields[] = $field; $sql_template .= $common_functions->backquote($val); } $sql_template .= ') '; } $required_fields = count($fields); $sql_template .= ' VALUES ('; } // Defaults for parser $i = 0; $len = 0; $line = 1; $lasti = -1; $values = array(); $csv_finish = false; $tempRow = array(); $rows = array(); $col_names = array(); $tables = array(); $col_count = 0; $max_cols = 0; while (!($finished && $i >= $len) && !$error && !$timeout_passed) { $data = PMA_importGetNextChunk(); if ($data === false) { // subtract data we didn't handle yet and stop processing $offset -= strlen($buffer); break; } elseif ($data === true) { // Handle rest of buffer } else { // Append new data to buffer $buffer .= $data; unset($data); // Do not parse string when we're not at the end // and don't have new line inside if ($csv_new_line == 'auto' && strpos($buffer, "\r") === false && strpos($buffer, "\n") === false || $csv_new_line != 'auto' && strpos($buffer, $csv_new_line) === false) { continue; } } // Current length of our buffer $len = strlen($buffer); // Currently parsed char $ch = $buffer[$i]; while ($i < $len) { // Deadlock protection if ($lasti == $i && $lastlen == $len) { $message = PMA_Message::error(__('Invalid format of CSV input on line %d.')); $message->addParam($line); $error = true; break; } $lasti = $i; $lastlen = $len; // This can happen with auto EOL and \r at the end of buffer if (!$csv_finish) { // Grab empty field if ($ch == $csv_terminated) { if ($i == $len - 1) { break; } $values[] = ''; $i++; $ch = $buffer[$i]; continue; } // Grab one field $fallbacki = $i; if ($ch == $csv_enclosed) { if ($i == $len - 1) { break; } $need_end = true; $i++; $ch = $buffer[$i]; } else { $need_end = false; } $fail = false; $value = ''; while ($need_end && ($ch != $csv_enclosed || $csv_enclosed == $csv_escaped) || !$need_end && !($ch == $csv_terminated || $ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n"))) { if ($ch == $csv_escaped) { if ($i == $len - 1) { $fail = true; break; } $i++; $ch = $buffer[$i]; if ($csv_enclosed == $csv_escaped && ($ch == $csv_terminated || $ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n"))) { break; } } $value .= $ch; if ($i == $len - 1) { if (!$finished) { $fail = true; } break; } $i++; $ch = $buffer[$i]; } // unquoted NULL string if (false === $need_end && $value === 'NULL') { $value = null; } if ($fail) { $i = $fallbacki; $ch = $buffer[$i]; break; } // Need to strip trailing enclosing char? if ($need_end && $ch == $csv_enclosed) { if ($finished && $i == $len - 1) { $ch = null; } elseif ($i == $len - 1) { $i = $fallbacki; $ch = $buffer[$i]; break; } else { $i++; $ch = $buffer[$i]; } } // Are we at the end? if ($ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n") || $finished && $i == $len - 1) { $csv_finish = true; } // Go to next char if ($ch == $csv_terminated) { if ($i == $len - 1) { $i = $fallbacki; $ch = $buffer[$i]; break; } $i++; $ch = $buffer[$i]; } // If everything went okay, store value $values[] = $value; } // End of line if ($csv_finish || $ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n")) { if ($csv_new_line == 'auto' && $ch == "\r") { // Handle "\r\n" if ($i >= $len - 2 && !$finished) { break; // We need more data to decide new line } if ($buffer[$i + 1] == "\n") { $i++; } } // We didn't parse value till the end of line, so there was // empty one if (!$csv_finish) { $values[] = ''; } if ($this->_getAnalyze()) { foreach ($values as $ley => $val) { $tempRow[] = $val; ++$col_count; } if ($col_count > $max_cols) { $max_cols = $col_count; } $col_count = 0; $rows[] = $tempRow; $tempRow = array(); } else { // Do we have correct count of values? if (count($values) != $required_fields) { // Hack for excel if ($values[count($values) - 1] == ';') { unset($values[count($values) - 1]); } else { $message = PMA_Message::error(__('Invalid column count in CSV input on line %d.')); $message->addParam($line); $error = true; break; } } $first = true; $sql = $sql_template; foreach ($values as $key => $val) { if (!$first) { $sql .= ', '; } if ($val === null) { $sql .= 'NULL'; } else { $sql .= '\'' . $common_functions->sqlAddSlashes($val) . '\''; } $first = false; } $sql .= ')'; /** * @todo maybe we could add original line to verbose * SQL in comment */ PMA_importRunQuery($sql, $sql); } $line++; $csv_finish = false; $values = array(); $buffer = substr($buffer, $i + 1); $len = strlen($buffer); $i = 0; $lasti = -1; $ch = $buffer[0]; } } // End of parser loop } // End of import loop if ($this->_getAnalyze()) { /* Fill out all rows */ $num_rows = count($rows); for ($i = 0; $i < $num_rows; ++$i) { for ($j = count($rows[$i]); $j < $max_cols; ++$j) { $rows[$i][] = 'NULL'; } } if (isset($_REQUEST['csv_col_names'])) { $col_names = array_splice($rows, 0, 1); $col_names = $col_names[0]; } if (isset($col_names) && count($col_names) != $max_cols || !isset($col_names)) { // Fill out column names for ($i = 0; $i < $max_cols; ++$i) { $col_names[] = 'COL ' . ($i + 1); } } if (strlen($db)) { $result = PMA_DBI_fetch_result('SHOW TABLES'); $tbl_name = 'TABLE ' . (count($result) + 1); } else { $tbl_name = 'TBL_NAME'; } $tables[] = array($tbl_name, $col_names, $rows); /* Obtain the best-fit MySQL types for each column */ $analyses = array(); $analyses[] = PMA_analyzeTable($tables[0]); /** * string $db_name (no backquotes) * * array $table = array(table_name, array() column_names, array()() rows) * array $tables = array of "$table"s * * array $analysis = array(array() column_types, array() column_sizes) * array $analyses = array of "$analysis"s * * array $create = array of SQL strings * * array $options = an associative array of options */ /* Set database name to the currently selected one, if applicable */ if (strlen($db)) { $db_name = $db; $options = array('create_db' => false); } else { $db_name = 'CSV_DB'; $options = null; } /* Non-applicable parameters */ $create = null; /* Created and execute necessary SQL statements from data */ PMA_buildSQL($db_name, $tables, $analyses, $create, $options); unset($tables); unset($analyses); } // Commit any possible data in buffers PMA_importRunQuery(); if (count($values) != 0 && !$error) { $message = PMA_Message::error(__('Invalid format of CSV input on line %d.')); $message->addParam($line); $error = true; } }
* $selected comes from multi_submits.inc.php */ if ($abort == false) { if (! isset($selected)) { $common_functions->checkParameters(array('field')); $selected[] = $_REQUEST['field']; $selected_cnt = 1; } else { // from a multiple submit $selected_cnt = count($selected); } /** * @todo optimize in case of multiple fields to modify */ for ($i = 0; $i < $selected_cnt; $i++) { $fields_meta[] = PMA_DBI_get_columns($db, $table, $selected[$i], true); } $num_fields = count($fields_meta); $action = 'tbl_alter.php'; // Get more complete field information. // For now, this is done to obtain MySQL 4.1.2+ new TIMESTAMP options // and to know when there is an empty DEFAULT value. // Later, if the analyser returns more information, it // could be executed to replace the info given by SHOW FULL COLUMNS FROM. /** * @todo put this code into a require() * or maybe make it part of PMA_DBI_get_columns(); */ // We also need this to correctly learn if a TIMESTAMP is NOT NULL, since
/** * Creates tracking version of a table / view * (in other words: create a job to track future changes on the table). * * @param string $dbname name of database * @param string $tablename name of table * @param string $version version * @param string $tracking_set set of tracking statements * @param bool $is_view if table is a view * * @static * * @return int result of version insertion */ static public function createVersion($dbname, $tablename, $version, $tracking_set = '', $is_view = false) { global $sql_backquotes; if ($tracking_set == '') { $tracking_set = self::$default_tracking_set; } include_once './libraries/export/sql.php'; $sql_backquotes = true; $date = date('Y-m-d H:i:s'); // Get data definition snapshot of table $columns = PMA_DBI_get_columns($dbname, $tablename, null, true); // int indices to reduce size $columns = array_values($columns); // remove Privileges to reduce size for ($i = 0; $i < count($columns); $i++) { unset($columns[$i]['Privileges']); } $indexes = PMA_DBI_get_table_indexes($dbname, $tablename); $snapshot = array('COLUMNS' => $columns, 'INDEXES' => $indexes); $snapshot = serialize($snapshot); // Get DROP TABLE / DROP VIEW and CREATE TABLE SQL statements $sql_backquotes = true; $create_sql = ""; if (self::$add_drop_table == true && $is_view == false) { $create_sql .= self::getLogComment() . 'DROP TABLE IF EXISTS ' . PMA_backquote($tablename) . ";\n"; } if (self::$add_drop_view == true && $is_view == true) { $create_sql .= self::getLogComment() . 'DROP VIEW IF EXISTS ' . PMA_backquote($tablename) . ";\n"; } $create_sql .= self::getLogComment() . PMA_getTableDef($dbname, $tablename, "\n", ""); // Save version $sql_query = "/*NOTRACK*/\n" . "INSERT INTO" . self::$pma_table . " (" . "db_name, " . "table_name, " . "version, " . "date_created, " . "date_updated, " . "schema_snapshot, " . "schema_sql, " . "data_sql, " . "tracking " . ") " . "values ( '" . PMA_sqlAddSlashes($dbname) . "', '" . PMA_sqlAddSlashes($tablename) . "', '" . PMA_sqlAddSlashes($version) . "', '" . PMA_sqlAddSlashes($date) . "', '" . PMA_sqlAddSlashes($date) . "', '" . PMA_sqlAddSlashes($snapshot) . "', '" . PMA_sqlAddSlashes($create_sql) . "', '" . PMA_sqlAddSlashes("\n") . "', '" . PMA_sqlAddSlashes(self::transformTrackingSet($tracking_set)) . "' )"; $result = PMA_query_as_controluser($sql_query); if ($result) { // Deactivate previous version self::deactivateTracking($dbname, $tablename, ($version - 1)); } return $result; }
public function dataDictionaryDoc($alltables) { global $db, $pdf, $orientation, $paper; // TOC $pdf->addpage($_POST['orientation']); $pdf->Cell(0, 9, __('Table of contents'), 1, 0, 'C'); $pdf->Ln(15); $i = 1; foreach ($alltables as $table) { $pdf->PMA_links['doc'][$table]['-'] = $pdf->AddLink(); $pdf->SetX(10); // $pdf->Ln(1); $pdf->Cell(0, 6, __('Page number:') . ' {' . sprintf("%02d", $i) . '}', 0, 0, 'R', 0, $pdf->PMA_links['doc'][$table]['-']); $pdf->SetX(10); $pdf->Cell(0, 6, $i . ' ' . $table, 0, 1, 'L', 0, $pdf->PMA_links['doc'][$table]['-']); // $pdf->Ln(1); $fields = PMA_DBI_get_columns($GLOBALS['db'], $table); foreach ($fields as $row) { $pdf->SetX(20); $field_name = $row['Field']; $pdf->PMA_links['doc'][$table][$field_name] = $pdf->AddLink(); //$pdf->Cell( // 0, 6, $field_name, 0, 1, // 'L', 0, $pdf->PMA_links['doc'][$table][$field_name] //); } $i++; } $pdf->PMA_links['RT']['-'] = $pdf->AddLink(); $pdf->SetX(10); $pdf->Cell(0, 6, __('Page number:') . ' {00}', 0, 0, 'R', 0, $pdf->PMA_links['RT']['-']); $pdf->SetX(10); $pdf->Cell(0, 6, $i . ' ' . __('Relational schema'), 0, 1, 'L', 0, $pdf->PMA_links['RT']['-']); $z = 0; foreach ($alltables as $table) { $z++; $pdf->SetAutoPageBreak(true, 15); $pdf->addpage($_POST['orientation']); $pdf->Bookmark($table); $pdf->SetAlias('{' . sprintf("%02d", $z) . '}', $pdf->PageNo()); $pdf->PMA_links['RT'][$table]['-'] = $pdf->AddLink(); $pdf->SetLink($pdf->PMA_links['doc'][$table]['-'], -1); $pdf->SetFont($this->_ff, 'B', 18); $pdf->Cell(0, 8, $z . ' ' . $table, 1, 1, 'C', 0, $pdf->PMA_links['RT'][$table]['-']); $pdf->SetFont($this->_ff, '', 8); $pdf->ln(); $cfgRelation = PMA_getRelationsParam(); $comments = PMA_getComments($db, $table); if ($cfgRelation['mimework']) { $mime_map = PMA_getMIME($db, $table, true); } /** * Gets table informations */ $showtable = PMA_Table::sGetStatusInfo($db, $table); $show_comment = isset($showtable['Comment']) ? $showtable['Comment'] : ''; $create_time = isset($showtable['Create_time']) ? PMA_localisedDate(strtotime($showtable['Create_time'])) : ''; $update_time = isset($showtable['Update_time']) ? PMA_localisedDate(strtotime($showtable['Update_time'])) : ''; $check_time = isset($showtable['Check_time']) ? PMA_localisedDate(strtotime($showtable['Check_time'])) : ''; /** * Gets table keys and retains them */ $result = PMA_DBI_query('SHOW KEYS FROM ' . PMA_backquote($table) . ';'); $primary = ''; $indexes = array(); $lastIndex = ''; $indexes_info = array(); $indexes_data = array(); $pk_array = array(); // will be use to emphasis prim. keys in the table // view while ($row = PMA_DBI_fetch_assoc($result)) { // Backups the list of primary keys if ($row['Key_name'] == 'PRIMARY') { $primary .= $row['Column_name'] . ', '; $pk_array[$row['Column_name']] = 1; } // Retains keys informations if ($row['Key_name'] != $lastIndex) { $indexes[] = $row['Key_name']; $lastIndex = $row['Key_name']; } $indexes_info[$row['Key_name']]['Sequences'][] = $row['Seq_in_index']; $indexes_info[$row['Key_name']]['Non_unique'] = $row['Non_unique']; if (isset($row['Cardinality'])) { $indexes_info[$row['Key_name']]['Cardinality'] = $row['Cardinality']; } // I don't know what does following column mean.... // $indexes_info[$row['Key_name']]['Packed'] = $row['Packed']; $indexes_info[$row['Key_name']]['Comment'] = $row['Comment']; $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Column_name'] = $row['Column_name']; if (isset($row['Sub_part'])) { $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Sub_part'] = $row['Sub_part']; } } // end while if ($result) { PMA_DBI_free_result($result); } /** * Gets fields properties */ $columns = PMA_DBI_get_columns($db, $table); // Check if we can use Relations if (!empty($cfgRelation['relation'])) { // Find which tables are related with the current one and write it in // an array $res_rel = PMA_getForeigners($db, $table); if (count($res_rel) > 0) { $have_rel = true; } else { $have_rel = false; } } else { $have_rel = false; } // end if /** * Displays the comments of the table if MySQL >= 3.23 */ $break = false; if (!empty($show_comment)) { $pdf->Cell(0, 3, __('Table comments') . ' : ' . $show_comment, 0, 1); $break = true; } if (!empty($create_time)) { $pdf->Cell(0, 3, __('Creation') . ': ' . $create_time, 0, 1); $break = true; } if (!empty($update_time)) { $pdf->Cell(0, 3, __('Last update') . ': ' . $update_time, 0, 1); $break = true; } if (!empty($check_time)) { $pdf->Cell(0, 3, __('Last check') . ': ' . $check_time, 0, 1); $break = true; } if ($break == true) { $pdf->Cell(0, 3, '', 0, 1); $pdf->Ln(); } $pdf->SetFont($this->_ff, 'B'); if (isset($orientation) && $orientation == 'L') { $pdf->Cell(25, 8, __('Column'), 1, 0, 'C'); $pdf->Cell(20, 8, __('Type'), 1, 0, 'C'); $pdf->Cell(20, 8, __('Attributes'), 1, 0, 'C'); $pdf->Cell(10, 8, __('Null'), 1, 0, 'C'); $pdf->Cell(20, 8, __('Default'), 1, 0, 'C'); $pdf->Cell(25, 8, __('Extra'), 1, 0, 'C'); $pdf->Cell(45, 8, __('Links to'), 1, 0, 'C'); if ($paper == 'A4') { $comments_width = 67; } else { // this is really intended for 'letter' /** * @todo find optimal width for all formats */ $comments_width = 50; } $pdf->Cell($comments_width, 8, __('Comments'), 1, 0, 'C'); $pdf->Cell(45, 8, 'MIME', 1, 1, 'C'); $pdf->SetWidths(array(25, 20, 20, 10, 20, 25, 45, $comments_width, 45)); } else { $pdf->Cell(20, 8, __('Column'), 1, 0, 'C'); $pdf->Cell(20, 8, __('Type'), 1, 0, 'C'); $pdf->Cell(20, 8, __('Attributes'), 1, 0, 'C'); $pdf->Cell(10, 8, __('Null'), 1, 0, 'C'); $pdf->Cell(15, 8, __('Default'), 1, 0, 'C'); $pdf->Cell(15, 8, __('Extra'), 1, 0, 'C'); $pdf->Cell(30, 8, __('Links to'), 1, 0, 'C'); $pdf->Cell(30, 8, __('Comments'), 1, 0, 'C'); $pdf->Cell(30, 8, 'MIME', 1, 1, 'C'); $pdf->SetWidths(array(20, 20, 20, 10, 15, 15, 30, 30, 30)); } $pdf->SetFont($this->_ff, ''); foreach ($columns as $row) { $extracted_fieldspec = PMA_extractFieldSpec($row['Type']); $type = $extracted_fieldspec['print_type']; $attribute = $extracted_fieldspec['attribute']; if (!isset($row['Default'])) { if ($row['Null'] != '' && $row['Null'] != 'NO') { $row['Default'] = 'NULL'; } } $field_name = $row['Field']; // $pdf->Ln(); $pdf->PMA_links['RT'][$table][$field_name] = $pdf->AddLink(); $pdf->Bookmark($field_name, 1, -1); $pdf->SetLink($pdf->PMA_links['doc'][$table][$field_name], -1); $pdf_row = array($field_name, $type, $attribute, $row['Null'] == '' || $row['Null'] == 'NO' ? __('No') : __('Yes'), isset($row['Default']) ? $row['Default'] : '', $row['Extra'], isset($res_rel[$field_name]) ? $res_rel[$field_name]['foreign_table'] . ' -> ' . $res_rel[$field_name]['foreign_field'] : '', isset($comments[$field_name]) ? $comments[$field_name] : '', isset($mime_map) && isset($mime_map[$field_name]) ? str_replace('_', '/', $mime_map[$field_name]['mimetype']) : ''); $links[0] = $pdf->PMA_links['RT'][$table][$field_name]; if (isset($res_rel[$field_name]['foreign_table']) and isset($res_rel[$field_name]['foreign_field']) and isset($pdf->PMA_links['doc'][$res_rel[$field_name]['foreign_table']][$res_rel[$field_name]['foreign_field']])) { $links[6] = $pdf->PMA_links['doc'][$res_rel[$field_name]['foreign_table']][$res_rel[$field_name]['foreign_field']]; } else { unset($links[6]); } $pdf->Row($pdf_row, $links); } // end foreach $pdf->SetFont($this->_ff, '', 14); } //end each }
/** * get the correct username and hostname lengths for this MySQL server * * @return array username length, hostname length */ function PMA_replication_get_username_hostname_length() { $fields_info = PMA_DBI_get_columns('mysql', 'user'); $username_length = 16; $hostname_length = 41; foreach ($fields_info as $val) { if ($val['Field'] == 'User') { strtok($val['Type'], '()'); $v = strtok('()'); if (is_int($v)) { $username_length = $v; } } elseif ($val['Field'] == 'Host') { strtok($val['Type'], '()'); $v = strtok('()'); if (is_int($v)) { $hostname_length = $v; } } } return array($username_length, $hostname_length); }
/** * Formats user string, expanding @VARIABLES@, accepting strftime format string. * * @param string $string Text where to do expansion. * @param function $escape Function to call for escaping variable values. * @param array $updates Array with overrides for default parameters * (obtained from GLOBALS). * * @return string */ function PMA_expandUserString($string, $escape = null, $updates = array()) { /* Content */ $vars['http_host'] = PMA_getenv('HTTP_HOST') ? PMA_getenv('HTTP_HOST') : ''; $vars['server_name'] = $GLOBALS['cfg']['Server']['host']; $vars['server_verbose'] = $GLOBALS['cfg']['Server']['verbose']; $vars['server_verbose_or_name'] = !empty($GLOBALS['cfg']['Server']['verbose']) ? $GLOBALS['cfg']['Server']['verbose'] : $GLOBALS['cfg']['Server']['host']; $vars['database'] = $GLOBALS['db']; $vars['table'] = $GLOBALS['table']; $vars['phpmyadmin_version'] = 'phpMyAdmin ' . PMA_VERSION; /* Update forced variables */ foreach ($updates as $key => $val) { $vars[$key] = $val; } /* Replacement mapping */ /* * The __VAR__ ones are for backward compatibility, because user * might still have it in cookies. */ $replace = array('@HTTP_HOST@' => $vars['http_host'], '@SERVER@' => $vars['server_name'], '__SERVER__' => $vars['server_name'], '@VERBOSE@' => $vars['server_verbose'], '@VSERVER@' => $vars['server_verbose_or_name'], '@DATABASE@' => $vars['database'], '__DB__' => $vars['database'], '@TABLE@' => $vars['table'], '__TABLE__' => $vars['table'], '@PHPMYADMIN@' => $vars['phpmyadmin_version']); /* Optional escaping */ if (!is_null($escape)) { foreach ($replace as $key => $val) { $replace[$key] = $escape($val); } } /* Backward compatibility in 3.5.x */ if (strpos($string, '@FIELDS@') !== false) { $string = strtr($string, array('@FIELDS@' => '@COLUMNS@')); } /* Fetch columns list if required */ if (strpos($string, '@COLUMNS@') !== false) { $columns_list = PMA_DBI_get_columns($GLOBALS['db'], $GLOBALS['table']); $column_names = array(); foreach ($columns_list as $column) { if (!is_null($escape)) { $column_names[] = $escape($column['Field']); } else { $column_names[] = $field['Field']; } } $replace['@COLUMNS@'] = implode(',', $column_names); } /* Do the replacement */ return strtr(strftime($string), $replace); }
/** * Returns $table's CREATE definition * * @param string $db the database name * @param string $table the table name * @param string $crlf the end of line sequence * @param string $error_url the url to go back in case of error * @param bool $do_relation whether to include relation comments * @param bool $do_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 * PMA_exportStructure() also for other * @param bool $do_mime whether to include mime comments * @param bool $show_dates whether to include creation/update/check dates * @param bool $add_semicolon whether to add semicolon and end-of-line at * the end * @param bool $view whether we're handling a view * * @return bool true */ public function getTableDef($db, $table, $crlf, $error_url, $do_relation, $do_comments, $do_mime, $show_dates = false, $add_semicolon = true, $view = false) { global $cfgRelation; /** * Gets fields properties */ PMA_DBI_select_db($db); // Check if we can use Relations if ($do_relation && !empty($cfgRelation['relation'])) { // Find which tables are related with the current one and write it in // an array $res_rel = PMA_getForeigners($db, $table); if ($res_rel && count($res_rel) > 0) { $have_rel = true; } else { $have_rel = false; } } else { $have_rel = false; } // end if /** * Displays the table structure */ $GLOBALS['odt_buffer'] .= '<table:table table:name="' . htmlspecialchars($table) . '_structure">'; $columns_cnt = 4; if ($do_relation && $have_rel) { $columns_cnt++; } if ($do_comments) { $columns_cnt++; } if ($do_mime && $cfgRelation['mimework']) { $columns_cnt++; } $GLOBALS['odt_buffer'] .= '<table:table-column' . ' table:number-columns-repeated="' . $columns_cnt . '"/>'; /* Header */ $GLOBALS['odt_buffer'] .= '<table:table-row>' . '<table:table-cell office:value-type="string">' . '<text:p>' . __('Column') . '</text:p>' . '</table:table-cell>' . '<table:table-cell office:value-type="string">' . '<text:p>' . __('Type') . '</text:p>' . '</table:table-cell>' . '<table:table-cell office:value-type="string">' . '<text:p>' . __('Null') . '</text:p>' . '</table:table-cell>' . '<table:table-cell office:value-type="string">' . '<text:p>' . __('Default') . '</text:p>' . '</table:table-cell>'; if ($do_relation && $have_rel) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Links to') . '</text:p>' . '</table:table-cell>'; } if ($do_comments) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('Comments') . '</text:p>' . '</table:table-cell>'; $comments = PMA_getComments($db, $table); } if ($do_mime && $cfgRelation['mimework']) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . __('MIME type') . '</text:p>' . '</table:table-cell>'; $mime_map = PMA_getMIME($db, $table, true); } $GLOBALS['odt_buffer'] .= '</table:table-row>'; $columns = PMA_DBI_get_columns($db, $table); foreach ($columns as $column) { $field_name = $column['Field']; $GLOBALS['odt_buffer'] .= $this->formatOneColumnDefinition($column); if ($do_relation && $have_rel) { if (isset($res_rel[$field_name])) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($res_rel[$field_name]['foreign_table'] . ' (' . $res_rel[$field_name]['foreign_field'] . ')') . '</text:p>' . '</table:table-cell>'; } } if ($do_comments) { if (isset($comments[$field_name])) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($comments[$field_name]) . '</text:p>' . '</table:table-cell>'; } else { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p></text:p>' . '</table:table-cell>'; } } if ($do_mime && $cfgRelation['mimework']) { if (isset($mime_map[$field_name])) { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars(str_replace('_', '/', $mime_map[$field_name]['mimetype'])) . '</text:p>' . '</table:table-cell>'; } else { $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p></text:p>' . '</table:table-cell>'; } } $GLOBALS['odt_buffer'] .= '</table:table-row>'; } // end foreach $GLOBALS['odt_buffer'] .= '</table:table>'; return true; }
/** * Displays the fields used by the "new user" form as well as the * "change login information / copy user" form. * * @param string $mode are we creating a new user or are we just * changing one? (allowed values: 'new', 'change') * * @global array $cfg the phpMyAdmin configuration * @global ressource $user_link the database connection * * @return void */ function PMA_displayLoginInformationFields($mode = 'new') { // Get user/host name lengths $fields_info = PMA_DBI_get_columns('mysql', 'user', null, true); $username_length = 16; $hostname_length = 41; foreach ($fields_info as $val) { if ($val['Field'] == 'User') { strtok($val['Type'], '()'); $v = strtok('()'); if (is_int($v)) { $username_length = $v; } } elseif ($val['Field'] == 'Host') { strtok($val['Type'], '()'); $v = strtok('()'); if (is_int($v)) { $hostname_length = $v; } } } unset($fields_info); if (isset($GLOBALS['username']) && strlen($GLOBALS['username']) === 0) { $GLOBALS['pred_username'] = '******'; } echo '<fieldset id="fieldset_add_user_login">' . "\n" . '<legend>' . __('Login Information') . '</legend>' . "\n" . '<div class="item">' . "\n" . '<label for="select_pred_username">' . "\n" . ' ' . __('User name') . ':' . "\n" . '</label>' . "\n" . '<span class="options">' . "\n" . ' <select name="pred_username" id="select_pred_username" title="' . __('User name') . '"' . "\n" . ' onchange="if (this.value == \'any\') { username.value = \'\'; } else if (this.value == \'userdefined\') { username.focus(); username.select(); }">' . "\n" . ' <option value="any"' . ((isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any') ? ' selected="selected"' : '') . '>' . __('Any user') . '</option>' . "\n" . ' <option value="userdefined"' . ((! isset($GLOBALS['pred_username']) || $GLOBALS['pred_username'] == 'userdefined') ? ' selected="selected"' : '') . '>' . __('Use text field') . ':</option>' . "\n" . ' </select>' . "\n" . '</span>' . "\n" . '<input type="text" name="username" maxlength="' . $username_length . '" title="' . __('User name') . '"' . (empty($GLOBALS['username']) ? '' : ' value="' . htmlspecialchars( isset($GLOBALS['new_username']) ? $GLOBALS['new_username'] : $GLOBALS['username'] ) . '"' ) . ' onchange="pred_username.value = \'userdefined\';" autofocus="autofocus" />' . "\n" . '</div>' . "\n" . '<div class="item">' . "\n" . '<label for="select_pred_hostname">' . "\n" . ' ' . __('Host') . ':' . "\n" . '</label>' . "\n" . '<span class="options">' . "\n" . ' <select name="pred_hostname" id="select_pred_hostname" title="' . __('Host') . '"' . "\n"; $_current_user = PMA_DBI_fetch_value('SELECT USER();'); if (! empty($_current_user)) { $thishost = str_replace("'", '', substr($_current_user, (strrpos($_current_user, '@') + 1))); if ($thishost == 'localhost' || $thishost == '127.0.0.1') { unset($thishost); } } echo ' onchange="if (this.value == \'any\') { hostname.value = \'%\'; } else if (this.value == \'localhost\') { hostname.value = \'localhost\'; } ' . (empty($thishost) ? '' : 'else if (this.value == \'thishost\') { hostname.value = \'' . addslashes(htmlspecialchars($thishost)) . '\'; } ') . 'else if (this.value == \'hosttable\') { hostname.value = \'\'; } else if (this.value == \'userdefined\') { hostname.focus(); hostname.select(); }">' . "\n"; unset($_current_user); // when we start editing a user, $GLOBALS['pred_hostname'] is not defined if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) { switch (strtolower($GLOBALS['hostname'])) { case 'localhost': case '127.0.0.1': $GLOBALS['pred_hostname'] = 'localhost'; break; case '%': $GLOBALS['pred_hostname'] = 'any'; break; default: $GLOBALS['pred_hostname'] = 'userdefined'; break; } } echo ' <option value="any"' . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'any') ? ' selected="selected"' : '') . '>' . __('Any host') . '</option>' . "\n" . ' <option value="localhost"' . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'localhost') ? ' selected="selected"' : '') . '>' . __('Local') . '</option>' . "\n"; if (! empty($thishost)) { echo ' <option value="thishost"' . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'thishost') ? ' selected="selected"' : '') . '>' . __('This Host') . '</option>' . "\n"; } unset($thishost); echo ' <option value="hosttable"' . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'hosttable') ? ' selected="selected"' : '') . '>' . __('Use Host Table') . '</option>' . "\n" . ' <option value="userdefined"' . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'userdefined') ? ' selected="selected"' : '') . '>' . __('Use text field') . ':</option>' . "\n" . ' </select>' . "\n" . '</span>' . "\n" . '<input type="text" name="hostname" maxlength="' . $hostname_length . '" value="' . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '') . '" title="' . __('Host') . '" onchange="pred_hostname.value = \'userdefined\';" />' . "\n" . PMA_showHint(__('When Host table is used, this field is ignored and values stored in Host table are used instead.')) . '</div>' . "\n" . '<div class="item">' . "\n" . '<label for="select_pred_password">' . "\n" . ' ' . __('Password') . ':' . "\n" . '</label>' . "\n" . '<span class="options">' . "\n" . ' <select name="pred_password" id="select_pred_password" title="' . __('Password') . '"' . "\n" . ' onchange="if (this.value == \'none\') { pma_pw.value = \'\'; pma_pw2.value = \'\'; } else if (this.value == \'userdefined\') { pma_pw.focus(); pma_pw.select(); }">' . "\n" . ($mode == 'change' ? ' <option value="keep" selected="selected">' . __('Do not change the password') . '</option>' . "\n" : '') . ' <option value="none"'; if (isset($GLOBALS['username']) && $mode != 'change') { echo ' selected="selected"'; } echo '>' . __('No Password') . '</option>' . "\n" . ' <option value="userdefined"' . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>' . __('Use text field') . ':</option>' . "\n" . ' </select>' . "\n" . '</span>' . "\n" . '<input type="password" id="text_pma_pw" name="pma_pw" title="' . __('Password') . '" onchange="pred_password.value = \'userdefined\';" />' . "\n" . '</div>' . "\n" . '<div class="item" id="div_element_before_generate_password">' . "\n" . '<label for="text_pma_pw2">' . "\n" . ' ' . __('Re-type') . ':' . "\n" . '</label>' . "\n" . '<span class="options"> </span>' . "\n" . '<input type="password" name="pma_pw2" id="text_pma_pw2" title="' . __('Re-type') . '" onchange="pred_password.value = \'userdefined\';" />' . "\n" . '</div>' . "\n" // Generate password added here via jQuery . '</fieldset>' . "\n"; } // end of the 'PMA_displayUserAndHostFields()' function
/** * Sets criteria tables and columns * */ private function _setCriteriaTablesAndColumns() { // The tables list sent by a previously submitted form if (PMA_isValid($_REQUEST['TableList'], 'array')) { foreach ($_REQUEST['TableList'] as $each_table) { $this->_criteriaTables[$each_table] = ' selected="selected"'; } } // end if $all_tables = PMA_DBI_query('SHOW TABLES FROM ' . $this->getCommonFunctions()->backquote($this->_db) . ';', null, PMA_DBI_QUERY_STORE); $all_tables_count = PMA_DBI_num_rows($all_tables); if (0 == $all_tables_count) { PMA_Message::error(__('No tables found in database.'))->display(); exit; } // The tables list gets from MySQL while (list($table) = PMA_DBI_fetch_row($all_tables)) { $columns = PMA_DBI_get_columns($this->_db, $table); if (empty($this->_criteriaTables[$table]) && !empty($_REQUEST['TableList'])) { $this->_criteriaTables[$table] = ''; } else { $this->_criteriaTables[$table] = ' selected="selected"'; } // end if // The fields list per selected tables if ($this->_criteriaTables[$table] == ' selected="selected"') { $each_table = $this->getCommonFunctions()->backquote($table); $this->_columnNames[] = $each_table . '.*'; foreach ($columns as $each_column) { $each_column = $each_table . '.' . $this->getCommonFunctions()->backquote($each_column['Field']); $this->_columnNames[] = $each_column; // increase the width if necessary $this->_form_column_width = max(strlen($each_column), $this->_form_column_width); } // end foreach } // end if } // end while PMA_DBI_free_result($all_tables); // sets the largest width found $this->_realwidth = $this->_form_column_width . 'ex'; }