diff --git a/db_operations.php b/db_operations.php index 933ffa8f7e..7ce004833c 100644 --- a/db_operations.php +++ b/db_operations.php @@ -20,8 +20,8 @@ require_once 'libraries/mysql_charsets.lib.php'; // add a javascript file for jQuery functions to handle Ajax actions $response = PMA_Response::getInstance(); -$header = $response->getHeader(); -$scripts = $header->getScripts(); +$header = $response->getHeader(); +$scripts = $header->getScripts(); $scripts->addFile('db_operations.js'); /** @@ -135,11 +135,21 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) { $views = array(); // remove all foreign key constraints, otherwise we can get errors - include_once 'libraries/export/sql.php'; + $export_sql_plugin = PMA_getPlugin( + "export", + "sql", + 'libraries/plugins/export/', + array( + 'export_type' => $export_type, + 'single_table' => isset($single_table) + ) + ); foreach ($tables_full as $each_table => $tmp) { $sql_constraints = ''; $sql_drop_foreign_keys = ''; - $sql_structure = PMA_getTableDef($db, $each_table, "\n", '', false, false); + $sql_structure = $export_sql_plugin->getTableDef( + $db, $each_table, "\n", '', false, false + ); if ($move && ! empty($sql_drop_foreign_keys)) { PMA_DBI_query($sql_drop_foreign_keys); } @@ -157,7 +167,9 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) { if (PMA_Table::isView($db, $each_table)) { $views[] = $each_table; // Create stand-in definition to resolve view dependencies - $sql_view_standin = PMA_getTableDefStandIn($db, $each_table, "\n"); + $sql_view_standin = $export_sql_plugin->getTableDefStandIn( + $db, $each_table, "\n" + ); PMA_DBI_select_db($newname); PMA_DBI_query($sql_view_standin); $GLOBALS['sql_query'] .= "\n" . $sql_view_standin; diff --git a/export.php b/export.php index bb8f290d77..5d81a4b082 100644 --- a/export.php +++ b/export.php @@ -23,9 +23,11 @@ foreach ($_POST as $one_post_param => $one_post_value) { PMA_checkParameters(array('what', 'export_type')); -// Scan plugins -$export_list = PMA_getPlugins( - 'libraries/export/', +// export class instance, not array of properties, as before +$export_plugin = PMA_getPlugin( + "export", + $what, + 'libraries/plugins/export/', array( 'export_type' => $export_type, 'single_table' => isset($single_table) @@ -36,8 +38,10 @@ $export_list = PMA_getPlugins( $type = $what; // Check export type -if (! isset($export_list[$type])) { +if (! isset($export_plugin)) { PMA_fatalError(__('Bad type!')); +} else { + $export_plugin_properties = $export_plugin->getProperties(); } /** @@ -86,7 +90,8 @@ if ($_REQUEST['output_format'] == 'astext') { } // Does export require to be into file? -if (isset($export_list[$type]['force_file']) && ! $asfile) { +if (isset($export_plugin_properties['force_file']) && ! $asfile) { + $message = PMA_Message::error(__('Selected export type has to be saved in file!')); if ($export_type == 'server') { $active_page = 'server_export.php'; @@ -118,9 +123,6 @@ if ($export_type == 'server') { PMA_fatalError(__('Bad parameters!')); } -// Get the functions specific to the export type -require 'libraries/export/' . PMA_securePath($type) . '.php'; - /** * Increase time limit for script execution and initializes some variables */ @@ -321,15 +323,14 @@ if ($asfile) { $filename = PMA_sanitizeFilename($filename); // Grab basic dump extension and mime type - // Check if the user already added extension; - // get the substring where the extension would be if it was included - $extension_start_pos = strlen($filename) - strlen($export_list[$type]['extension']) - 1; + // Check if the user already added extension; get the substring where the extension would be if it was included + $extension_start_pos = strlen($filename) - strlen($export_plugin_properties['extension']) - 1; $user_extension = substr($filename, $extension_start_pos, strlen($filename)); - $required_extension = "." . $export_list[$type]['extension']; + $required_extension = "." . $export_plugin_properties['extension']; if (strtolower($user_extension) != $required_extension) { $filename .= $required_extension; } - $mime_type = $export_list[$type]['mime_type']; + $mime_type = $export_plugin_properties['mime_type']; // If dump is going to be compressed, set correct mime_type and add // compression to extension @@ -352,17 +353,25 @@ if ($save_on_server) { unset($message); if (file_exists($save_filename) && ((! $quick_export && empty($onserverover)) - || ($quick_export && $_REQUEST['quick_export_onserverover'] != 'saveitover')) + || ($quick_export + && $_REQUEST['quick_export_onserverover'] != 'saveitover')) ) { - $message = PMA_Message::error(__('File %s already exists on server, change filename or check overwrite option.')); + $message = PMA_Message::error(__( + 'File %s already exists on server, change filename or check' + . ' overwrite option.' + )); $message->addParam($save_filename); } else { if (is_file($save_filename) && ! is_writable($save_filename)) { - $message = PMA_Message::error(__('The web server does not have permission to save the file %s.')); + $message = PMA_Message::error(__( + 'The web server does not have permission to save the file %s.' + )); $message->addParam($save_filename); } else { if (! $file_handle = @fopen($save_filename, 'w')) { - $message = PMA_Message::error(__('The web server does not have permission to save the file %s.')); + $message = PMA_Message::error(__( + 'The web server does not have permission to save the file %s.' + )); $message->addParam($save_filename); } } @@ -452,7 +461,7 @@ if (! $save_on_server) { do { // Add possibly some comments to export - if (! PMA_exportHeader()) { + if (! $export_plugin->exportHeader($db)) { break; } @@ -468,7 +477,7 @@ do { } // Include dates in export? - $do_dates = isset($GLOBALS[$what . '_dates']); + $do_dates = isset($GLOBALS[$what . '_dates']); /** * Builds the dump @@ -485,17 +494,17 @@ do { && strpos(' ' . $tmp_select, '|' . $current_db . '|')) || ! isset($tmp_select) ) { - if (! PMA_exportDBHeader($current_db)) { + if (! $export_plugin->exportDBHeader($current_db)) { break 2; } - if (! PMA_exportDBCreate($current_db)) { + if (! $export_plugin->exportDBCreate($current_db)) { break 2; } - if (function_exists('PMA_exportRoutines') + if (method_exists($export_plugin, 'exportRoutines') && strpos($GLOBALS['sql_structure_or_data'], 'structure') !== false && isset($GLOBALS['sql_procedure_function']) ) { - PMA_exportRoutines($current_db); + $export_plugin->exportRoutines($current_db); } $tables = PMA_DBI_get_tables($current_db); @@ -512,7 +521,7 @@ do { ) { // for a view, export a stand-in definition of the table // to resolve view dependencies - if (! PMA_exportStructure( + if (! $export_plugin->exportStructure( $current_db, $table, $crlf, $err_url, $is_view ? 'stand_in' : 'create_table', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -527,7 +536,7 @@ do { ) { $local_query = 'SELECT * FROM ' . PMA_backquote($current_db) . '.' . PMA_backquote($table); - if (! PMA_exportData($current_db, $table, $crlf, $err_url, $local_query)) { + if (! $export_plugin->exportData($current_db, $table, $crlf, $err_url, $local_query)) { break 3; } } @@ -536,7 +545,7 @@ do { if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data' ) { - if (! PMA_exportStructure( + if (! $export_plugin->exportStructure( $current_db, $table, $crlf, $err_url, 'triggers', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -550,7 +559,7 @@ do { if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data' ) { - if (! PMA_exportStructure( + if (! $export_plugin->exportStructure( $current_db, $view, $crlf, $err_url, 'create_view', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -559,21 +568,21 @@ do { } } } - if (! PMA_exportDBFooter($current_db)) { + if (! $export_plugin->exportDBFooter($current_db)) { break 2; } } } } elseif ($export_type == 'database') { - if (! PMA_exportDBHeader($db)) { + if (! $export_plugin->exportDBHeader($db)) { break; } - if (function_exists('PMA_exportRoutines') + if (method_exists($export_plugin, 'exportRoutines') && strpos($GLOBALS['sql_structure_or_data'], 'structure') !== false && isset($GLOBALS['sql_procedure_function']) ) { - PMA_exportRoutines($db); + $export_plugin->exportRoutines($db); } $i = 0; @@ -591,7 +600,7 @@ do { ) { // for a view, export a stand-in definition of the table // to resolve view dependencies - if (! PMA_exportStructure( + if (! $export_plugin->exportStructure( $db, $table, $crlf, $err_url, $is_view ? 'stand_in' : 'create_table', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -606,16 +615,14 @@ do { ) { $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table); - if (! PMA_exportData($db, $table, $crlf, $err_url, $local_query)) { + if (! $export_plugin->exportData($db, $table, $crlf, $err_url, $local_query)) { break 2; } } // now export the triggers (needs to be done after the data because // triggers can modify already imported tables) - if ($GLOBALS[$what . '_structure_or_data'] == 'structure' - || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data' - ) { - if (! PMA_exportStructure( + if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') { + if (! $export_plugin->exportStructure( $db, $table, $crlf, $err_url, 'triggers', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -626,10 +633,8 @@ do { } foreach ($views as $view) { // no data export for a view - if ($GLOBALS[$what . '_structure_or_data'] == 'structure' - || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data' - ) { - if (! PMA_exportStructure( + if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') { + if (! $export_plugin->exportStructure( $db, $view, $crlf, $err_url, 'create_view', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -639,11 +644,11 @@ do { } } - if (! PMA_exportDBFooter($db)) { + if (! $export_plugin->exportDBFooter($db)) { break; } } else { - if (! PMA_exportDBHeader($db)) { + if (! $export_plugin->exportDBHeader($db)) { break; } // We export just one table @@ -657,10 +662,8 @@ do { } $is_view = PMA_Table::isView($db, $table); - if ($GLOBALS[$what . '_structure_or_data'] == 'structure' - || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data' - ) { - if (! PMA_exportStructure( + if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') { + if (! $export_plugin->exportStructure( $db, $table, $crlf, $err_url, $is_view ? 'create_view' : 'create_table', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -684,10 +687,12 @@ do { $local_query = $sql_query . $add_query; PMA_DBI_select_db($db); } else { - $local_query = 'SELECT * FROM ' . PMA_backquote($db) - . '.' . PMA_backquote($table) . $add_query; + $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' + . PMA_backquote($table) . $add_query; } - if (! PMA_exportData($db, $table, $crlf, $err_url, $local_query)) { + if (! $export_plugin->exportData($db, $table, $crlf, $err_url, + $local_query + )) { break; } } @@ -696,7 +701,7 @@ do { if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data' ) { - if (! PMA_exportStructure( + if (! $export_plugin->exportStructure( $db, $table, $crlf, $err_url, 'triggers', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -704,11 +709,11 @@ do { break 2; } } - if (! PMA_exportDBFooter($db)) { + if (! $export_plugin->exportDBFooter($db)) { break; } } - if (! PMA_exportFooter()) { + if (! $export_plugin->exportFooter()) { break; } diff --git a/import.php b/import.php index 85dfaea5e1..86488a1947 100644 --- a/import.php +++ b/import.php @@ -428,13 +428,20 @@ if (! $error && isset($skip)) { if (! $error) { // Check for file existance - if (!file_exists('libraries/import/' . $format . '.php')) { + require_once("libraries/plugin_interface.lib.php"); + $import_plugin = PMA_getPlugin( + "import", + $format, + 'libraries/plugins/import/' + ); + if ($import_plugin == null) { $error = true; - $message = PMA_Message::error(__('Could not load import plugins, please check your installation!')); + $message = PMA_Message::error( + __('Could not load import plugins, please check your installation!') + ); } else { // Do the real import - $plugin_param = $import_type; - include 'libraries/import/' . $format . '.php'; + $import_plugin->doImport(); } } diff --git a/libraries/DisplayResults.class.php b/libraries/DisplayResults.class.php index 2d0fb66dd4..c4eb12fea0 100644 --- a/libraries/DisplayResults.class.php +++ b/libraries/DisplayResults.class.php @@ -13,33 +13,33 @@ if (! defined('PHPMYADMIN')) { * Handle all the functionalities related to displaying results * of sql queries, stored procedure, browsing sql processes or * displaying binary log. - * + * * @package PhpMyAdmin */ class PMA_DisplayResults { - + const NO_EDIT_OR_DELETE = 'nn'; const UPDATE_ROW = 'ur'; const DELETE_ROW = 'dr'; const KILL_PROCESS = 'kp'; - + const POSITION_LEFT = 'left'; const POSITION_RIGHT = 'right'; const POSITION_BOTH = 'both'; const POSITION_NONE = 'none'; - + const DISP_DIR_HORIZONTAL = 'horizontal'; const DISP_DIR_HORIZONTAL_FLIPPED = 'horizontalflipped'; const DISP_DIR_VERTICAL = 'vertical'; - + const DISPLAY_FULL_TEXT = 'F'; const DISPLAY_PARTIAL_TEXT = 'P'; - + const HEADER_FLIP_TYPE_AUTO = 'auto'; const HEADER_FLIP_TYPE_CSS = 'css'; const HEADER_FLIP_TYPE_FAKE = 'fake'; - + const DATE_FIELD = 'date'; const DATETIME_FIELD = 'datetime'; const TIMESTAMP_FIELD = 'timestamp'; @@ -47,34 +47,34 @@ class PMA_DisplayResults const GEOMETRY_FIELD = 'geometry'; const BLOB_FIELD = 'BLOB'; const BINARY_FIELD = 'BINARY'; - + const RELATIONAL_KEY = 'K'; const RELATIONAL_DISPLAY_COLUMN = 'D'; - + const GEOMETRY_DISP_GEOM = 'GEOM'; const GEOMETRY_DISP_WKT = 'WKT'; const GEOMETRY_DISP_WKB = 'WKB'; - + const SMART_SORT_ORDER = 'SMART'; const ASCENDING_SORT_DIR = 'ASC'; const DESCENDING_SORT_DIR = 'DESC'; - + const TABLE_TYPE_INNO_DB = 'InnoDB'; const ALL_ROWS = 'all'; const QUERY_TYPE_SELECT = 'SELECT'; - - + + private $_db, $_table, $_goto, $_sql_query, $_cfgRelation; /** * Constructor for PMA_DisplayResults class - * + * * @param string $db the database name * @param string $table the table name * @param string $goto the URL to go back in case of errors * @param string $sql_query the SQL query - * + * * @access public */ public function __construct($db, $table, $goto, $sql_query) @@ -275,9 +275,9 @@ class PMA_DisplayResults * "SELECT * FROM ..." * * @return boolean - * + * * @access private - * + * * @see _getTableHeaders(), _getColumnParams() */ private function _isSelect() @@ -534,7 +534,7 @@ class PMA_DisplayResults * @param integer $pos_prev the offset for the "previous" page * * @return string html content - * + * * @access private * * @see _getTableNavigation() @@ -556,9 +556,9 @@ class PMA_DisplayResults * Prepare Show All button for table navigation * * @param string $html_sql_query the sql encoded by html special characters - * + * * @return string html content - * + * * @access private * * @see _getTableNavigation() @@ -590,7 +590,7 @@ class PMA_DisplayResults * @param integer $num_rows the total number of rows returned by the * * @return string $buttons_html html content - * + * * @access private * * @see _getTableNavigation() @@ -652,7 +652,7 @@ class PMA_DisplayResults * @param string $id_for_direction_dropdown the id for the direction dropdown * * @return string $additional_fields_html html content - * + * * @access private * * @see _getTableNavigation() @@ -1164,7 +1164,7 @@ class PMA_DisplayResults * @param string $unsorted_sql_query the unsorted sql query * * @return string $drop_down_html html content - * + * * @access private * * @see _getTableHeaders() @@ -1249,7 +1249,7 @@ class PMA_DisplayResults * Prepare data for column restoring and show/hide * * @return string $data_html html content - * + * * @access private * * @see _getTableHeaders() @@ -1292,7 +1292,7 @@ class PMA_DisplayResults * Prepare option fields block * * @return string $options_html html content - * + * * @access private * * @see _getTableHeaders() @@ -1413,7 +1413,7 @@ class PMA_DisplayResults * Get full/partial text button or link * * @return string html content - * + * * @access private * * @see _getTableHeaders() @@ -1455,7 +1455,7 @@ class PMA_DisplayResults * @param string $del_lnk the delete link of current row * * @return string $form_html html content - * + * * @access private * * @see _getTableHeaders() @@ -1497,7 +1497,7 @@ class PMA_DisplayResults * @param array $fields_meta set of field properties * * @return string $comment html content - * + * * @access private * * @see _getTableHeaders() @@ -1528,7 +1528,7 @@ class PMA_DisplayResults * @param string $name_to_use_in_sort the sorting column name * * @return boolean $is_in_sort the column sorted or not - * + * * @access private * * @see _getTableHeaders() @@ -1585,7 +1585,7 @@ class PMA_DisplayResults * @param integer $column_index the index of the column * * @return array 2 element array - $sort_order, $order_img - * + * * @access private * * @see _getTableHeaders() @@ -1651,7 +1651,7 @@ class PMA_DisplayResults * @param string $order_url the url for sort * * @return string the sort order link - * + * * @access private * * @see _getTableHeaders() @@ -1717,7 +1717,7 @@ class PMA_DisplayResults * @param string $comments the comment for the column * * @return string $draggable_html html content - * + * * @access private * * @see _getTableHeaders() @@ -1774,7 +1774,7 @@ class PMA_DisplayResults * @param string $comments the comment for the column * * @return string $draggable_html html content - * + * * @access private * * @see _getTableHeaders() @@ -1838,9 +1838,9 @@ class PMA_DisplayResults * @param string $value value to display * * @return string the td - * + * * @access private - * + * * @see _getDataCellForBlobColumns(), _getDataCellForGeometryColumns(), * _getDataCellForNonNumericAndNonBlobColumns() */ @@ -1860,9 +1860,9 @@ class PMA_DisplayResults * @param string $align cell allignment * * @return string the td - * + * * @access private - * + * * @see _getDataCellForNumericColumns(), _getDataCellForBlobColumns(), * _getDataCellForGeometryColumns(), * _getDataCellForNonNumericAndNonBlobColumns() @@ -1887,9 +1887,9 @@ class PMA_DisplayResults * @param string $align cell allignment * * @return string the td - * + * * @access private - * + * * @see _getDataCellForNumericColumns(), _getDataCellForBlobColumns(), * _getDataCellForGeometryColumns(), * _getDataCellForNonNumericAndNonBlobColumns() @@ -1907,23 +1907,25 @@ class PMA_DisplayResults /** * Adds the relavant classes. * - * @param string $class class of table cell - * @param bool $condition_field whether to add CSS class condition - * @param object $meta the meta-information about this field - * @param string $nowrap avoid wrapping - * @param bool $is_field_truncated is field truncated (display ...) - * @param string $transform_function transformation function - * @param string $default_function default transformation function + * @param string $class class of table cell + * @param bool $condition_field whether to add CSS class condition + * @param object $meta the meta-information about the field + * @param string $nowrap avoid wrapping + * @param bool $is_field_truncated is field truncated (display ...) + * @param string $transformation_plugin transformation plugin. + * Can also be the default function: + * PMA_mimeDefaultFunction + * @param string $default_function default transformation function * * @return string the list of classes - * + * * @access private - * + * * @see _buildNullDisplay(), _getRowData() */ private function _addClass( $class, $condition_field, $meta, $nowrap, $is_field_truncated = false, - $transform_function = '', $default_function = '' + $transformation_plugin = '', $default_function = '' ) { // Define classes to be added to this data field based on the type of data @@ -1949,7 +1951,7 @@ class PMA_DisplayResults return $class . ($condition_field ? ' condition' : '') . $nowrap . ' ' . ($is_field_truncated ? ' truncated' : '') - . ($transform_function != $default_function ? ' transformed' : '') + . ($transformation_plugin != $default_function ? ' transformed' : '') . $enum_class . $set_class . $bit_class . $mime_type_class; } // end of the '_addClass()' function @@ -2154,7 +2156,7 @@ class PMA_DisplayResults // Wrap MIME-transformations. [MIME] $default_function = 'PMA_mimeDefaultFunction'; // default_function - $transform_function = $default_function; + $transformation_plugin = $default_function; $transform_options = array(); if ($GLOBALS['cfgRelation']['mimework'] @@ -2165,40 +2167,26 @@ class PMA_DisplayResults && isset($GLOBALS['mime_map'][$meta->name]['transformation']) && !empty($GLOBALS['mime_map'][$meta->name]['transformation']) ) { - - $include_file - = './libraries/transformations/' . PMA_securePath( - $GLOBALS['mime_map'][$meta->name]['transformation'] - ); - + $file = $GLOBALS['mime_map'][$meta->name]['transformation']; + $include_file = 'libraries/plugins/transformations/' . $file; if (file_exists($include_file)) { - - $transformfunction_name = 'PMA_transformation_' - . str_replace( - '.inc.php', '', - $GLOBALS['mime_map'][$meta->name]['transformation'] - ); - include_once $include_file; - - if (function_exists($transformfunction_name)) { - - $transform_function = $transformfunction_name; - - $transform_options = PMA_transformation_getOptions( - isset($GLOBALS['mime_map'][$meta->name] - ['transformation_options'] - ) - ? $GLOBALS['mime_map'][$meta->name] + $class_name = str_replace('.class.php', '', $file); + // todo add $plugin_manager + $plugin_manager = null; + $transformation_plugin = new $class_name($plugin_manager); + $transform_options = PMA_transformation_getOptions( + isset($GLOBALS['mime_map'][$meta->name] ['transformation_options'] - : '' - ); - - $meta->mimetype = str_replace( - '_', '/', - $GLOBALS['mime_map'][$meta->name]['mimetype'] - ); - } + ) + ? $GLOBALS['mime_map'][$meta->name] + ['transformation_options'] + : '' + ); + $meta->mimetype = str_replace( + '_', '/', + $GLOBALS['mime_map'][$meta->name]['mimetype'] + ); } // end if file_exists } // end if transformation is set } // end if mime/transformation works. @@ -2228,8 +2216,9 @@ class PMA_DisplayResults $GLOBALS['vertical_display']['data'][$row_no][$i] = $this->_getDataCellForNumericColumns( $row[$i], $class, $condition_field, $meta, $map, - $is_field_truncated, $analyzed_sql, $transform_function, - $default_function, $transform_options + $is_field_truncated, $analyzed_sql, + $transformation_plugin, $default_function, + $transform_options ); } elseif (stristr($meta->type, self::BLOB_FIELD)) { @@ -2242,7 +2231,7 @@ class PMA_DisplayResults $GLOBALS['vertical_display']['data'][$row_no][$i] = $this->_getDataCellForBlobColumns( $row[$i], $class, $meta, $_url_params, $field_flags, - $transform_function, $default_function, + $transformation_plugin, $default_function, $transform_options, $condition_field, $is_field_truncated ); @@ -2256,8 +2245,9 @@ class PMA_DisplayResults $GLOBALS['vertical_display']['data'][$row_no][$i] = $this->_getDataCellForGeometryColumns( $row[$i], $class, $meta, $map, $_url_params, - $condition_field, $transform_function, $default_function, - $transform_options, $is_field_truncated, $analyzed_sql + $condition_field, $transformation_plugin, + $default_function, $transform_options, + $is_field_truncated, $analyzed_sql ); } else { @@ -2266,9 +2256,9 @@ class PMA_DisplayResults $GLOBALS['vertical_display']['data'][$row_no][$i] = $this->_getDataCellForNonNumericAndNonBlobColumns( $row[$i], $class, $meta, $map, $_url_params, - $condition_field, $transform_function, $default_function, - $transform_options, $is_field_truncated, $analyzed_sql, - $dt_result, $i + $condition_field, $transformation_plugin, + $default_function, $transform_options, + $is_field_truncated, $analyzed_sql, $dt_result, $i ); } @@ -2393,9 +2383,9 @@ class PMA_DisplayResults * Get url sql query without conditions to shorten URLs * * @param array $analyzed_sql analyzed query - * + * * @return string $url_sql analyzed sql query - * + * * @access private * * @see _getTableBody() @@ -2432,7 +2422,7 @@ class PMA_DisplayResults * Get column order and column visibility * * @return array 2 element array - $col_order, $col_visib - * + * * @access private * * @see _getTableBody() @@ -2461,7 +2451,7 @@ class PMA_DisplayResults * @param boolean $directionCondition the directional condition * * @return string $vertical_disp_html html content - * + * * @access private * * @see _getTableBody() @@ -2662,7 +2652,7 @@ class PMA_DisplayResults * @param string $js_conf text for the JS confirmation * * @return string html content - * + * * @access private * * @see _getTableBody() @@ -2698,7 +2688,7 @@ class PMA_DisplayResults * @param integer $row_no the row index * * @return string $class the resetted class - * + * * @access private * * @see _getTableBody() @@ -2736,7 +2726,7 @@ class PMA_DisplayResults * @param string $type the type of the column field * * @return string $field_type_class the class for the column - * + * * @access private * * @see _getTableBody() @@ -2759,26 +2749,30 @@ class PMA_DisplayResults /** * Prepare data cell for numeric type fields * - * @param string $column the relavent column in data row - * @param string $class the html class for column - * @param boolean $condition_field the column should highlighted or not - * @param object $meta the meta-information about this field - * @param array $map the list of relations - * @param boolean $is_field_truncated the condition for blob data replacements - * @param array $analyzed_sql the analyzed query - * @param string $transform_function the name of transformation function - * @param string $default_function the default transformation function - * @param string $transform_options the transformation parameters + * @param string $column the relavent column in data row + * @param string $class the html class for column + * @param boolean $condition_field the column should highlighted + * or not + * @param object $meta the meta-information about this + * field + * @param array $map the list of relations + * @param boolean $is_field_truncated the condition for blob data + * replacements + * @param array $analyzed_sql the analyzed query + * @param string $transformation_plugin the name of transformation plugin + * @param string $default_function the default transformation function + * @param string $transform_options the transformation parameters * * @return string $cell the prepared cell, html content - * + * * @access private * * @see _getTableBody() */ private function _getDataCellForNumericColumns( $column, $class, $condition_field, $meta, $map, $is_field_truncated, - $analyzed_sql, $transform_function, $default_function, $transform_options + $analyzed_sql, $transformation_plugin, $default_function, + $transform_options ) { if (! isset($column) || is_null($column)) { @@ -2795,7 +2789,7 @@ class PMA_DisplayResults $cell = $this->_getRowData( 'right '.$class, $condition_field, $analyzed_sql, $meta, $map, $column, - $transform_function, $default_function, $nowrap, + $transformation_plugin, $default_function, $nowrap, $where_comparison, $transform_options, $is_field_truncated ); @@ -2814,25 +2808,29 @@ class PMA_DisplayResults /** * Get data cell for blob type fields * - * @param string $column the relavent column in data row - * @param string $class the html class for column - * @param object $meta the meta-information about this field - * @param array $_url_params the parameters for generate url - * @param string $field_flags field flags for column(blob, primary etc) - * @param string $transform_function the name of transformation function - * @param string $default_function the default transformation function - * @param string $transform_options the transformation parameters - * @param boolean $condition_field the column should highlighted or not - * @param boolean $is_field_truncated the condition for blob data replacements + * @param string $column the relavent column in data row + * @param string $class the html class for column + * @param object $meta the meta-information about this + * field + * @param array $_url_params the parameters for generate url + * @param string $field_flags field flags for column(blob, + * primary etc) + * @param string $transformation_plugin the name of transformation function + * @param string $default_function the default transformation function + * @param string $transform_options the transformation parameters + * @param boolean $condition_field the column should highlighted + * or not + * @param boolean $is_field_truncated the condition for blob data + * replacements + * + * @return string $cell the prepared cell, html content * - * @return string $cell the prepared cell, html content - * * @access private * * @see _getTableBody() */ private function _getDataCellForBlobColumns( - $column, $class, $meta, $_url_params, $field_flags, $transform_function, + $column, $class, $meta, $_url_params, $field_flags, $transformation_plugin, $default_function, $transform_options, $condition_field, $is_field_truncated ) { @@ -2849,7 +2847,7 @@ class PMA_DisplayResults $blobtext = $this->_handleNonPrintableContents( self::BLOB_FIELD, (isset($column) ? $column : ''), - $transform_function, $transform_options, + $transformation_plugin, $transform_options, $default_function, $meta, $_url_params ); @@ -2879,8 +2877,12 @@ class PMA_DisplayResults // displays all space characters, 4 space // characters for tabulations and / - $column = ($default_function != $transform_function) - ? $transform_function($column, $transform_options, $meta) + $column = ($default_function != $transformation_plugin) + ? $transformation_plugin->applyTransformation( + $column, + $transform_options, + $meta + ) : $default_function($column, array(), $meta); if ($is_field_truncated) { @@ -2902,27 +2904,27 @@ class PMA_DisplayResults /** * Get data cell for geometry type fields * - * @param string $column the relavent column in data row - * @param string $class the html class for column - * @param object $meta the meta-information about this field - * @param array $map the list of relations - * @param array $_url_params the parameters for generate url - * @param boolean $condition_field the column should highlighted or not - * @param string $transform_function the name of transformation function - * @param string $default_function the default transformation function - * @param string $transform_options the transformation parameters - * @param boolean $is_field_truncated the condition for blob data replacements - * @param array $analyzed_sql the analyzed query + * @param string $column the relavent column in data row + * @param string $class the html class for column + * @param object $meta the meta-information about this field + * @param array $map the list of relations + * @param array $_url_params the parameters for generate url + * @param boolean $condition_field the column should highlighted or not + * @param string $transformation_plugin the name of transformation function + * @param string $default_function the default transformation function + * @param string $transform_options the transformation parameters + * @param boolean $is_field_truncated the condition for blob data replacements + * @param array $analyzed_sql the analyzed query + * + * @return string $cell the prepared data cell, html content * - * @return string $cell the prepared data cell, html content - * * @access private * * @see _getTableBody() */ private function _getDataCellForGeometryColumns( $column, $class, $meta, $map, $_url_params, $condition_field, - $transform_function, $default_function, $transform_options, + $transformation_plugin, $default_function, $transform_options, $is_field_truncated, $analyzed_sql ) { @@ -2937,7 +2939,7 @@ class PMA_DisplayResults $geometry_text = $this->_handleNonPrintableContents( strtoupper(self::GEOMETRY_FIELD), - (isset($column) ? $column : ''), $transform_function, + (isset($column) ? $column : ''), $transformation_plugin, $transform_options, $default_function, $meta ); @@ -2965,7 +2967,7 @@ class PMA_DisplayResults $cell = $this->_getRowData( $class, $condition_field, $analyzed_sql, $meta, $map, - $wktval, $transform_function, $default_function, '', + $wktval, $transformation_plugin, $default_function, '', $where_comparison, $transform_options, $is_field_truncated ); @@ -2999,14 +3001,14 @@ class PMA_DisplayResults $cell = $this->_getRowData( $class, $condition_field, $analyzed_sql, $meta, $map, $wkbval, - $transform_function, $default_function, '', + $transformation_plugin, $default_function, '', $where_comparison, $transform_options, $is_field_truncated ); } else { $wkbval = $this->_handleNonPrintableContents( - self::BINARY_FIELD, $column, $transform_function, + self::BINARY_FIELD, $column, $transformation_plugin, $transform_options, $default_function, $meta, $_url_params ); @@ -3028,30 +3030,32 @@ class PMA_DisplayResults /** * Get data cell for non numeric and non blob type fields * - * @param string $column the relavent column in data row - * @param string $class the html class for column - * @param object $meta the meta-information about this field - * @param array $map the list of relations - * @param array $_url_params the parameters for generate url - * @param boolean $condition_field the column should highlighted or not - * @param string $transform_function the name of transformation function - * @param string $default_function the default transformation function - * @param string $transform_options the transformation parameters - * @param boolean $is_field_truncated the condition for blob data replacements - * @param array $analyzed_sql the analyzed query - * @param integer &$dt_result the link id associated to the query - * which results have to be displayed - * @param integer $col_index the column index + * @param string $column the relavent column in data row + * @param string $class the html class for column + * @param object $meta the meta-information about the field + * @param array $map the list of relations + * @param array $_url_params the parameters for generate url + * @param boolean $condition_field the column should highlighted + * or not + * @param string $transformation_plugin the name of transformation function + * @param string $default_function the default transformation function + * @param string $transform_options the transformation parameters + * @param boolean $is_field_truncated the condition for blob data + * replacements + * @param array $analyzed_sql the analyzed query + * @param integer &$dt_result the link id associated to the query + * which results have to be displayed + * @param integer $col_index the column index * * @return string $cell the prepared data cell, html content - * + * * @access private * * @see _getTableBody() */ private function _getDataCellForNonNumericAndNonBlobColumns( $column, $class, $meta, $map, $_url_params, $condition_field, - $transform_function, $default_function, $transform_options, + $transformation_plugin, $default_function, $transform_options, $is_field_truncated, $analyzed_sql, &$dt_result, $col_index ) { @@ -3065,7 +3069,7 @@ class PMA_DisplayResults // (unless it's a link-type transformation) if (PMA_strlen($column) > $GLOBALS['cfg']['LimitChars'] && ($_SESSION['tmp_user_values']['display_text'] == self::DISPLAY_PARTIAL_TEXT) - && !strpos($transform_function, 'link') === true + && ! strpos($transformation_plugin, 'Link') === true ) { $column = PMA_substr($column, 0, $GLOBALS['cfg']['LimitChars']) . '...'; @@ -3108,7 +3112,7 @@ class PMA_DisplayResults // we show the BINARY message and field's size // (or maybe use a transformation) $column = $this->_handleNonPrintableContents( - self::BINARY_FIELD, $column, $transform_function, + self::BINARY_FIELD, $column, $transformation_plugin, $transform_options, $default_function, $meta, $_url_params ); @@ -3125,11 +3129,11 @@ class PMA_DisplayResults } else { // transform functions may enable no-wrapping: - $function_nowrap = $transform_function . '_nowrap'; + $function_nowrap = 'applyTransformationNoWrap'; - $bool_nowrap = (($default_function != $transform_function) - && function_exists($function_nowrap)) - ? $function_nowrap($transform_options) + $bool_nowrap = (($default_function != $transformation_plugin) + && function_exists($transformation_plugin->$function_nowrap())) + ? $transformation_plugin->$function_nowrap($transform_options) : false; // do not wrap if date field type @@ -3142,7 +3146,7 @@ class PMA_DisplayResults $cell = $this->_getRowData( $class, $condition_field, $analyzed_sql, $meta, $map, $column, - $transform_function, $default_function, $nowrap, + $transformation_plugin, $default_function, $nowrap, $where_comparison, $transform_options, $is_field_truncated ); @@ -3364,7 +3368,7 @@ class PMA_DisplayResults * @param string $dir _left / _right * * @return $checkBoxes_html html content - * + * * @access private * * @see _getVerticalTable() @@ -3408,9 +3412,9 @@ class PMA_DisplayResults * @todo move/split into SQL class!? * @todo currently this is called twice unnecessary * @todo ignore LIMIT and ORDER in query!? - * + * * @return void - * + * * @access public * * @see sql.php file @@ -3885,7 +3889,7 @@ class PMA_DisplayResults * Get offsets for next page and previous page * * @return array array with two elements - $pos_next, $pos_prev - * + * * @access private * * @see getTable() @@ -3921,7 +3925,7 @@ class PMA_DisplayResults * * @return array 3 element array: $sort_expression, * $sort_expression_nodirection, $sort_direction - * + * * @access private * * @see getTable() @@ -3969,10 +3973,10 @@ class PMA_DisplayResults * @param integer $num_rows the total number of rows returned * by the SQL query * @param string $sort_expression_nodirection sort expression without direction - * + * * @return string html content * null if not found sorted column - * + * * @access private * * @see getTable() @@ -4012,7 +4016,7 @@ class PMA_DisplayResults // initializing default arguments $default_function = 'PMA_mimeDefaultFunction'; - $transform_function = $default_function; + $transformation_plugin = $default_function; $transform_options = array(); // check for non printable sorted row data @@ -4023,8 +4027,9 @@ class PMA_DisplayResults ) { $column_for_first_row = $this->_handleNonPrintableContents( - $meta->type, $row[$sorted_column_index], $transform_function, - $transform_options, $default_function, $meta, null + $meta->type, $row[$sorted_column_index], + $transformation_plugin, $transform_options, + $default_function, $meta, null ); } else { @@ -4046,8 +4051,9 @@ class PMA_DisplayResults ) { $column_for_last_row = $this->_handleNonPrintableContents( - $meta->type, $row[$sorted_column_index], $transform_function, - $transform_options, $default_function, $meta, null + $meta->type, $row[$sorted_column_index], + $transformation_plugin, $transform_options, + $default_function, $meta, null ); } else { @@ -4089,7 +4095,7 @@ class PMA_DisplayResults * @param string $after_count the string renders after row count * * @return PMA_Message $message an object of PMA_Message - * + * * @access private * * @see getTable() @@ -4201,7 +4207,7 @@ class PMA_DisplayResults * @param string $del_link the display element - 'del_link' * * @return string $links_html html content - * + * * @access private * * @see getTable() @@ -4221,8 +4227,6 @@ class PMA_DisplayResults 'goto' => $this->_goto, ); - - if ($_SESSION['tmp_user_values']['disp_direction'] != self::DISP_DIR_VERTICAL) { $links_html .= ' 0) { - if ($default_function != $transform_function) { - $result = $transform_function($result, $transform_options, $meta); + if ($default_function != $transformation_plugin) { + $result = $transformation_plugin->applyTransformation( + $result, + $transform_options, + $meta + ); } else { $result = $default_function($result, array(), $meta); @@ -4538,20 +4548,22 @@ class PMA_DisplayResults * 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 string $analyzed_sql the analyzed query - * @param object $meta the meta-information about this field - * @param array $map the list of relations - * @param string $data data - * @param string $transform_function transformation function - * @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 array of options for transformation - * @param bool $is_field_truncated whether the field is truncated + * @param string $class css classes for the td element + * @param bool $condition_field whether the column is a part of the + * where clause + * @param string $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 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 array of options for transformation + * @param bool $is_field_truncated whether the field is truncated * * @return string formatted data * @@ -4563,14 +4575,14 @@ class PMA_DisplayResults */ private function _getRowData( $class, $condition_field, $analyzed_sql, $meta, $map, $data, - $transform_function, $default_function, $nowrap, $where_comparison, + $transformation_plugin, $default_function, $nowrap, $where_comparison, $transform_options, $is_field_truncated ) { $result = ''; @@ -4626,10 +4638,15 @@ class PMA_DisplayResults if (isset($GLOBALS['printview']) && $GLOBALS['printview'] == '1') { - $result .= ($transform_function != $default_function - ? $transform_function($data, $transform_options, $meta) - : $transform_function($data, array(), $meta)) - . ' [->' . $dispval . ']'; + $result .= ($transformation_plugin != $default_function + ? $transformation_plugin->applyTransformation( + $data, + $transform_options, + $meta + ) + : $default_function($data) + ) + . ' [->' . $dispval . ']'; } else { @@ -4659,19 +4676,23 @@ class PMA_DisplayResults $result .= ''; - if ($transform_function != $default_function) { + if ($transformation_plugin != $default_function) { // always apply a transformation on the real data, // not on the display field - $result .= $transform_function($data, $transform_options, $meta); + $result .= $transformation_plugin->applyTransformation( + $data, + $transform_options, + $meta + ); } else { if ($_SESSION['tmp_user_values']['relational_display'] == self::RELATIONAL_DISPLAY_COLUMN) { // user chose "relational display field" in the // display options, so show display field in the cell - $result .= $transform_function($dispval, array(), $meta); + $result .= $default_function($dispval); } else { // otherwise display data in the cell - $result .= $transform_function($data, array(), $meta); + $result .= $default_function($data); } } @@ -4679,9 +4700,14 @@ class PMA_DisplayResults } } else { - $result .= ($transform_function != $default_function) - ? $transform_function($data, $transform_options, $meta) - : $transform_function($data, array(), $meta); + $result .= ($transformation_plugin != $default_function + ? $transformation_plugin->applyTransformation( + $data, + $transform_options, + $meta + ) + : $default_function($data) + ); } // create hidden field if results from structure table @@ -4750,7 +4776,7 @@ class PMA_DisplayResults . ' $export_type, + 'single_table' => isset($single_table) + ) + ); $no_constraints_comments = true; $GLOBALS['sql_constraints_query'] = ''; - $sql_structure = PMA_getTableDef( + $sql_structure = $export_sql_plugin->getTableDef( $source_db, $source_table, "\n", $err_url, false, false ); unset($no_constraints_comments); @@ -947,11 +956,11 @@ class PMA_Table if ($GLOBALS['cfgRelation']['commwork']) { // Get all comments and MIME-Types for current table $comments_copy_query = 'SELECT - column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ' - FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . ' - WHERE - db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND - table_name = \'' . PMA_sqlAddSlashes($source_table) . '\''; + column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ' + FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . ' + WHERE + db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND + table_name = \'' . PMA_sqlAddSlashes($source_table) . '\''; $comments_copy_rs = PMA_queryAsControlUser($comments_copy_query); // Write every comment as new copied entry. [MIME] diff --git a/libraries/Tracker.class.php b/libraries/Tracker.class.php index 0e4c95b61f..f26f2d7e7a 100644 --- a/libraries/Tracker.class.php +++ b/libraries/Tracker.class.php @@ -257,7 +257,16 @@ class PMA_Tracker $tracking_set = self::$default_tracking_set; } - include_once './libraries/export/sql.php'; + // get Export SQL instance + $export_sql_plugin = PMA_getPlugin( + "export", + "sql", + 'libraries/plugins/export/', + array( + 'export_type' => $export_type, + 'single_table' => isset($single_table) + ) + ); $sql_backquotes = true; @@ -295,7 +304,7 @@ class PMA_Tracker } $create_sql .= self::getLogComment() . - PMA_getTableDef($dbname, $tablename, "\n", ""); + $export_sql_plugin->getTableDef($dbname, $tablename, "\n", ""); // Save version diff --git a/libraries/auth/config.auth.lib.php b/libraries/auth/config.auth.lib.php deleted file mode 100644 index 2eca204d89..0000000000 --- a/libraries/auth/config.auth.lib.php +++ /dev/null @@ -1,133 +0,0 @@ - authentication failed - * - * @global string the MySQL error message PHP returns - * @global string the connection type (persistent or not) - * @global string the MySQL server port to use - * @global string the MySQL socket port to use - * @global array the current server settings - * @global string the font face to use in case of failure - * @global string the default font size to use in case of failure - * @global string the big font size to use in case of failure - * @global boolean tell the "PMA_mysqlDie()" function headers have been - * sent - * - * @return boolean always true (no return indeed) - * - * @access public - */ -function PMA_auth_fails() -{ - $conn_error = PMA_DBI_getError(); - if (! $conn_error) { - $conn_error = __('Cannot connect: invalid settings.'); - } - - /* HTML header */ - $response = PMA_Response::getInstance(); - $response->getFooter()->setMinimal(); - $header = $response->getHeader(); - $header->setTitle(__('Access denied')); - $header->disableMenu(); - -?> -

-
-

-
-
- - - - - 1) { - // offer a chance to login to other servers if the current one failed - include_once './libraries/select_server.lib.php'; - echo '' . "\n"; - echo ' ' . "\n"; - echo '' . "\n"; - } - echo '
- source_mtime == 0) { - echo '

' . sprintf(__('You probably did not create a configuration file. You might want to use the %1$ssetup script%2$s to create one.'), '', '') . '

' . "\n"; - } elseif (! isset($GLOBALS['errno']) - || (isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002) - && $GLOBALS['errno'] != 2003 - ) { - // if we display the "Server not responding" error, do not confuse users - // by telling them they have a settings problem - // (note: it's true that they could have a badly typed host name, but - // anyway the current message tells that the server - // rejected the connection, which is not really what happened) - // 2002 is the error given by mysqli - // 2003 is the error given by mysql - trigger_error(__('phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.'), E_USER_WARNING); - } - PMA_mysqlDie($conn_error, '', true, '', false); - } - $GLOBALS['error_handler']->dispUserErrors(); -?> -
' . "\n"; - PMA_selectServer(true, true); - echo '
' . "\n"; - exit; - return true; -} // end of the 'PMA_auth_fails()' function - -?> diff --git a/libraries/auth/cookie.auth.lib.php b/libraries/auth/cookie.auth.lib.php deleted file mode 100644 index 5befae7883..0000000000 --- a/libraries/auth/cookie.auth.lib.php +++ /dev/null @@ -1,643 +0,0 @@ -setCookie('pma_mcrypt_iv', base64_encode($iv)); - } - - /** - * Encryption using blowfish algorithm (mcrypt) - * - * @param string $data original data - * @param string $secret the secret - * - * @return string the encrypted result - * - * @access public - * - */ - function PMA_blowfish_encrypt($data, $secret) - { - global $iv; - return base64_encode( - mcrypt_encrypt(MCRYPT_BLOWFISH, $secret, $data, MCRYPT_MODE_CBC, $iv) - ); - } - - /** - * Decryption using blowfish algorithm (mcrypt) - * - * @param string $encdata encrypted data - * @param string $secret the secret - * - * @return string original data - * - * @access public - * - */ - function PMA_blowfish_decrypt($encdata, $secret) - { - global $iv; - $data = base64_decode($encdata); - $decrypted = mcrypt_decrypt( - MCRYPT_BLOWFISH, - $secret, - $data, - MCRYPT_MODE_CBC, - $iv - ); - return trim($decrypted); - } - -} else { - include_once './libraries/blowfish.php'; -} - -/** - * Returns blowfish secret or generates one if needed. - * - * @access public - * @return string - */ -function PMA_get_blowfish_secret() -{ - if (empty($GLOBALS['cfg']['blowfish_secret'])) { - if (empty($_SESSION['auto_blowfish_secret'])) { - // this returns 23 characters - $_SESSION['auto_blowfish_secret'] = uniqid('', true); - } - return $_SESSION['auto_blowfish_secret']; - } else { - // apply md5() to work around too long secrets (returns 32 characters) - return md5($GLOBALS['cfg']['blowfish_secret']); - } -} - -/** - * Displays authentication form - * - * this function MUST exit/quit the application - * - * @global string the last connection error - * - * @access public - */ -function PMA_auth() -{ - global $conn_error; - - $response = PMA_Response::getInstance(); - if ($response->isAjax()) { - $response->isSuccess(false); - if (! empty($conn_error)) { - $response->addJSON('message', $conn_error); - } else { - $response->addJSON('message', PMA_Message::error(__('Your session has expired. Please login again.'))); - } - exit; - } - - /* Perform logout to custom URL */ - if (! empty($_REQUEST['old_usr']) - && ! empty($GLOBALS['cfg']['Server']['LogoutURL']) - ) { - PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']); - exit; - } - - /* No recall if blowfish secret is not configured as it would produce garbage */ - if ($GLOBALS['cfg']['LoginCookieRecall'] - && ! empty($GLOBALS['cfg']['blowfish_secret']) - ) { - $default_user = $GLOBALS['PHP_AUTH_USER']; - $default_server = $GLOBALS['pma_auth_server']; - $autocomplete = ''; - } else { - $default_user = ''; - $default_server = ''; - // skip the IE autocomplete feature. - $autocomplete = ' autocomplete="off"'; - } - - $cell_align = ($GLOBALS['text_dir'] == 'ltr') ? 'left' : 'right'; - - $response->getFooter()->setMinimal(); - $header = $response->getHeader(); - $header->setBodyId('loginform'); - $header->setTitle('phpMyAdmin'); - $header->disableMenu(); - $header->disableWarnings(); - - if (file_exists(CUSTOM_HEADER_FILE)) { - include CUSTOM_HEADER_FILE; - } - ?> - -
- -

- phpMyAdmin' - ); - ?> -

- display(); - } - - echo "\n"; - - echo "
"; - // Displays the languages form - if (empty($GLOBALS['cfg']['Lang'])) { - include_once './libraries/display_select_lang.lib.php'; - // use fieldset, don't show doc link - PMA_select_language(true, false); - } - echo "
"; - - ?> -
- -
target="_top" class="login hide js-show"> -
- - - - - -
- - -
- -
- - -
-
- - -
- 1) { - ?> -
- -
'; - } else { - echo ' '; - } // end if (server choice) - ?> -
-
- - -
-
- - hasDisplayErrors()) { - echo '
'; - $GLOBALS['error_handler']->dispErrors(); - echo '
'; - } - ?> -
- - - $val) { - $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key); - $GLOBALS['PMA_Config']->removeCookie('pmaServer-' . $key); - $GLOBALS['PMA_Config']->removeCookie('pmaUser-' . $key); - } - return false; - } - - if (! empty($_REQUEST['old_usr'])) { - // The user wants to be logged out - // -> delete his choices that were stored in session - - // according to the PHP manual we should do this before the destroy: - //$_SESSION = array(); - - session_destroy(); - // -> delete password cookie(s) - if ($GLOBALS['cfg']['LoginCookieDeleteAll']) { - foreach ($GLOBALS['cfg']['Servers'] as $key => $val) { - $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key); - if (isset($_COOKIE['pmaPass-' . $key])) { - unset($_COOKIE['pmaPass-' . $key]); - } - } - } else { - $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']); - if (isset($_COOKIE['pmaPass-' . $GLOBALS['server']])) { - unset($_COOKIE['pmaPass-' . $GLOBALS['server']]); - } - } - } - - if (! empty($_REQUEST['pma_username'])) { - // The user just logged in - $GLOBALS['PHP_AUTH_USER'] = $_REQUEST['pma_username']; - $GLOBALS['PHP_AUTH_PW'] = empty($_REQUEST['pma_password']) - ? '' - : $_REQUEST['pma_password']; - if ($GLOBALS['cfg']['AllowArbitraryServer'] - && isset($_REQUEST['pma_servername']) - ) { - $GLOBALS['pma_auth_server'] = $_REQUEST['pma_servername']; - } - return true; - } - - // At the end, try to set the $GLOBALS['PHP_AUTH_USER'] - // and $GLOBALS['PHP_AUTH_PW'] variables from cookies - - // servername - if ($GLOBALS['cfg']['AllowArbitraryServer'] - && ! empty($_COOKIE['pmaServer-' . $GLOBALS['server']]) - ) { - $GLOBALS['pma_auth_server'] = $_COOKIE['pmaServer-' . $GLOBALS['server']]; - } - - // username - if (empty($_COOKIE['pmaUser-' . $GLOBALS['server']])) { - return false; - } - - $GLOBALS['PHP_AUTH_USER'] = PMA_blowfish_decrypt( - $_COOKIE['pmaUser-' . $GLOBALS['server']], - PMA_get_blowfish_secret() - ); - - // user was never logged in since session start - if (empty($_SESSION['last_access_time'])) { - return false; - } - - // User inactive too long - if ($_SESSION['last_access_time'] < time() - $GLOBALS['cfg']['LoginCookieValidity']) { - PMA_cacheUnset('is_create_db_priv', true); - PMA_cacheUnset('is_process_priv', true); - PMA_cacheUnset('is_reload_priv', true); - PMA_cacheUnset('db_to_create', true); - PMA_cacheUnset('dbs_where_create_table_allowed', true); - $GLOBALS['no_activity'] = true; - PMA_auth_fails(); - exit; - } - - // password - if (empty($_COOKIE['pmaPass-' . $GLOBALS['server']])) { - return false; - } - - $GLOBALS['PHP_AUTH_PW'] = PMA_blowfish_decrypt( - $_COOKIE['pmaPass-' . $GLOBALS['server']], - PMA_get_blowfish_secret() - ); - - if ($GLOBALS['PHP_AUTH_PW'] == "\xff(blank)") { - $GLOBALS['PHP_AUTH_PW'] = ''; - } - - $GLOBALS['from_cookie'] = true; - - return true; -} // end of the 'PMA_auth_check()' function - - -/** - * Set the user and password after last checkings if required - * - * @return boolean always true - * - * @access public - */ -function PMA_auth_set_user() -{ - global $cfg; - - // Ensures valid authentication mode, 'only_db', bookmark database and - // table names and relation table name are used - if ($cfg['Server']['user'] != $GLOBALS['PHP_AUTH_USER']) { - foreach ($cfg['Servers'] as $idx => $current) { - if ($current['host'] == $cfg['Server']['host'] - && $current['port'] == $cfg['Server']['port'] - && $current['socket'] == $cfg['Server']['socket'] - && $current['ssl'] == $cfg['Server']['ssl'] - && $current['connect_type'] == $cfg['Server']['connect_type'] - && $current['user'] == $GLOBALS['PHP_AUTH_USER'] - ) { - $GLOBALS['server'] = $idx; - $cfg['Server'] = $current; - break; - } - } // end foreach - } // end if - - if ($GLOBALS['cfg']['AllowArbitraryServer'] - && ! empty($GLOBALS['pma_auth_server']) - ) { - /* Allow to specify 'host port' */ - $parts = explode(' ', $GLOBALS['pma_auth_server']); - if (count($parts) == 2) { - $tmp_host = $parts[0]; - $tmp_port = $parts[1]; - } else { - $tmp_host = $GLOBALS['pma_auth_server']; - $tmp_port = ''; - } - if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) { - $cfg['Server']['host'] = $tmp_host; - if (! empty($tmp_port)) { - $cfg['Server']['port'] = $tmp_port; - } - } - unset($tmp_host, $tmp_port, $parts); - } - $cfg['Server']['user'] = $GLOBALS['PHP_AUTH_USER']; - $cfg['Server']['password'] = $GLOBALS['PHP_AUTH_PW']; - - // Avoid showing the password in phpinfo()'s output - unset($GLOBALS['PHP_AUTH_PW']); - unset($_SERVER['PHP_AUTH_PW']); - - $_SESSION['last_access_time'] = time(); - - // Name and password cookies need to be refreshed each time - // Duration = one month for username - $GLOBALS['PMA_Config']->setCookie( - 'pmaUser-' . $GLOBALS['server'], - PMA_blowfish_encrypt( - $cfg['Server']['user'], PMA_get_blowfish_secret() - ) - ); - - // Duration = as configured - $GLOBALS['PMA_Config']->setCookie( - 'pmaPass-' . $GLOBALS['server'], - PMA_blowfish_encrypt( - ! empty($cfg['Server']['password']) ? $cfg['Server']['password'] : "\xff(blank)", - PMA_get_blowfish_secret() - ), - null, - $GLOBALS['cfg']['LoginCookieStore'] - ); - - // Set server cookies if required (once per session) and, in this case, force - // reload to ensure the client accepts cookies - if (! $GLOBALS['from_cookie']) { - if ($GLOBALS['cfg']['AllowArbitraryServer']) { - if (! empty($GLOBALS['pma_auth_server'])) { - // Duration = one month for servername - $GLOBALS['PMA_Config']->setCookie( - 'pmaServer-' . $GLOBALS['server'], - $cfg['Server']['host'] - ); - } else { - // Delete servername cookie - $GLOBALS['PMA_Config']->removeCookie( - 'pmaServer-' . $GLOBALS['server'] - ); - } - } - - // URL where to go: - $redirect_url = $cfg['PmaAbsoluteUri'] . 'index.php'; - - // any parameters to pass? - $url_params = array(); - if (strlen($GLOBALS['db'])) { - $url_params['db'] = $GLOBALS['db']; - } - if (strlen($GLOBALS['table'])) { - $url_params['table'] = $GLOBALS['table']; - } - // any target to pass? - if (! empty($GLOBALS['target']) && $GLOBALS['target'] != 'index.php') { - $url_params['target'] = $GLOBALS['target']; - } - - /** - * Clear user cache. - */ - PMA_clearUserCache(); - - PMA_Response::getInstance()->disable(); - - PMA_sendHeaderLocation( - $redirect_url . PMA_generate_common_url($url_params, '&'), - true - ); - exit; - } // end if - - return true; -} // end of the 'PMA_auth_set_user()' function - - -/** - * User is not allowed to login to MySQL -> authentication failed - * - * prepares error message and switches to PMA_auth() which display the error - * and the login form - * - * this function MUST exit/quit the application, - * currently doen by call to PMA_auth() - * - * @access public - */ -function PMA_auth_fails() -{ - global $conn_error; - - // Deletes password cookie and displays the login form - $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']); - - if (! empty($GLOBALS['login_without_password_is_forbidden'])) { - $conn_error = __('Login without a password is forbidden by configuration (see AllowNoPassword)'); - } elseif (! empty($GLOBALS['allowDeny_forbidden'])) { - $conn_error = __('Access denied'); - } elseif (! empty($GLOBALS['no_activity'])) { - $conn_error = sprintf(__('No activity within %s seconds; please log in again'), $GLOBALS['cfg']['LoginCookieValidity']); - // Remember where we got timeout to return on same place - if (PMA_getenv('SCRIPT_NAME')) { - $GLOBALS['target'] = basename(PMA_getenv('SCRIPT_NAME')); - // avoid "missing parameter: field" on re-entry - if ('tbl_alter.php' == $GLOBALS['target']) { - $GLOBALS['target'] = 'tbl_structure.php'; - } - } - } elseif (PMA_DBI_getError()) { - $conn_error = '#' . $GLOBALS['errno'] . ' ' - . __('Cannot log in to the MySQL server'); - } else { - $conn_error = __('Cannot log in to the MySQL server'); - } - - // needed for PHP-CGI (not need for FastCGI or mod-php) - header('Cache-Control: no-store, no-cache, must-revalidate'); - header('Pragma: no-cache'); - - PMA_auth(); -} // end of the 'PMA_auth_fails()' function - -?> diff --git a/libraries/auth/http.auth.lib.php b/libraries/auth/http.auth.lib.php deleted file mode 100644 index 422fcbbe26..0000000000 --- a/libraries/auth/http.auth.lib.php +++ /dev/null @@ -1,235 +0,0 @@ -getFooter()->setMinimal(); - $header = $response->getHeader(); - $header->setTitle(__('Access denied')); - $header->disableMenu(); - -?> -

-
-

-
-
- - display(); - - if (file_exists(CUSTOM_FOOTER_FILE)) { - include CUSTOM_FOOTER_FILE; - } - - exit; -} // end of the 'PMA_auth()' function - - -/** - * Gets advanced authentication settings - * - * @global string the username if register_globals is on - * @global string the password if register_globals is on - * @global array the array of server variables if register_globals is - * off - * @global array the array of environment variables if register_globals - * is off - * @global string the username for the ? server - * @global string the password for the ? server - * @global string the username for the WebSite Professional server - * @global string the password for the WebSite Professional server - * @global string the username of the user who logs out - * - * @return boolean whether we get authentication settings or not - * - * @access public - */ -function PMA_auth_check() -{ - global $PHP_AUTH_USER, $PHP_AUTH_PW; - global $old_usr; - - // Grabs the $PHP_AUTH_USER variable whatever are the values of the - // 'register_globals' and the 'variables_order' directives - if (empty($PHP_AUTH_USER)) { - if (PMA_getenv('PHP_AUTH_USER')) { - $PHP_AUTH_USER = PMA_getenv('PHP_AUTH_USER'); - } elseif (PMA_getenv('REMOTE_USER')) { - // CGI, might be encoded, see below - $PHP_AUTH_USER = PMA_getenv('REMOTE_USER'); - } elseif (PMA_getenv('REDIRECT_REMOTE_USER')) { - // CGI, might be encoded, see below - $PHP_AUTH_USER = PMA_getenv('REDIRECT_REMOTE_USER'); - } elseif (PMA_getenv('AUTH_USER')) { - // WebSite Professional - $PHP_AUTH_USER = PMA_getenv('AUTH_USER'); - } elseif (PMA_getenv('HTTP_AUTHORIZATION') - && false === strpos(PMA_getenv('HTTP_AUTHORIZATION'), '<') - ) { - // IIS, might be encoded, see below; also prevent XSS - $PHP_AUTH_USER = PMA_getenv('HTTP_AUTHORIZATION'); - } elseif (PMA_getenv('Authorization')) { - // FastCGI, might be encoded, see below - $PHP_AUTH_USER = PMA_getenv('Authorization'); - } - } - // Grabs the $PHP_AUTH_PW variable whatever are the values of the - // 'register_globals' and the 'variables_order' directives - if (empty($PHP_AUTH_PW)) { - if (PMA_getenv('PHP_AUTH_PW')) { - $PHP_AUTH_PW = PMA_getenv('PHP_AUTH_PW'); - } elseif (PMA_getenv('REMOTE_PASSWORD')) { - // Apache/CGI - $PHP_AUTH_PW = PMA_getenv('REMOTE_PASSWORD'); - } elseif (PMA_getenv('AUTH_PASSWORD')) { - // WebSite Professional - $PHP_AUTH_PW = PMA_getenv('AUTH_PASSWORD'); - } - } - - // Decode possibly encoded information (used by IIS/CGI/FastCGI) - // (do not use explode() because a user might have a colon in his password - if (strcmp(substr($PHP_AUTH_USER, 0, 6), 'Basic ') == 0) { - $usr_pass = base64_decode(substr($PHP_AUTH_USER, 6)); - if (! empty($usr_pass)) { - $colon = strpos($usr_pass, ':'); - if ($colon) { - $PHP_AUTH_USER = substr($usr_pass, 0, $colon); - $PHP_AUTH_PW = substr($usr_pass, $colon + 1); - } - unset($colon); - } - unset($usr_pass); - } - - // User logged out -> ensure the new username is not the same - if (!empty($old_usr) - && (isset($PHP_AUTH_USER) && $old_usr == $PHP_AUTH_USER) - ) { - $PHP_AUTH_USER = ''; - // -> delete user's choices that were stored in session - session_destroy(); - } - - // Returns whether we get authentication settings or not - if (empty($PHP_AUTH_USER)) { - return false; - } else { - return true; - } -} // end of the 'PMA_auth_check()' function - - -/** - * Set the user and password after last checkings if required - * - * @global array the valid servers settings - * @global integer the id of the current server - * @global array the current server settings - * @global string the current username - * @global string the current password - * - * @return boolean always true - * - * @access public - */ -function PMA_auth_set_user() -{ - global $cfg, $server; - global $PHP_AUTH_USER, $PHP_AUTH_PW; - - // Ensures valid authentication mode, 'only_db', bookmark database and - // table names and relation table name are used - if ($cfg['Server']['user'] != $PHP_AUTH_USER) { - $servers_cnt = count($cfg['Servers']); - for ($i = 1; $i <= $servers_cnt; $i++) { - if (isset($cfg['Servers'][$i]) - && ($cfg['Servers'][$i]['host'] == $cfg['Server']['host'] - && $cfg['Servers'][$i]['user'] == $PHP_AUTH_USER) - ) { - $server = $i; - $cfg['Server'] = $cfg['Servers'][$i]; - break; - } - } // end for - } // end if - - $cfg['Server']['user'] = $PHP_AUTH_USER; - $cfg['Server']['password'] = $PHP_AUTH_PW; - - // Avoid showing the password in phpinfo()'s output - unset($GLOBALS['PHP_AUTH_PW']); - unset($_SERVER['PHP_AUTH_PW']); - - return true; -} // end of the 'PMA_auth_set_user()' function - - -/** - * User is not allowed to login to MySQL -> authentication failed - * - * @return boolean always true (no return indeed) - * - * @access public - */ -function PMA_auth_fails() -{ - $error = PMA_DBI_getError(); - if ($error && $GLOBALS['errno'] != 1045) { - PMA_fatalError($error); - } else { - PMA_auth(); - return true; - } - -} // end of the 'PMA_auth_fails()' function - -?> diff --git a/libraries/auth/signon.auth.lib.php b/libraries/auth/signon.auth.lib.php deleted file mode 100644 index 332ead3dc3..0000000000 --- a/libraries/auth/signon.auth.lib.php +++ /dev/null @@ -1,259 +0,0 @@ - authentication failed - * - * @return boolean always true (no return indeed) - * - * @access public - */ -function PMA_auth_fails() -{ - /* Session name */ - $session_name = $GLOBALS['cfg']['Server']['SignonSession']; - - /* Does session exist? */ - if (isset($_COOKIE[$session_name])) { - /* End current session */ - $old_session = session_name(); - $old_id = session_id(); - session_write_close(); - - /* Load single signon session */ - session_name($session_name); - session_id($_COOKIE[$session_name]); - session_start(); - - /* Set error message */ - if (! empty($GLOBALS['login_without_password_is_forbidden'])) { - $_SESSION['PMA_single_signon_error_message'] = __('Login without a password is forbidden by configuration (see AllowNoPassword)'); - } elseif (! empty($GLOBALS['allowDeny_forbidden'])) { - $_SESSION['PMA_single_signon_error_message'] = __('Access denied'); - } elseif (! empty($GLOBALS['no_activity'])) { - $_SESSION['PMA_single_signon_error_message'] = sprintf(__('No activity within %s seconds; please log in again'), $GLOBALS['cfg']['LoginCookieValidity']); - } elseif (PMA_DBI_getError()) { - $_SESSION['PMA_single_signon_error_message'] = PMA_sanitize(PMA_DBI_getError()); - } else { - $_SESSION['PMA_single_signon_error_message'] = __('Cannot log in to the MySQL server'); - } - } - PMA_auth(); -} // end of the 'PMA_auth_fails()' function - -?> diff --git a/libraries/blowfish.php b/libraries/blowfish.php index 82c67331eb..7c297ec701 100644 --- a/libraries/blowfish.php +++ b/libraries/blowfish.php @@ -478,59 +478,5 @@ class Horde_Cipher_blowfish return pack("NN", $R ^ $this->p[0], $L); } - } - -// higher-level functions: -/** - * Encryption using blowfish algorithm - * - * @param string $data original data - * @param string $secret the secret - * - * @return string the encrypted result - * - * @access public - * - */ -function PMA_blowfish_encrypt($data, $secret) -{ - $pma_cipher = new Horde_Cipher_blowfish; - $encrypt = ''; - - $mod = strlen($data) % 8; - - if ($mod > 0) { - $data .= str_repeat("\0", 8 - $mod); - } - - foreach (str_split($data, 8) as $chunk) { - $encrypt .= $pma_cipher->encryptBlock($chunk, $secret); - } - return base64_encode($encrypt); -} - -/** - * Decryption using blowfish algorithm - * - * @param string $encdata encrypted data - * @param string $secret the secret - * - * @return string original data - * - * @access public - * - */ -function PMA_blowfish_decrypt($encdata, $secret) -{ - $pma_cipher = new Horde_Cipher_blowfish; - $decrypt = ''; - $data = base64_decode($encdata); - - foreach (str_split($data, 8) as $chunk) { - $decrypt .= $pma_cipher->decryptBlock($chunk, $secret); - } - return trim($decrypt); -} - ?> diff --git a/libraries/check_user_privileges.lib.php b/libraries/check_user_privileges.lib.php index 402bb4674a..ed9ff11b4d 100644 --- a/libraries/check_user_privileges.lib.php +++ b/libraries/check_user_privileges.lib.php @@ -136,7 +136,8 @@ function PMA_analyseShowGrant() PMA_DBI_free_result($rs_usr); - // must also PMA_cacheUnset() them in libraries/auth/cookie.auth.lib.php + // must also PMA_cacheUnset() them in + // libraries/plugins/auth/AuthenticationCookie.class.php PMA_cacheSet('is_create_db_priv', $GLOBALS['is_create_db_priv'], true); PMA_cacheSet('is_process_priv', $GLOBALS['is_process_priv'], true); PMA_cacheSet('is_reload_priv', $GLOBALS['is_reload_priv'], true); diff --git a/libraries/common.inc.php b/libraries/common.inc.php index e0eb6e786c..c60a783b17 100644 --- a/libraries/common.inc.php +++ b/libraries/common.inc.php @@ -839,21 +839,28 @@ if (! defined('PMA_MINIMUM_COMMON')) { // to allow HTTP or http $cfg['Server']['auth_type'] = strtolower($cfg['Server']['auth_type']); - if (! file_exists('./libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php')) { - PMA_fatalError( - __('Invalid authentication method set in configuration:') . ' ' . $cfg['Server']['auth_type'] - ); - } + /** * the required auth type plugin */ - include_once './libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php'; - if (! PMA_auth_check()) { + $auth_class = "Authentication" . ucfirst($cfg['Server']['auth_type']); + if (! file_exists('./libraries/plugins/auth/' . $auth_class . '.class.php')) { + PMA_fatalError( + __('Invalid authentication method set in configuration:') + . ' ' . $cfg['Server']['auth_type'] + ); + } + include_once './libraries/plugins/auth/' . $auth_class . '.class.php'; + // todo: add plugin manager + $plugin_manager = null; + $auth_plugin = new $auth_class($plugin_manager); + + if (! $auth_plugin->authCheck()) { /* Force generating of new session on login */ PMA_secureSession(); - PMA_auth(); + $auth_plugin->auth(); } else { - PMA_auth_set_user(); + $auth_plugin->authSetUser(); } // Check IP-based Allow/Deny rules as soon as possible to reject the @@ -897,7 +904,7 @@ if (! defined('PMA_MINIMUM_COMMON')) { // Ejects the user if banished if ($allowDeny_forbidden) { PMA_log_user($cfg['Server']['user'], 'allow-denied'); - PMA_auth_fails(); + $auth_plugin->authFails(); } } // end if @@ -905,14 +912,14 @@ if (! defined('PMA_MINIMUM_COMMON')) { if (!$cfg['Server']['AllowRoot'] && $cfg['Server']['user'] == 'root') { $allowDeny_forbidden = true; PMA_log_user($cfg['Server']['user'], 'root-denied'); - PMA_auth_fails(); + $auth_plugin->authFails(); } // is a login without password allowed? if (!$cfg['Server']['AllowNoPassword'] && $cfg['Server']['password'] == '') { $login_without_password_is_forbidden = true; PMA_log_user($cfg['Server']['user'], 'empty-denied'); - PMA_auth_fails(); + $auth_plugin->authFails(); } // if using TCP socket is not needed diff --git a/libraries/common.lib.php b/libraries/common.lib.php index 7d363f1cbe..71b847307d 100644 --- a/libraries/common.lib.php +++ b/libraries/common.lib.php @@ -3326,13 +3326,19 @@ function PMA_getTitleForTarget($target) * * @param string $string Text where to do expansion. * @param function $escape Function to call for escaping variable values. + * @param function $class The name of the class, if the above function is + * actually a method inside a class. * @param array $updates Array with overrides for default parameters - * (obtained from GLOBALS). + * (obtained from GLOBALS). * * @return string */ -function PMA_expandUserString($string, $escape = null, $updates = array()) -{ +function PMA_expandUserString( + $string, + $escape = null, + $class = null, + $updates = array() +) { /* Content */ $vars['http_host'] = PMA_getenv('HTTP_HOST'); $vars['server_name'] = $GLOBALS['cfg']['Server']['host']; @@ -3374,7 +3380,13 @@ function PMA_expandUserString($string, $escape = null, $updates = array()) /* Optional escaping */ if (! is_null($escape)) { foreach ($replace as $key => $val) { - $replace[$key] = $escape($val); + if (is_null($class)) { + // Use as function + $replace[$key] = $escape($val); + } else { + // Use as method + call_user_func($class . "::" . $escape, $val); + } } } @@ -3390,7 +3402,16 @@ function PMA_expandUserString($string, $escape = null, $updates = array()) $column_names = array(); foreach ($columns_list as $column) { if (! is_null($escape)) { - $column_names[] = $escape($column['Field']); + if (is_null($class)) { + // Use as function + $column_names[] = $escape($column['Field']); + } else { + // Use as method + $column_names[] = call_user_func( + $class . "::" . $escape, + $column['Field'] + ); + } } else { $column_names[] = $column['Field']; } @@ -3457,17 +3478,19 @@ function PMA_getSelectUploadFileBlock($import_list, $uploaddir) . ''; $extensions = ''; - foreach ($import_list as $val) { + foreach ($import_list as $plugin) { + $properties = $plugin->getProperties(); if (! empty($extensions)) { $extensions .= '|'; } - $extensions .= $val['extension']; + $extensions .= $properties['extension']; } $matcher = '@\.(' . $extensions . ')(\.(' . PMA_supportedDecompressions() . '))?$@'; - $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed'] + $active = (isset($GLOBALS['timeout_passed']) + && $GLOBALS['timeout_passed'] && isset($local_import_file)) ? $local_import_file : ''; @@ -3653,6 +3676,7 @@ function PMA_getGISDatatypes($upper_case = false) $gis_data_types[$i] = strtoupper($gis_data_types[$i]); } } + return $gis_data_types; } diff --git a/libraries/config.default.php b/libraries/config.default.php index 5ec68f017d..55c6748cf7 100644 --- a/libraries/config.default.php +++ b/libraries/config.default.php @@ -1680,9 +1680,9 @@ $cfg['Export']['pdf_structure_or_data'] = 'data'; /** * * - * @global string $cfg['Export']['php_array_structure_or_data'] + * @global string $cfg['Export']['phparray_structure_or_data'] */ -$cfg['Export']['php_array_structure_or_data'] = 'data'; +$cfg['Export']['phparray_structure_or_data'] = 'data'; /** * diff --git a/libraries/dbi/drizzle.dbi.lib.php b/libraries/dbi/drizzle.dbi.lib.php index 817b7b057a..d0493d1cb5 100644 --- a/libraries/dbi/drizzle.dbi.lib.php +++ b/libraries/dbi/drizzle.dbi.lib.php @@ -122,7 +122,8 @@ function PMA_DBI_connect($user, $password, $is_controluser = false, $server = nu // go back to main login if it fails if (! $auxiliary_connection) { PMA_log_user($user, 'drizzle-denied'); - PMA_auth_fails(); + global $auth_plugin; + $auth_plugin->authFails(); } else { return false; } diff --git a/libraries/dbi/mysql.dbi.lib.php b/libraries/dbi/mysql.dbi.lib.php index 19c7f415da..0e4a5587a1 100644 --- a/libraries/dbi/mysql.dbi.lib.php +++ b/libraries/dbi/mysql.dbi.lib.php @@ -125,7 +125,8 @@ function PMA_DBI_connect($user, $password, $is_controluser = false, $server = nu // go back to main login if it fails if (! $auxiliary_connection) { PMA_log_user($user, 'mysql-denied'); - PMA_auth_fails(); + global $auth_plugin; + $auth_plugin->authFails(); } else { return false; } diff --git a/libraries/dbi/mysqli.dbi.lib.php b/libraries/dbi/mysqli.dbi.lib.php index 3e66f2752d..316796c36c 100644 --- a/libraries/dbi/mysqli.dbi.lib.php +++ b/libraries/dbi/mysqli.dbi.lib.php @@ -199,7 +199,8 @@ function PMA_DBI_connect($user, $password, $is_controluser = false, $server = nu // go back to main login if it fails if (! $auxiliary_connection) { PMA_log_user($user, 'mysql-denied'); - PMA_auth_fails(); + global $auth_plugin; + $auth_plugin->authFails(); } else { return false; } diff --git a/libraries/display_export.lib.php b/libraries/display_export.lib.php index 3be047844e..f46e085225 100644 --- a/libraries/display_export.lib.php +++ b/libraries/display_export.lib.php @@ -33,11 +33,20 @@ function PMA_exportIsActive($what, $val) } /* Scan for plugins */ -$export_list = PMA_getPlugins('./libraries/export/', array('export_type' => $export_type, 'single_table' => isset($single_table))); +$export_list = PMA_getPlugins( + "export", + 'libraries/plugins/export/', + array( + 'export_type' => $export_type, + 'single_table' => isset($single_table) + ) +); /* Fail if we didn't find any plugin */ if (empty($export_list)) { - PMA_Message::error(__('Could not load export plugins, please check your installation!'))->display(); + PMA_Message::error(__( + 'Could not load export plugins, please check your installation!' + ))->display(); exit; } ?> diff --git a/libraries/display_import.lib.php b/libraries/display_import.lib.php index 5856ac037a..abfee40275 100644 --- a/libraries/display_import.lib.php +++ b/libraries/display_import.lib.php @@ -16,11 +16,17 @@ require_once './libraries/plugin_interface.lib.php'; require_once './libraries/display_import_ajax.lib.php'; /* Scan for plugins */ -$import_list = PMA_getPlugins('./libraries/import/', $import_type); +$import_list = PMA_getPlugins( + "import", + 'libraries/plugins/import/', + $import_type +); /* Fail if we didn't find any plugin */ if (empty($import_list)) { - PMA_Message::error(__('Could not load import plugins, please check your installation!'))->display(); + PMA_Message::error(__( + 'Could not load import plugins, please check your installation!' + ))->display(); exit; } ?> @@ -38,7 +44,7 @@ if (empty($import_list)) { $('#upload_form_status').css("display", "inline"); // show progress bar $('#upload_form_status_info').css("display", "inline"); // - || - var finished = false; var percent = 0.0; @@ -155,10 +161,12 @@ if ($_SESSION[$SESSION_KEY]["handler"] != "noplugin") {
> - + " value="" /> 'CodeGen', - 'extension' => 'cs', - 'mime_type' => 'text/cs', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['codegen']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data' - ), - array('type' => 'select', - 'name' => 'format', - 'text' => __('Format:'), - 'values' => $CG_FORMATS - ), - array( - 'type' => 'end_group' - ) - ); -} else { - - /** - * Set of functions used to build exports of tables - */ - - /** - * Outputs export footer - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - return true; - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - return true; - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - return true; - } - - /** - * Outputs database footer - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBFooter($db) - { - return true; - } - - /** - * Outputs CREATE DATABASE statement - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBCreate($db) - { - return true; - } - - /** - * Outputs the content of a table in NHibernate 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) - { - global $CG_FORMATS, $CG_HANDLERS, $what; - $format = $GLOBALS[$what . '_format']; - if (isset($CG_FORMATS[$format])) { - return PMA_exportOutputHandler( - $CG_HANDLERS[$format]($db, $table, $crlf) - ); - } - return PMA_exportOutputHandler(sprintf("%s is not supported.", $format)); - } - - /** - * TableProperty class - * - * @package PhpMyAdmin-Export - * @subpackage Codegen - */ - class TableProperty - { - public $name; - public $type; - public $nullable; - public $key; - public $defaultValue; - public $ext; - function __construct($row) - { - $this->name = trim($row[0]); - $this->type = trim($row[1]); - $this->nullable = trim($row[2]); - $this->key = trim($row[3]); - $this->defaultValue = trim($row[4]); - $this->ext = trim($row[5]); - } - function getPureType() - { - $pos=strpos($this->type, "("); - if ($pos > 0) { - return substr($this->type, 0, $pos); - } - return $this->type; - } - function isNotNull() - { - return $this->nullable == "NO" ? "true" : "false"; - } - function isUnique() - { - return $this->key == "PRI" || $this->key == "UNI" ? "true" : "false"; - } - function getDotNetPrimitiveType() - { - if (strpos($this->type, "int") === 0) { - return "int"; - } - if (strpos($this->type, "long") === 0) { - return "long"; - } - if (strpos($this->type, "char") === 0) { - return "string"; - } - if (strpos($this->type, "varchar") === 0) { - return "string"; - } - if (strpos($this->type, "text") === 0) { - return "string"; - } - if (strpos($this->type, "longtext") === 0) { - return "string"; - } - if (strpos($this->type, "tinyint") === 0) { - return "bool"; - } - if (strpos($this->type, "datetime") === 0) { - return "DateTime"; - } - return "unknown"; - } - function getDotNetObjectType() - { - if (strpos($this->type, "int") === 0) { - return "Int32"; - } - if (strpos($this->type, "long") === 0) { - return "Long"; - } - if (strpos($this->type, "char") === 0) { - return "String"; - } - if (strpos($this->type, "varchar") === 0) { - return "String"; - } - if (strpos($this->type, "text") === 0) { - return "String"; - } - if (strpos($this->type, "longtext") === 0) { - return "String"; - } - if (strpos($this->type, "tinyint") === 0) { - return "Boolean"; - } - if (strpos($this->type, "datetime") === 0) { - return "DateTime"; - } - return "Unknown"; - } - function getIndexName() - { - if (strlen($this->key) > 0) { - return "index=\"" - . htmlspecialchars($this->name, ENT_COMPAT, 'UTF-8') - . "\""; - } - return ""; - } - function isPK() - { - return $this->key=="PRI"; - } - function formatCs($text) - { - $text = str_replace( - "#name#", - cgMakeIdentifier($this->name, false), - $text - ); - return $this->format($text); - } - function formatXml($text) - { - $text = str_replace( - "#name#", - htmlspecialchars($this->name, ENT_COMPAT, 'UTF-8'), - $text - ); - $text = str_replace( - "#indexName#", - $this->getIndexName(), - $text - ); - return $this->format($text); - } - function format($text) - { - $text = str_replace( - "#ucfirstName#", - cgMakeIdentifier($this->name), - $text - ); - $text = str_replace( - "#dotNetPrimitiveType#", - $this->getDotNetPrimitiveType(), - $text - ); - $text = str_replace( - "#dotNetObjectType#", - $this->getDotNetObjectType(), - $text - ); - $text = str_replace( - "#type#", - $this->getPureType(), - $text - ); - $text = str_replace( - "#notNull#", - $this->isNotNull(), - $text - ); - $text = str_replace( - "#unique#", - $this->isUnique(), - $text - ); - return $text; - } - } - - function cgMakeIdentifier($str, $ucfirst = true) - { - // remove unsafe characters - $str = preg_replace('/[^\p{L}\p{Nl}_]/u', '', $str); - // make sure first character is a letter or _ - if (! preg_match('/^\pL/u', $str)) { - $str = '_' . $str; - } - if ($ucfirst) { - $str = ucfirst($str); - } - return $str; - } - - function handleNHibernateCSBody($db, $table, $crlf) - { - $lines = array(); - $result = PMA_DBI_query( - sprintf('DESC %s.%s', PMA_backquote($db), PMA_backquote($table)) - ); - if ($result) { - $tableProperties = array(); - while ($row = PMA_DBI_fetch_row($result)) { - $tableProperties[] = new TableProperty($row); - } - PMA_DBI_free_result($result); - $lines[] = 'using System;'; - $lines[] = 'using System.Collections;'; - $lines[] = 'using System.Collections.Generic;'; - $lines[] = 'using System.Text;'; - $lines[] = 'namespace ' . cgMakeIdentifier($db); - $lines[] = '{'; - $lines[] = ' #region ' . cgMakeIdentifier($table); - $lines[] = ' public class ' . cgMakeIdentifier($table); - $lines[] = ' {'; - $lines[] = ' #region Member Variables'; - foreach ($tableProperties as $tableProperty) { - $lines[] = $tableProperty->formatCs( - ' protected #dotNetPrimitiveType# _#name#;' - ); - } - $lines[] = ' #endregion'; - $lines[] = ' #region Constructors'; - $lines[] = ' public ' . cgMakeIdentifier($table).'() { }'; - $temp = array(); - foreach ($tableProperties as $tableProperty) { - if (! $tableProperty->isPK()) { - $temp[] = $tableProperty->formatCs( - '#dotNetPrimitiveType# #name#' - ); - } - } - $lines[] = ' public ' - . cgMakeIdentifier($table) - . '(' - . implode(', ', $temp) - . ')'; - $lines[] = ' {'; - foreach ($tableProperties as $tableProperty) { - if (! $tableProperty->isPK()) { - $lines[] = $tableProperty->formatCs( - ' this._#name#=#name#;' - ); - } - } - $lines[] = ' }'; - $lines[] = ' #endregion'; - $lines[] = ' #region Public Properties'; - foreach ($tableProperties as $tableProperty) { - $lines[] = $tableProperty->formatCs( - ' public virtual #dotNetPrimitiveType# #ucfirstName#' - . "\n" - . ' {' . "\n" - . ' get {return _#name#;}' . "\n" - . ' set {_#name#=value;}' . "\n" - . ' }' - ); - } - $lines[] = ' #endregion'; - $lines[] = ' }'; - $lines[] = ' #endregion'; - $lines[] = '}'; - } - return implode("\n", $lines); - } - - function handleNHibernateXMLBody($db, $table, $crlf) - { - $lines = array(); - $lines[] = ''; - $lines[] = ''; - $lines[] = ' '; - $result = PMA_DBI_query( - sprintf("DESC %s.%s", PMA_backquote($db), PMA_backquote($table)) - ); - if ($result) { - while ($row = PMA_DBI_fetch_row($result)) { - $tableProperty = new TableProperty($row); - if ($tableProperty->isPK()) { - $lines[] = $tableProperty->formatXml( - ' ' . "\n" - . ' ' . "\n" - . ' ' . "\n" - . ' ' - ); - } else { - $lines[] = $tableProperty->formatXml( - ' ' . "\n" - . ' ' . "\n" - . ' ' - ); - } - } - PMA_DBI_free_result($result); - } - $lines[] = ' '; - $lines[] = ''; - return implode("\n", $lines); - } -} -?> diff --git a/libraries/export/excel.php b/libraries/export/excel.php deleted file mode 100644 index 645e8354ff..0000000000 --- a/libraries/export/excel.php +++ /dev/null @@ -1,67 +0,0 @@ - __('CSV for MS Excel'), - 'extension' => 'csv', - 'mime_type' => 'text/comma-separated-values', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['excel']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'text', - 'name' => 'null', - 'text' => __('Replace NULL with:') - ), - array( - 'type' => 'bool', - 'name' => 'removeCRLF', - 'text' => __( - 'Remove carriage return/line feed characters within columns' - ) - ), - array( - 'type' => 'bool', - 'name' => 'columns', - 'text' => __('Put columns names in the first row') - ), - array( - 'type' => 'select', - 'name' => 'edition', - 'values' => array( - 'win' => 'Windows', - 'mac_excel2003' => 'Excel 2003 / Macintosh', - 'mac_excel2008' => 'Excel 2008 / Macintosh'), - 'text' => __('Excel edition:')), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data' - ), - array( - 'type' => 'end_group' - ) - ); -} else { - /* Everything rest is coded in csv plugin */ - include './libraries/export/csv.php'; -} -?> diff --git a/libraries/export/mediawiki.php b/libraries/export/mediawiki.php deleted file mode 100644 index 3a7e087106..0000000000 --- a/libraries/export/mediawiki.php +++ /dev/null @@ -1,334 +0,0 @@ - __('MediaWiki Table'), - 'extension' => 'mediawiki', - 'mime_type' => 'text/plain', - 'options' => array(), - 'options_text' => __('Options') - ); - - // general options - $plugin_list['mediawiki']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ); - - // what to dump (structure/data/both) - $plugin_list['mediawiki']['options'][] = array( - 'type' => 'begin_subgroup', - 'subgroup_header' => array( - 'type' => 'message_only', - 'text' => __('Dump table') - ) - ); - $plugin_list['mediawiki']['options'][] = array( - 'type' => 'radio', - 'name' => 'structure_or_data', - 'values' => array( - 'structure' => __('structure'), - 'data' => __('data'), - 'structure_and_data' => __('structure and data') - ) - ); - $plugin_list['mediawiki']['options'][] = array( - 'type' => 'end_subgroup' - ); - - // export table name - $plugin_list['mediawiki']['options'][] = array( - 'type' => 'bool', - 'name' => 'caption', - 'text' => __('Export table names') - ); - - // export table headers - $plugin_list['mediawiki']['options'][] = array( - 'type' => 'bool', - 'name' => 'headers', - 'text' => __('Export table headers') - ); - - // end general options - $plugin_list['mediawiki']['options'][] = array( - 'type' => 'end_group' - ); -} else { - - /** - * Outputs comments containing info about the exported tables - * - * @param string $text Text of comment - * - * @return string The formatted comment - * - * @access private - */ - function PMA_exportComment($text = '') - { - // see http://www.mediawiki.org/wiki/Help:Formatting - $comment = PMA_exportCRLF(); - $comment .= '' . str_repeat(PMA_exportCRLF(), 2); - - return $comment; - } - - /** - * Outputs CRLF - * - * @return string CRLF - * - * @access private - */ - function PMA_exportCRLF() - { - // The CRLF expected by the mediawiki format is "\n" - return "\n"; - } - - /** - * Outputs export footer - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - return true; - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - return true; - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - return true; - } - - /** - * Outputs database footer - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBFooter($db) - { - return true; - } - - /** - * Outputs CREATE DATABASE statement - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBCreate($db) - { - return true; - } - - /** - * 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 $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 - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportStructure( - $db, - $table, - $crlf, - $error_url, - $export_mode, - $export_type, - $do_relation = false, - $do_comments = false, - $do_mime = false, - $dates = false - ) { - switch($export_mode) { - case 'create_table': - $columns = PMA_DBI_get_columns($db, $table); - $columns = array_values($columns); - $row_cnt = count($columns); - - // Print structure comment - $output = PMA_exportComment( - "Table structure for " - . PMA_backquote($table) - ); - - // Begin the table construction - $output .= "{| class=\"wikitable\" style=\"text-align:center;\"" - . PMA_exportCRLF(); - - // Add the table name - if ($GLOBALS['mediawiki_caption']) { - $output .= "|+'''" . $table . "'''" . PMA_exportCRLF(); - } - - // Add the table headers - if ($GLOBALS['mediawiki_headers']) { - $output .= "|- style=\"background:#ffdead;\"" . PMA_exportCRLF(); - $output .= "! style=\"background:#ffffff\" | " . PMA_exportCRLF(); - for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Field']. PMA_exportCRLF(); - } - } - - // Add the table structure - $output .= "|-" . PMA_exportCRLF(); - $output .= "! Type" . PMA_exportCRLF(); - for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Type'] . PMA_exportCRLF(); - } - - $output .= "|-" . PMA_exportCRLF(); - $output .= "! Null" . PMA_exportCRLF(); - for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Null'] . PMA_exportCRLF(); - } - - $output .= "|-" . PMA_exportCRLF(); - $output .= "! Default" . PMA_exportCRLF(); - for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Default'] . PMA_exportCRLF(); - } - - $output .= "|-" . PMA_exportCRLF(); - $output .= "! Extra" . PMA_exportCRLF(); - for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Extra'] . PMA_exportCRLF(); - } - - $output .= "|}" . str_repeat(PMA_exportCRLF(), 2); - break; - } // end switch - - return PMA_exportOutputHandler($output); - } - - /** - * 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 - ) { - // Print data comment - $output = PMA_exportComment("Table data for ". PMA_backquote($table)); - - // Begin the table construction - // Use the "wikitable" class for style - // Use the "sortable" class for allowing tables to be sorted by column - $output .= "{| class=\"wikitable sortable\" style=\"text-align:center;\"" - . PMA_exportCRLF(); - - // Add the table name - if ($GLOBALS['mediawiki_caption']) { - $output .= "|+'''" . $table . "'''" . PMA_exportCRLF(); - } - - // Add the table headers - if ($GLOBALS['mediawiki_headers']) { - // Get column names - $column_names = PMA_DBI_get_column_names($db, $table); - - // Add column names as table headers - if ( ! is_null($column_names) ) { - // Use '|-' for separating rows - $output .= "|-" . PMA_exportCRLF(); - - // Use '!' for separating table headers - foreach ($column_names as $column) { - $output .= " ! " . $column . "" . PMA_exportCRLF(); - } - } - } - - // Get the table data from the database - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - $fields_cnt = PMA_DBI_num_fields($result); - - while ($row = PMA_DBI_fetch_row($result)) { - $output .= "|-" . PMA_exportCRLF(); - - // Use '|' for separating table columns - for ($i = 0; $i < $fields_cnt; ++ $i) { - $output .= " | " . $row[$i] . "" . PMA_exportCRLF(); - } - } - - // End table construction - $output .= "|}" . str_repeat(PMA_exportCRLF(), 2); - return PMA_exportOutputHandler($output); - } -} -?> \ No newline at end of file diff --git a/libraries/export/pdf.php b/libraries/export/pdf.php deleted file mode 100644 index e7343b71b6..0000000000 --- a/libraries/export/pdf.php +++ /dev/null @@ -1,520 +0,0 @@ - __('PDF'), - 'extension' => 'pdf', - 'mime_type' => 'application/pdf', - 'force_file' => true, - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['pdf']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'message_only', - 'name' => 'explanation', - 'text' => __( - '(Generates a report containing the data of a single table)' - ) - ), - array( - 'type' => 'text', - 'name' => 'report_title', - 'text' => __('Report title:') - ), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data' - ), - array( - 'type' => 'end_group' - ) - ); -} else { - - include_once './libraries/PDF.class.php'; - - /** - * Adapted from a LGPL script by Philip Clarke - * - * @package PhpMyAdmin-Export - * @subpackage PDF - */ - class PMA_Export_PDF extends PMA_PDF - { - var $tablewidths; - var $headerset; - - function checkPageBreak($h = 0, $y = '', $addpage = true) - { - if ($this->empty_string($y)) { - $y = $this->y; - } - $current_page = $this->page; - if ((($y + $h) > $this->PageBreakTrigger) - AND (! $this->InFooter) - AND ($this->AcceptPageBreak()) - ) { - if ($addpage) { - //Automatic page break - $x = $this->x; - $this->AddPage($this->CurOrientation); - $this->y = $this->dataY; - $oldpage = $this->page - 1; - - $this_page_orm = $this->pagedim[$this->page]['orm']; - $old_page_orm = $this->pagedim[$oldpage]['orm']; - $this_page_olm = $this->pagedim[$this->page]['olm']; - $old_page_olm = $this->pagedim[$oldpage]['olm']; - if ($this->rtl) { - if ($this_page_orm!= $old_page_orm) { - $this->x = $x - ($this_page_orm - $old_page_orm); - } else { - $this->x = $x; - } - } else { - if ($this_page_olm != $old_page_olm) { - $this->x = $x + ($this_page_olm - $old_page_olm); - } else { - $this->x = $x; - } - } - } - return true; - } - if ($current_page != $this->page) { - // account for columns mode - return true; - } - return false; - } - - function Header() - { - global $maxY; - // Check if header for this page already exists - if (! isset($this->headerset[$this->page])) { - $fullwidth = 0; - foreach ($this->tablewidths as $width) { - $fullwidth += $width; - } - $this->SetY(($this->tMargin) - ($this->FontSizePt / $this->k) * 5); - $this->cellFontSize = $this->FontSizePt ; - $this->SetFont( - PMA_PDF_FONT, - '', - ($this->titleFontSize - ? $this->titleFontSize - : $this->FontSizePt) - ); - $this->Cell(0, $this->FontSizePt, $this->titleText, 0, 1, 'C'); - $this->SetFont(PMA_PDF_FONT, '', $this->cellFontSize); - $this->SetY(($this->tMargin) - ($this->FontSizePt / $this->k) * 2.5); - $this->Cell( - 0, - $this->FontSizePt, - __('Database') . ': ' . $this->currentDb . ', ' - . __('Table') . ': ' . $this->currentTable, - 0, 1, 'L' - ); - $l = ($this->lMargin); - foreach ($this->colTitles as $col => $txt) { - $this->SetXY($l, ($this->tMargin)); - $this->MultiCell( - $this->tablewidths[$col], - $this->FontSizePt, - $txt - ); - $l += $this->tablewidths[$col] ; - $maxY = ($maxY < $this->getY()) ? $this->getY() : $maxY ; - } - $this->SetXY($this->lMargin, $this->tMargin); - $this->setFillColor(200, 200, 200); - $l = ($this->lMargin); - foreach ($this->colTitles as $col => $txt) { - $this->SetXY($l, $this->tMargin); - $this->cell( - $this->tablewidths[$col], - $maxY-($this->tMargin), - '', - 1, - 0, - 'L', - 1 - ); - $this->SetXY($l, $this->tMargin); - $this->MultiCell( - $this->tablewidths[$col], - $this->FontSizePt, - $txt, - 0, - 'C' - ); - $l += $this->tablewidths[$col]; - } - $this->setFillColor(255, 255, 255); - // set headerset - $this->headerset[$this->page] = 1; - } - - $this->dataY = $maxY; - } - - function morepagestable($lineheight=8) - { - // some things to set and 'remember' - $l = $this->lMargin; - $startheight = $h = $this->dataY; - $startpage = $currpage = $this->page; - - // calculate the whole width - $fullwidth = 0; - foreach ($this->tablewidths as $width) { - $fullwidth += $width; - } - - // Now let's start to write the table - $row = 0; - $tmpheight = array(); - $maxpage = $this->page; - - while ($data = PMA_DBI_fetch_row($this->results)) { - $this->page = $currpage; - // write the horizontal borders - $this->Line($l, $h, $fullwidth+$l, $h); - // write the content and remember the height of the highest col - foreach ($data as $col => $txt) { - $this->page = $currpage; - $this->SetXY($l, $h); - if ($this->tablewidths[$col] > 0) { - $this->MultiCell( - $this->tablewidths[$col], - $lineheight, - $txt, - 0, - $this->colAlign[$col] - ); - $l += $this->tablewidths[$col]; - } - - if (! isset($tmpheight[$row.'-'.$this->page])) { - $tmpheight[$row.'-'.$this->page] = 0; - } - if ($tmpheight[$row.'-'.$this->page] < $this->GetY()) { - $tmpheight[$row.'-'.$this->page] = $this->GetY(); - } - if ($this->page > $maxpage) { - $maxpage = $this->page; - } - unset($data[$col]); - } - - // get the height we were in the last used page - $h = $tmpheight[$row.'-'.$maxpage]; - // set the "pointer" to the left margin - $l = $this->lMargin; - // set the $currpage to the last page - $currpage = $maxpage; - unset($data[$row]); - $row++; - } - // draw the borders - // we start adding a horizontal line on the last page - $this->page = $maxpage; - $this->Line($l, $h, $fullwidth+$l, $h); - // now we start at the top of the document and walk down - for ($i = $startpage; $i <= $maxpage; $i++) { - $this->page = $i; - $l = $this->lMargin; - $t = ($i == $startpage) ? $startheight : $this->tMargin; - $lh = ($i == $maxpage) ? $h : $this->h-$this->bMargin; - $this->Line($l, $t, $l, $lh); - foreach ($this->tablewidths as $width) { - $l += $width; - $this->Line($l, $t, $l, $lh); - } - } - // set it to the last page, if not it'll cause some problems - $this->page = $maxpage; - } - - function setAttributes($attr = array()) - { - foreach ($attr as $key => $val) { - $this->$key = $val ; - } - } - - function setTopMargin($topMargin) - { - $this->tMargin = $topMargin; - } - - function mysqlReport($query) - { - unset($this->tablewidths); - unset($this->colTitles); - unset($this->titleWidth); - unset($this->colFits); - unset($this->display_column); - unset($this->colAlign); - - /** - * Pass 1 for column widths - */ - $this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED); - $this->numFields = PMA_DBI_num_fields($this->results); - $this->fields = PMA_DBI_get_fields_meta($this->results); - - // sColWidth = starting col width (an average size width) - $availableWidth = $this->w - $this->lMargin - $this->rMargin; - $this->sColWidth = $availableWidth / $this->numFields; - $totalTitleWidth = 0; - - // loop through results header and set initial - // col widths/ titles/ alignment - // if a col title is less than the starting col width, - // reduce that column size - $colFits = array(); - for ($i = 0; $i < $this->numFields; $i++) { - $stringWidth = $this->getstringwidth($this->fields[$i]->name) + 6 ; - // save the real title's width - $titleWidth[$i] = $stringWidth; - $totalTitleWidth += $stringWidth; - - // set any column titles less than the start width to - // the column title width - if ($stringWidth < $this->sColWidth) { - $colFits[$i] = $stringWidth ; - } - $this->colTitles[$i] = $this->fields[$i]->name; - $this->display_column[$i] = true; - - switch ($this->fields[$i]->type) { - case 'int': - $this->colAlign[$i] = 'R'; - break; - case 'blob': - case 'tinyblob': - case 'mediumblob': - case 'longblob': - /** - * @todo do not deactivate completely the display - * but show the field's name and [BLOB] - */ - if (stristr($this->fields[$i]->flags, 'BINARY')) { - $this->display_column[$i] = false; - unset($this->colTitles[$i]); - } - $this->colAlign[$i] = 'L'; - break; - default: - $this->colAlign[$i] = 'L'; - } - } - - // title width verification - if ($totalTitleWidth > $availableWidth) { - $adjustingMode = true; - } else { - $adjustingMode = false; - // we have enough space for all the titles at their - // original width so use the true title's width - foreach ($titleWidth as $key => $val) { - $colFits[$key] = $val; - } - } - - // loop through the data; any column whose contents - // is greater than the column size is resized - /** - * @todo force here a LIMIT to avoid reading all rows - */ - while ($row = PMA_DBI_fetch_row($this->results)) { - foreach ($colFits as $key => $val) { - $stringWidth = $this->getstringwidth($row[$key]) + 6 ; - if ($adjustingMode && ($stringWidth > $this->sColWidth)) { - // any column whose data's width is bigger than - // the start width is now discarded - unset($colFits[$key]); - } else { - // if data's width is bigger than the current column width, - // enlarge the column (but avoid enlarging it if the - // data's width is very big) - if ($stringWidth > $val - && $stringWidth < ($this->sColWidth * 3) - ) { - $colFits[$key] = $stringWidth ; - } - } - } - } - - $totAlreadyFitted = 0; - foreach ($colFits as $key => $val) { - // set fitted columns to smallest size - $this->tablewidths[$key] = $val; - // to work out how much (if any) space has been freed up - $totAlreadyFitted += $val; - } - - if ($adjustingMode) { - $surplus = (sizeof($colFits) * $this->sColWidth) - $totAlreadyFitted; - $surplusToAdd = $surplus / ($this->numFields - sizeof($colFits)); - } else { - $surplusToAdd = 0; - } - - for ($i = 0; $i < $this->numFields; $i++) { - if (! in_array($i, array_keys($colFits))) { - $this->tablewidths[$i] = $this->sColWidth + $surplusToAdd; - } - if ($this->display_column[$i] == false) { - $this->tablewidths[$i] = 0; - } - } - - ksort($this->tablewidths); - - PMA_DBI_free_result($this->results); - - // Pass 2 - - $this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED); - $this->setY($this->tMargin); - $this->AddPage(); - $this->SetFont(PMA_PDF_FONT, '', 9); - $this->morepagestable($this->FontSizePt); - PMA_DBI_free_result($this->results); - - } // end of mysqlReport function - - } // end of PMA_Export_PDF class - - $pdf = new PMA_Export_PDF('L', 'pt', 'A3'); - - /** - * Finalize the pdf. - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - global $pdf; - - // instead of $pdf->Output(): - if (! PMA_exportOutputHandler($pdf->getPDFData())) { - return false; - } - - return true; - } - - /** - * Initialize the pdf to export data. - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - global $pdf_report_title; - global $pdf; - - $pdf->Open(); - - $attr = array('titleFontSize' => 18, 'titleText' => $pdf_report_title); - $pdf->setAttributes($attr); - $pdf->setTopMargin(30); - - return true; - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - return true; - } - - /** - * Outputs database footer - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBFooter($db) - { - return true; - } - - /** - * Outputs CREATE DATABASE statement - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBCreate($db) - { - return true; - } - - /** - * Outputs the content of a table in PDF 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) - { - global $pdf; - - $attr = array('currentDb' => $db, 'currentTable' => $table); - $pdf->setAttributes($attr); - $pdf->mysqlReport($sql_query); - - return true; - } // end of the 'PMA_exportData()' function -} -?> diff --git a/libraries/import/csv.php b/libraries/import/csv.php deleted file mode 100644 index a7fcc0ffcf..0000000000 --- a/libraries/import/csv.php +++ /dev/null @@ -1,529 +0,0 @@ - __('CSV'), - 'extension' => 'csv', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['csv']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'bool', - 'name' => 'replace', - 'text' => __('Replace table data with file') - ), - array( - 'type' => 'bool', - 'name' => 'ignore', - 'text' => __('Do not abort on INSERT error') - ), - array( - 'type' => 'text', - 'name' => 'terminated', - 'text' => __('Columns separated with:'), - 'size' => 2, - 'len' => 2 - ), - array( - 'type' => 'text', - 'name' => 'enclosed', - 'text' => __('Columns enclosed with:'), - 'size' => 2, - 'len' => 2 - ), - array( - 'type' => 'text', - 'name' => 'escaped', - 'text' => __('Columns escaped with:'), - 'size' => 2, - 'len' => 2 - ), - array( - 'type' => 'text', - 'name' => 'new_line', - 'text' => __('Lines terminated with:'), - 'size' => 2 - ) - ); - - if ($plugin_param !== 'table') { - $plugin_list['csv']['options'][] = array( - 'type' => 'bool', - 'name' => 'col_names', - 'text' => __( - 'The first line of the file contains the table column names ' - . '(if this is unchecked, the first line will become part of the' - . ' data)' - ) - ); - } else { - $hint = new PMA_Message( - __( - 'If the data in each row of the file is not' - . ' in the same order as in the database, list the corresponding' - . ' column names here. Column names must be separated by commas' - . ' and not enclosed in quotations.' - ) - ); - $plugin_list['csv']['options'][] = array( - 'type' => 'text', - 'name' => 'columns', - 'text' => __('Column names: ') . PMA_showHint($hint) - ); - } - - $plugin_list['csv']['options'][] = array('type' => 'end_group'); - - /* We do not define function when plugin is just queried for information above */ - return; -} - -$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) { - PMA_mysqlDie($message->getMessage(), '', '', $err_url); -} - -$buffer = ''; -$required_fields = 0; - -if (! $analyze) { - if (isset($csv_replace)) { - $sql_template = 'REPLACE'; - } else { - $sql_template = 'INSERT'; - if (isset($csv_ignore)) { - $sql_template .= ' IGNORE'; - } - } - $sql_template .= ' INTO ' . PMA_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\0\x0B`"); - $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 .= PMA_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 ($analyze) { - 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 .= '\'' . PMA_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 ($analyze) { - /* 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; -} -?> diff --git a/libraries/import/docsql.php b/libraries/import/docsql.php deleted file mode 100644 index 47b9c389e2..0000000000 --- a/libraries/import/docsql.php +++ /dev/null @@ -1,97 +0,0 @@ - __('DocSQL'), // text to be displayed as choice - 'extension' => '', // extension this plugin can handle - 'options' => array( // array of options for your plugin (optional) - array('type' => 'begin_group', 'name' => 'general_opts'), - array('type' => 'text', 'name' => 'table', 'text' => __('Table name')), - array('type' => 'end_group') - ), - 'options_text' => __('Options'), // text to describe plugin options (must be set if options are used) - ); - /* We do not define function when plugin is just queried for information above */ - return; -} - -$tab = $_POST['docsql_table']; -$buffer = ''; -/* Read whole buffer, we except it is small enough */ -while (!$finished && !$error && !$timeout_passed) { - $data = PMA_importGetNextChunk(); - if ($data === false) { - // subtract data we didn't handle yet and stop processing - break; - } elseif ($data === true) { - // nothing to read - break; - } else { - // Append new data to buffer - $buffer .= $data; - } -} // End of import loop -/* Process the data */ -if ($data === true && !$error && !$timeout_passed) { - $buffer = str_replace("\r\n", "\n", $buffer); - $buffer = str_replace("\r", "\n", $buffer); - $lines = explode("\n", $buffer); - foreach ($lines AS $lkey => $line) { - //echo '

' . $line . '

'; - $inf = explode('|', $line); - if (!empty($inf[1]) && strlen(trim($inf[1])) > 0) { - $qry = ' - INSERT INTO - ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' - (db_name, table_name, column_name, comment) - VALUES ( - \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\', - \'' . PMA_sqlAddSlashes(trim($tab)) . '\', - \'' . PMA_sqlAddSlashes(trim($inf[0])) . '\', - \'' . PMA_sqlAddSlashes(trim($inf[1])) . '\')'; - PMA_importRunQuery($qry, $qry . '-- ' . htmlspecialchars($tab) . '.' . htmlspecialchars($inf[0]), true); - } // end inf[1] exists - if (!empty($inf[2]) && strlen(trim($inf[2])) > 0) { - $for = explode('->', $inf[2]); - $qry = ' - INSERT INTO - ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' - (master_db, master_table, master_field, foreign_db, foreign_table, foreign_field) - VALUES ( - \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\', - \'' . PMA_sqlAddSlashes(trim($tab)) . '\', - \'' . PMA_sqlAddSlashes(trim($inf[0])) . '\', - \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\', - \'' . PMA_sqlAddSlashes(trim($for[0])) . '\', - \'' . PMA_sqlAddSlashes(trim($for[1])) . '\')'; - PMA_importRunQuery($qry, $qry . '-- ' . htmlspecialchars($tab) . '.' . htmlspecialchars($inf[0]) . '(' . htmlspecialchars($inf[2]) . ')', true); - } // end inf[2] exists - } // End lines loop -} // End import -// Commit any possible data in buffers -PMA_importRunQuery(); -?> diff --git a/libraries/import/ldi.php b/libraries/import/ldi.php deleted file mode 100644 index a339b2c654..0000000000 --- a/libraries/import/ldi.php +++ /dev/null @@ -1,155 +0,0 @@ - 0) { - $tmp = PMA_DBI_fetch_row($result); - if ($tmp[1] == 'ON') { - $GLOBALS['cfg']['Import']['ldi_local_option'] = true; - } - } - PMA_DBI_free_result($result); - unset($result); - } - $plugin_list['ldi'] = array( - 'text' => __('CSV using LOAD DATA'), - // Following is nonsense, however we want to default to our parser for csv - 'extension' => 'ldi', - 'options' => array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'bool', - 'name' => 'replace', - 'text' => __('Replace table data with file') - ), - array( - 'type' => 'bool', - 'name' => 'ignore', - 'text' => __('Do not abort on INSERT error') - ), - array( - 'type' => 'text', - 'name' => 'terminated', - 'text' => __('Columns terminated by'), - 'size' => 2, - 'len' => 2 - ), - array( - 'type' => 'text', - 'name' => 'enclosed', - 'text' => __('Columns enclosed by'), - 'size' => 2, - 'len' => 2 - ), - array( - 'type' => 'text', - 'name' => 'escaped', - 'text' => __('Columns escaped by'), - 'size' => 2, - 'len' => 2 - ), - array( - 'type' => 'text', - 'name' => 'new_line', - 'text' => __('Lines terminated by'), - 'size' => 2 - ), - array( - 'type' => 'text', - 'name' => 'columns', - 'text' => __('Column names') - ), - array( - 'type' => 'bool', - 'name' => 'local_option', - 'text' => __('Use LOCAL keyword') - ), - array( - 'type' => 'end_group' - ) - ), - 'options_text' => __('Options'), - ); - /* We do not define function when plugin is just queried for information above */ - return; -} - -if ($import_file == 'none' || $compression != 'none' || $charset_conversion) { - // We handle only some kind of data! - $message = PMA_Message::error(__('This plugin does not support compressed imports!')); - $error = true; - return; -} - -$sql = 'LOAD DATA'; -if (isset($ldi_local_option)) { - $sql .= ' LOCAL'; -} -$sql .= ' INFILE \'' . PMA_sqlAddSlashes($import_file) . '\''; -if (isset($ldi_replace)) { - $sql .= ' REPLACE'; -} elseif (isset($ldi_ignore)) { - $sql .= ' IGNORE'; -} -$sql .= ' INTO TABLE ' . PMA_backquote($table); - -if (strlen($ldi_terminated) > 0) { - $sql .= ' FIELDS TERMINATED BY \'' . $ldi_terminated . '\''; -} -if (strlen($ldi_enclosed) > 0) { - $sql .= ' ENCLOSED BY \'' . PMA_sqlAddSlashes($ldi_enclosed) . '\''; -} -if (strlen($ldi_escaped) > 0) { - $sql .= ' ESCAPED BY \'' . PMA_sqlAddSlashes($ldi_escaped) . '\''; -} -if (strlen($ldi_new_line) > 0) { - if ($ldi_new_line == 'auto') { - $ldi_new_line = PMA_whichCrlf() == "\n" ? '\n' : '\r\n'; - } - $sql .= ' LINES TERMINATED BY \'' . $ldi_new_line . '\''; -} -if ($skip_queries > 0) { - $sql .= ' IGNORE ' . $skip_queries . ' LINES'; - $skip_queries = 0; -} -if (strlen($ldi_columns) > 0) { - $sql .= ' ('; - $tmp = preg_split('/,( ?)/', $ldi_columns); - $cnt_tmp = count($tmp); - for ($i = 0; $i < $cnt_tmp; $i++) { - if ($i > 0) { - $sql .= ', '; - } - /* Trim also `, if user already included backquoted fields */ - $sql .= PMA_backquote(trim($tmp[$i], " \t\r\n\0\x0B`")); - } // end for - $sql .= ')'; -} - -PMA_importRunQuery($sql, $sql); -PMA_importRunQuery(); -$finished = true; -?> diff --git a/libraries/import/mediawiki.php b/libraries/import/mediawiki.php deleted file mode 100644 index 6a5bd9005a..0000000000 --- a/libraries/import/mediawiki.php +++ /dev/null @@ -1,489 +0,0 @@ - __('MediaWiki Table'), - 'extension' => 'txt', - 'mime_type' => 'text/plain', - 'options' => array(), - 'options_text' => __('Options'), - ); - - // We do not define function when plugin is just - // queried for information above - return; -} - -// Defaults for parser - -// The buffer that will be used to store chunks read from the imported file -$buffer = ''; - -// Used as storage for the last part of the current chunk data -// Will be appended to the first line of the next chunk, if there is one -$last_chunk_line = ''; - -// Remembers whether the current buffer line is part of a comment -$inside_comment = false; -// Remembers whether the current buffer line is part of a data comment -$inside_data_comment = false; -// Remembers whether the current buffer line is part of a structure comment -$inside_structure_comment = false; - -// MediaWiki only accepts "\n" as row terminator -$mediawiki_new_line = "\n"; - -// Initialize the name of the current table -$cur_table_name = ""; - -while (! $finished && ! $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); - // Don't parse string if we're not at the end - // and don't have a new line inside - if ( strpos($buffer, $mediawiki_new_line) === false ) { - continue; - } - } - - // Because of reading chunk by chunk, the first line from the buffer - // contains only a portion of an actual line from the imported file. - // Therefore, we have to append it to the last line from the previous - // chunk. If we are at the first chunk, $last_chunk_line should be empty. - $buffer = $last_chunk_line . $buffer; - - // Process the buffer line by line - $buffer_lines = explode($mediawiki_new_line, $buffer); - - $full_buffer_lines_count = count($buffer_lines); - // If the reading is not finalised, the final line of the current chunk - // will not be complete - if (! $finished) { - $full_buffer_lines_count -= 1; - $last_chunk_line = $buffer_lines[$full_buffer_lines_count]; - } - - for ($line_nr = 0; $line_nr < $full_buffer_lines_count; ++ $line_nr) { - $cur_buffer_line = trim($buffer_lines[$line_nr]); - - // If the line is empty, go to the next one - if ( $cur_buffer_line === '' ) { - continue; - } - - $first_character = $cur_buffer_line[0]; - $matches = array(); - - // Check beginnning of comment - if (! strcmp(substr($cur_buffer_line, 0, 4), "")) { - // Only data comments are closed. The structure comments will - // be closed when a data comment begins (in order to skip - // structure tables) - if ($inside_data_comment) { - $inside_data_comment = false; - } - - // End comments that are not related to table structure - if (! $inside_structure_comment) { - $inside_comment = false; - } - } else { - // Check table name - $match_table_name = array(); - if (preg_match( - "/^Table data for `(.*)`$/", - $cur_buffer_line, - $match_table_name - ) - ) { - $cur_table_name = $match_table_name[1]; - $inside_data_comment = true; - - // End ignoring structure rows - if ($inside_structure_comment) { - $inside_structure_comment = false; - } - } elseif (preg_match( - "/^Table structure for `(.*)`$/", - $cur_buffer_line, - $match_table_name - ) - ) { - // The structure comments will be ignored - $inside_structure_comment = true; - } - } - continue; - } elseif (preg_match('/^\{\|(.*)$/', $cur_buffer_line, $matches)) { - // Check start of table - - // This will store all the column info on all rows from - // the current table read from the buffer - $cur_temp_table = array(); - - // Will be used as storage for the current row in the buffer - // Once all its columns are read, it will be added to - // $cur_temp_table and then it will be emptied - $cur_temp_line = array(); - - // Helps us differentiate the header columns - // from the normal columns - $in_table_header = false; - // End processing because the current line does not - // contain any column information - } elseif (substr($cur_buffer_line, 0, 2) === '|-' - || substr($cur_buffer_line, 0, 2) === '|+' - || substr($cur_buffer_line, 0, 2) === '|}' - ) { - // Check begin row or end table - - // Add current line to the values storage - if (! empty($cur_temp_line)) { - // If the current line contains header cells ( marked with '!' ), - // it will be marked as table header - if ( $in_table_header ) { - // Set the header columns - $cur_temp_table_headers = $cur_temp_line; - } else { - // Normal line, add it to the table - $cur_temp_table [] = $cur_temp_line; - } - } - - // Empty the temporary buffer - $cur_temp_line = array(); - - // No more processing required at the end of the table - if (substr($cur_buffer_line, 0, 2) === '|}') { - $current_table = array( - $cur_table_name, - $cur_temp_table_headers, - $cur_temp_table - ); - - // Import the current table data into the database - PMA_importDataOneTable($current_table); - - // Reset table name - $cur_table_name = ""; - } - // What's after the row tag is now only attributes - - } elseif (($first_character === '|') || ($first_character === '!')) { - // Check cell elements - - // Header cells - if ($first_character === '!') { - // Mark as table header, but treat as normal row - $cur_buffer_line = str_replace('!!', '||', $cur_buffer_line); - // Will be used to set $cur_temp_line as table header - $in_table_header = true; - } else { - $in_table_header = false; - } - - // Loop through each table cell - $cells = PMA_explodeMarkup($cur_buffer_line); - foreach ($cells as $cell) { - // A cell could contain both parameters and data - $cell_data = explode('|', $cell, 2); - - // A '|' inside an invalid link should not - // be mistaken as delimiting cell parameters - if (strpos($cell_data[0], '[[') === true ) { - if (count($cell_data) == 1) { - $cell = $cell_data[0]; - } else { - $cell = $cell_data[1]; - } - } - - // Delete the beginning of the column, if there is one - $cell = trim($cell); - $col_start_chars = array( "|", "!"); - foreach ($col_start_chars as $col_start_char) { - if (strpos($cell, $col_start_char) === 0) { - $cell = trim(substr($cell, 1)); - } - } - - // Add the cell to the row - $cur_temp_line [] = $cell; - } // foreach $cells - } else { - // If it's none of the above, then the current line has a bad format - $message = PMA_Message::error( - __('Invalid format of mediawiki input on line:
%s.') - ); - $message->addParam($cur_buffer_line); - $error = true; - } - } // End treating full buffer lines -} // while - finished parsing buffer - -/** - * Imports data from a single table - * - * @param array $table containing all table info: - * - * $table[0] - string containing table name - * $table[1] - array[] of table headers - * $table[2] - array[][] of table content rows - * - * - * @global bool $analyze whether to scan for column types - * - * @return void - */ -function PMA_importDataOneTable ($table) -{ - global $analyze; - if ($analyze) { - // Set the table name - PMA_setTableName($table[0]); - - // Set generic names for table headers if they don't exist - PMA_setTableHeaders($table[1], $table[2][0]); - - // Create the tables array to be used in PMA_buildSQL() - $tables = array(); - $tables [] = array($table[0], $table[1], $table[2]); - - // Obtain the best-fit MySQL types for each column - $analyses = array(); - $analyses [] = PMA_analyzeTable($tables[0]); - - PMA_executeImportTables($tables, $analyses); - } - - // Commit any possible data in buffers - PMA_importRunQuery(); -} - -/** - * Sets the table name - * - * @param string &$table_name reference to the name of the table - * - * @return void - */ -function PMA_setTableName(&$table_name) -{ - if (empty($table_name)) { - $result = PMA_DBI_fetch_result('SHOW TABLES'); - // todo check if the name below already exists - $table_name = 'TABLE '.(count($result) + 1); - } -} - -/** - * Set generic names for table headers, if they don't exist - * - * @param array &$table_headers reference to the array containing the headers - * of a table - * @param array $table_row array containing the first content row - * - * @return void - */ -function PMA_setTableHeaders(&$table_headers, $table_row) -{ - if (empty($table_headers)) { - // The first table row should contain the number of columns - // If they are not set, generic names will be given (COL 1, COL 2, etc) - $num_cols = count($table_row); - for ($i = 0; $i < $num_cols; ++ $i) { - $table_headers [$i] = 'COL '. ($i + 1); - } - } -} - -/** - * Sets the database name and additional options and calls PMA_buildSQL() - * Used in PMA_importDataAllTables() and PMA_importDataOneTable() - * - * @param array &$tables structure: - * array( - * array(table_name, array() column_names, array()() rows) - * ) - * @param array &$analyses structure: - * $analyses = array( - * array(array() column_types, array() column_sizes) - * ) - * - * @global string $db name of the database to import in - * - * @return void - */ -function PMA_executeImportTables(&$tables, &$analyses) -{ - global $db; - - // $db_name : The currently selected database name, if applicable - // No backquotes - // $options : An associative array of options - if (strlen($db)) { - $db_name = $db; - $options = array('create_db' => false); - } else { - $db_name = 'mediawiki_DB'; - $options = null; - } - - // Array of SQL strings - // Non-applicable parameters - $create = null; - - // Create and execute necessary SQL statements from data - PMA_buildSQL($db_name, $tables, $analyses, $create, $options); - - unset($tables); - unset($analyses); -} - - -/** - * Replaces all instances of the '||' separator between delimiters - * in a given string - * - * @param string $start_delim start delimiter - * @param string $end_delim end delimiter - * @param string $replace the string to be replaced with - * @param string $subject the text to be replaced - * - * @return string with replacements - */ -function PMA_delimiterReplace($start_delim, $end_delim, $replace, $subject) -{ - // String that will be returned - $cleaned = ""; - // Possible states of current character - $inside_tag = false; - $inside_attribute = false; - // Attributes can be declared with either " or ' - $start_attribute_character = false; - - // The full separator is "||"; - // This rembembers if the previous character was '|' - $partial_separator = false; - - // Parse text char by char - for ($i = 0; $i < strlen($subject); $i ++) { - $cur_char = $subject[$i]; - // Check for separators - if ($cur_char == '|') { - // If we're not inside a tag, then this is part of a real separator, - // so we append it to the current segment - if (! $inside_attribute) { - $cleaned .= $cur_char; - if ($partial_separator) { - $inside_tag = false; - $inside_attribute = false; - } - } elseif ($partial_separator) { - // If we are inside a tag, we replace the current char with - // the placeholder and append that to the current segment - $cleaned .= $replace; - } - - // If the previous character was also '|', then this ends a - // full separator. If not, this may be the beginning of one - $partial_separator = ! $partial_separator; - } else { - // If we're inside a tag attribute and the current character is - // not '|', but the previous one was, it means that the single '|' - // was not appended, so we append it now - if ($partial_separator && $inside_attribute) { - $cleaned .= "|"; - } - // If the char is different from "|", no separator can be formed - $partial_separator = false; - - // any other character should be appended to the current segment - $cleaned .= $cur_char; - - if ($cur_char == '<' && ! $inside_attribute) { - // start of a tag - $inside_tag = true; - } elseif ($cur_char == '>' && ! $inside_attribute) { - // end of a tag - $inside_tag = false; - } elseif (($cur_char == '"' || $cur_char == "'") && $inside_tag) { - // start or end of an attribute - if (! $inside_attribute) { - $inside_attribute = true; - // remember the attribute`s declaration character (" or ') - $start_attribute_character = $cur_char; - } else { - if ($cur_char == $start_attribute_character) { - $inside_attribute = false; - // unset attribute declaration character - $start_attribute_character = false; - } - } - } - } - } // end for each character in $subject - - return $cleaned; -} - -/** - * Separates a string into items, similarly to explode - * Uses the '||' separator (which is standard in the mediawiki format) - * and ignores any instances of it inside markup tags - * Used in parsing buffer lines containing data cells - * - * @param string $text text to be split - * - * @return array - */ -function PMA_explodeMarkup($text) -{ - $separator = "||"; - $placeholder = "\x00"; - - // Remove placeholder instances - $text = str_replace($placeholder, '', $text); - - // Replace instances of the separator inside HTML-like - // tags with the placeholder - $cleaned = PMA_delimiterReplace("<", ">", $placeholder, $text); - // Explode, then put the replaced separators back in - $items = explode($separator, $cleaned); - foreach ($items as $i => $str) { - $items[$i] = str_replace($placeholder, $separator, $str); - } - - return $items; -} -?> diff --git a/libraries/import/ods.php b/libraries/import/ods.php deleted file mode 100644 index 5407c127b4..0000000000 --- a/libraries/import/ods.php +++ /dev/null @@ -1,329 +0,0 @@ - __('Open Document Spreadsheet'), - 'extension' => 'ods', - 'options' => array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'bool', - 'name' => 'col_names', - 'text' => __('The first line of the file contains the table column names (if this is unchecked, the first line will become part of the data)') - ), - array( - 'type' => 'bool', - 'name' => 'empty_rows', - 'text' => __('Do not import empty rows') - ), - array( - 'type' => 'bool', - 'name' => 'recognize_percentages', - 'text' => __('Import percentages as proper decimals (ex. 12.00% to .12)') - ), - array( - 'type' => 'bool', - 'name' => 'recognize_currency', - 'text' => __('Import currencies (ex. $5.00 to 5.00)') - ), - array('type' => 'end_group') - ), - 'options_text' => __('Options'), - ); - /* We do not define function when plugin is just queried for information above */ - return; -} - -$i = 0; -$len = 0; -$buffer = ""; - -/** - * Read in the file via PMA_importGetNextChunk so that - * it can process compressed files - */ -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); - } -} - -unset($data); - -/** - * Disable loading of external XML entities. - */ -libxml_disable_entity_loader(); - -/** - * Load the XML string - * - * The option LIBXML_COMPACT is specified because it can - * result in increased performance without the need to - * alter the code in any way. It's basically a freebee. - */ -$xml = simplexml_load_string($buffer, "SimpleXMLElement", LIBXML_COMPACT); - -unset($buffer); - -if ($xml === false) { - $sheets = array(); - $message = PMA_Message::error(__('The XML file specified was either malformed or incomplete. Please correct the issue and try again.')); - $error = true; -} else { - $sheets = $xml->children('office', true)->{'body'}->{'spreadsheet'}->children('table', true); -} - -$tables = array(); - -$max_cols = 0; - -$row_count = 0; -$col_count = 0; -$col_names = array(); - -$tempRow = array(); -$tempRows = array(); -$rows = array(); - -/* Iterate over tables */ -foreach ($sheets as $sheet) { - $col_names_in_first_row = isset($_REQUEST['ods_col_names']); - - /* Iterate over rows */ - foreach ($sheet as $row) { - $type = $row->getName(); - if (! strcmp('table-row', $type)) { - /* Iterate over columns */ - foreach ($row as $cell) { - $text = $cell->children('text', true); - $cell_attrs = $cell->attributes('office', true); - - if (count($text) != 0) { - $attr = $cell->attributes('table', true); - $num_repeat = (int) $attr['number-columns-repeated']; - $num_iterations = $num_repeat ? $num_repeat : 1; - - for ($k = 0; $k < $num_iterations; $k++) { - if ($_REQUEST['ods_recognize_percentages'] - && ! strcmp('percentage', $cell_attrs['value-type']) - ) { - $value = (double)$cell_attrs['value']; - } elseif ($_REQUEST['ods_recognize_currency'] - && !strcmp('currency', $cell_attrs['value-type']) - ) { - $value = (double)$cell_attrs['value']; - } else { - /* We need to concatenate all paragraphs */ - $values = array(); - foreach ($text as $paragraph) { - $values[] = (string)$paragraph; - } - $value = implode("\n", $values); - } - if (! $col_names_in_first_row) { - $tempRow[] = $value; - } else { - $col_names[] = $value; - } - - ++$col_count; - } - } else { - /* Number of blank columns repeated */ - if ($col_count < count($row->children('table', true)) - 1) { - $attr = $cell->attributes('table', true); - $num_null = (int)$attr['number-columns-repeated']; - - if ($num_null) { - if (! $col_names_in_first_row) { - for ($i = 0; $i < $num_null; ++$i) { - $tempRow[] = 'NULL'; - ++$col_count; - } - } else { - for ($i = 0; $i < $num_null; ++$i) { - $col_names[] = PMA_getColumnAlphaName($col_count + 1); - ++$col_count; - } - } - } else { - if (! $col_names_in_first_row) { - $tempRow[] = 'NULL'; - } else { - $col_names[] = PMA_getColumnAlphaName($col_count + 1); - } - - ++$col_count; - } - } - } - } - - /* Find the widest row */ - if ($col_count > $max_cols) { - $max_cols = $col_count; - } - - /* Don't include a row that is full of NULL values */ - if (! $col_names_in_first_row) { - if ($_REQUEST['ods_empty_rows']) { - foreach ($tempRow as $cell) { - if (strcmp('NULL', $cell)) { - $tempRows[] = $tempRow; - break; - } - } - } else { - $tempRows[] = $tempRow; - } - } - - $col_count = 0; - $col_names_in_first_row = false; - $tempRow = array(); - } - } - - /* Skip over empty sheets */ - if (count($tempRows) == 0 || count($tempRows[0]) == 0) { - $col_names = array(); - $tempRow = array(); - $tempRows = array(); - continue; - } - - /** - * Fill out each row as necessary to make - * every one exactly as wide as the widest - * row. This included column names. - */ - - /* Fill out column names */ - for ($i = count($col_names); $i < $max_cols; ++$i) { - $col_names[] = PMA_getColumnAlphaName($i + 1); - } - - /* Fill out all rows */ - $num_rows = count($tempRows); - for ($i = 0; $i < $num_rows; ++$i) { - for ($j = count($tempRows[$i]); $j < $max_cols; ++$j) { - $tempRows[$i][] = 'NULL'; - } - } - - /* Store the table name so we know where to place the row set */ - $tbl_attr = $sheet->attributes('table', true); - $tables[] = array((string)$tbl_attr['name']); - - /* Store the current sheet in the accumulator */ - $rows[] = array((string)$tbl_attr['name'], $col_names, $tempRows); - $tempRows = array(); - $col_names = array(); - $max_cols = 0; -} - -unset($tempRow); -unset($tempRows); -unset($col_names); -unset($sheets); -unset($xml); - -/** - * Bring accumulated rows into the corresponding table - */ -$num_tbls = count($tables); -for ($i = 0; $i < $num_tbls; ++$i) { - for ($j = 0; $j < count($rows); ++$j) { - if (! strcmp($tables[$i][TBL_NAME], $rows[$j][TBL_NAME])) { - if (! isset($tables[$i][COL_NAMES])) { - $tables[$i][] = $rows[$j][COL_NAMES]; - } - - $tables[$i][ROWS] = $rows[$j][ROWS]; - } - } -} - -/* No longer needed */ -unset($rows); - -/* Obtain the best-fit MySQL types for each column */ -$analyses = array(); - -$len = count($tables); -for ($i = 0; $i < $len; ++$i) { - $analyses[] = PMA_analyzeTable($tables[$i]); -} - -/** - * 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 = 'ODS_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(); -?> diff --git a/libraries/import/shp.php b/libraries/import/shp.php deleted file mode 100644 index 252f114a95..0000000000 --- a/libraries/import/shp.php +++ /dev/null @@ -1,508 +0,0 @@ - __('ESRI Shape File'), - 'extension' => 'shp', - 'options' => array(), - 'options_text' => __('Options'), - ); -} else { - - if ((int) ini_get('memory_limit') < 512) { - @ini_set('memory_limit', '512M'); - } - @set_time_limit(300); - - - // Append the bfShapeFiles directory to the include path variable - set_include_path( - get_include_path() . PATH_SEPARATOR . getcwd() . '/libraries/bfShapeFiles/' - ); - include_once './libraries/bfShapeFiles/ShapeFile.lib.php'; - - $GLOBALS['finished'] = false; - $buffer = ''; - $eof = false; - - // Returns specified number of bytes from the buffer. - // Buffer automatically fetches next chunk of data when the buffer falls short. - // Sets $eof when $GLOBALS['finished'] is set and the buffer falls short. - function readFromBuffer($length) - { - global $buffer, $eof; - - if (strlen($buffer) < $length) { - if ($GLOBALS['finished']) { - $eof = true; - } else { - $buffer .= PMA_importGetNextChunk(); - } - } - $result = substr($buffer, 0, $length); - $buffer = substr($buffer, $length); - return $result; - } - - /** - * This class extends ShapeFile class to cater the following phpMyAdmin - * specific requirements. - * 1) To load data from .dbf file only when the dBase extension is available. - * 2) To use PMA_importGetNextChunk() functionality to read data, rather than - * reading directly from a file. Using readFromBuffer() in place of fread(). - * This makes it possible to use compressions. - * - * @package PhpMyAdmin-Import - * @subpackage ESRI_Shape - */ - class PMA_ShapeFile extends ShapeFile - { - /** - * Returns whether the 'dbase' extension is loaded - * - * @return boolean whether the 'dbase' extension is loaded - */ - function _isDbaseLoaded() - { - return extension_loaded('dbase'); - } - - /** - * Loads ESRI shape data from the imported file - * - * @param string $FileName not used, it's here only to match the method - * signature of the method being overidden - * - * @return void - * @see ShapeFile::loadFromFile() - */ - function loadFromFile($FileName) - { - $this->_loadHeaders(); - $this->_loadRecords(); - if ($this->_isDbaseLoaded()) { - $this->_closeDBFFile(); - } - } - - /** - * Loads metadata from the ESRI shape file header - * - * @return void - * @see ShapeFile::_loadHeaders() - */ - function _loadHeaders() - { - readFromBuffer(24); - $this->fileLength = loadData("N", readFromBuffer(4)); - - readFromBuffer(4); - $this->shapeType = loadData("V", readFromBuffer(4)); - - $this->boundingBox = array(); - $this->boundingBox["xmin"] = loadData("d", readFromBuffer(8)); - $this->boundingBox["ymin"] = loadData("d", readFromBuffer(8)); - $this->boundingBox["xmax"] = loadData("d", readFromBuffer(8)); - $this->boundingBox["ymax"] = loadData("d", readFromBuffer(8)); - - if ($this->_isDbaseLoaded() && $this->_openDBFFile()) { - $this->DBFHeader = $this->_loadDBFHeader(); - } - } - - /** - * Loads geometry data from the ESRI shape file - * - * @return void - * @see ShapeFile::_loadRecords() - */ - function _loadRecords() - { - global $eof; - readFromBuffer(32); - while (true) { - $record = new PMA_ShapeRecord(-1); - $record->loadFromFile($this->SHPFile, $this->DBFFile); - if ($record->lastError != "") { - return false; - } - if ($eof) { - break; - } - - $this->records[] = $record; - } - } - } - - /** - * This class extends ShapeRecord class to cater the following phpMyAdmin - * specific requirements. - * 1) To load data from .dbf file only when the dBase extension is available. - * 2) To use PMA_importGetNextChunk() functionality to read data, rather than - * reading directly from a file. Using readFromBuffer() in place of fread(). - * This makes it possible to use compressions. - * - * @package PhpMyAdmin-Import - * @subpackage ESRI_Shape - */ - class PMA_ShapeRecord extends ShapeRecord - { - /** - * Loads a geometry data record from the file - * - * @param object &$SHPFile .shp file - * @param object &$DBFFile .dbf file - * - * @return void - * @see ShapeRecord::loadFromFile() - */ - function loadFromFile(&$SHPFile, &$DBFFile) - { - $this->DBFFile = $DBFFile; - $this->_loadHeaders(); - - switch ($this->shapeType) { - case 0: - $this->_loadNullRecord(); - break; - case 1: - $this->_loadPointRecord(); - break; - case 3: - $this->_loadPolyLineRecord(); - break; - case 5: - $this->_loadPolygonRecord(); - break; - case 8: - $this->_loadMultiPointRecord(); - break; - default: - $this->setError( - sprintf( - __("Geometry type '%s' is not supported by MySQL."), - $this->shapeType - ) - ); - break; - } - if (extension_loaded('dbase') && isset($this->DBFFile)) { - $this->_loadDBFData(); - } - } - - /** - * Loads metadata from the ESRI shape record header - * - * @return void - * @see ShapeRecord::_loadHeaders() - */ - function _loadHeaders() - { - $this->recordNumber = loadData("N", readFromBuffer(4)); - readFromBuffer(4); - $this->shapeType = loadData("V", readFromBuffer(4)); - } - - /** - * Loads data from a point record - * - * @return void - * @see ShapeRecord::_loadPoint() - */ - function _loadPoint() - { - $data = array(); - - $data["x"] = loadData("d", readFromBuffer(8)); - $data["y"] = loadData("d", readFromBuffer(8)); - - return $data; - } - - /** - * Loads data from a multipoint record - * - * @return void - * @see ShapeRecord::_loadMultiPointRecord() - */ - function _loadMultiPointRecord() - { - $this->SHPData = array(); - $this->SHPData["xmin"] = loadData("d", readFromBuffer(8)); - $this->SHPData["ymin"] = loadData("d", readFromBuffer(8)); - $this->SHPData["xmax"] = loadData("d", readFromBuffer(8)); - $this->SHPData["ymax"] = loadData("d", readFromBuffer(8)); - - $this->SHPData["numpoints"] = loadData("V", readFromBuffer(4)); - - for ($i = 0; $i <= $this->SHPData["numpoints"]; $i++) { - $this->SHPData["points"][] = $this->_loadPoint(); - } - } - - /** - * Loads data from a polyline record - * - * @return void - * @see ShapeRecord::_loadPolyLineRecord() - */ - function _loadPolyLineRecord() - { - $this->SHPData = array(); - $this->SHPData["xmin"] = loadData("d", readFromBuffer(8)); - $this->SHPData["ymin"] = loadData("d", readFromBuffer(8)); - $this->SHPData["xmax"] = loadData("d", readFromBuffer(8)); - $this->SHPData["ymax"] = loadData("d", readFromBuffer(8)); - - $this->SHPData["numparts"] = loadData("V", readFromBuffer(4)); - $this->SHPData["numpoints"] = loadData("V", readFromBuffer(4)); - - for ($i = 0; $i < $this->SHPData["numparts"]; $i++) { - $this->SHPData["parts"][$i] = loadData("V", readFromBuffer(4)); - } - - $readPoints = 0; - reset($this->SHPData["parts"]); - while (list($partIndex, $partData) = each($this->SHPData["parts"])) { - if (! isset($this->SHPData["parts"][$partIndex]["points"]) - || !is_array($this->SHPData["parts"][$partIndex]["points"]) - ) { - $this->SHPData["parts"][$partIndex] = array(); - $this->SHPData["parts"][$partIndex]["points"] = array(); - } - while (! in_array($readPoints, $this->SHPData["parts"]) - && ($readPoints < ($this->SHPData["numpoints"])) - ) { - $this->SHPData["parts"][$partIndex]["points"][] - = $this->_loadPoint(); - $readPoints++; - } - } - } - } - - $shp = new PMA_ShapeFile(1); - // If the zip archive has more than one file, - // get the correct content to the buffer from .shp file. - if ($compression == 'application/zip' - && PMA_getNoOfFilesInZip($import_file) > 1 - ) { - $zip_content = PMA_getZipContents($import_file, '/^.*\.shp$/i'); - $GLOBALS['import_text'] = $zip_content['data']; - } - - $temp_dbf_file = false; - // We need dbase extension to handle .dbf file - if (extension_loaded('dbase')) { - // If we can extract the zip archive to 'TempDir' - // and use the files in it for import - if ($compression == 'application/zip' - && ! empty($cfg['TempDir']) - && is_writable($cfg['TempDir']) - ) { - $dbf_file_name = PMA_findFileFromZipArchive( - '/^.*\.dbf$/i', $import_file - ); - // If the corresponding .dbf file is in the zip archive - if ($dbf_file_name) { - // Extract the .dbf file and point to it. - $extracted = PMA_zipExtract( - $import_file, - realpath($cfg['TempDir']), - array($dbf_file_name) - ); - if ($extracted) { - $dbf_file_path = realpath($cfg['TempDir']) - . (PMA_IS_WINDOWS ? '\\' : '/') . $dbf_file_name; - $temp_dbf_file = true; - // Replace the .dbf with .*, as required - // by the bsShapeFiles library. - $file_name = substr( - $dbf_file_path, 0, strlen($dbf_file_path) - 4 - ) . '.*'; - $shp->FileName = $file_name; - } - } - } elseif (! empty($local_import_file) - && ! empty($cfg['UploadDir']) - && $compression == 'none' - ) { - // If file is in UploadDir, use .dbf file in the same UploadDir - // to load extra data. - // Replace the .shp with .*, - // so the bsShapeFiles library correctly locates .dbf file. - $file_name = substr($import_file, 0, strlen($import_file) - 4) . '.*'; - $shp->FileName = $file_name; - } - } - - // Load data - $shp->loadFromFile(''); - if ($shp->lastError != "") { - $error = true; - $message = PMA_Message::error(__('There was an error importing the ESRI shape file: "%s".')); - $message->addParam($shp->lastError); - return; - } - - // Delete the .dbf file extracted to 'TempDir' - if ($temp_dbf_file) { - unlink($dbf_file_path); - } - - $esri_types = array( - 0 => 'Null Shape', - 1 => 'Point', - 3 => 'PolyLine', - 5 => 'Polygon', - 8 => 'MultiPoint', - 11 => 'PointZ', - 13 => 'PolyLineZ', - 15 => 'PolygonZ', - 18 => 'MultiPointZ', - 21 => 'PointM', - 23 => 'PolyLineM', - 25 => 'PolygonM', - 28 => 'MultiPointM', - 31 => 'MultiPatch', - ); - - switch ($shp->shapeType) { - // ESRI Null Shape - case 0: - break; - // ESRI Point - case 1: - $gis_type = 'point'; - break; - // ESRI PolyLine - case 3: - $gis_type = 'multilinestring'; - break; - // ESRI Polygon - case 5: - $gis_type = 'multipolygon'; - break; - // ESRI MultiPoint - case 8: - $gis_type = 'multipoint'; - break; - default: - $error = true; - if (! isset($esri_types[$shp->shapeType])) { - $message = PMA_Message::error(__('You tried to import an invalid file or the imported file contains invalid data')); - } else { - $message = PMA_Message::error(__('MySQL Spatial Extension does not support ESRI type "%s".')); - $message->addParam($param); - } - return; - } - - if (isset($gis_type)) { - include_once './libraries/gis/pma_gis_factory.php'; - $gis_obj = PMA_GIS_Factory::factory($gis_type); - } else { - $gis_obj = null; - } - - $num_rows = count($shp->records); - // If .dbf file is loaded, the number of extra data columns - $num_data_cols = isset($shp->DBFHeader) ? count($shp->DBFHeader) : 0; - - $rows = array(); - $col_names = array(); - if ($num_rows != 0) { - foreach ($shp->records as $record) { - $tempRow = array(); - if ($gis_obj == null) { - $tempRow[] = null; - } else { - $tempRow[] = "GeomFromText('" - . $gis_obj->getShape($record->SHPData) . "')"; - } - - if (isset($shp->DBFHeader)) { - foreach ($shp->DBFHeader as $c) { - $cell = trim($record->DBFData[$c[0]]); - - if (! strcmp($cell, '')) { - $cell = 'NULL'; - } - - $tempRow[] = $cell; - } - } - $rows[] = $tempRow; - } - } - - if (count($rows) == 0) { - $error = true; - $message = PMA_Message::error(__('The imported file does not contain any data')); - return; - } - - // Column names for spatial column and the rest of the columns, - // if they are available - $col_names[] = 'SPATIAL'; - for ($n = 0; $n < $num_data_cols; $n++) { - $col_names[] = $shp->DBFHeader[$n][0]; - } - - // Set table name based on the number of tables - if (strlen($db)) { - $result = PMA_DBI_fetch_result('SHOW TABLES'); - $table_name = 'TABLE '.(count($result) + 1); - } else { - $table_name = 'TBL_NAME'; - } - $tables = array(array($table_name, $col_names, $rows)); - - // Use data from shape file to chose best-fit MySQL types for each column - $analyses = array(); - $analyses[] = PMA_analyzeTable($tables[0]); - - $table_no = 0; $spatial_col = 0; - $analyses[$table_no][TYPES][$spatial_col] = GEOMETRY; - $analyses[$table_no][FORMATTEDSQL][$spatial_col] = true; - - // Set database name to the currently selected one, if applicable - if (strlen($db)) { - $db_name = $db; - $options = array('create_db' => false); - } else { - $db_name = 'SHP_DB'; - $options = null; - } - - // Created and execute necessary SQL statements from data - $null_param = null; - PMA_buildSQL($db_name, $tables, $analyses, $null_param, $options); - - unset($tables); - unset($analyses); - - $finished = true; - $error = false; - - // Commit any possible data in buffers - PMA_importRunQuery(); -} -?> diff --git a/libraries/import/sql.php b/libraries/import/sql.php deleted file mode 100644 index 4dda0467d1..0000000000 --- a/libraries/import/sql.php +++ /dev/null @@ -1,346 +0,0 @@ - __('SQL'), - 'extension' => 'sql', - 'options_text' => __('Options'), - ); - $compats = PMA_DBI_getCompatibilities(); - if (count($compats) > 0) { - $values = array(); - foreach ($compats as $val) { - $values[$val] = $val; - } - $plugin_list['sql']['options'] = array( - array('type' => 'begin_group', 'name' => 'general_opts'), - array( - 'type' => 'select', - 'name' => 'compatibility', - 'text' => __('SQL compatibility mode:'), - 'values' => $values, - 'doc' => array( - 'manual_MySQL_Database_Administration', - 'Server_SQL_mode', - ), - ), - array( - 'type' => 'bool', - 'name' => 'no_auto_value_on_zero', - 'text' => __('Do not use AUTO_INCREMENT for zero values'), - 'doc' => array( - 'manual_MySQL_Database_Administration', - 'Server_SQL_mode', - 'sqlmode_no_auto_value_on_zero' - ), - - ), - array('type' => 'end_group'), - ); - } - - /* We do not define function when plugin is just queried for information above */ - return; -} - -$buffer = ''; -// Defaults for parser -$sql = ''; -$start_pos = 0; -$i = 0; -$len= 0; -$big_value = 2147483647; -$delimiter_keyword = 'DELIMITER '; // include the space because it's mandatory -$length_of_delimiter_keyword = strlen($delimiter_keyword); - -if (isset($_POST['sql_delimiter'])) { - $sql_delimiter = $_POST['sql_delimiter']; -} else { - $sql_delimiter = ';'; -} - -// Handle compatibility options -$sql_modes = array(); -if (isset($_REQUEST['sql_compatibility']) - && 'NONE' != $_REQUEST['sql_compatibility'] -) { - $sql_modes[] = $_REQUEST['sql_compatibility']; -} -if (isset($_REQUEST['sql_no_auto_value_on_zero'])) { - $sql_modes[] = 'NO_AUTO_VALUE_ON_ZERO'; -} -if (count($sql_modes) > 0) { - PMA_DBI_try_query('SET SQL_MODE="' . implode(',', $sql_modes) . '"'); -} -unset($sql_modes); - -/** - * will be set in PMA_importGetNextChunk() - * - * @global boolean $GLOBALS['finished'] - */ -$GLOBALS['finished'] = false; - -while (! ($GLOBALS['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; - // free memory - unset($data); - // Do not parse string when we're not at the end and don't have ; inside - if ((strpos($buffer, $sql_delimiter, $i) === false) - && ! $GLOBALS['finished'] - ) { - continue; - } - } - // Current length of our buffer - $len = strlen($buffer); - - // Grab some SQL queries out of it - while ($i < $len) { - $found_delimiter = false; - // Find first interesting character - $old_i = $i; - // this is about 7 times faster that looking for each sequence i - // one by one with strpos() - $match = preg_match( - '/(\'|"|#|-- |\/\*|`|(?i)(? unclosed quote, - // but we handle it as end of query - if ($GLOBALS['finished']) { - $endq = true; - $i = $len - 1; - } - $found_delimiter = false; - break; - } - // Was not the quote escaped? - $j = $pos - 1; - while ($buffer[$j] == '\\') { - $j--; - } - // Even count means it was not escaped - $endq = (((($pos - 1) - $j) % 2) == 0); - // Skip the string - $i = $pos; - - if ($first_sql_delimiter < $pos) { - $found_delimiter = false; - } - } - if (!$endq) { - break; - } - $i++; - // Aren't we at the end? - if ($GLOBALS['finished'] && $i == $len) { - $i--; - } else { - continue; - } - } - - // Not enough data to decide - if ((($i == ($len - 1) && ($ch == '-' || $ch == '/')) - || ($i == ($len - 2) && (($ch == '-' && $buffer[$i + 1] == '-') - || ($ch == '/' && $buffer[$i + 1] == '*')))) && !$GLOBALS['finished'] - ) { - break; - } - - // Comments - if ($ch == '#' - || ($i < ($len - 1) && $ch == '-' && $buffer[$i + 1] == '-' - && (($i < ($len - 2) && $buffer[$i + 2] <= ' ') - || ($i == ($len - 1) && $GLOBALS['finished']))) - || ($i < ($len - 1) && $ch == '/' && $buffer[$i + 1] == '*') - ) { - // Copy current string to SQL - if ($start_pos != $i) { - $sql .= substr($buffer, $start_pos, $i - $start_pos); - } - // Skip the rest - $start_of_comment = $i; - // do not use PHP_EOL here instead of "\n", because the export - // file might have been produced on a different system - $i = strpos($buffer, $ch == '/' ? '*/' : "\n", $i); - // didn't we hit end of string? - if ($i === false) { - if ($GLOBALS['finished']) { - $i = $len - 1; - } else { - break; - } - } - // Skip * - if ($ch == '/') { - $i++; - } - // Skip last char - $i++; - // We need to send the comment part in case we are defining - // a procedure or function and comments in it are valuable - $sql .= substr($buffer, $start_of_comment, $i - $start_of_comment); - // Next query part will start here - $start_pos = $i; - // Aren't we at the end? - if ($i == $len) { - $i--; - } else { - continue; - } - } - // Change delimiter, if redefined, and skip it (don't send to server!) - if (strtoupper(substr($buffer, $i, $length_of_delimiter_keyword)) == $delimiter_keyword - && ($i + $length_of_delimiter_keyword < $len) - ) { - // look for EOL on the character immediately after 'DELIMITER ' - // (see previous comment about PHP_EOL) - $new_line_pos = strpos($buffer, "\n", $i + $length_of_delimiter_keyword); - // it might happen that there is no EOL - if (false === $new_line_pos) { - $new_line_pos = $len; - } - $sql_delimiter = substr( - $buffer, - $i + $length_of_delimiter_keyword, - $new_line_pos - $i - $length_of_delimiter_keyword - ); - $i = $new_line_pos + 1; - // Next query part will start here - $start_pos = $i; - continue; - } - - // End of SQL - if ($found_delimiter || ($GLOBALS['finished'] && ($i == $len - 1))) { - $tmp_sql = $sql; - if ($start_pos < $len) { - $length_to_grab = $i - $start_pos; - - if (! $found_delimiter) { - $length_to_grab++; - } - $tmp_sql .= substr($buffer, $start_pos, $length_to_grab); - unset($length_to_grab); - } - // Do not try to execute empty SQL - if (! preg_match('/^([\s]*;)*$/', trim($tmp_sql))) { - $sql = $tmp_sql; - PMA_importRunQuery( - $sql, - substr($buffer, 0, $i + strlen($sql_delimiter)) - ); - $buffer = substr($buffer, $i + strlen($sql_delimiter)); - // Reset parser: - $len = strlen($buffer); - $sql = ''; - $i = 0; - $start_pos = 0; - // Any chance we will get a complete query? - //if ((strpos($buffer, ';') === false) && !$GLOBALS['finished']) { - if (strpos($buffer, $sql_delimiter) === false - && ! $GLOBALS['finished'] - ) { - break; - } - } else { - $i++; - $start_pos = $i; - } - } - } // End of parser loop -} // End of import loop -// Commit any possible data in buffers -PMA_importRunQuery('', substr($buffer, 0, $len)); -PMA_importRunQuery(); -?> diff --git a/libraries/import/upload/apc.php b/libraries/import/upload/apc.php deleted file mode 100644 index 61440def9a..0000000000 --- a/libraries/import/upload/apc.php +++ /dev/null @@ -1,67 +0,0 @@ - $id, - 'finished' => false, - 'percent' => 0, - 'total' => 0, - 'complete' => 0, - 'plugin' => $ID_KEY - ); - } - $ret = $_SESSION[$SESSION_KEY][$id]; - - if (! PMA_import_apcCheck() || $ret['finished']) { - return $ret; - } - $status = apc_fetch('upload_' . $id); - - if ($status) { - $ret['finished'] = (bool)$status['done']; - $ret['total'] = $status['total']; - $ret['complete'] = $status['current']; - - if ($ret['total'] > 0) { - $ret['percent'] = $ret['complete'] / $ret['total'] * 100; - } - - if ($ret['percent'] == 100) { - $ret['finished'] = (bool)true; - } - - $_SESSION[$SESSION_KEY][$id] = $ret; - } - - return $ret; -} - -?> diff --git a/libraries/import/upload/noplugin.php b/libraries/import/upload/noplugin.php deleted file mode 100644 index c54baca7d2..0000000000 --- a/libraries/import/upload/noplugin.php +++ /dev/null @@ -1,45 +0,0 @@ - $id, - 'finished' => false, - 'percent' => 0, - 'total' => 0, - 'complete' => 0, - 'plugin' => $ID_KEY - ); - } - $ret = $_SESSION[$SESSION_KEY][$id]; - - return $ret; -} -?> diff --git a/libraries/import/upload/session.php b/libraries/import/upload/session.php deleted file mode 100644 index d1199d8a72..0000000000 --- a/libraries/import/upload/session.php +++ /dev/null @@ -1,77 +0,0 @@ - $id, - 'finished' => false, - 'percent' => 0, - 'total' => 0, - 'complete' => 0, - 'plugin' => $ID_KEY - ); - } - $ret = $_SESSION[$SESSION_KEY][$id]; - - if (! PMA_import_sessionCheck() || $ret['finished']) { - return $ret; - } - - $status = false; - $sessionkey = ini_get('session.upload_progress.prefix') . $id; - - if (isset($_SESSION[$sessionkey])) { - $status = $_SESSION[$sessionkey]; - } - - if ($status) { - $ret['finished'] = $status['done']; - $ret['total'] = $status['content_length']; - $ret['complete'] = $status['bytes_processed']; - - if ($ret['total'] > 0) { - $ret['percent'] = $ret['complete'] / $ret['total'] * 100; - } - } else { - $ret = array( - 'id' => $id, - 'finished' => true, - 'percent' => 100, - 'total' => $ret['total'], - 'complete' => $ret['total'], - 'plugin' => $ID_KEY - ); - } - - $_SESSION[$SESSION_KEY][$id] = $ret; - - return $ret; -} -?> diff --git a/libraries/import/upload/uploadprogress.php b/libraries/import/upload/uploadprogress.php deleted file mode 100644 index 43f2461d8e..0000000000 --- a/libraries/import/upload/uploadprogress.php +++ /dev/null @@ -1,76 +0,0 @@ - $id, - 'finished' => false, - 'percent' => 0, - 'total' => 0, - 'complete' => 0, - 'plugin' => $ID_KEY - ); - } - $ret = $_SESSION[$SESSION_KEY][$id]; - - if (! PMA_import_uploadprogressCheck() || $ret['finished']) { - return $ret; - } - - $status = uploadprogress_get_info($id); - - if ($status) { - if ($status['bytes_uploaded'] == $status['bytes_total']) { - $ret['finished'] = true; - } else { - $ret['finished'] = false; - } - $ret['total'] = $status['bytes_total']; - $ret['complete'] = $status['bytes_uploaded']; - - if ($ret['total'] > 0) { - $ret['percent'] = $ret['complete'] / $ret['total'] * 100; - } - } else { - $ret = array( - 'id' => $id, - 'finished' => true, - 'percent' => 100, - 'total' => $ret['total'], - 'complete' => $ret['total'], - 'plugin' => $ID_KEY - ); - } - - $_SESSION[$SESSION_KEY][$id] = $ret; - - return $ret; -} -?> diff --git a/libraries/import/xml.php b/libraries/import/xml.php deleted file mode 100644 index a1b1a337ee..0000000000 --- a/libraries/import/xml.php +++ /dev/null @@ -1,318 +0,0 @@ - __('XML'), - 'extension' => 'xml', - 'options' => array( - ), - 'options_text' => __('Options'), - ); - /* We do not define function when plugin is just queried for information above */ - return; -} - -$i = 0; -$len = 0; -$buffer = ""; - -/** - * Read in the file via PMA_importGetNextChunk so that - * it can process compressed files - */ -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); - } -} - -unset($data); - -/** - * Disable loading of external XML entities. - */ -libxml_disable_entity_loader(); - -/** - * Load the XML string - * - * The option LIBXML_COMPACT is specified because it can - * result in increased performance without the need to - * alter the code in any way. It's basically a freebee. - */ -$xml = simplexml_load_string($buffer, "SimpleXMLElement", LIBXML_COMPACT); - -unset($buffer); - -/** - * The XML was malformed - */ -if ($xml === false) { - PMA_Message::error(__('The XML file specified was either malformed or incomplete. Please correct the issue and try again.'))->display(); - unset($xml); - $GLOBALS['finished'] = false; - return; -} - -/** - * Table accumulator - */ -$tables = array(); -/** - * Row accumulator - */ -$rows = array(); - -/** - * Temp arrays - */ -$tempRow = array(); -$tempCells = array(); - -/** - * CREATE code included (by default: no) - */ -$struct_present = false; - -/** - * Analyze the data in each table - */ -$namespaces = $xml->getNameSpaces(true); - -/** - * Get the database name, collation and charset - */ -$db_attr = $xml->children($namespaces['pma'])->{'structure_schemas'}->{'database'}; - -if ($db_attr instanceof SimpleXMLElement) { - $db_attr = $db_attr->attributes(); - $db_name = (string)$db_attr['name']; - $collation = (string)$db_attr['collation']; - $charset = (string)$db_attr['charset']; -} else { - /** - * If the structure section is not present - * get the database name from the data section - */ - $db_attr = $xml->children()->attributes(); - $db_name = (string)$db_attr['name']; - $collation = null; - $charset = null; -} - -/** - * The XML was malformed - */ -if ($db_name === null) { - PMA_Message::error(__('The XML file specified was either malformed or incomplete. Please correct the issue and try again.'))->display(); - unset($xml); - $GLOBALS['finished'] = false; - return; -} - -/** - * Retrieve the structure information - */ -if (isset($namespaces['pma'])) { - /** - * Get structures for all tables - */ - $struct = $xml->children($namespaces['pma']); - - $create = array(); - - foreach ($struct as $tier1 => $val1) { - foreach ($val1 as $tier2 => $val2) { - // Need to select the correct database for the creation of tables, - // views, triggers, etc. - /** - * @todo Generating a USE here blocks importing of a table - * into another database. - */ - $attrs = $val2->attributes(); - $create[] = "USE " . PMA_backquote($attrs["name"]); - - foreach ($val2 as $val3) { - /** - * Remove the extra cosmetic spacing - */ - $val3 = str_replace(" ", "", (string)$val3); - $create[] = $val3; - } - } - } - - $struct_present = true; -} - -/** - * Move down the XML tree to the actual data - */ -$xml = $xml->children()->children(); - -$data_present = false; - -/** - * Only attempt to analyze/collect data if there is data present - */ -if ($xml && @$xml->count()) { - $data_present = true; - - /** - * Process all database content - */ - foreach ($xml as $k1 => $v1) { - $tbl_attr = $v1->attributes(); - - $isInTables = false; - for ($i = 0; $i < count($tables); ++$i) { - if (! strcmp($tables[$i][TBL_NAME], (string)$tbl_attr['name'])) { - $isInTables = true; - break; - } - } - - if ($isInTables == false) { - $tables[] = array((string)$tbl_attr['name']); - } - - foreach ($v1 as $k2 => $v2) { - $row_attr = $v2->attributes(); - if (! array_search((string)$row_attr['name'], $tempRow)) { - $tempRow[] = (string)$row_attr['name']; - } - $tempCells[] = (string)$v2; - } - - $rows[] = array((string)$tbl_attr['name'], $tempRow, $tempCells); - - $tempRow = array(); - $tempCells = array(); - } - - unset($tempRow); - unset($tempCells); - unset($xml); - - /** - * Bring accumulated rows into the corresponding table - */ - $num_tbls = count($tables); - for ($i = 0; $i < $num_tbls; ++$i) { - for ($j = 0; $j < count($rows); ++$j) { - if (! strcmp($tables[$i][TBL_NAME], $rows[$j][TBL_NAME])) { - if (! isset($tables[$i][COL_NAMES])) { - $tables[$i][] = $rows[$j][COL_NAMES]; - } - - $tables[$i][ROWS][] = $rows[$j][ROWS]; - } - } - } - - unset($rows); - - if (! $struct_present) { - $analyses = array(); - - $len = count($tables); - for ($i = 0; $i < $len; ++$i) { - $analyses[] = PMA_analyzeTable($tables[$i]); - } - } -} - -unset($xml); -unset($tempRows); -unset($tempCells); -unset($rows); - -/** - * Only build SQL from data if there is data present - */ -if ($data_present) { - /** - * Set values to NULL if they were not present - * to maintain PMA_buildSQL() call integrity - */ - if (! isset($analyses)) { - $analyses = null; - if (! $struct_present) { - $create = null; - } - } -} - -/** - * 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)) { - /* Override the database name in the XML file, if one is selected */ - $db_name = $db; - $options = array('create_db' => false); -} else { - if ($db_name === null) { - $db_name = 'XML_DB'; - } - - /* Set database collation/charset */ - $options = array( - 'db_collation' => $collation, - 'db_charset' => $charset, - ); -} - -/* Created and execute necessary SQL statements from data */ -PMA_buildSQL($db_name, $tables, $analyses, $create, $options); - -unset($analyses); -unset($tables); -unset($create); - -/* Commit any possible data in buffers */ -PMA_importRunQuery(); -?> diff --git a/libraries/plugin_interface.lib.php b/libraries/plugin_interface.lib.php index 98e5e3cfb1..b659af3475 100644 --- a/libraries/plugin_interface.lib.php +++ b/libraries/plugin_interface.lib.php @@ -7,16 +7,49 @@ */ /** - * Reads all plugin information from directory $plugins_dir. + * Includes and instantiates the specified plugin type for a certain format * - * @param string $plugins_dir directrory with plugins - * @param mixed $plugin_param parameter to plugin by which they can - * decide whether they can work + * @param string $plugin_type the type of the plugin (import, export, etc) + * @param string $plugin_format the format of the plugin (sql, xml, et ) + * @param string $plugins_dir directrory with plugins + * @param mixed $plugin_param parameter to plugin by which they can + * decide whether they can work * - * @return array list of plugins + * @return new plugin instance */ -function PMA_getPlugins($plugins_dir, $plugin_param) +function PMA_getPlugin( + $plugin_type, + $plugin_format, + $plugins_dir, + $plugin_param = false +){ + $GLOBALS['plugin_param'] = $plugin_param; + $class_name = strtoupper($plugin_type[0]) + . strtolower(substr($plugin_type, 1)) + . strtoupper($plugin_format[0]) + . strtolower(substr($plugin_format, 1)); + $file = $class_name . ".class.php"; + if (is_file($plugins_dir . $file)) { + include_once $plugins_dir . $file; + return new $class_name; + } + + return null; +} + +/** + * Reads all plugin information from directory $plugins_dir + * + * @param string $plugin_type the type of the plugin (import, export, etc) + * @param string $plugins_dir directrory with plugins + * @param mixed $plugin_param parameter to plugin by which they can + * decide whether they can work + * + * @return array list of plugin instances + */ +function PMA_getPlugins($plugin_type, $plugins_dir, $plugin_param) { + $GLOBALS['plugin_param'] = $plugin_param; /* Scan for plugins */ $plugin_list = array(); if ($handle = @opendir($plugins_dir)) { @@ -25,8 +58,21 @@ function PMA_getPlugins($plugins_dir, $plugin_param) // (for example ._csv.php) so the following regexp // matches a file which does not start with a dot but ends // with ".php" - if (is_file($plugins_dir . $file) && preg_match('@^[^\.](.)*\.php$@i', $file)) { + $class_type = strtoupper($plugin_type[0]) + . strtolower(substr($plugin_type, 1)); + if (is_file($plugins_dir . $file) + && preg_match( + '@^' . $class_type . '(.+)\.class\.php$@i', + $file, + $matches + ) + ) { + $GLOBALS['skip_import'] = false; include_once $plugins_dir . $file; + if (! $GLOBALS['skip_import']) { + $class_name = $class_type . $matches[1]; + $plugin_list [] = new $class_name; + } } } } @@ -61,8 +107,11 @@ function PMA_pluginCheckboxCheck($section, $opt) // If the form is being repopulated using $_GET data, that is priority if (isset($_GET[$opt]) || ! isset($_GET['repopulate']) - && ((isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed'] && isset($_REQUEST[$opt])) - || (isset($GLOBALS['cfg'][$section][$opt]) && $GLOBALS['cfg'][$section][$opt])) + && ((isset($GLOBALS['timeout_passed']) + && $GLOBALS['timeout_passed'] + && isset($_REQUEST[$opt])) + || (isset($GLOBALS['cfg'][$section][$opt]) + && $GLOBALS['cfg'][$section][$opt])) ) { return ' checked="checked"'; } @@ -109,7 +158,7 @@ function PMA_pluginGetDefault($section, $opt) * @param string $section name of config section in * $GLOBALS['cfg'][$section] for plugin * @param string $name name of select element - * @param array &$list array with plugin configuration defined in plugin file + * @param array &$list array with plugin instances * @param string $cfgname name of config value, if none same as $name * * @return string html select tag @@ -121,20 +170,30 @@ function PMA_pluginGetChoice($section, $name, &$list, $cfgname = null) } $ret = '' . "\n"; // Whether each plugin has to be saved as a file - foreach ($list as $plugin_name => $val) { + foreach ($list as $plugin) { + $plugin_name = strtolower(substr(get_class($plugin), strlen($section))); + $properties = $plugin->getProperties(); $ret .= ''; $count = 0; - $ret .= '

' . PMA_getString($val['text']) . '

'; - if (isset($val['options']) && count($val['options']) > 0) { - foreach ($val['options'] as $id => $opt) { - if ($opt['type'] != 'hidden' && $opt['type'] != 'begin_group' && $opt['type'] != 'end_group' && $opt['type'] != 'begin_subgroup' && $opt['type'] != 'end_subgroup') { + $ret .= '

' . PMA_getString($properties['text']) . '

'; + if (isset($properties['options']) && count($properties['options']) > 0) { + foreach ($properties['options'] as $id => $opt) { + if ($opt['type'] != 'hidden' + && $opt['type'] != 'begin_group' + && $opt['type'] != 'end_group' + && $opt['type'] != 'begin_subgroup' + && $opt['type'] != 'end_subgroup' + ) { $count++; } $ret .= PMA_pluginGetOneOption($section, $plugin_name, $id, $opt); diff --git a/libraries/plugins/AuthenticationPlugin.class.php b/libraries/plugins/AuthenticationPlugin.class.php new file mode 100644 index 0000000000..9b2ea57aac --- /dev/null +++ b/libraries/plugins/AuthenticationPlugin.class.php @@ -0,0 +1,51 @@ + \ No newline at end of file diff --git a/libraries/plugins/ExportPlugin.class.php b/libraries/plugins/ExportPlugin.class.php new file mode 100644 index 0000000000..620db86a3a --- /dev/null +++ b/libraries/plugins/ExportPlugin.class.php @@ -0,0 +1,409 @@ +properties; + } + + /** + * Sets the export plugins properties and is implemented by each export + * plugin + * + * @return void + */ + abstract protected function setProperties(); + + /** + * Gets the type of the newline character + * + * @return string + */ + protected function getCrlf() + { + return $this->_crlf; + } + + /** + * Sets the type of the newline character + * + * @param String $crlf type of the newline character + * + * @return void + */ + protected function setCrlf($crlf) + { + $this->_crlf = $crlf; + } + + /** + * Gets the database name + * + * @return string + */ + protected function getDb() + { + return $this->_db; + } + + /** + * Sets the database name + * + * @param String $db database name + * + * @return void + */ + protected function setDb($db) + { + $this->_db = $db; + } + + /** + * Gets the configuration settings + * + * @return array + */ + protected function getCfg() + { + return $this->_cfg; + } + + /** + * Sets the configuration settings + * + * @param array $cfg array with configuration settings + * + * @return void + */ + protected function setCfg($cfg) + { + $this->_cfg = $cfg; + } + + /** + * Gets the relation configuration + * + * @return array + */ + protected function getCfgRelation() + { + return $this->_cfgRelation; + } + + /** + * Sets the relation configuration + * + * @param array $cfgRelation relation configuration + * + * @return array + */ + protected function setCfgRelation($cfgRelation) + { + $this->_cfgRelation = $cfgRelation; + } + + /** + * Gets the type of the export plugin + * + * @return string + */ + protected function getWhat() + { + return $this->_what; + } + + /** + * Sets the type of the export plugin + * + * @param string $what type of the export plugin + * + * @return void + */ + protected function setWhat($what) + { + $this->_what = $what; + } + + /** + * Gets the parameter to plugin by which it can decide whether it can work + * + * @return mixed + */ + protected function getPluginParam() + { + return $this->_pluginParam; + } + + /** + * Sets the parameter to plugin by which it can decide whether it can work + * + * @param mixed $pluginParam plugin parameter + * + * @return void + */ + protected function setPluginParam($pluginParam) + { + $this->_pluginParam = $pluginParam; + } + + /** + * Gets the file charset + * + * @return string + */ + protected function getCharsetOfFile() + { + return $this->_charsetOfFile; + } + + /** + * Sets the file charset + * + * @param string $charsetOfFile file charset + * + * @return void + */ + protected function setCharsetOfFile($charsetOfFile) + { + $this->_charsetOfFile = $charsetOfFile; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/ImportPlugin.class.php b/libraries/plugins/ImportPlugin.class.php new file mode 100644 index 0000000000..018f3a60a0 --- /dev/null +++ b/libraries/plugins/ImportPlugin.class.php @@ -0,0 +1,59 @@ +properties; + } + + /** + * Sets the export plugins properties and is implemented by each import + * plugin + * + * @return void + */ + abstract protected function setProperties(); +} +?> \ No newline at end of file diff --git a/libraries/plugins/PluginManager.class.php b/libraries/plugins/PluginManager.class.php new file mode 100644 index 0000000000..828f9dfd91 --- /dev/null +++ b/libraries/plugins/PluginManager.class.php @@ -0,0 +1,131 @@ +_storage = new SplObjectStorage(); + } + + /** + * Attaches an SplObserver so that it can be notified of updates + * + * @param SplObserver $observer The SplObserver to attach + * + * @return void + */ + function attach (SplObserver $observer ) + { + $this->_storage->attach($observer); + } + + /** + * Detaches an observer from the subject to no longer notify it of updates + * + * @param SplObserver $observer The SplObserver to detach + * + * @return void + */ + function detach (SplObserver $observer) + { + $this->_storage->detach($observer); + } + + /** + * It is called after setStatus() was run by a certain plugin, and has + * the role of sending a notification to all of the plugins in $_storage, + * by calling the update() method for each of them. + * + * @todo implement + * @return void + */ + function notify () + { + } + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + /** + * Gets the list with all the plugins that attach to it + * + * @return type SplObjectStorage + */ + public function getStorage() + { + return $this->_storage; + } + + /** + * Setter for $_storage + * + * @param SplObjectStorage $_storage the list with all the plugins that + * attach to it + * + * @return void + */ + public function setStorage($_storage) + { + $this->_storage = $_storage; + } + + /** + * Gets the information about the current plugin state + * It is called by all the plugins in $_storage in their update() method + * + * @return type mixed + */ + public function getStatus() + { + return $this->_status; + } + + /** + * Setter for $_status + * If a plugin changes its status, this has to be remembered in order to + * notify the rest of the plugins that they should update + * + * @param mixed $_status contains information about the current plugin state + * + * @return void + */ + public function setStatus($_status) + { + $this->_status = $_status; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/PluginObserver.class.php b/libraries/plugins/PluginObserver.class.php new file mode 100644 index 0000000000..190f02d747 --- /dev/null +++ b/libraries/plugins/PluginObserver.class.php @@ -0,0 +1,81 @@ +_pluginManager = $pluginManager; + } + + /** + * This method is called when any PluginManager to which the observer + * is attached calls PluginManager::notify() + * + * @param SplSubject $subject The PluginManager notifying the observer + * of an update. + * + * @return void + */ + abstract public function update (SplSubject $subject); + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Gets the PluginManager instance that contains the list with all the + * plugins that attached to it + * + * @return type PluginManager + */ + public function getPluginManager() + { + return $this->_pluginManager; + } + + /** + * Setter for $_pluginManager + * + * @param PluginManager $_pluginManager the private instance that it will + * attach to + * + * @return void + */ + public function setPluginManager($_pluginManager) + { + $this->_pluginManager = $_pluginManager; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/TransformationsInterface.int.php b/libraries/plugins/TransformationsInterface.int.php new file mode 100644 index 0000000000..7519cae210 --- /dev/null +++ b/libraries/plugins/TransformationsInterface.int.php @@ -0,0 +1,48 @@ + diff --git a/libraries/plugins/TransformationsPlugin.class.php b/libraries/plugins/TransformationsPlugin.class.php new file mode 100644 index 0000000000..fec79a9619 --- /dev/null +++ b/libraries/plugins/TransformationsPlugin.class.php @@ -0,0 +1,49 @@ + \ No newline at end of file diff --git a/libraries/plugins/UploadInterface.int.php b/libraries/plugins/UploadInterface.int.php new file mode 100644 index 0000000000..35444420a8 --- /dev/null +++ b/libraries/plugins/UploadInterface.int.php @@ -0,0 +1,35 @@ +upload plugins + * + * @package PhpMyAdmin + */ +if (! defined('PHPMYADMIN')) { + exit; +} + +/** + * Provides a common interface that will have to implemented by all of the + * import->upload plugins. + * + * @package PhpMyAdmin + */ +interface UploadInterface { + /** + * Gets the specific upload ID Key + * + * @return string ID Key + */ + public static function getIdKey(); + + /** + * Returns upload status. + * + * @param string $id upload id + * + * @return array|null + */ + public static function getUploadStatus($id); +} +?> \ No newline at end of file diff --git a/libraries/plugins/auth/AuthenticationConfig.class.php b/libraries/plugins/auth/AuthenticationConfig.class.php new file mode 100644 index 0000000000..0f49b876f0 --- /dev/null +++ b/libraries/plugins/auth/AuthenticationConfig.class.php @@ -0,0 +1,160 @@ + authentication failed + * + * @global string the MySQL error message PHP returns + * @global string the connection type (persistent or not) + * @global string the MySQL server port to use + * @global string the MySQL socket port to use + * @global array the current server settings + * @global string the font face to use in case of failure + * @global string the default font size to use in case of failure + * @global string the big font size to use in case of failure + * @global boolean tell the "PMA_mysqlDie()" function headers have been + * sent + * + * @return boolean always true (no return indeed) + */ + public function authFails() + { + $conn_error = PMA_DBI_getError(); + if (! $conn_error) { + $conn_error = __('Cannot connect: invalid settings.'); + } + + /* HTML header */ + $response = PMA_Response::getInstance(); + $response->getFooter()->setMinimal(); + $header = $response->getHeader(); + $header->setTitle(__('Access denied')); + $header->disableMenu(); + echo '

+
+

'; + echo sprintf(__('Welcome to %s'), ' phpMyAdmin '); + echo '

+
+
+ + + + '; + if (count($GLOBALS['cfg']['Servers']) > 1) { + // offer a chance to login to other servers if the current one failed + include_once './libraries/select_server.lib.php'; + echo '' . "\n"; + echo ' ' . "\n"; + echo '' . "\n"; + } + echo '
'; + if (isset($GLOBALS['allowDeny_forbidden']) + && $GLOBALS['allowDeny_forbidden'] + ) { + trigger_error(__('Access denied'), E_USER_NOTICE); + } else { + // Check whether user has configured something + if ($GLOBALS['PMA_Config']->source_mtime == 0) { + echo '

' . sprintf( + __( + 'You probably did not create a configuration file.' + . ' You might want to use the %1$ssetup script%2$s to' + . ' create one.' + ), + '', + '' + ) . '

' . "\n"; + } elseif (! isset($GLOBALS['errno']) + || (isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002) + && $GLOBALS['errno'] != 2003 + ) { + // if we display the "Server not responding" error, do not confuse + // users by telling them they have a settings problem + // (note: it's true that they could have a badly typed host name, + // but anyway the current message tells that the server + // rejected the connection, which is not really what happened) + // 2002 is the error given by mysqli + // 2003 is the error given by mysql + trigger_error( + __( + 'phpMyAdmin tried to connect to the MySQL server, and the' + . ' server rejected the connection. You should check the' + . ' host, username and password in your configuration and' + . ' make sure that they correspond to the information given' + . ' by the administrator of the MySQL server.' + ), E_USER_WARNING + ); + } + PMA_mysqlDie($conn_error, '', true, '', false); + } + $GLOBALS['error_handler']->dispUserErrors(); + echo '
' . "\n"; + PMA_selectServer(true, true); + echo '
' . "\n"; + exit; + return true; + } + + /** + * This method is called when any PluginManager to which the observer + * is attached calls PluginManager::notify() + * + * @param SplSubject $subject The PluginManager notifying the observer + * of an update. + * + * @return void + */ + public function update (SplSubject $subject) + { + } +} \ No newline at end of file diff --git a/libraries/plugins/auth/AuthenticationCookie.class.php b/libraries/plugins/auth/AuthenticationCookie.class.php new file mode 100644 index 0000000000..c921631178 --- /dev/null +++ b/libraries/plugins/auth/AuthenticationCookie.class.php @@ -0,0 +1,689 @@ +setCookie( + 'pma_mcrypt_iv', + base64_encode($iv) + ); + } +} + +/** + * Handles the cookie authentication method + * + * @package PhpMyAdmin-Authentication + */ +class AuthenticationCookie extends AuthenticationPlugin +{ + /** + * Displays authentication form + * + * this function MUST exit/quit the application + * + * @global string the last connection error + * + * @return void + */ + public function auth() + { + global $conn_error; + + $response = PMA_Response::getInstance(); + if ($response->isAjax()) { + $response->isSuccess(false); + if (! empty($conn_error)) { + $response->addJSON('message', $conn_error); + } else { + $response->addJSON( + 'message', + PMA_Message::error( + __('Your session has expired. Please login again.') + ) + ); + } + exit; + } + + /* Perform logout to custom URL */ + if (! empty($_REQUEST['old_usr']) + && ! empty($GLOBALS['cfg']['Server']['LogoutURL']) + ) { + PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']); + exit; + } + + // No recall if blowfish secret is not configured as it would produce + // garbage + if ($GLOBALS['cfg']['LoginCookieRecall'] + && ! empty($GLOBALS['cfg']['blowfish_secret']) + ) { + $default_user = $GLOBALS['PHP_AUTH_USER']; + $default_server = $GLOBALS['pma_auth_server']; + $autocomplete = ''; + } else { + $default_user = ''; + $default_server = ''; + // skip the IE autocomplete feature. + $autocomplete = ' autocomplete="off"'; + } + + $cell_align = ($GLOBALS['text_dir'] == 'ltr') ? 'left' : 'right'; + + $response->getFooter()->setMinimal(); + $header = $response->getHeader(); + $header->setBodyId('loginform'); + $header->setTitle('phpMyAdmin'); + $header->disableMenu(); + $header->disableWarnings(); + + if (file_exists(CUSTOM_HEADER_FILE)) { + include CUSTOM_HEADER_FILE; + } + echo ' +
+ +

'; + echo sprintf( + __('Welcome to %s'), + 'phpMyAdmin' + ); + echo "

"; + + // Show error message + if (! empty($conn_error)) { + PMA_Message::rawError($conn_error)->display(); + } + + echo "\n"; + + echo "
"; + // Displays the languages form + if (empty($GLOBALS['cfg']['Lang'])) { + include_once './libraries/display_select_lang.lib.php'; + // use fieldset, don't show doc link + PMA_select_language(true, false); + } + echo '
+
+ + +
+ '; + echo __('Log in'); + echo PMA_showDocu(''); + echo ''; + if ($GLOBALS['cfg']['AllowArbitraryServer']) { + echo ' +
+ + +
'; + } + echo '
+ + +
+
+ + +
'; + if (count($GLOBALS['cfg']['Servers']) > 1) { + echo '
+ +
'; + } else { + echo ' '; + } // end if (server choice) + + echo '
+
+ '; + $_form_params = array(); + if (! empty($GLOBALS['target'])) { + $_form_params['target'] = $GLOBALS['target']; + } + if (! empty($GLOBALS['db'])) { + $_form_params['db'] = $GLOBALS['db']; + } + if (! empty($GLOBALS['table'])) { + $_form_params['table'] = $GLOBALS['table']; + } + // do not generate a "server" hidden field as we want the "server" + // drop-down to have priority + echo PMA_generate_common_hidden_inputs($_form_params, '', 0, 'server'); + echo '
+ '; + + // BEGIN Swekey Integration + Swekey_login('input_username', 'input_go'); + // END Swekey Integration + + // show the "Cookies required" message only if cookies are disabled + // (we previously tried to set some cookies) + if (empty($_COOKIE)) { + trigger_error(__('Cookies must be enabled past this point.'), E_USER_NOTICE); + } + if ($GLOBALS['error_handler']->hasDisplayErrors()) { + echo '
'; + $GLOBALS['error_handler']->dispErrors(); + echo '
'; + } + echo '
'; + if (file_exists(CUSTOM_FOOTER_FILE)) { + include CUSTOM_FOOTER_FILE; + } + echo ' + '; + exit; + } + + /** + * Gets advanced authentication settings + * + * this function DOES NOT check authentication - it just checks/provides + * authentication credentials required to connect to the MySQL server + * usually with PMA_DBI_connect() + * + * it returns false if something is missing - which usually leads to + * auth() which displays login form + * + * it returns true if all seems ok which usually leads to auth_set_user() + * + * it directly switches to authFails() if user inactivity timout is reached + * + * @todo AllowArbitraryServer on does not imply that the user wants an + * arbitrary server, or? so we should also check if this is filled + * and not only if allowed + * + * @return boolean whether we get authentication settings or not + */ + public function authCheck() + { + // Initialization + /** + * @global $GLOBALS['pma_auth_server'] the user provided server to + * connect to + */ + $GLOBALS['pma_auth_server'] = ''; + + $GLOBALS['PHP_AUTH_USER'] = $GLOBALS['PHP_AUTH_PW'] = ''; + $GLOBALS['from_cookie'] = false; + + // BEGIN Swekey Integration + if (! Swekey_auth_check()) { + return false; + } + // END Swekey Integration + + if (defined('PMA_CLEAR_COOKIES')) { + foreach ($GLOBALS['cfg']['Servers'] as $key => $val) { + $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key); + $GLOBALS['PMA_Config']->removeCookie('pmaServer-' . $key); + $GLOBALS['PMA_Config']->removeCookie('pmaUser-' . $key); + } + return false; + } + + if (! empty($_REQUEST['old_usr'])) { + // The user wants to be logged out + // -> delete his choices that were stored in session + + // according to the PHP manual we should do this before the destroy: + //$_SESSION = array(); + + session_destroy(); + // -> delete password cookie(s) + if ($GLOBALS['cfg']['LoginCookieDeleteAll']) { + foreach ($GLOBALS['cfg']['Servers'] as $key => $val) { + $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key); + if (isset($_COOKIE['pmaPass-' . $key])) { + unset($_COOKIE['pmaPass-' . $key]); + } + } + } else { + $GLOBALS['PMA_Config']->removeCookie( + 'pmaPass-' . $GLOBALS['server'] + ); + if (isset($_COOKIE['pmaPass-' . $GLOBALS['server']])) { + unset($_COOKIE['pmaPass-' . $GLOBALS['server']]); + } + } + } + + if (! empty($_REQUEST['pma_username'])) { + // The user just logged in + $GLOBALS['PHP_AUTH_USER'] = $_REQUEST['pma_username']; + $GLOBALS['PHP_AUTH_PW'] = empty($_REQUEST['pma_password']) + ? '' + : $_REQUEST['pma_password']; + if ($GLOBALS['cfg']['AllowArbitraryServer'] + && isset($_REQUEST['pma_servername']) + ) { + $GLOBALS['pma_auth_server'] = $_REQUEST['pma_servername']; + } + return true; + } + + // At the end, try to set the $GLOBALS['PHP_AUTH_USER'] + // and $GLOBALS['PHP_AUTH_PW'] variables from cookies + + // servername + if ($GLOBALS['cfg']['AllowArbitraryServer'] + && ! empty($_COOKIE['pmaServer-' . $GLOBALS['server']]) + ) { + $GLOBALS['pma_auth_server'] + = $_COOKIE['pmaServer-' . $GLOBALS['server']]; + } + + // username + if (empty($_COOKIE['pmaUser-' . $GLOBALS['server']])) { + return false; + } + + $GLOBALS['PHP_AUTH_USER'] = $this->blowfishDecrypt( + $_COOKIE['pmaUser-' . $GLOBALS['server']], + $this->_getBlowfishSecret() + ); + + // user was never logged in since session start + if (empty($_SESSION['last_access_time'])) { + return false; + } + + // User inactive too long + $last_access_time = time() - $GLOBALS['cfg']['LoginCookieValidity']; + if ($_SESSION['last_access_time'] < $last_access_time + ) { + PMA_cacheUnset('is_create_db_priv', true); + PMA_cacheUnset('is_process_priv', true); + PMA_cacheUnset('is_reload_priv', true); + PMA_cacheUnset('db_to_create', true); + PMA_cacheUnset('dbs_where_create_table_allowed', true); + $GLOBALS['no_activity'] = true; + $this->authFails(); + exit; + } + + // password + if (empty($_COOKIE['pmaPass-' . $GLOBALS['server']])) { + return false; + } + + $GLOBALS['PHP_AUTH_PW'] = $this->blowfishDecrypt( + $_COOKIE['pmaPass-' . $GLOBALS['server']], + $this->_getBlowfishSecret() + ); + + if ($GLOBALS['PHP_AUTH_PW'] == "\xff(blank)") { + $GLOBALS['PHP_AUTH_PW'] = ''; + } + + $GLOBALS['from_cookie'] = true; + + return true; + } + + /** + * Set the user and password after last checkings if required + * + * @return boolean always true + */ + public function authSetUser() + { + global $cfg; + + // Ensures valid authentication mode, 'only_db', bookmark database and + // table names and relation table name are used + if ($cfg['Server']['user'] != $GLOBALS['PHP_AUTH_USER']) { + foreach ($cfg['Servers'] as $idx => $current) { + if ($current['host'] == $cfg['Server']['host'] + && $current['port'] == $cfg['Server']['port'] + && $current['socket'] == $cfg['Server']['socket'] + && $current['ssl'] == $cfg['Server']['ssl'] + && $current['connect_type'] == $cfg['Server']['connect_type'] + && $current['user'] == $GLOBALS['PHP_AUTH_USER'] + ) { + $GLOBALS['server'] = $idx; + $cfg['Server'] = $current; + break; + } + } // end foreach + } // end if + + if ($GLOBALS['cfg']['AllowArbitraryServer'] + && ! empty($GLOBALS['pma_auth_server']) + ) { + /* Allow to specify 'host port' */ + $parts = explode(' ', $GLOBALS['pma_auth_server']); + if (count($parts) == 2) { + $tmp_host = $parts[0]; + $tmp_port = $parts[1]; + } else { + $tmp_host = $GLOBALS['pma_auth_server']; + $tmp_port = ''; + } + if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) { + $cfg['Server']['host'] = $tmp_host; + if (! empty($tmp_port)) { + $cfg['Server']['port'] = $tmp_port; + } + } + unset($tmp_host, $tmp_port, $parts); + } + $cfg['Server']['user'] = $GLOBALS['PHP_AUTH_USER']; + $cfg['Server']['password'] = $GLOBALS['PHP_AUTH_PW']; + + // Avoid showing the password in phpinfo()'s output + unset($GLOBALS['PHP_AUTH_PW']); + unset($_SERVER['PHP_AUTH_PW']); + + $_SESSION['last_access_time'] = time(); + + // Name and password cookies need to be refreshed each time + // Duration = one month for username + $GLOBALS['PMA_Config']->setCookie( + 'pmaUser-' . $GLOBALS['server'], + $this->blowfishEncrypt( + $cfg['Server']['user'], + $this->_getBlowfishSecret() + ) + ); + + // Duration = as configured + $GLOBALS['PMA_Config']->setCookie( + 'pmaPass-' . $GLOBALS['server'], + $this->blowfishEncrypt( + ! empty($cfg['Server']['password']) + ? $cfg['Server']['password'] : "\xff(blank)", + $this->_getBlowfishSecret() + ), + null, + $GLOBALS['cfg']['LoginCookieStore'] + ); + + // Set server cookies if required (once per session) and, in this case, + // force reload to ensure the client accepts cookies + if (! $GLOBALS['from_cookie']) { + if ($GLOBALS['cfg']['AllowArbitraryServer']) { + if (! empty($GLOBALS['pma_auth_server'])) { + // Duration = one month for servername + $GLOBALS['PMA_Config']->setCookie( + 'pmaServer-' . $GLOBALS['server'], + $cfg['Server']['host'] + ); + } else { + // Delete servername cookie + $GLOBALS['PMA_Config']->removeCookie( + 'pmaServer-' . $GLOBALS['server'] + ); + } + } + + // URL where to go: + $redirect_url = $cfg['PmaAbsoluteUri'] . 'index.php'; + + // any parameters to pass? + $url_params = array(); + if (strlen($GLOBALS['db'])) { + $url_params['db'] = $GLOBALS['db']; + } + if (strlen($GLOBALS['table'])) { + $url_params['table'] = $GLOBALS['table']; + } + // any target to pass? + if (! empty($GLOBALS['target']) + && $GLOBALS['target'] != 'index.php' + ) { + $url_params['target'] = $GLOBALS['target']; + } + + /** + * Clear user cache. + */ + PMA_clearUserCache(); + + PMA_Response::getInstance()->disable(); + + PMA_sendHeaderLocation( + $redirect_url . PMA_generate_common_url($url_params, '&'), + true + ); + exit; + } // end if + + return true; + + } + + /** + * User is not allowed to login to MySQL -> authentication failed + * + * prepares error message and switches to auth() which display the error + * and the login form + * + * this function MUST exit/quit the application, + * currently doen by call to auth() + * + * @return void + */ + public function authFails() + { + global $conn_error; + + // Deletes password cookie and displays the login form + $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']); + + if (! empty($GLOBALS['login_without_password_is_forbidden'])) { + $conn_error = __( + 'Login without a password is forbidden by configuration' + . ' (see AllowNoPassword)' + ); + } elseif (! empty($GLOBALS['allowDeny_forbidden'])) { + $conn_error = __('Access denied'); + } elseif (! empty($GLOBALS['no_activity'])) { + $conn_error = sprintf( + __('No activity within %s seconds; please log in again'), + $GLOBALS['cfg']['LoginCookieValidity'] + ); + // Remember where we got timeout to return on same place + if (PMA_getenv('SCRIPT_NAME')) { + $GLOBALS['target'] = basename(PMA_getenv('SCRIPT_NAME')); + // avoid "missing parameter: field" on re-entry + if ('tbl_alter.php' == $GLOBALS['target']) { + $GLOBALS['target'] = 'tbl_structure.php'; + } + } + } elseif (PMA_DBI_getError()) { + $conn_error = '#' . $GLOBALS['errno'] . ' ' + . __('Cannot log in to the MySQL server'); + } else { + $conn_error = __('Cannot log in to the MySQL server'); + } + + // needed for PHP-CGI (not need for FastCGI or mod-php) + header('Cache-Control: no-store, no-cache, must-revalidate'); + header('Pragma: no-cache'); + + $this->auth(); + } + + /** + * Returns blowfish secret or generates one if needed. + * + * @return string + */ + private function _getBlowfishSecret() + { + if (empty($GLOBALS['cfg']['blowfish_secret'])) { + if (empty($_SESSION['auto_blowfish_secret'])) { + // this returns 23 characters + $_SESSION['auto_blowfish_secret'] = uniqid('', true); + } + return $_SESSION['auto_blowfish_secret']; + } else { + // apply md5() to work around too long secrets (returns 32 characters) + return md5($GLOBALS['cfg']['blowfish_secret']); + } + } + + /** + * Encryption using blowfish algorithm (mcrypt) + * + * @param string $data original data + * @param string $secret the secret + * + * @return string the encrypted result + */ + public function blowfishEncrypt($data, $secret) + { + global $iv; + if (! function_exists('mcrypt_encrypt')) { + include_once "HordeCipherBlowfishOperations.class.php"; + return HordeCipherBlowfishOperations::blowfishEncrypt($data, $secret); + } + + return base64_encode( + mcrypt_encrypt( + MCRYPT_BLOWFISH, + $secret, + $data, + MCRYPT_MODE_CBC, + $iv + ) + ); + } + + /** + * Decryption using blowfish algorithm (mcrypt) + * + * @param string $encdata encrypted data + * @param string $secret the secret + * + * @return string original data + */ + public function blowfishDecrypt($encdata, $secret) + { + global $iv; + if (! function_exists('mcrypt_encrypt')) { + include_once "HordeCipherBlowfishOperations.class.php"; + return HordeCipherBlowfishOperations::blowfishDecrypt( + $encdata, + $secret + ); + } + + $data = base64_decode($encdata); + $decrypted = mcrypt_decrypt( + MCRYPT_BLOWFISH, + $secret, + $data, + MCRYPT_MODE_CBC, + $iv + ); + return trim($decrypted); + } + + /** + * This method is called when any PluginManager to which the observer + * is attached calls PluginManager::notify() + * + * @param SplSubject $subject The PluginManager notifying the observer + * of an update. + * + * @return void + */ + public function update (SplSubject $subject) + { + } +} \ No newline at end of file diff --git a/libraries/plugins/auth/AuthenticationHttp.class.php b/libraries/plugins/auth/AuthenticationHttp.class.php new file mode 100644 index 0000000000..89eeab9a5f --- /dev/null +++ b/libraries/plugins/auth/AuthenticationHttp.class.php @@ -0,0 +1,248 @@ +getFooter()->setMinimal(); + $header = $response->getHeader(); + $header->setTitle(__('Access denied')); + $header->disableMenu(); + echo ' +

+
+

'; + echo sprintf(__('Welcome to %s'), ' phpMyAdmin'); + echo '

+
+
' . + PMA_Message::error( + __('Wrong username/password. Access denied.') + )->display(); + + if (file_exists(CUSTOM_FOOTER_FILE)) { + include CUSTOM_FOOTER_FILE; + } + + exit; + } + + /** + * Gets advanced authentication settings + * + * @global string the username if register_globals is on + * @global string the password if register_globals is on + * @global array the array of server variables if register_globals is + * off + * @global array the array of environment variables if register_globals + * is off + * @global string the username for the ? server + * @global string the password for the ? server + * @global string the username for the WebSite Professional server + * @global string the password for the WebSite Professional server + * @global string the username of the user who logs out + * + * @return boolean whether we get authentication settings or not + */ + public function authCheck() + { + global $PHP_AUTH_USER, $PHP_AUTH_PW; + global $old_usr; + + // Grabs the $PHP_AUTH_USER variable whatever are the values of the + // 'register_globals' and the 'variables_order' directives + if (empty($PHP_AUTH_USER)) { + if (PMA_getenv('PHP_AUTH_USER')) { + $PHP_AUTH_USER = PMA_getenv('PHP_AUTH_USER'); + } elseif (PMA_getenv('REMOTE_USER')) { + // CGI, might be encoded, see below + $PHP_AUTH_USER = PMA_getenv('REMOTE_USER'); + } elseif (PMA_getenv('REDIRECT_REMOTE_USER')) { + // CGI, might be encoded, see below + $PHP_AUTH_USER = PMA_getenv('REDIRECT_REMOTE_USER'); + } elseif (PMA_getenv('AUTH_USER')) { + // WebSite Professional + $PHP_AUTH_USER = PMA_getenv('AUTH_USER'); + } elseif (PMA_getenv('HTTP_AUTHORIZATION') + && false === strpos(PMA_getenv('HTTP_AUTHORIZATION'), '<') + ) { + // IIS, might be encoded, see below; also prevent XSS + $PHP_AUTH_USER = PMA_getenv('HTTP_AUTHORIZATION'); + } elseif (PMA_getenv('Authorization')) { + // FastCGI, might be encoded, see below + $PHP_AUTH_USER = PMA_getenv('Authorization'); + } + } + // Grabs the $PHP_AUTH_PW variable whatever are the values of the + // 'register_globals' and the 'variables_order' directives + if (empty($PHP_AUTH_PW)) { + if (PMA_getenv('PHP_AUTH_PW')) { + $PHP_AUTH_PW = PMA_getenv('PHP_AUTH_PW'); + } elseif (PMA_getenv('REMOTE_PASSWORD')) { + // Apache/CGI + $PHP_AUTH_PW = PMA_getenv('REMOTE_PASSWORD'); + } elseif (PMA_getenv('AUTH_PASSWORD')) { + // WebSite Professional + $PHP_AUTH_PW = PMA_getenv('AUTH_PASSWORD'); + } + } + + // Decode possibly encoded information (used by IIS/CGI/FastCGI) + // (do not use explode() because a user might have a colon in his password + if (strcmp(substr($PHP_AUTH_USER, 0, 6), 'Basic ') == 0) { + $usr_pass = base64_decode(substr($PHP_AUTH_USER, 6)); + if (! empty($usr_pass)) { + $colon = strpos($usr_pass, ':'); + if ($colon) { + $PHP_AUTH_USER = substr($usr_pass, 0, $colon); + $PHP_AUTH_PW = substr($usr_pass, $colon + 1); + } + unset($colon); + } + unset($usr_pass); + } + + // User logged out -> ensure the new username is not the same + if (!empty($old_usr) + && (isset($PHP_AUTH_USER) && $old_usr == $PHP_AUTH_USER) + ) { + $PHP_AUTH_USER = ''; + // -> delete user's choices that were stored in session + session_destroy(); + } + + // Returns whether we get authentication settings or not + if (empty($PHP_AUTH_USER)) { + return false; + } else { + return true; + } + } + + /** + * Set the user and password after last checkings if required + * + * @global array the valid servers settings + * @global integer the id of the current server + * @global array the current server settings + * @global string the current username + * @global string the current password + * + * @return boolean always true + */ + public function authSetUser() + { + global $cfg, $server; + global $PHP_AUTH_USER, $PHP_AUTH_PW; + + // Ensures valid authentication mode, 'only_db', bookmark database and + // table names and relation table name are used + if ($cfg['Server']['user'] != $PHP_AUTH_USER) { + $servers_cnt = count($cfg['Servers']); + for ($i = 1; $i <= $servers_cnt; $i++) { + if (isset($cfg['Servers'][$i]) + && ($cfg['Servers'][$i]['host'] == $cfg['Server']['host'] + && $cfg['Servers'][$i]['user'] == $PHP_AUTH_USER) + ) { + $server = $i; + $cfg['Server'] = $cfg['Servers'][$i]; + break; + } + } // end for + } // end if + + $cfg['Server']['user'] = $PHP_AUTH_USER; + $cfg['Server']['password'] = $PHP_AUTH_PW; + + // Avoid showing the password in phpinfo()'s output + unset($GLOBALS['PHP_AUTH_PW']); + unset($_SERVER['PHP_AUTH_PW']); + + return true; + } + + /** + * User is not allowed to login to MySQL -> authentication failed + * + * @return boolean always true (no return indeed) + */ + public function authFails() + { + $error = PMA_DBI_getError(); + if ($error && $GLOBALS['errno'] != 1045) { + PMA_fatalError($error); + } else { + $this->auth(); + return true; + } + } + + /** + * This method is called when any PluginManager to which the observer + * is attached calls PluginManager::notify() + * + * @param SplSubject $subject The PluginManager notifying the observer + * of an update. + * + * @return void + */ + public function update (SplSubject $subject) + { + } +} \ No newline at end of file diff --git a/libraries/plugins/auth/AuthenticationSignon.class.php b/libraries/plugins/auth/AuthenticationSignon.class.php new file mode 100644 index 0000000000..ba109d1850 --- /dev/null +++ b/libraries/plugins/auth/AuthenticationSignon.class.php @@ -0,0 +1,284 @@ + authentication failed + * + * @return boolean always true (no return indeed) + */ + public function authFails() + { + /* Session name */ + $session_name = $GLOBALS['cfg']['Server']['SignonSession']; + + /* Does session exist? */ + if (isset($_COOKIE[$session_name])) { + /* End current session */ + $old_session = session_name(); + $old_id = session_id(); + session_write_close(); + + /* Load single signon session */ + session_name($session_name); + session_id($_COOKIE[$session_name]); + session_start(); + + /* Set error message */ + if (! empty($GLOBALS['login_without_password_is_forbidden'])) { + $_SESSION['PMA_single_signon_error_message'] = __( + 'Login without a password is forbidden by configuration ' + . '(see AllowNoPassword)' + ); + } elseif (! empty($GLOBALS['allowDeny_forbidden'])) { + $_SESSION['PMA_single_signon_error_message'] = __('Access denied'); + } elseif (! empty($GLOBALS['no_activity'])) { + $_SESSION['PMA_single_signon_error_message'] = sprintf( + __('No activity within %s seconds; please log in again'), + $GLOBALS['cfg']['LoginCookieValidity'] + ); + } elseif (PMA_DBI_getError()) { + $_SESSION['PMA_single_signon_error_message'] = PMA_sanitize( + PMA_DBI_getError() + ); + } else { + $_SESSION['PMA_single_signon_error_message'] = __( + 'Cannot log in to the MySQL server' + ); + } + } + $this->auth(); + } + + /** + * This method is called when any PluginManager to which the observer + * is attached calls PluginManager::notify() + * + * @param SplSubject $subject The PluginManager notifying the observer + * of an update. + * + * @return void + */ + public function update (SplSubject $subject) + { + } +} \ No newline at end of file diff --git a/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php b/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php new file mode 100644 index 0000000000..ac1f728742 --- /dev/null +++ b/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php @@ -0,0 +1,69 @@ + 0) { + $data .= str_repeat("\0", 8 - $mod); + } + + foreach (str_split($data, 8) as $chunk) { + $encrypt .= $pma_cipher->encryptBlock($chunk, $secret); + } + return base64_encode($encrypt); + } + + /** + * Decryption using blowfish algorithm + * + * @param string $encdata encrypted data + * @param string $secret the secret + * + * @return string original data + */ + public static function blowfishDecrypt($encdata, $secret) + { + $pma_cipher = new Horde_Cipher_blowfish; + $decrypt = ''; + $data = base64_decode($encdata); + + foreach (str_split($data, 8) as $chunk) { + $decrypt .= $pma_cipher->decryptBlock($chunk, $secret); + } + return trim($decrypt); + } +} +?> diff --git a/libraries/auth/swekey/authentication.inc.php b/libraries/plugins/auth/swekey/authentication.inc.php similarity index 100% rename from libraries/auth/swekey/authentication.inc.php rename to libraries/plugins/auth/swekey/authentication.inc.php diff --git a/libraries/auth/swekey/musbe-ca.crt b/libraries/plugins/auth/swekey/musbe-ca.crt similarity index 100% rename from libraries/auth/swekey/musbe-ca.crt rename to libraries/plugins/auth/swekey/musbe-ca.crt diff --git a/libraries/auth/swekey/swekey.auth.lib.php b/libraries/plugins/auth/swekey/swekey.auth.lib.php similarity index 98% rename from libraries/auth/swekey/swekey.auth.lib.php rename to libraries/plugins/auth/swekey/swekey.auth.lib.php index 29d4a7f72b..def135d3ae 100644 --- a/libraries/auth/swekey/swekey.auth.lib.php +++ b/libraries/plugins/auth/swekey/swekey.auth.lib.php @@ -79,7 +79,7 @@ function Swekey_auth_error() return null; } - include_once './libraries/auth/swekey/authentication.inc.php'; + include_once './libraries/plugins/auth/swekey/authentication.inc.php'; ?>