From a87f283a23e2b2d0e4a11c14e5b484ed57d865b5 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Thu, 10 May 2012 15:48:43 +0300 Subject: [PATCH 01/55] plugins and OOP: create general class structure and ExportXML --- export.php | 37 +- import.php | 15 +- libraries/common.lib.php | 9 +- libraries/display_export.lib.php | 13 +- libraries/display_import.lib.php | 10 +- libraries/import.lib.php | 4 +- libraries/plugin_interface.lib.php | 98 +++- .../plugins/AuthenticationPlugin.class.php | 51 ++ libraries/plugins/ExportPlugin.class.php | 215 ++++++++ libraries/plugins/ImportPlugin.class.php | 112 ++++ libraries/plugins/PluginManager.class.php | 130 +++++ libraries/plugins/PluginObserver.class.php | 81 +++ .../plugins/TransformationsPlugin.class.php | 66 +++ libraries/plugins/export/ExportXML.class.php | 521 ++++++++++++++++++ 14 files changed, 1313 insertions(+), 49 deletions(-) create mode 100644 libraries/plugins/AuthenticationPlugin.class.php create mode 100644 libraries/plugins/ExportPlugin.class.php create mode 100644 libraries/plugins/ImportPlugin.class.php create mode 100644 libraries/plugins/PluginManager.class.php create mode 100644 libraries/plugins/PluginObserver.class.php create mode 100644 libraries/plugins/TransformationsPlugin.class.php create mode 100644 libraries/plugins/export/ExportXML.class.php diff --git a/export.php b/export.php index 37efc02c62..623173a1ab 100644 --- a/export.php +++ b/export.php @@ -22,9 +22,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) @@ -35,8 +37,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(); } /** @@ -83,7 +87,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!')); include_once 'libraries/header.inc.php'; if ($export_type == 'server') { @@ -297,13 +302,13 @@ if ($asfile) { // 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; + $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 @@ -424,7 +429,7 @@ if (!$save_on_server) { do { // Add possibly some comments to export - if (!PMA_exportHeader()) { + if (! $export_plugin->exportHeader($db)) { break; } @@ -456,10 +461,10 @@ do { if ((isset($tmp_select) && 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') && strpos($GLOBALS['sql_structure_or_data'], 'structure') !== false && isset($GLOBALS['sql_procedure_function'])) { @@ -489,7 +494,7 @@ do { // if this is a view or a merge table, don't export data if (($GLOBALS[$what . '_structure_or_data'] == 'data' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') && !($is_view || PMA_Table::isMerge($current_db, $table))) { $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; } } @@ -555,7 +560,7 @@ do { // if this is a view or a merge table, don't export data if (($GLOBALS[$what . '_structure_or_data'] == 'data' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') && !($is_view || PMA_Table::isMerge($db, $table))) { $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; } } @@ -626,7 +631,7 @@ do { } else { $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; } } @@ -641,11 +646,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 49fb2edb1b..fa5630be42 100644 --- a/import.php +++ b/import.php @@ -409,13 +409,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/common.lib.php b/libraries/common.lib.php index db1d425950..9dec937678 100644 --- a/libraries/common.lib.php +++ b/libraries/common.lib.php @@ -3337,16 +3337,19 @@ function PMA_selectUploadFile($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'] && isset($local_import_file)) + $active = (isset($GLOBALS['timeout_passed']) + && $GLOBALS['timeout_passed'] + && isset($local_import_file)) ? $local_import_file : ''; $files = PMA_getFileSelectOptions( diff --git a/libraries/display_export.lib.php b/libraries/display_export.lib.php index f21a71bc9d..0731f64a85 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(); include './libraries/footer.inc.php'; } ?> diff --git a/libraries/display_import.lib.php b/libraries/display_import.lib.php index f8ff0c25eb..164f8d6ab1 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(); include './libraries/footer.inc.php'; } ?> diff --git a/libraries/import.lib.php b/libraries/import.lib.php index 1213881671..6acd04cf46 100644 --- a/libraries/import.lib.php +++ b/libraries/import.lib.php @@ -316,7 +316,9 @@ function PMA_importGetNextChunk($size = 32768) if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) { $result = substr($result, 3); // UTF-16 BE, LE - } elseif (strncmp($result, "\xFE\xFF", 2) == 0 || strncmp($result, "\xFF\xFE", 2) == 0) { + } elseif (strncmp($result, "\xFE\xFF", 2) == 0 + || strncmp($result, "\xFF\xFE", 2) == 0 + ) { $result = substr($result, 2); } } diff --git a/libraries/plugin_interface.lib.php b/libraries/plugin_interface.lib.php index 98e5e3cfb1..39969001e4 100644 --- a/libraries/plugin_interface.lib.php +++ b/libraries/plugin_interface.lib.php @@ -7,15 +7,41 @@ */ /** - * 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) +{ + // todo replace strtoupper with CamelCaps (ex: HtmlWord) + $class_name = strtoupper($plugin_type[0]) + . strtolower(substr($plugin_type, 1)) + . strtoupper($plugin_format); + $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) { /* Scan for plugins */ $plugin_list = array(); @@ -25,8 +51,18 @@ 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 + ) + ) { include_once $plugins_dir . $file; + $class_name = $class_type . $matches[1]; + $plugin_list [] = new $class_name; } } } @@ -61,8 +97,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 +148,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 +160,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..ae845f4830 --- /dev/null +++ b/libraries/plugins/ExportPlugin.class.php @@ -0,0 +1,215 @@ +setCrlf($crlf); + $this->setCfg($cfg); + $this->setDb($db); + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Gets the export specific format plugin properties + * + * @return array + */ + public function getProperties() + { + return $this->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 + */ + public 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 configuration settings + * + * @return array + */ + public 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 database name + * + * @return string + */ + public function getDb() + { + return $this->_db; + } + + /** + * Sets the database name + * + * @param String $db database name + * + * @return void + */ + protected function setDb($db) + { + $this->_db = $db; + } +} +?> \ 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..e2a11d07ab --- /dev/null +++ b/libraries/plugins/ImportPlugin.class.php @@ -0,0 +1,112 @@ +setError($error); + $this->setTimeout_passed($timeout_passed); + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Gets the import specific format plugin properties + * + * @return array + */ + public function getProperties() + { + return $this->properties; + } + + /** + * Sets the export plugins properties and is implemented by each import + * plugin + * + * @return void + */ + abstract protected function setProperties(); + + public function getError() + { + return $this->_error; + } + + public function setError($error) + { + $this->_error = $error; + } + + public function getTimeout_passed() + { + return $this->_timeout_passed; + } + + public function setTimeout_passed($timeout_passed) + { + $this->_timeout_passed = $timeout_passed; + } +} +?> \ 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..52c981346d --- /dev/null +++ b/libraries/plugins/PluginManager.class.php @@ -0,0 +1,130 @@ +_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. + * + * @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/TransformationsPlugin.class.php b/libraries/plugins/TransformationsPlugin.class.php new file mode 100644 index 0000000000..be17845425 --- /dev/null +++ b/libraries/plugins/TransformationsPlugin.class.php @@ -0,0 +1,66 @@ + \ No newline at end of file diff --git a/libraries/plugins/export/ExportXML.class.php b/libraries/plugins/export/ExportXML.class.php new file mode 100644 index 0000000000..6403ce7968 --- /dev/null +++ b/libraries/plugins/export/ExportXML.class.php @@ -0,0 +1,521 @@ +setProperties(); + + } + + /** + * Initialize the local variables that are used specific for export SQL + * + * @global type $table + * @global type $tables + * + * @return void + */ + private function initLocalVariables() + { + global $table; + global $tables; + $this->setTable($table); + $this->setTables($tables); + } + + /** + * Sets the export XML properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('XML'), + 'extension' => 'xml', + 'mime_type' => 'text/xml', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'hidden', + 'name' => 'structure_or_data' + ), + array( + 'type' => 'end_group' + ) + ); + + /* Export structure */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'structure', + 'text' => __('Object creation options (all are recommended)') + ); + if (! PMA_DRIZZLE) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_functions', + 'text' => __('Functions') + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_procedures', + 'text' => __('Procedures') + ); + } + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_tables', + 'text' => __('Tables') + ); + if (! PMA_DRIZZLE) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_triggers', + 'text' => __('Triggers') + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_views', + 'text' => __('Views') + ); + } + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + + /* Data */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'data', + 'text' => __('Data dump options') + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_contents', + 'text' => __('Export contents') + ); + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header. It is the first method to be called, so all + * the required variables are initialized here. + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + // initialize the general export variables + $this->initExportCommonVariables(); + + // initialize the specific export sql variables + $this->initLocalVariables(); + + $crlf = $this->getCrlf(); + $cfg = $this->getCfg(); + $db = $this->getDb(); + $table = $this->getTable(); + $tables = $this->getTables(); + + $export_struct = isset($GLOBALS['xml_export_functions']) + || isset($GLOBALS['xml_export_procedures']) + || isset($GLOBALS['xml_export_tables']) + || isset($GLOBALS['xml_export_triggers']) + || isset($GLOBALS['xml_export_views']); + $export_data = isset($GLOBALS['xml_export_contents']) ? true : false; + + if ($GLOBALS['output_charset_conversion']) { + $charset = $GLOBALS['charset_of_file']; + } else { + $charset = 'utf-8'; + } + + $head = '' . $crlf + . '' . $crlf . $crlf; + + $head .= '' . $crlf; + + if ($export_struct) { + if (PMA_DRIZZLE) { + $result = PMA_DBI_fetch_result( + "SELECT + 'utf8' AS DEFAULT_CHARACTER_SET_NAME, + DEFAULT_COLLATION_NAME + FROM data_dictionary.SCHEMAS + WHERE SCHEMA_NAME = '" . PMA_sqlAddSlashes($db) . "'" + ); + } else { + $result = PMA_DBI_fetch_result( + 'SELECT `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`' + . ' FROM `information_schema`.`SCHEMATA` WHERE `SCHEMA_NAME`' + . ' = \''.PMA_sqlAddSlashes($db).'\' LIMIT 1' + ); + } + $db_collation = $result[0]['DEFAULT_COLLATION_NAME']; + $db_charset = $result[0]['DEFAULT_CHARACTER_SET_NAME']; + + $head .= ' ' . $crlf; + $head .= ' ' . $crlf; + $head .= ' ' . $crlf; + + if (count($tables) == 0) { + $tables[] = $table; + } + + foreach ($tables as $table) { + // Export tables and views + $result = PMA_DBI_fetch_result( + 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' + . PMA_backquote($table), + 0 + ); + $tbl = $result[$table][1]; + + $is_view = PMA_Table::isView($db, $table); + + if ($is_view) { + $type = 'view'; + } else { + $type = 'table'; + } + + if ($is_view && ! isset($GLOBALS['xml_export_views'])) { + continue; + } + + if (! $is_view && ! isset($GLOBALS['xml_export_tables'])) { + continue; + } + + $head .= ' ' + . $crlf; + + $tbl = " " . htmlspecialchars($tbl); + $tbl = str_replace("\n", "\n ", $tbl); + + $head .= $tbl . ';' . $crlf; + $head .= ' ' . $crlf; + + if (isset($GLOBALS['xml_export_triggers']) + && $GLOBALS['xml_export_triggers'] + ) { + // Export triggers + $triggers = PMA_DBI_get_triggers($db, $table); + if ($triggers) { + foreach ($triggers as $trigger) { + $code = $trigger['create']; + $head .= ' ' . $crlf; + + // Do some formatting + $code = substr(rtrim($code), 0, -3); + $code = " " . htmlspecialchars($code); + $code = str_replace("\n", "\n ", $code); + + $head .= $code . $crlf; + $head .= ' ' . $crlf; + } + + unset($trigger); + unset($triggers); + } + } + } + + if (isset($GLOBALS['xml_export_functions']) + && $GLOBALS['xml_export_functions'] + ) { + // Export functions + $functions = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION'); + if ($functions) { + foreach ($functions as $function) { + $head .= ' ' . $crlf; + + // Do some formatting + $sql = PMA_DBI_get_definition($db, 'FUNCTION', $function); + $sql = rtrim($sql); + $sql = " " . htmlspecialchars($sql); + $sql = str_replace("\n", "\n ", $sql); + + $head .= $sql . $crlf; + $head .= ' ' . $crlf; + } + + unset($function); + unset($functions); + } + } + + if (isset($GLOBALS['xml_export_procedures']) + && $GLOBALS['xml_export_procedures'] + ) { + // Export procedures + $procedures = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE'); + if ($procedures) { + foreach ($procedures as $procedure) { + $head .= ' ' . $crlf; + + // Do some formatting + $sql = PMA_DBI_get_definition($db, 'PROCEDURE', $procedure); + $sql = rtrim($sql); + $sql = " " . htmlspecialchars($sql); + $sql = str_replace("\n", "\n ", $sql); + + $head .= $sql . $crlf; + $head .= ' ' . $crlf; + } + + unset($procedure); + unset($procedures); + } + } + + unset($result); + + $head .= ' ' . $crlf; + $head .= ' ' . $crlf; + + if ($export_data) { + $head .= $crlf; + } + } + + return PMA_exportOutputHandler($head); + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + $foot = ''; + + return PMA_exportOutputHandler($foot); + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + $crlf = $this->getCrlf(); + + if (isset($GLOBALS['xml_export_contents']) + && $GLOBALS['xml_export_contents'] + ) { + $head = ' ' . $crlf + . ' ' . $crlf; + + return PMA_exportOutputHandler($head); + } else { + return true; + } + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + $crlf = $this->getCrlf(); + + if (isset($GLOBALS['xml_export_contents']) + && $GLOBALS['xml_export_contents'] + ) { + return PMA_exportOutputHandler(' ' . $crlf); + } else { + return true; + } + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + return true; + } + + /** + * Outputs the content of a table in XML format + * + * @param string $db database name + * @param string $table table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param string $sql_query SQL query for obtaining data + * + * @return bool Whether it succeeded + */ + public function exportData ($db, $table, $crlf, $error_url, $sql_query) + { + if (isset($GLOBALS['xml_export_contents']) + && $GLOBALS['xml_export_contents'] + ) { + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + + $columns_cnt = PMA_DBI_num_fields($result); + $columns = array(); + for ($i = 0; $i < $columns_cnt; $i++) { + $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); + } + unset($i); + + $buffer = ' ' . $crlf; + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + while ($record = PMA_DBI_fetch_row($result)) { + $buffer = ' ' . $crlf; + for ($i = 0; $i < $columns_cnt; $i++) { + // If a cell is NULL, still export it to preserve + // the XML structure + if (! isset($record[$i]) || is_null($record[$i])) { + $record[$i] = 'NULL'; + } + $buffer .= ' ' + . htmlspecialchars((string)$record[$i]) + . '' . $crlf; + } + $buffer .= '
' . $crlf; + + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + } + PMA_DBI_free_result($result); + } + + return true; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + private function getTable() + { + return $this->table; + } + + private function setTable($table) + { + $this->table = $table; + } + + private function getTables() + { + return $this->tables; + } + + private function setTables($tables) + { + $this->tables = $tables; + } +} +?> \ No newline at end of file From b0e8486ef1e2be20b65492a8017b143f53b406a2 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 28 May 2012 00:59:49 +0300 Subject: [PATCH 02/55] plugins and OOP: import XML, export and import SQL; auth structure --- .../auth/AuthenticationConfig.class.php | 71 + .../auth/AuthenticationCookie.class.php | 89 + .../plugins/auth/AuthenticationHTTP.class.php | 71 + .../auth/AuthenticationSIgnOn.class.php | 71 + .../auth/swekey/authentication.inc.php | 172 ++ libraries/plugins/auth/swekey/musbe-ca.crt | 25 + .../plugins/auth/swekey/swekey.auth.lib.php | 291 +++ libraries/plugins/auth/swekey/swekey.php | 517 +++++ libraries/plugins/export/ExportSQL.class.php | 1886 +++++++++++++++++ libraries/plugins/import/ImportSQL.class.php | 392 ++++ libraries/plugins/import/ImportXML.class.php | 458 ++++ 11 files changed, 4043 insertions(+) create mode 100644 libraries/plugins/auth/AuthenticationConfig.class.php create mode 100644 libraries/plugins/auth/AuthenticationCookie.class.php create mode 100644 libraries/plugins/auth/AuthenticationHTTP.class.php create mode 100644 libraries/plugins/auth/AuthenticationSIgnOn.class.php create mode 100644 libraries/plugins/auth/swekey/authentication.inc.php create mode 100644 libraries/plugins/auth/swekey/musbe-ca.crt create mode 100644 libraries/plugins/auth/swekey/swekey.auth.lib.php create mode 100644 libraries/plugins/auth/swekey/swekey.php create mode 100644 libraries/plugins/export/ExportSQL.class.php create mode 100644 libraries/plugins/import/ImportSQL.class.php create mode 100644 libraries/plugins/import/ImportXML.class.php diff --git a/libraries/plugins/auth/AuthenticationConfig.class.php b/libraries/plugins/auth/AuthenticationConfig.class.php new file mode 100644 index 0000000000..d9837db1eb --- /dev/null +++ b/libraries/plugins/auth/AuthenticationConfig.class.php @@ -0,0 +1,71 @@ + + + diff --git a/libraries/plugins/auth/swekey/musbe-ca.crt b/libraries/plugins/auth/swekey/musbe-ca.crt new file mode 100644 index 0000000000..2a31ad18f9 --- /dev/null +++ b/libraries/plugins/auth/swekey/musbe-ca.crt @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIJAMjw7QcLWCd6MA0GCSqGSIb3DQEBBQUAMGsxCzAJBgNV +BAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQKEwtNdXNiZSwgSW5j +LjESMBAGA1UEAxMJbXVzYmUuY29tMR0wGwYJKoZIhvcNAQkBFg5pbmZvQG11c2Jl +LmNvbTAeFw0wODA5MDQxNDE2MTNaFw0zNzEyMjExNDE2MTNaMGsxCzAJBgNVBAYT +AlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQKEwtNdXNiZSwgSW5jLjES +MBAGA1UEAxMJbXVzYmUuY29tMR0wGwYJKoZIhvcNAQkBFg5pbmZvQG11c2JlLmNv +bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOBhOljxVzQfK4gted2I +d3BemcjW4abAUOzn3KYWXpPO5xIfVeXNDGkDbyH+X+7fo94sX25/ewuKNFDSOcvo +tXHq7uQenTHB35r+a+LY81KceUHgW90a3XsqPAkwAjyYcgo3zmM2DtLvw+5Yod8T +wAHk9m3qavnQ1uk99jBTwL7RZ9jIZHh9pFCL93uJc2obtd8O96Iycbn2q0w/AWbb ++eUVWIHzvLtfPvROeL3lJzr/Uz5LjKapxJ3qyqASflfHpnj9pU8l6g2TQ6Hg5KT5 +tLFkRe7uGhOfRtOQ/+NjaWrEuNCFnpyN4Q5Fv+5qA1Ip1IpH0200sWbAf/k2u0Qp +Sx0CAwEAAaOB0DCBzTAdBgNVHQ4EFgQUczJrQ7hCvtsnzcqiDIZ/GSn/CiwwgZ0G +A1UdIwSBlTCBkoAUczJrQ7hCvtsnzcqiDIZ/GSn/Ciyhb6RtMGsxCzAJBgNVBAYT +AlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQKEwtNdXNiZSwgSW5jLjES +MBAGA1UEAxMJbXVzYmUuY29tMR0wGwYJKoZIhvcNAQkBFg5pbmZvQG11c2JlLmNv +bYIJAMjw7QcLWCd6MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAGxk +8xzIljeBDQWWVRr0NEALVSv3i09V4jAKkyEOfmZ8lKMKJi0atwbtjrXTzLnNYj+Q +pyUbyY/8ItWvV7pnVxMiF9qcer7e9X4vw358GZuMVE/da1nWxz+CwzTm5oO30RzA +antM9bISFFr9lJq69bDWOnCUi1IG8DSL3TxtlABso7S4vqiZ+sB33l6k1K4a/Njb +QkU9UejKhKkVVZTsOrumfnOJ4MCmPfX8Y/AY2o670y5HnzpxerIYziCVzApPVrW7 +sKH0tuVGturMfQOKgstYe4/m9glBTeTLMkjD+6MJC2ONBD7GAiOO95gNl5M1fzJQ +FEe5CJ7DCYl0GdmLXXw= +-----END CERTIFICATE----- diff --git a/libraries/plugins/auth/swekey/swekey.auth.lib.php b/libraries/plugins/auth/swekey/swekey.auth.lib.php new file mode 100644 index 0000000000..29d4a7f72b --- /dev/null +++ b/libraries/plugins/auth/swekey/swekey.auth.lib.php @@ -0,0 +1,291 @@ + + + \n"; +// if (file_exists($caFile)) +// echo "\n"; + } + + if (file_exists($caFile)) { + Swekey_SetCAFile($caFile); + } elseif (! empty($caFile) && (substr($_SESSION['SWEKEY']['CONF_SERVER_CHECK'], 0, 8) == "https://")) { + return "Internal Error: CA File $caFile not found"; + } + + $result = null; + $swekey_id = $_GET['swekey_id']; + $swekey_otp = $_GET['swekey_otp']; + + if (isset($swekey_id)) { + unset($_SESSION['SWEKEY']['AUTHENTICATED_SWEKEY']); + if (! isset($_SESSION['SWEKEY']['RND_TOKEN'])) { + unset($swekey_id); + } else { + if (strlen($swekey_id) == 32) { + $res = Swekey_CheckOtp($swekey_id, $_SESSION['SWEKEY']['RND_TOKEN'], $swekey_otp); + unset($_SESSION['SWEKEY']['RND_TOKEN']); + if (! $res) { + $result = __('Hardware authentication failed') . ' (' . Swekey_GetLastError() . ')'; + } else { + $_SESSION['SWEKEY']['AUTHENTICATED_SWEKEY'] = $swekey_id; + $_SESSION['SWEKEY']['FORCE_USER'] = $_SESSION['SWEKEY']['VALID_SWEKEYS'][$swekey_id]; + return null; + } + } else { + $result = __('No valid authentication key plugged'); + if ($_SESSION['SWEKEY']['CONF_DEBUG']) { + $result .= "
" . htmlspecialchars($swekey_id); + } + unset($_SESSION['SWEKEY']['CONF_LOADED']); // reload the conf file + } + } + } else { + unset($_SESSION['SWEKEY']); + } + + $_SESSION['SWEKEY']['RND_TOKEN'] = Swekey_GetFastRndToken(); + if (strlen($_SESSION['SWEKEY']['RND_TOKEN']) != 64) { + $result = __('Hardware authentication failed') . ' (' . Swekey_GetLastError() . ')'; + unset($_SESSION['SWEKEY']['CONF_LOADED']); // reload the conf file + } + + if (! isset($swekey_id)) { + ?> + + display(); + if ($GLOBALS['error_handler']->hasDisplayErrors()) { + echo '
'; + $GLOBALS['error_handler']->dispErrors(); + echo '
'; + } + } + + if (isset($_SESSION['SWEKEY']) && $_SESSION['SWEKEY']['ENABLED']) { + echo ''; + } +} + +if (!empty($_GET['session_to_unset'])) { + session_write_close(); + session_id($_GET['session_to_unset']); + session_start(); + $_SESSION = array(); + session_write_close(); + session_destroy(); + exit; +} + +if (isset($_GET['swekey_reset'])) { + unset($_SESSION['SWEKEY']); +} + +?> diff --git a/libraries/plugins/auth/swekey/swekey.php b/libraries/plugins/auth/swekey/swekey.php new file mode 100644 index 0000000000..0f49732101 --- /dev/null +++ b/libraries/plugins/auth/swekey/swekey.php @@ -0,0 +1,517 @@ +"; + +/** + * Servers addresses + * Use the Swekey_SetXxxServer($server) functions to set them + */ + +global $gSwekeyCheckServer; +if (! isset($gSwekeyCheckServer)) { + $gSwekeyCheckServer = SWEKEY_DEFAULT_CHECK_SERVER; +} + +global $gSwekeyRndTokenServer; +if (! isset($gSwekeyRndTokenServer)) { + $gSwekeyRndTokenServer = SWEKEY_DEFAULT_RND_SERVER; +} + +global $gSwekeyStatusServer; +if (! isset($gSwekeyStatusServer)) { + $gSwekeyStatusServer = SWEKEY_DEFAULT_STATUS_SERVER; +} + +global $gSwekeyCA; + +global $gSwekeyTokenCacheEnabled; +if (! isset($gSwekeyTokenCacheEnabled)) { + $gSwekeyTokenCacheEnabled = true; +} + +/** + * Change the address of the Check server. + * If $server is empty the default value 'http://auth-check.musbe.net' will be used + * + * @param server The protocol and hostname to use + * @access public + */ +function Swekey_SetCheckServer($server) +{ + global $gSwekeyCheckServer; + if (empty($server)) { + $gSwekeyCheckServer = SWEKEY_DEFAULT_CHECK_SERVER; + } else { + $gSwekeyCheckServer = $server; + } +} + +/** + * Change the address of the Random Token Generator server. + * If $server is empty the default value 'http://auth-rnd-gen.musbe.net' will be used + * + * @param server The protocol and hostname to use + * @access public + */ +function Swekey_SetRndTokenServer($server) +{ + global $gSwekeyRndTokenServer; + if (empty($server)) { + $gSwekeyRndTokenServer = SWEKEY_DEFAULT_RND_SERVER; + } else { + $gSwekeyRndTokenServer = $server; + } +} + +/** + * Change the address of the Satus server. + * If $server is empty the default value 'http://auth-status.musbe.net' will be used + * + * @param server The protocol and hostname to use + * @access public + */ +function Swekey_SetStatusServer($server) +{ + global $gSwekeyStatusServer; + if (empty($server)) { + $gSwekeyStatusServer = SWEKEY_DEFAULT_STATUS_SERVER; + } else { + $gSwekeyStatusServer = $server; + } +} + +/** + * Change the certificat file in case of the the severs use https instead of http + * + * @param cafile The path of the crt file to use + * @access public + */ +function Swekey_SetCAFile($cafile) +{ + global $gSwekeyCA; + $gSwekeyCA = $cafile; +} + +/** + * Enable or disable the random token caching + * Because everybody has full access to the cache file, it can be a DOS vulnerability + * So disable it if you are running in a non secure enviromnement + * + * @param $enable + * @access public + */ +function Swekey_EnableTokenCache($enable) +{ + global $gSwekeyTokenCacheEnabled; + $gSwekeyTokenCacheEnabled = ! empty($enable); +} + + +/** + * Return the last error. + * + * @return The Last Error + * @access public + */ +function Swekey_GetLastError() +{ + global $gSwekeyLastError; + return $gSwekeyLastError; +} + +/** + * Return the last result. + * + * @return The Last Error + * @access public + */ +function Swekey_GetLastResult() +{ + global $gSwekeyLastResult; + return $gSwekeyLastResult; +} + +/** + * Send a synchronous request to the server. + * This function manages timeout then will not block if one of the server is down + * + * @param url The url to get + * @param response_code The response code + * + * @return The body of the response or "" in case of error + * @access private + */ +function Swekey_HttpGet($url, &$response_code) +{ + global $gSwekeyLastError; + $gSwekeyLastError = 0; + global $gSwekeyLastResult; + $gSwekeyLastResult = ""; + + // use curl if available + if (function_exists('curl_init')) { + $sess = curl_init($url); + if (substr($url, 0, 8) == "https://") { + global $gSwekeyCA; + + if (! empty($gSwekeyCA)) { + if (file_exists($gSwekeyCA)) { + if (! curl_setopt($sess, CURLOPT_CAINFO, $gSwekeyCA)) { + error_log("SWEKEY_ERROR:Could not set CA file : ".curl_error($sess)); + } else { + $caFileOk = true; + } + } else { + error_log("SWEKEY_ERROR:Could not find CA file $gSwekeyCA getting $url"); + } + } + + curl_setopt($sess, CURLOPT_SSL_VERIFYHOST, '2'); + curl_setopt($sess, CURLOPT_SSL_VERIFYPEER, '2'); + curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '20'); + curl_setopt($sess, CURLOPT_TIMEOUT, '20'); + } else { + curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '3'); + curl_setopt($sess, CURLOPT_TIMEOUT, '5'); + } + + curl_setopt($sess, CURLOPT_RETURNTRANSFER, '1'); + $res=curl_exec($sess); + $response_code = curl_getinfo($sess, CURLINFO_HTTP_CODE); + $curlerr = curl_error($sess); + curl_close($sess); + + if ($response_code == 200) { + $gSwekeyLastResult = $res; + return $res; + } + + if (! empty($response_code)) { + $gSwekeyLastError = $response_code; + error_log("SWEKEY_ERROR:Error $gSwekeyLastError ($curlerr) getting $url"); + return ""; + } + + $response_code = 408; // Request Timeout + $gSwekeyLastError = $response_code; + error_log("SWEKEY_ERROR:Error $curlerr getting $url"); + return ""; + } + + // use pecl_http if available + if (class_exists('HttpRequest')) { + // retry if one of the server is down + for ($num=1; $num <= 3; $num++ ) { + $r = new HttpRequest($url); + $options = array('timeout' => '3'); + + if (substr($url, 0, 6) == "https:") { + $sslOptions = array(); + $sslOptions['verifypeer'] = true; + $sslOptions['verifyhost'] = true; + + $capath = __FILE__; + $name = strrchr($capath, '/'); + // windows + if (empty($name)) { + $name = strrchr($capath, '\\'); + } + $capath = substr($capath, 0, strlen($capath) - strlen($name) + 1).'musbe-ca.crt'; + + if (! empty($gSwekeyCA)) { + $sslOptions['cainfo'] = $gSwekeyCA; + } + + $options['ssl'] = $sslOptions; + } + + $r->setOptions($options); + + // try + { + $reply = $r->send(); + $res = $reply->getBody(); + $info = $r->getResponseInfo(); + $response_code = $info['response_code']; + if ($response_code != 200) { + $gSwekeyLastError = $response_code; + error_log("SWEKEY_ERROR:Error ".$gSwekeyLastError." getting ".$url); + return ""; + } + + + $gSwekeyLastResult = $res; + return $res; + } + // catch (HttpException $e) + // { + // error_log("SWEKEY_WARNING:HttpException ".$e." getting ".$url); + // } + } + + $response_code = 408; // Request Timeout + $gSwekeyLastError = $response_code; + error_log("SWEKEY_ERROR:Error ".$gSwekeyLastError." getting ".$url); + return ""; + } + + global $http_response_header; + $res = @file_get_contents($url); + $response_code = substr($http_response_header[0], 9, 3); //HTTP/1.0 + if ($response_code == 200) { + $gSwekeyLastResult = $res; + return $res; + } + + $gSwekeyLastError = $response_code; + error_log("SWEKEY_ERROR:Error ".$response_code." getting ".$url); + return ""; +} + +/** + * Get a Random Token from a Token Server + * The RT is a 64 vhars hexadecimal value + * You should better use Swekey_GetFastRndToken() for performance + * @access public + */ +function Swekey_GetRndToken() +{ + global $gSwekeyRndTokenServer; + return Swekey_HttpGet($gSwekeyRndTokenServer.'/FULL-RND-TOKEN', $response_code); +} + +/** + * Get a Half Random Token from a Token Server + * The RT is a 64 vhars hexadecimal value + * Use this value if you want to make your own Swekey_GetFastRndToken() + * @access public + */ +function Swekey_GetHalfRndToken() +{ + global $gSwekeyRndTokenServer; + return Swekey_HttpGet($gSwekeyRndTokenServer.'/HALF-RND-TOKEN', $response_code); +} + +/** + * Get a Half Random Token + * The RT is a 64 vhars hexadecimal value + * This function get a new random token and reuse it. + * Token are refetched from the server only once every 30 seconds. + * You should always use this function to get half random token. + * @access public + */ +function Swekey_GetFastHalfRndToken() +{ + global $gSwekeyTokenCacheEnabled; + + $res = ""; + $cachefile = ""; + + // We check if we have a valid RT is the session + if (isset($_SESSION['rnd-token-date'])) { + if (time() - $_SESSION['rnd-token-date'] < 30) { + $res = $_SESSION['rnd-token']; + } + } + + // If not we try to get it from a temp file (PHP >= 5.2.1 only) + if (strlen($res) != 32 && $gSwekeyTokenCacheEnabled) { + if (function_exists('sys_get_temp_dir')) { + $tempdir = sys_get_temp_dir(); + $cachefile = $tempdir."/swekey-rnd-token-".get_current_user(); + $modif = filemtime($cachefile); + if ($modif != false) { + if (time() - $modif < 30) { + $res = @file_get_contents($cachefile); + if (strlen($res) != 32) { + $res = ""; + } else { + $_SESSION['rnd-token'] = $res; + $_SESSION['rnd-token-date'] = $modif; + } + } + } + } + } + + // If we don't have a valid RT here we have to get it from the server + if (strlen($res) != 32) { + $res = substr(Swekey_GetHalfRndToken(), 0, 32); + $_SESSION['rnd-token'] = $res; + $_SESSION['rnd-token-date'] = time(); + if (! empty($cachefile)) { + // we unlink the file so no possible tempfile race attack + unlink($cachefile); + $file = fopen($cachefile, "x"); + if ($file != false) { + @fwrite($file, $res); + @fclose($file); + } + } + } + + return $res."00000000000000000000000000000000"; +} + +/** + * Get a Random Token + * The RT is a 64 vhars hexadecimal value + * This function generates a unique random token for each call but call the + * server only once every 30 seconds. + * You should always use this function to get random token. + * @access public + */ +function Swekey_GetFastRndToken() +{ + $res = Swekey_GetFastHalfRndToken(); + if (strlen($res) == 64) { + return substr($res, 0, 32).strtoupper(md5("Musbe Authentication Key" + mt_rand() + date(DATE_ATOM))); + } + return ""; +} + + +/** + * Checks that an OTP generated by a Swekey is valid + * + * @param id The id of the swekey + * @param rt The random token used to generate the otp + * @param otp The otp generated by the swekey + * + * @return true or false + * @access public + */ +function Swekey_CheckOtp($id, $rt, $otp) +{ + global $gSwekeyCheckServer; + $res = Swekey_HttpGet($gSwekeyCheckServer.'/CHECK-OTP/'.$id.'/'.$rt.'/'.$otp, $response_code); + return $response_code == 200 && $res == "OK"; +} + +/** + * Values that are associated with a key. + * The following values can be returned by the Swekey_GetStatus() function + */ +define("SWEKEY_STATUS_OK", 0); +define("SWEKEY_STATUS_NOT_FOUND", 1); // The key does not exist in the db +define("SWEKEY_STATUS_INACTIVE", 2); // The key has never been activated +define("SWEKEY_STATUS_LOST", 3); // The user has lost his key +define("SWEKEY_STATUS_STOLEN", 4); // The key was stolen +define("SWEKEY_STATUS_FEE_DUE", 5); // The annual fee was not paid +define("SWEKEY_STATUS_OBSOLETE", 6); // The hardware is no longer supported +define("SWEKEY_STATUS_UNKOWN", 201); // We could not connect to the authentication server + +/** + * Values that are associated with a key. + * The Javascript Api can also return the following values + */ +define("SWEKEY_STATUS_REPLACED", 100); // This key has been replaced by a backup key +define("SWEKEY_STATUS_BACKUP_KEY", 101); // This key is a backup key that is not activated yet +define("SWEKEY_STATUS_NOTPLUGGED", 200); // This key is not plugged in the computer + + +/** + * Return the text corresponding to the integer status of a key + * + * @param status The status + * + * @return The text corresponding to the status + * @access public + */ +function Swekey_GetStatusStr($status) +{ + switch($status) + { + case SWEKEY_STATUS_OK : + return 'OK'; + case SWEKEY_STATUS_NOT_FOUND : + return 'Key does not exist in the db'; + case SWEKEY_STATUS_INACTIVE : + return 'Key not activated'; + case SWEKEY_STATUS_LOST : + return 'Key was lost'; + case SWEKEY_STATUS_STOLEN : + return 'Key was stolen'; + case SWEKEY_STATUS_FEE_DUE : + return 'The annual fee was not paid'; + case SWEKEY_STATUS_OBSOLETE : + return 'Key no longer supported'; + case SWEKEY_STATUS_REPLACED : + return 'This key has been replaced by a backup key'; + case SWEKEY_STATUS_BACKUP_KEY : + return 'This key is a backup key that is not activated yet'; + case SWEKEY_STATUS_NOTPLUGGED : + return 'This key is not plugged in the computer'; + case SWEKEY_STATUS_UNKOWN : + return 'Unknow Status, could not connect to the authentication server'; + } + return 'unknown status '.$status; +} + +/** + * If your web site requires a key to login you should check that the key + * is still valid (has not been lost or stolen) before requiring it. + * A key can be authenticated only if its status is SWEKEY_STATUS_OK + * + * @param id The id of the swekey + * + * @return The status of the swekey + * @access public + */ +function Swekey_GetStatus($id) +{ + global $gSwekeyStatusServer; + $res = Swekey_HttpGet($gSwekeyStatusServer.'/GET-STATUS/'.$id, $response_code); + if ($response_code == 200) { + return intval($res); + } + return SWEKEY_STATUS_UNKOWN; +} + +?> diff --git a/libraries/plugins/export/ExportSQL.class.php b/libraries/plugins/export/ExportSQL.class.php new file mode 100644 index 0000000000..fe04056362 --- /dev/null +++ b/libraries/plugins/export/ExportSQL.class.php @@ -0,0 +1,1886 @@ +setProperties(); + + // Avoids undefined variables, use NULL so isset() returns false + if (! isset($GLOBALS['sql_backquotes'])) { + $GLOBALS['sql_backquotes'] = null; + } + } + + /** + * Initialize the local variables that are used specific for export SQL + * + * @global type $plugin_param + * @global type $mysql_charset_map + * @global type $sql_drop_table + * @global type $sql_backquotes + * @global type $sql_constraints + * @global type $sql_constraints_query + * @global type $sql_drop_foreign_keys + * @global type $cfgRelation + * @global type $current_row + * + * @return void + */ + private function initLocalVariables() + { + global $plugin_param; + global $mysql_charset_map; + global $sql_drop_table; + global $sql_backquotes; + global $sql_constraints; + global $sql_constraints_query; + global $sql_drop_foreign_keys; + global $cfgRelation; + global $current_row; + $this->setPlugin_param($plugin_param); + $this->setMysql_charset_map($mysql_charset_map); + $this->setSql_drop_table($sql_drop_table); + $this->setSql_backquotes($sql_backquotes); + $this->setSql_constraints($sql_constraints); + $this->setSql_constraints_query($sql_constraints_query); + $this->setSql_drop_foreign_keys($sql_drop_foreign_keys); + $this->setCfgRelation($cfgRelation); + $this->setCurrent_row($current_row); + } + + /** + * Sets the export XML properties + * + * @return void + */ + protected function setProperties() + { + $plugin_param = $this->getPlugin_param(); + + $hide_sql = false; + $hide_structure = false; + if ($plugin_param['export_type'] == 'table' + && ! $plugin_param['single_table'] + ) { + $hide_structure = true; + $hide_sql = true; + } + if (! $hide_sql) { + $this->properties = array( + 'text' => __('SQL'), + 'extension' => 'sql', + 'mime_type' => 'text/x-sql', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ); + + /* comments */ + $this->properties['options'][] = array( + 'type' => 'begin_subgroup', + 'subgroup_header' => array( + 'type' => 'bool', + 'name' => 'include_comments', + 'text' => __( + 'Display comments (includes info such as export timestamp,' + . ' PHP version, and server version)' + ) + ) + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'header_comment', + 'text' => __('Additional custom header comment (\n splits lines):') + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'dates', + 'text' => __( + 'Include a timestamp of when databases were created, last' + . ' updated, and last checked' + ) + ); + if (! empty($GLOBALS['cfgRelation']['relation'])) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'relation', + 'text' => __('Display foreign key relationships') + ); + } + if (! empty($GLOBALS['cfgRelation']['mimework'])) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'mime', + 'text' => __('Display MIME types') + ); + } + $this->properties['options'][] = array( + 'type' => 'end_subgroup' + ); + /* end comments */ + + /* enclose in a transaction */ + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'use_transaction', + 'text' => __('Enclose export in a transaction'), + 'doc' => array( + 'programs', + 'mysqldump', + 'option_mysqldump_single-transaction' + ) + ); + + /* disable foreign key checks */ + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'disable_fk', + 'text' => __('Disable foreign key checks'), + 'doc' => array( + 'manual_MySQL_Database_Administration', + 'server-system-variables', + 'sysvar_foreign_key_checks' + ) + ); + + /* compatibility maximization */ + $compats = PMA_DBI_getCompatibilities(); + if (count($compats) > 0) { + $values = array(); + foreach ($compats as $val) { + $values[$val] = $val; + } + $this->properties['options'][] = array( + 'type' => 'select', + 'name' => 'compatibility', + 'text' => __( + 'Database system or older MySQL server to maximize output' + . ' compatibility with:' + ), + 'values' => $values, + 'doc' => array( + 'manual_MySQL_Database_Administration', + 'Server_SQL_mode' + ) + ); + unset($values); + } + + /* server export options */ + if ($plugin_param['export_type'] == 'server') { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'drop_database', + 'text' => sprintf( + __('Add %s statement'), 'DROP DATABASE' + ) + ); + } + + /* what to dump (structure/data/both) */ + $this->properties['options'][] = array( + 'type' => 'begin_subgroup', + 'subgroup_header' => array( + 'type' => 'message_only', + 'text' => __('Dump table') + ) + ); + $this->properties['options'][] = array( + 'type' => 'radio', + 'name' => 'structure_or_data', + 'values' => array( + 'structure' => __('structure'), + 'data' => __('data'), + 'structure_and_data' => __('structure and data') + ) + ); + $this->properties['options'][] = array( + 'type' => 'end_subgroup' + ); + + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + + /* begin Structure options */ + if (! $hide_structure) { + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'structure', + 'text' => __('Object creation options'), + 'force' => 'data' + ); + + /* begin SQL Statements */ + $this->properties['options'][] = array( + 'type' => 'begin_subgroup', + 'subgroup_header' => array( + 'type' => 'message_only', + 'name' => 'add_statements', + 'text' => __('Add statements:') + ) + ); + if ($plugin_param['export_type'] == 'table') { + if (PMA_Table::isView($GLOBALS['db'], $GLOBALS['table'])) { + $drop_clause = 'DROP VIEW'; + } else { + $drop_clause = 'DROP TABLE'; + } + } else { + if (PMA_DRIZZLE) { + $drop_clause = 'DROP TABLE'; + } else { + $drop_clause = 'DROP TABLE / VIEW / PROCEDURE' + . ' / FUNCTION'; + if (PMA_MYSQL_INT_VERSION > 50100) { + $drop_clause .= ' / EVENT'; + } + } + } + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'drop_table', + 'text' => sprintf(__('Add %s statement'), $drop_clause) + ); + // Drizzle doesn't support procedures and functions + if (! PMA_DRIZZLE) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'procedure_function', + 'text' => sprintf( + __('Add %s statement'), + 'CREATE PROCEDURE / FUNCTION' + . (PMA_MYSQL_INT_VERSION > 50100 + ? ' / EVENT' : '') + ) + ); + } + + /* begin CREATE TABLE statements*/ + $this->properties['options'][] = array( + 'type' => 'begin_subgroup', + 'subgroup_header' => array( + 'type' => 'bool', + 'name' => 'create_table_statements', + 'text' => __('CREATE TABLE options:') + ) + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'if_not_exists', + 'text' => 'IF NOT EXISTS' + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'auto_increment', + 'text' => 'AUTO_INCREMENT' + ); + $this->properties['options'][] = array( + 'type' => 'end_subgroup' + ); + /* end CREATE TABLE statements */ + + $this->properties['options'][] = array( + 'type' => 'end_subgroup' + ); + /* end SQL statements */ + + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'backquotes', + 'text' => __( + 'Enclose table and column names with backquotes ' + . '(Protects column and table names formed with' + . ' special characters or keywords)' + ) + ); + + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + /* end Structure options */ + + /* begin Data options */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'data', + 'text' => __('Data dump options'), + 'force' => 'structure' + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'truncate', + 'text' => __('Truncate table before insert') + ); + /* begin SQL statements */ + $this->properties['options'][] = array( + 'type' => 'begin_subgroup', + 'subgroup_header' => array( + 'type' => 'message_only', + 'text' => __('Instead of INSERT statements, use:') + ) + ); + // Not supported in Drizzle + if (! PMA_DRIZZLE) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'delayed', + 'text' => __('INSERT DELAYED statements'), + 'doc' => array( + 'manual_MySQL_Database_Administration', + 'insert_delayed' + ) + ); + } + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'ignore', + 'text' => __('INSERT IGNORE statements'), + 'doc' => array( + 'manual_MySQL_Database_Administration', + 'insert' + ) + ); + $this->properties['options'][] = array( + 'type' => 'end_subgroup' + ); + /* end SQL statements */ + + /* Function to use when dumping data */ + $this->properties['options'][] = array( + 'type' => 'select', + 'name' => 'type', + 'text' => __('Function to use when dumping data:'), + 'values' => array( + 'INSERT' => 'INSERT', + 'UPDATE' => 'UPDATE', + 'REPLACE' => 'REPLACE' + ) + ); + + /* Syntax to use when inserting data */ + $this->properties['options'][] = array( + 'type' => 'begin_subgroup', + 'subgroup_header' => array( + 'type' => 'message_only', + 'text' => __('Syntax to use when inserting data:') + ) + ); + $this->properties['options'][] = array( + 'type' => 'radio', + 'name' => 'insert_syntax', + 'values' => array( + 'complete' => __( + 'include column names in every INSERT statement' + . '
      Example: INSERT INTO' + . ' tbl_name (col_A,col_B,col_C) VALUES (1,2,3)' + ), + 'extended' => __( + 'insert multiple rows in every INSERT statement' + . '
      Example: INSERT INTO' + . ' tbl_name VALUES (1,2,3), (4,5,6), (7,8,9)' + ), + 'both' => __( + 'both of the above
      Example:' + . ' INSERT INTO tbl_name (col_A,col_B) VALUES (1,2,3),' + . ' (4,5,6), (7,8,9)' + ), + 'none' => __( + 'neither of the above
      Example:' + . ' INSERT INTO tbl_name VALUES (1,2,3)' + ) + ) + ); + $this->properties['options'][] = array( + 'type' => 'end_subgroup' + ); + + /* Max length of query */ + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'max_query_size', + 'text' => __('Maximal length of created query') + ); + + /* Dump binary columns in hexadecimal */ + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'hex_for_blob', + 'text' => __( + 'Dump binary columns in hexadecimal notation' + . ' (for example, "abc" becomes 0x616263)' + ) + ); + + // Drizzle works only with UTC timezone + if (! PMA_DRIZZLE) { + /* Dump time in UTC */ + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'utc_time', + 'text' => __( + 'Dump TIMESTAMP columns in UTC (enables TIMESTAMP columns' + . ' to be dumped and reloaded between servers in different' + . ' time zones)' + ) + ); + } + + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + /* end Data options */ + } + } + + /** + * 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) + { + } + + /** + * Exports routines (procedures and functions) + * + * @param string $db Database + * + * @return bool Whether it succeeded + */ + public function exportRoutines($db) + { + $text = ''; + $delimiter = '$$'; + + $procedure_names = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE'); + $function_names = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION'); + + if ($procedure_names || $function_names) { + $text .= $crlf + . 'DELIMITER ' . $delimiter . $crlf; + } + + if ($procedure_names) { + $text .= + $this->exportComment() + . $this->exportComment(__('Procedures')) + . $this->exportComment(); + + foreach ($procedure_names as $procedure_name) { + if (! empty($GLOBALS['sql_drop_table'])) { + $text .= 'DROP PROCEDURE IF EXISTS ' + . PMA_backquote($procedure_name) + . $delimiter . $crlf; + } + $text .= PMA_DBI_get_definition($db, 'PROCEDURE', $procedure_name) + . $delimiter . $crlf . $crlf; + } + } + + if ($function_names) { + $text .= + $this->exportComment() + . $this->exportComment(__('Functions')) + . $this->exportComment(); + + foreach ($function_names as $function_name) { + if (! empty($GLOBALS['sql_drop_table'])) { + $text .= 'DROP FUNCTION IF EXISTS ' + . PMA_backquote($function_name) + . $delimiter . $crlf; + } + $text .= PMA_DBI_get_definition($db, 'FUNCTION', $function_name) + . $delimiter . $crlf . $crlf; + } + } + + if ($procedure_names || $function_names) { + $text .= 'DELIMITER ;' . $crlf; + } + + if (! empty($text)) { + return PMA_exportOutputHandler($text); + } else { + return false; + } + } + + /** + * Possibly outputs comment + * + * @param string $text Text of comment + * + * @return string The formatted comment + */ + private function exportComment($text = '') + { + if (isset($GLOBALS['sql_include_comments']) + && $GLOBALS['sql_include_comments'] + ) { + // see http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html + return '--' . (empty($text) ? '' : ' ') . $text . $GLOBALS['crlf']; + } else { + return ''; + } + } + + /** + * Possibly outputs CRLF + * + * @return string $crlf or nothing + */ + private function possibleCRLF() + { + if (isset($GLOBALS['sql_include_comments']) + && $GLOBALS['sql_include_comments'] + ) { + return $GLOBALS['crlf']; + } else { + return ''; + } + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + * + * @access public + */ + public function exportFooter() + { + $crlf = $this->getCrlf(); + $mysql_charset_map = $this->getMysql_charset_map(); + + $foot = ''; + + if (isset($GLOBALS['sql_disable_fk'])) { + $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf; + } + + if (isset($GLOBALS['sql_use_transaction'])) { + $foot .= 'COMMIT;' . $crlf; + } + + // restore connection settings + $charset_of_file = isset($GLOBALS['charset_of_file']) + ? $GLOBALS['charset_of_file'] : ''; + if (! empty($GLOBALS['asfile']) + && isset($mysql_charset_map[$charset_of_file]) + && ! PMA_DRIZZLE + ) { + $foot .= $crlf + . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' + . $crlf + . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' + . $crlf + . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' + . $crlf; + } + + /* Restore timezone */ + if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) { + PMA_DBI_query('SET time_zone = "' . $GLOBALS['old_tz'] . '"'); + } + + return PMA_exportOutputHandler($foot); + } + + /** + * Outputs export header. It is the first method to be called, so all + * the required variables are initialized here. + * + * @return bool Whether it succeeded + * + * @access public + */ + public function exportHeader() + { + // initialize the general export variables + $this->initExportCommonVariables(); + + // initialize the specific export sql variables + $this->initLocalVariables(); + + $crlf = $this->getCrlf(); + $cfg = $this->getCfg(); + $mysql_charset_map = $this->getMysql_charset_map(); + + if (isset($GLOBALS['sql_compatibility'])) { + $tmp_compat = $GLOBALS['sql_compatibility']; + if ($tmp_compat == 'NONE') { + $tmp_compat = ''; + } + PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"'); + unset($tmp_compat); + } + $head = $this->exportComment('phpMyAdmin SQL Dump') + . $this->exportComment('version ' . PMA_VERSION) + . $this->exportComment('http://www.phpmyadmin.net') + . $this->exportComment(); + $host_string = __('Host') . ': ' . $cfg['Server']['host']; + if (! empty($cfg['Server']['port'])) { + $host_string .= ':' . $cfg['Server']['port']; + } + $head .= $this->exportComment($host_string); + $head .= + $this->exportComment( + __('Generation Time') . ': ' . PMA_localisedDate() + ) + . $this->exportComment(__('Server version') . ': ' . PMA_MYSQL_STR_VERSION) + . $this->exportComment(__('PHP Version') . ': ' . phpversion()) + . $this->possibleCRLF(); + + if (isset($GLOBALS['sql_header_comment']) + && ! empty($GLOBALS['sql_header_comment']) + ) { + // '\n' is not a newline (like "\n" would be), it's the characters + // backslash and n, as explained on the export interface + $lines = explode('\n', $GLOBALS['sql_header_comment']); + $head .= $this->exportComment(); + foreach ($lines as $one_line) { + $head .= $this->exportComment($one_line); + } + $head .= $this->exportComment(); + } + + if (isset($GLOBALS['sql_disable_fk'])) { + $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf; + } + + // We want exported AUTO_INCREMENT columns to have still same value, + // do this only for recent MySQL exports + if ((! isset($GLOBALS['sql_compatibility']) + || $GLOBALS['sql_compatibility'] == 'NONE') + && ! PMA_DRIZZLE + ) { + $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $crlf; + } + + if (isset($GLOBALS['sql_use_transaction'])) { + $head .= 'SET AUTOCOMMIT = 0;' . $crlf + . 'START TRANSACTION;' . $crlf; + } + + /* Change timezone if we should export timestamps in UTC */ + if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) { + $head .= 'SET time_zone = "+00:00";' . $crlf; + $GLOBALS['old_tz'] = PMA_DBI_fetch_value('SELECT @@session.time_zone'); + PMA_DBI_query('SET time_zone = "+00:00"'); + } + + $head .= $this->possibleCRLF(); + + if (! empty($GLOBALS['asfile']) && ! PMA_DRIZZLE) { + // we are saving as file, therefore we provide charset information + // so that a utility like the mysql client can interpret + // the file correctly + if (isset($GLOBALS['charset_of_file']) + && isset($mysql_charset_map[$GLOBALS['charset_of_file']]) + ) { + // we got a charset from the export dialog + $set_names = $mysql_charset_map[$GLOBALS['charset_of_file']]; + } else { + // by default we use the connection charset + $set_names = $mysql_charset_map['utf-8']; + } + $head .= $crlf + . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=' + . '@@CHARACTER_SET_CLIENT */;' . $crlf + . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=' + . '@@CHARACTER_SET_RESULTS */;' . $crlf + . '/*!40101 SET @OLD_COLLATION_CONNECTION=' + . '@@COLLATION_CONNECTION */;'. $crlf + . '/*!40101 SET NAMES ' . $set_names . ' */;' . $crlf . $crlf; + } + + return PMA_exportOutputHandler($head); + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + $crlf = $this->getCrlf(); + if (isset($GLOBALS['sql_drop_database'])) { + if (! PMA_exportOutputHandler( + 'DROP DATABASE ' + . (isset($GLOBALS['sql_backquotes']) + ? PMA_backquote($db) : $db) + . ';' . $crlf + )) { + return false; + } + } + $create_query = 'CREATE DATABASE ' + . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db); + $collation = PMA_getDbCollation($db); + if (PMA_DRIZZLE) { + $create_query .= ' COLLATE ' . $collation; + } else { + if (strpos($collation, '_')) { + $create_query .= ' DEFAULT CHARACTER SET ' + . substr($collation, 0, strpos($collation, '_')) + . ' COLLATE ' . $collation; + } else { + $create_query .= ' DEFAULT CHARACTER SET ' . $collation; + } + } + $create_query .= ';' . $crlf; + if (! PMA_exportOutputHandler($create_query)) { + return false; + } + if (isset($GLOBALS['sql_backquotes']) + && ((isset($GLOBALS['sql_compatibility']) + && $GLOBALS['sql_compatibility'] == 'NONE') + || PMA_DRIZZLE) + ) { + $result = PMA_exportOutputHandler( + 'USE ' . PMA_backquote($db) . ';' . $crlf + ); + } else { + $result = PMA_exportOutputHandler('USE ' . $db . ';' . $crlf); + } + + return $result; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader($db) + { + $head = $this->exportComment() + . $this->exportComment( + __('Database') . ': ' + . (isset($GLOBALS['sql_backquotes']) + ? PMA_backquote($db) : '\'' . $db . '\'') + ) + . $this->exportComment(); + return PMA_exportOutputHandler($head); + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter($db) + { + $crlf = $this->getCrlf(); + + $result = true; + if (isset($GLOBALS['sql_constraints'])) { + $result = PMA_exportOutputHandler($GLOBALS['sql_constraints']); + unset($GLOBALS['sql_constraints']); + } + + if (($GLOBALS['sql_structure_or_data'] == 'structure' + || $GLOBALS['sql_structure_or_data'] == 'structure_and_data') + && isset($GLOBALS['sql_procedure_function']) + ) { + $text = ''; + $delimiter = '$$'; + + if (PMA_MYSQL_INT_VERSION > 50100) { + $event_names = PMA_DBI_fetch_result( + 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE' + . ' EVENT_SCHEMA= \'' . PMA_sqlAddSlashes($db, true) . '\';' + ); + } else { + $event_names = array(); + } + + if ($event_names) { + $text .= $crlf + . 'DELIMITER ' . $delimiter . $crlf; + + $text .= + $this->exportComment() + . $this->exportComment(__('Events')) + . $this->exportComment(); + + foreach ($event_names as $event_name) { + if (! empty($GLOBALS['sql_drop_table'])) { + $text .= 'DROP EVENT ' . PMA_backquote($event_name) + . $delimiter . $crlf; + } + $text .= PMA_DBI_get_definition($db, 'EVENT', $event_name) + . $delimiter . $crlf . $crlf; + } + + $text .= 'DELIMITER ;' . $crlf; + } + + if (! empty($text)) { + $result = PMA_exportOutputHandler($text); + } + } + return $result; + } + + /** + * Returns a stand-in CREATE definition to resolve view dependencies + * + * @param string $db the database name + * @param string $view the view name + * @param string $crlf the end of line sequence + * + * @return string resulting definition + */ + public function getTableDefStandIn($db, $view, $crlf) + { + $create_query = ''; + if (! empty($GLOBALS['sql_drop_table'])) { + $create_query .= 'DROP VIEW IF EXISTS ' . PMA_backquote($view) + . ';' . $crlf; + } + + $create_query .= 'CREATE TABLE '; + + if (isset($GLOBALS['sql_if_not_exists']) + && $GLOBALS['sql_if_not_exists'] + ) { + $create_query .= 'IF NOT EXISTS '; + } + $create_query .= PMA_backquote($view) . ' (' . $crlf; + $tmp = array(); + $columns = PMA_DBI_get_columns_full($db, $view); + foreach ($columns as $column_name => $definition) { + $tmp[] = PMA_backquote($column_name) . ' ' . $definition['Type'] . $crlf; + } + $create_query .= implode(',', $tmp) . ');'; + return($create_query); + } + + /** + * Returns $table's CREATE definition + * + * @param string $db the database name + * @param string $table the table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param bool $show_dates whether to include creation/update/check dates + * @param bool $add_semicolon whether to add semicolon and end-of-line at + * the end + * @param bool $view whether we're handling a view + * + * @return string resulting schema + */ + public function getTableDef( + $db, + $table, + $crlf, + $error_url, + $show_dates = false, + $add_semicolon = true, + $view = false + ) { + $sql_drop_table = $this->getSql_drop_table(); + $sql_backquotes = $this->getSql_backquotes(); + $sql_constraints = $this->getSql_constraints(); + $sql_constraints_query = $this->getSql_constraints_query(); + $sql_drop_foreign_keys = $this->getSql_drop_foreign_keys(); + + $schema_create = ''; + $auto_increment = ''; + $new_crlf = $crlf; + + // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli + $result = PMA_DBI_query( + 'SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' + . PMA_sqlAddSlashes($table, true) . '\'', + null, + PMA_DBI_QUERY_STORE + ); + if ($result != false) { + if (PMA_DBI_num_rows($result) > 0) { + $tmpres = PMA_DBI_fetch_assoc($result); + if (PMA_DRIZZLE && $show_dates) { + // Drizzle doesn't give Create_time and Update_time in + // SHOW TABLE STATUS, add it + $sql ="SELECT + TABLE_CREATION_TIME AS Create_time, + TABLE_UPDATE_TIME AS Update_time + FROM data_dictionary.TABLES + WHERE TABLE_SCHEMA = '" . PMA_sqlAddSlashes($db) . "' + AND TABLE_NAME = '" . PMA_sqlAddSlashes($table) . "'"; + $tmpres = array_merge(PMA_DBI_fetch_single_row($sql), $tmpres); + } + // Here we optionally add the AUTO_INCREMENT next value, + // but starting with MySQL 5.0.24, the clause is already included + // in SHOW CREATE TABLE so we'll remove it below + // It's required for Drizzle because SHOW CREATE TABLE uses + // the value from table's creation time + if (isset($GLOBALS['sql_auto_increment']) + && ! empty($tmpres['Auto_increment']) + ) { + $auto_increment .= ' AUTO_INCREMENT=' + . $tmpres['Auto_increment'] . ' '; + } + + if ($show_dates + && isset($tmpres['Create_time']) + && ! empty($tmpres['Create_time']) + ) { + $schema_create .= $this->exportComment( + __('Creation') . ': ' + . PMA_localisedDate(strtotime($tmpres['Create_time'])) + ); + $new_crlf = $this->exportComment() . $crlf; + } + + if ($show_dates + && isset($tmpres['Update_time']) + && ! empty($tmpres['Update_time']) + ) { + $schema_create .= $this->exportComment( + __('Last update') . ': ' + . PMA_localisedDate(strtotime($tmpres['Update_time'])) + ); + $new_crlf = $this->exportComment() . $crlf; + } + + if ($show_dates + && isset($tmpres['Check_time']) + && ! empty($tmpres['Check_time']) + ) { + $schema_create .= $this->exportComment( + __('Last check') . ': ' + . PMA_localisedDate(strtotime($tmpres['Check_time'])) + ); + $new_crlf = $this->exportComment() . $crlf; + } + } + PMA_DBI_free_result($result); + } + + $schema_create .= $new_crlf; + + // no need to generate a DROP VIEW here, it was done earlier + if (! empty($sql_drop_table) && ! PMA_Table::isView($db, $table)) { + $schema_create .= 'DROP TABLE IF EXISTS ' + . PMA_backquote($table, $sql_backquotes) . ';' . $crlf; + } + + // Complete table dump, + // Whether to quote table and column names or not + // Drizzle always quotes names + if (! PMA_DRIZZLE) { + if ($sql_backquotes) { + PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1'); + } else { + PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0'); + } + } + + // I don't see the reason why this unbuffered query could cause problems, + // because SHOW CREATE TABLE returns only one row, and we free the + // results below. Nonetheless, we got 2 user reports about this + // (see bug 1562533) so I removed the unbuffered mode. + // $result = PMA_DBI_query('SHOW CREATE TABLE ' . PMA_backquote($db) + // . '.' . PMA_backquote($table), null, PMA_DBI_QUERY_UNBUFFERED); + // + // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not + // produce a displayable result for the default value of a BIT + // column, nor does the mysqldump command. See MySQL bug 35796 + $result = PMA_DBI_try_query( + 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table) + ); + // an error can happen, for example the table is crashed + $tmp_error = PMA_DBI_getError(); + if ($tmp_error) { + return $this->exportComment(__('in use') . '(' . $tmp_error . ')'); + } + + if ($result != false && ($row = PMA_DBI_fetch_row($result))) { + $create_query = $row[1]; + unset($row); + + // Convert end of line chars to one that we want (note that MySQL + // doesn't return query it will accept in all cases) + if (strpos($create_query, "(\r\n ")) { + $create_query = str_replace("\r\n", $crlf, $create_query); + } elseif (strpos($create_query, "(\n ")) { + $create_query = str_replace("\n", $crlf, $create_query); + } elseif (strpos($create_query, "(\r ")) { + $create_query = str_replace("\r", $crlf, $create_query); + } + + /* + * Drop database name from VIEW creation. + * + * This is a bit tricky, but we need to issue SHOW CREATE TABLE with + * database name, but we don't want name to show up in CREATE VIEW + * statement. + */ + if ($view) { + $create_query = preg_replace( + '/' . PMA_backquote($db) . '\./', + '', + $create_query + ); + } + + // Should we use IF NOT EXISTS? + if (isset($GLOBALS['sql_if_not_exists'])) { + $create_query = preg_replace( + '/^CREATE TABLE/', + 'CREATE TABLE IF NOT EXISTS', + $create_query + ); + } + + // Drizzle (checked on 2011.03.13) returns ROW_FORMAT surrounded + // with quotes, which is not accepted by parser + if (PMA_DRIZZLE) { + $create_query = preg_replace( + '/ROW_FORMAT=\'(\S+)\'/', + 'ROW_FORMAT=$1', + $create_query + ); + } + + // are there any constraints to cut out? + if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) { + + // Split the query into lines, so we can easily handle it. + // We know lines are separated by $crlf (done few lines above). + $sql_lines = explode($crlf, $create_query); + $sql_count = count($sql_lines); + + // lets find first line with constraints + for ($i = 0; $i < $sql_count; $i++) { + if (preg_match( + '@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@', + $sql_lines[$i] + )) { + break; + } + } + + // If we really found a constraint + if ($i != $sql_count) { + + // remove, from the end of create statement + $sql_lines[$i - 1] = preg_replace( + '@,$@', + '', + $sql_lines[$i - 1] + ); + + // prepare variable for constraints + if (! isset($sql_constraints)) { + if (isset($GLOBALS['no_constraints_comments'])) { + $sql_constraints = ''; + } else { + $sql_constraints = $crlf + . $this->exportComment() + . $this->exportComment( + __('Constraints for dumped tables') + ) + . $this->exportComment(); + } + } + + // comments for current table + if (! isset($GLOBALS['no_constraints_comments'])) { + $sql_constraints .= $crlf + . $this->exportComment() + . $this->exportComment( + __('Constraints for table') + . ' ' + . PMA_backquote($table) + ) + . $this->exportComment(); + } + + // let's do the work + $sql_constraints_query .= 'ALTER TABLE ' + . PMA_backquote($table) . $crlf; + $sql_constraints .= 'ALTER TABLE ' + . PMA_backquote($table) . $crlf; + $sql_drop_foreign_keys .= 'ALTER TABLE ' + . PMA_backquote($db) . '.' + . PMA_backquote($table) . $crlf; + + $first = true; + for ($j = $i; $j < $sql_count; $j++) { + if (preg_match( + '@CONSTRAINT|FOREIGN[\s]+KEY@', + $sql_lines[$j] + )) { + if (! $first) { + $sql_constraints .= $crlf; + } + if (strpos($sql_lines[$j], 'CONSTRAINT') === false) { + $tmp_str = preg_replace( + '/(FOREIGN[\s]+KEY)/', + 'ADD \1', + $sql_lines[$j] + ); + $sql_constraints_query .= $tmp_str; + $sql_constraints .= $tmp_str; + } else { + $tmp_str = preg_replace( + '/(CONSTRAINT)/', + 'ADD \1', + $sql_lines[$j] + ); + $sql_constraints_query .= $tmp_str; + $sql_constraints .= $tmp_str; + preg_match( + '/(CONSTRAINT)([\s])([\S]*)([\s])/', + $sql_lines[$j], + $matches + ); + if (! $first) { + $sql_drop_foreign_keys .= ', '; + } + $sql_drop_foreign_keys .= 'DROP FOREIGN KEY ' + . $matches[3]; + } + $first = false; + } else { + break; + } + } + $sql_constraints .= ';' . $crlf; + $sql_constraints_query .= ';'; + + $create_query = implode( + $crlf, + array_slice($sql_lines, 0, $i) + ) + . $crlf + . implode( + $crlf, + array_slice($sql_lines, $j, $sql_count - 1) + ); + unset($sql_lines); + } + } + $schema_create .= $create_query; + } + + // remove a possible "AUTO_INCREMENT = value" clause + // that could be there starting with MySQL 5.0.24 + // in Drizzle it's useless as it contains the value given at table + // creation time + $schema_create = preg_replace( + '/AUTO_INCREMENT\s*=\s*([0-9])+/', + '', + $schema_create + ); + + $schema_create .= $auto_increment; + + PMA_DBI_free_result($result); + return $schema_create . ($add_semicolon ? ';' . $crlf : ''); + } // end of the 'getTableDef()' function + + /** + * Returns $table's comments, relations etc. + * + * @param string $db database name + * @param string $table table name + * @param string $crlf end of line sequence + * @param bool $do_relation whether to include relation comments + * @param bool $do_mime whether to include mime comments + * + * @return string resulting comments + */ + private function getTableComments( + $db, + $table, + $crlf, + $do_relation = false, + $do_mime = false + ) { + $cfgRelation = $this->getCfgRelation(); + $sql_backquotes = $this->getSql_backquotes(); + + $schema_create = ''; + + // Check if we can use Relations + if ($do_relation && ! empty($cfgRelation['relation'])) { + // Find which tables are related with the current one and write it in + // an array + $res_rel = PMA_getForeigners($db, $table); + + if ($res_rel && count($res_rel) > 0) { + $have_rel = true; + } else { + $have_rel = false; + } + } else { + $have_rel = false; + } // end if + + if ($do_mime && $cfgRelation['mimework']) { + if (! ($mime_map = PMA_getMIME($db, $table, true))) { + unset($mime_map); + } + } + + if (isset($mime_map) && count($mime_map) > 0) { + $schema_create .= $this->possibleCRLF() + . $this->exportComment() + . $this->exportComment( + __('MIME TYPES FOR TABLE'). ' ' + . PMA_backquote($table, $sql_backquotes) . ':' + ); + @reset($mime_map); + foreach ($mime_map AS $mime_field => $mime) { + $schema_create .= + $this->exportComment( + ' ' + . PMA_backquote($mime_field, $sql_backquotes) + ) + . $this->exportComment( + ' ' + . PMA_backquote($mime['mimetype'], $sql_backquotes) + ); + } + $schema_create .= $this->exportComment(); + } + + if ($have_rel) { + $schema_create .= $this->possibleCRLF() + . $this->exportComment() + . $this->exportComment( + __('RELATIONS FOR TABLE') . ' ' + . PMA_backquote($table, $sql_backquotes) + . ':' + ); + foreach ($res_rel AS $rel_field => $rel) { + $schema_create .= + $this->exportComment( + ' ' + . PMA_backquote($rel_field, $sql_backquotes) + ) + . $this->exportComment( + ' ' + . PMA_backquote($rel['foreign_table'], $sql_backquotes) + . ' -> ' + . PMA_backquote($rel['foreign_field'], $sql_backquotes) + ); + } + $schema_create .= $this->exportComment(); + } + + return $schema_create; + + } // end of the 'getTableComments()' function + + /** + * Outputs table's structure + * + * @param string $db database name + * @param string $table table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param string $export_mode 'create_table','triggers','create_view', + * 'stand_in' + * @param string $export_type 'server', 'database', 'table' + * @param bool $relation whether to include relation comments + * @param bool $comments whether to include the pmadb-style column comments + * as comments in the structure; this is deprecated + * but the parameter is left here because export.php + * calls exportStructure() also for other export + * types which use this parameter + * @param bool $mime whether to include mime comments + * @param bool $dates whether to include creation/update/check dates + * + * @return bool Whether it succeeded + */ + public function exportStructure( + $db, + $table, + $crlf, + $error_url, + $export_mode, + $export_type, + $relation = false, + $comments = false, + $mime = false, + $dates = false + ) { + $formatted_table_name = (isset($GLOBALS['sql_backquotes'])) + ? PMA_backquote($table) + : '\'' . $table . '\''; + $dump = $this->possibleCRLF() + . $this->exportComment(str_repeat('-', 56)) + . $this->possibleCRLF() + . $this->exportComment(); + + switch($export_mode) { + case 'create_table': + $dump .= $this->exportComment( + __('Table structure for table') . ' '. $formatted_table_name + ); + $dump .= $this->exportComment(); + $dump .= getTableDef($db, $table, $crlf, $error_url, $dates); + $dump .= $this->getTableComments($db, $table, $crlf, $relation, $mime); + break; + case 'triggers': + $dump = ''; + $triggers = PMA_DBI_get_triggers($db, $table); + if ($triggers) { + $dump .= $this->possibleCRLF() + . $this->exportComment() + . $this->exportComment( + __('Triggers') . ' ' . $formatted_table_name + ) + . $this->exportComment(); + $delimiter = '//'; + foreach ($triggers as $trigger) { + $dump .= $trigger['drop'] . ';' . $crlf; + $dump .= 'DELIMITER ' . $delimiter . $crlf; + $dump .= $trigger['create']; + $dump .= 'DELIMITER ;' . $crlf; + } + } + break; + case 'create_view': + $dump .= + $this->exportComment( + __('Structure for view') + . ' ' + . $formatted_table_name + ) + . $this->exportComment(); + // delete the stand-in table previously created (if any) + if ($export_type != 'table') { + $dump .= 'DROP TABLE IF EXISTS ' + . PMA_backquote($table) . ';' . $crlf; + } + $dump .= getTableDef( + $db, $table, $crlf, $error_url, $dates, true, true + ); + break; + case 'stand_in': + $dump .= + $this->exportComment( + __('Stand-in structure for view') . ' ' . $formatted_table_name + ) + . $this->exportComment(); + // export a stand-in definition to resolve view dependencies + $dump .= getTableDefStandIn($db, $table, $crlf); + } // end switch + + // this one is built by getTableDef() to use in table copy/move + // but not in the case of export + unset($GLOBALS['sql_constraints_query']); + + return PMA_exportOutputHandler($dump); + } + + /** + * Outputs the content of a table in SQL format + * + * @param string $db database name + * @param string $table table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param string $sql_query SQL query for obtaining data + * + * @return bool Whether it succeeded + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $sql_backquotes = $this->getSql_backquotes(); + $current_row = $this->getCurrent_row(); + + $formatted_table_name = (isset($GLOBALS['sql_backquotes'])) + ? PMA_backquote($table) + : '\'' . $table . '\''; + + // Do not export data for a VIEW + // (For a VIEW, this is called only when exporting a single VIEW) + if (PMA_Table::isView($db, $table)) { + $head = $this->possibleCRLF() + . $this->exportComment() + . $this->exportComment('VIEW ' . ' ' . $formatted_table_name) + . $this->exportComment(__('Data') . ': ' . __('None')) + . $this->exportComment() + . $this->possibleCRLF(); + + if (! PMA_exportOutputHandler($head)) { + return false; + } + return true; + } + + // analyze the query to get the true column names, not the aliases + // (this fixes an undefined index, also if Complete inserts + // are used, we did not get the true column name in case of aliases) + $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query)); + + $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + // a possible error: the table has crashed + $tmp_error = PMA_DBI_getError(); + if ($tmp_error) { + return PMA_exportOutputHandler( + $this->exportComment( + __('Error reading data:') . ' (' . $tmp_error . ')' + ) + ); + } + + if ($result != false) { + $fields_cnt = PMA_DBI_num_fields($result); + + // Get field information + $fields_meta = PMA_DBI_get_fields_meta($result); + $field_flags = array(); + for ($j = 0; $j < $fields_cnt; $j++) { + $field_flags[$j] = PMA_DBI_field_flags($result, $j); + } + + for ($j = 0; $j < $fields_cnt; $j++) { + if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) { + $field_set[$j] = PMA_backquote( + $analyzed_sql[0]['select_expr'][$j]['column'], + $sql_backquotes + ); + } else { + $field_set[$j] = PMA_backquote( + $fields_meta[$j]->name, + $sql_backquotes + ); + } + } + + if (isset($GLOBALS['sql_type']) + && $GLOBALS['sql_type'] == 'UPDATE' + ) { + // update + $schema_insert = 'UPDATE '; + if (isset($GLOBALS['sql_ignore'])) { + $schema_insert .= 'IGNORE '; + } + // avoid EOL blank + $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET'; + } else { + // insert or replace + if (isset($GLOBALS['sql_type']) + && $GLOBALS['sql_type'] == 'REPLACE' + ) { + $sql_command = 'REPLACE'; + } else { + $sql_command = 'INSERT'; + } + + // delayed inserts? + if (isset($GLOBALS['sql_delayed'])) { + $insert_delayed = ' DELAYED'; + } else { + $insert_delayed = ''; + } + + // insert ignore? + if (isset($GLOBALS['sql_type']) + && $GLOBALS['sql_type'] == 'INSERT' + && isset($GLOBALS['sql_ignore']) + ) { + $insert_delayed .= ' IGNORE'; + } + //truncate table before insert + if (isset($GLOBALS['sql_truncate']) + && $GLOBALS['sql_truncate'] + && $sql_command == 'INSERT' + ) { + $truncate = 'TRUNCATE TABLE ' + . PMA_backquote($table, $sql_backquotes) . ";"; + $truncatehead = $this->possibleCRLF() + . $this->exportComment() + . $this->exportComment( + __('Truncate table before insert') . ' ' + . $formatted_table_name + ) + . $this->exportComment() + . $crlf; + PMA_exportOutputHandler($truncatehead); + PMA_exportOutputHandler($truncate); + } else { + $truncate = ''; + } + // scheme for inserting fields + if ($GLOBALS['sql_insert_syntax'] == 'complete' + || $GLOBALS['sql_insert_syntax'] == 'both' + ) { + $fields = implode(', ', $field_set); + $schema_insert = $sql_command . $insert_delayed .' INTO ' + . PMA_backquote($table, $sql_backquotes) + // avoid EOL blank + . ' (' . $fields . ') VALUES'; + } else { + $schema_insert = $sql_command . $insert_delayed .' INTO ' + . PMA_backquote($table, $sql_backquotes) + . ' VALUES'; + } + } + + //\x08\\x09, not required + $search = array("\x00", "\x0a", "\x0d", "\x1a"); + $replace = array('\0', '\n', '\r', '\Z'); + $current_row = 0; + $query_size = 0; + if (($GLOBALS['sql_insert_syntax'] == 'extended' + || $GLOBALS['sql_insert_syntax'] == 'both') + && (! isset($GLOBALS['sql_type']) + || $GLOBALS['sql_type'] != 'UPDATE') + ) { + $separator = ','; + $schema_insert .= $crlf; + } else { + $separator = ';'; + } + + while ($row = PMA_DBI_fetch_row($result)) { + if ($current_row == 0) { + $head = $this->possibleCRLF() + . $this->exportComment() + . $this->exportComment( + __('Dumping data for table') . ' ' + . $formatted_table_name + ) + . $this->exportComment() + . $crlf; + if (! PMA_exportOutputHandler($head)) { + return false; + } + } + $current_row++; + for ($j = 0; $j < $fields_cnt; $j++) { + // NULL + if (! isset($row[$j]) || is_null($row[$j])) { + $values[] = 'NULL'; + } elseif ($fields_meta[$j]->numeric + && $fields_meta[$j]->type != 'timestamp' + && ! $fields_meta[$j]->blob + ) { + // a number + // timestamp is numeric on some MySQL 4.1, BLOBs are + // sometimes numeric + $values[] = $row[$j]; + } elseif (stristr($field_flags[$j], 'BINARY') + && $fields_meta[$j]->blob + && isset($GLOBALS['sql_hex_for_blob']) + ) { + // a true BLOB + // - mysqldump only generates hex data when the --hex-blob + // option is used, for fields having the binary attribute + // no hex is generated + // - a TEXT field returns type blob but a real blob + // returns also the 'binary' flag + + // empty blobs need to be different, but '0' is also empty + // :-( + if (empty($row[$j]) && $row[$j] != '0') { + $values[] = '\'\''; + } else { + $values[] = '0x' . bin2hex($row[$j]); + } + } elseif ($fields_meta[$j]->type == 'bit') { + // detection of 'bit' works only on mysqli extension + $values[] = "b'" . PMA_sqlAddSlashes( + PMA_printable_bit_value( + $row[$j], $fields_meta[$j]->length + ) + ) + . "'"; + } else { + // something else -> treat as a string + $values[] = '\'' + . str_replace( + $search, $replace, PMA_sqlAddSlashes($row[$j]) + ) + . '\''; + } // end if + } // end for + + // should we make update? + if (isset($GLOBALS['sql_type']) + && $GLOBALS['sql_type'] == 'UPDATE' + ) { + + $insert_line = $schema_insert; + for ($i = 0; $i < $fields_cnt; $i++) { + if (0 == $i) { + $insert_line .= ' '; + } + if ($i > 0) { + // avoid EOL blank + $insert_line .= ','; + } + $insert_line .= $field_set[$i] . ' = ' . $values[$i]; + } + + list($tmp_unique_condition, $tmp_clause_is_unique) + = PMA_getUniqueCondition( + $result, + $fields_cnt, + $fields_meta, + $row + ); + $insert_line .= ' WHERE ' . $tmp_unique_condition; + unset($tmp_unique_condition, $tmp_clause_is_unique); + + } else { + + // Extended inserts case + if ($GLOBALS['sql_insert_syntax'] == 'extended' + || $GLOBALS['sql_insert_syntax'] == 'both' + ) { + if ($current_row == 1) { + $insert_line = $schema_insert . '(' + . implode(', ', $values) . ')'; + } else { + $insert_line = '(' . implode(', ', $values) . ')'; + $sql_max_size = $GLOBALS['sql_max_query_size']; + if (isset($sql_max_size) + && $sql_max_size > 0 + && $query_size + strlen($insert_line) > $sql_max_size + ) { + if (! PMA_exportOutputHandler(';' . $crlf)) { + return false; + } + $query_size = 0; + $current_row = 1; + $insert_line = $schema_insert . $insert_line; + } + } + $query_size += strlen($insert_line); + // Other inserts case + } else { + $insert_line = $schema_insert + . '(' + . implode(', ', $values) + . ')'; + } + } + unset($values); + + if (! PMA_exportOutputHandler( + ($current_row == 1 ? '' : $separator . $crlf) + . $insert_line + )) { + return false; + } + + } // end while + if ($current_row > 0) { + if (! PMA_exportOutputHandler(';' . $crlf)) { + return false; + } + } + } // end if ($result != false) + PMA_DBI_free_result($result); + + return true; + } // end of the 'exportData()' function + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + private function getPlugin_param() + { + return $this->plugin_param; + } + + private function setPlugin_param($plugin_param) + { + $this->plugin_param = $plugin_param; + } + + private function getMysql_charset_map() + { + return $this->mysql_charset_map; + } + + private function setMysql_charset_map($mysql_charset_map) + { + $this->mysql_charset_map = $mysql_charset_map; + } + + private function getSql_drop_table() + { + return $this->sql_drop_table; + } + + private function setSql_drop_table($sql_drop_table) + { + $this->sql_drop_table = $sql_drop_table; + } + + private function getSql_backquotes() + { + return $this->sql_backquotes; + } + + private function setSql_backquotes($sql_backquotes) + { + $this->sql_backquotes = $sql_backquotes; + } + + private function getSql_constraints() + { + return $this->sql_constraints; + } + + private function setSql_constraints($sql_constraints) + { + $this->sql_constraints = $sql_constraints; + } + + private function getSql_constraints_query() + { + return $this->sql_constraints_query; + } + + private function setSql_constraints_query($sql_constraints_query) + { + $this->sql_constraints_query = $sql_constraints_query; + } + + private function getSql_drop_foreign_keys() + { + return $this->sql_drop_foreign_keys; + } + + private function setSql_drop_foreign_keys($sql_drop_foreign_keys) + { + $this->sql_drop_foreign_keys = $sql_drop_foreign_keys; + } + + private function getCfgRelation() + { + return $this->cfgRelation; + } + + private function setCfgRelation($cfgRelation) + { + $this->cfgRelation = $cfgRelation; + } + + private function getCurrent_row() + { + return $this->current_row; + } + + private function setCurrent_row($current_row) + { + $this->current_row = $current_row; + } +} \ No newline at end of file diff --git a/libraries/plugins/import/ImportSQL.class.php b/libraries/plugins/import/ImportSQL.class.php new file mode 100644 index 0000000000..eb1b510af7 --- /dev/null +++ b/libraries/plugins/import/ImportSQL.class.php @@ -0,0 +1,392 @@ +setProperties(); + } + + /** + * Sets the import plugin properties. + * Called in the constructor. + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('SQL'), + 'extension' => 'sql', + 'options' => array(), + 'options_text' => __('Options'), + ); + + $compats = PMA_DBI_getCompatibilities(); + if (count($compats) > 0) { + $values = array(); + foreach ($compats as $val) { + $values[$val] = $val; + } + $this->properties['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'), + ); + } + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + */ + public function doImport() + { + // initialize the general import variables + $this->initImportCommonVariables(); + + $error = $this->getError(); + $timeout_passed = $this->getTimeout_passed(); + + $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(); + } +} \ No newline at end of file diff --git a/libraries/plugins/import/ImportXML.class.php b/libraries/plugins/import/ImportXML.class.php new file mode 100644 index 0000000000..677ef8ef1d --- /dev/null +++ b/libraries/plugins/import/ImportXML.class.php @@ -0,0 +1,458 @@ +setProperties(); + } + + /** + * Initialize the local variables that are used specific for import XML + * + * @global type $table + * @global type $tables + * + * @return void + */ + private function initLocalVariables() + { + global $table; + global $tables; + $this->setTable($table); + $this->setTables($tables); + } + + /** + * Sets the import plugin properties. + * Called in the constructor. + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('XML'), + 'extension' => 'xml', + 'mime_type' => 'text/xml', + 'options' => array(), + 'options_text' => __('Options') + ); + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + */ + public function doImport() + { + // initialize the general import variables + $this->initImportCommonVariables(); + + // initialize the specific import xml variables + $this->initLocalVariables(); + + $error = $this->getError(); + $timeout_passed = $this->getTimeout_passed(); + $db = $this->getDb(); + // this is used in other functions while doImport() is being run + global $finished; + + $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(); + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Gets the database name + * + * @return string + */ + public function getDb() + { + return $this->db; + } + + /** + * Sets the database name + * + * @param String $db database name + * + * @return void + */ + public function setDb($db) + { + $this->db = $db; + } + + private function getTable() + { + return $this->table; + } + + private function setTable($table) + { + $this->table = $table; + } + + private function getTables() + { + return $this->tables; + } + + private function setTables($tables) + { + $this->tables = $tables; + } +} \ No newline at end of file From 1e4b0cd0dd8df49bfc2c4ce96f6bd422d2482839 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Thu, 7 Jun 2012 14:57:14 +0300 Subject: [PATCH 03/55] oop: transformations backbone --- ...onApplicationOctetStreamDownload.class.php | 60 +++++++++++++++++ ...rmationApplicationOctetStreamHex.class.php | 58 ++++++++++++++++ .../TransformationImageJPEGInline.class.php | 57 ++++++++++++++++ .../TransformationImageJPEGLink.class.php | 56 ++++++++++++++++ .../TransformationImagePNGInline.class.php | 57 ++++++++++++++++ .../TransformationTextPlainAppend.class.php | 58 ++++++++++++++++ ...ransformationTextPlainDateFormat.class.php | 64 ++++++++++++++++++ .../TransformationTextPlainExternal.class.php | 67 +++++++++++++++++++ ...TransformationTextPlainFormatted.class.php | 58 ++++++++++++++++ ...TransformationTextPlainImageLink.class.php | 58 ++++++++++++++++ .../TransformationTextPlainLink.class.php | 58 ++++++++++++++++ ...ransformationTextPlainLongToIPv4.class.php | 57 ++++++++++++++++ .../TransformationTextPlainSQL.class.php | 56 ++++++++++++++++ ...TransformationTextPlainSubstring.class.php | 60 +++++++++++++++++ .../AppendTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../DateFormatTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../DownloadTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../ExternalTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../FormattedTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../HexTransformationsPlugin.class.php.php | 67 +++++++++++++++++++ .../ImageLinkTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../InlineTransformationsPlugin.class.php.php | 67 +++++++++++++++++++ .../LinkTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../LongToIPv4TransformationsPlugin.class.php | 67 +++++++++++++++++++ .../SQLTransformationsPlugin.class.php | 67 +++++++++++++++++++ .../SubstringTransformationsPlugin.class.php | 67 +++++++++++++++++++ 26 files changed, 1628 insertions(+) create mode 100644 libraries/plugins/transformations/TransformationApplicationOctetStreamDownload.class.php create mode 100644 libraries/plugins/transformations/TransformationApplicationOctetStreamHex.class.php create mode 100644 libraries/plugins/transformations/TransformationImageJPEGInline.class.php create mode 100644 libraries/plugins/transformations/TransformationImageJPEGLink.class.php create mode 100644 libraries/plugins/transformations/TransformationImagePNGInline.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainAppend.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainDateFormat.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainExternal.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainFormatted.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainImageLink.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainLink.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainLongToIPv4.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainSQL.class.php create mode 100644 libraries/plugins/transformations/TransformationTextPlainSubstring.class.php create mode 100644 libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php.php create mode 100644 libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php.php create mode 100644 libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php create mode 100644 libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php diff --git a/libraries/plugins/transformations/TransformationApplicationOctetStreamDownload.class.php b/libraries/plugins/transformations/TransformationApplicationOctetStreamDownload.class.php new file mode 100644 index 0000000000..369bc850b8 --- /dev/null +++ b/libraries/plugins/transformations/TransformationApplicationOctetStreamDownload.class.php @@ -0,0 +1,60 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationApplicationOctetStreamHex.class.php b/libraries/plugins/transformations/TransformationApplicationOctetStreamHex.class.php new file mode 100644 index 0000000000..89e5e3d06f --- /dev/null +++ b/libraries/plugins/transformations/TransformationApplicationOctetStreamHex.class.php @@ -0,0 +1,58 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationImageJPEGInline.class.php b/libraries/plugins/transformations/TransformationImageJPEGInline.class.php new file mode 100644 index 0000000000..1ea682980c --- /dev/null +++ b/libraries/plugins/transformations/TransformationImageJPEGInline.class.php @@ -0,0 +1,57 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationImageJPEGLink.class.php b/libraries/plugins/transformations/TransformationImageJPEGLink.class.php new file mode 100644 index 0000000000..4b62deb82e --- /dev/null +++ b/libraries/plugins/transformations/TransformationImageJPEGLink.class.php @@ -0,0 +1,56 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationImagePNGInline.class.php b/libraries/plugins/transformations/TransformationImagePNGInline.class.php new file mode 100644 index 0000000000..5a056ad179 --- /dev/null +++ b/libraries/plugins/transformations/TransformationImagePNGInline.class.php @@ -0,0 +1,57 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainAppend.class.php b/libraries/plugins/transformations/TransformationTextPlainAppend.class.php new file mode 100644 index 0000000000..3287dd0032 --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainAppend.class.php @@ -0,0 +1,58 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainDateFormat.class.php b/libraries/plugins/transformations/TransformationTextPlainDateFormat.class.php new file mode 100644 index 0000000000..6319fefbc6 --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainDateFormat.class.php @@ -0,0 +1,64 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainExternal.class.php b/libraries/plugins/transformations/TransformationTextPlainExternal.class.php new file mode 100644 index 0000000000..a1c5a5ffb6 --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainExternal.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainFormatted.class.php b/libraries/plugins/transformations/TransformationTextPlainFormatted.class.php new file mode 100644 index 0000000000..795a1fc597 --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainFormatted.class.php @@ -0,0 +1,58 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainImageLink.class.php b/libraries/plugins/transformations/TransformationTextPlainImageLink.class.php new file mode 100644 index 0000000000..5356c8700c --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainImageLink.class.php @@ -0,0 +1,58 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainLink.class.php b/libraries/plugins/transformations/TransformationTextPlainLink.class.php new file mode 100644 index 0000000000..87350f077b --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainLink.class.php @@ -0,0 +1,58 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainLongToIPv4.class.php b/libraries/plugins/transformations/TransformationTextPlainLongToIPv4.class.php new file mode 100644 index 0000000000..22b690c406 --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainLongToIPv4.class.php @@ -0,0 +1,57 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainSQL.class.php b/libraries/plugins/transformations/TransformationTextPlainSQL.class.php new file mode 100644 index 0000000000..62fc3dace6 --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainSQL.class.php @@ -0,0 +1,56 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/TransformationTextPlainSubstring.class.php b/libraries/plugins/transformations/TransformationTextPlainSubstring.class.php new file mode 100644 index 0000000000..de118cfdfe --- /dev/null +++ b/libraries/plugins/transformations/TransformationTextPlainSubstring.class.php @@ -0,0 +1,60 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php new file mode 100644 index 0000000000..c3f323d64e --- /dev/null +++ b/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php new file mode 100644 index 0000000000..cc0c000ea1 --- /dev/null +++ b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php new file mode 100644 index 0000000000..f6ff46d787 --- /dev/null +++ b/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php new file mode 100644 index 0000000000..0adf1a5d50 --- /dev/null +++ b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php new file mode 100644 index 0000000000..a9431f137c --- /dev/null +++ b/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php.php b/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php.php new file mode 100644 index 0000000000..63b8e96360 --- /dev/null +++ b/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php new file mode 100644 index 0000000000..2cb6b4c6e6 --- /dev/null +++ b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php.php b/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php.php new file mode 100644 index 0000000000..8fcdec25b3 --- /dev/null +++ b/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php new file mode 100644 index 0000000000..b1dd95d705 --- /dev/null +++ b/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php new file mode 100644 index 0000000000..0b968b97e1 --- /dev/null +++ b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php new file mode 100644 index 0000000000..ae51182abb --- /dev/null +++ b/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php new file mode 100644 index 0000000000..33eab316ec --- /dev/null +++ b/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php @@ -0,0 +1,67 @@ + \ No newline at end of file From 04f82137cbb76aa5dca53e28a29cc1cb9d099fcf Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Thu, 7 Jun 2012 19:47:02 +0300 Subject: [PATCH 04/55] oop: export properties bug --- export.php | 6 +- .../plugins/export/ExportCodegen.class.php | 521 ++++++++++++++++++ 2 files changed, 524 insertions(+), 3 deletions(-) create mode 100644 libraries/plugins/export/ExportCodegen.class.php diff --git a/export.php b/export.php index b2494fd280..df182d15f9 100644 --- a/export.php +++ b/export.php @@ -328,13 +328,13 @@ if ($asfile) { // 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; + $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 diff --git a/libraries/plugins/export/ExportCodegen.class.php b/libraries/plugins/export/ExportCodegen.class.php new file mode 100644 index 0000000000..6403ce7968 --- /dev/null +++ b/libraries/plugins/export/ExportCodegen.class.php @@ -0,0 +1,521 @@ +setProperties(); + + } + + /** + * Initialize the local variables that are used specific for export SQL + * + * @global type $table + * @global type $tables + * + * @return void + */ + private function initLocalVariables() + { + global $table; + global $tables; + $this->setTable($table); + $this->setTables($tables); + } + + /** + * Sets the export XML properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('XML'), + 'extension' => 'xml', + 'mime_type' => 'text/xml', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'hidden', + 'name' => 'structure_or_data' + ), + array( + 'type' => 'end_group' + ) + ); + + /* Export structure */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'structure', + 'text' => __('Object creation options (all are recommended)') + ); + if (! PMA_DRIZZLE) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_functions', + 'text' => __('Functions') + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_procedures', + 'text' => __('Procedures') + ); + } + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_tables', + 'text' => __('Tables') + ); + if (! PMA_DRIZZLE) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_triggers', + 'text' => __('Triggers') + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_views', + 'text' => __('Views') + ); + } + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + + /* Data */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'data', + 'text' => __('Data dump options') + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'export_contents', + 'text' => __('Export contents') + ); + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header. It is the first method to be called, so all + * the required variables are initialized here. + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + // initialize the general export variables + $this->initExportCommonVariables(); + + // initialize the specific export sql variables + $this->initLocalVariables(); + + $crlf = $this->getCrlf(); + $cfg = $this->getCfg(); + $db = $this->getDb(); + $table = $this->getTable(); + $tables = $this->getTables(); + + $export_struct = isset($GLOBALS['xml_export_functions']) + || isset($GLOBALS['xml_export_procedures']) + || isset($GLOBALS['xml_export_tables']) + || isset($GLOBALS['xml_export_triggers']) + || isset($GLOBALS['xml_export_views']); + $export_data = isset($GLOBALS['xml_export_contents']) ? true : false; + + if ($GLOBALS['output_charset_conversion']) { + $charset = $GLOBALS['charset_of_file']; + } else { + $charset = 'utf-8'; + } + + $head = '' . $crlf + . '' . $crlf . $crlf; + + $head .= '' . $crlf; + + if ($export_struct) { + if (PMA_DRIZZLE) { + $result = PMA_DBI_fetch_result( + "SELECT + 'utf8' AS DEFAULT_CHARACTER_SET_NAME, + DEFAULT_COLLATION_NAME + FROM data_dictionary.SCHEMAS + WHERE SCHEMA_NAME = '" . PMA_sqlAddSlashes($db) . "'" + ); + } else { + $result = PMA_DBI_fetch_result( + 'SELECT `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`' + . ' FROM `information_schema`.`SCHEMATA` WHERE `SCHEMA_NAME`' + . ' = \''.PMA_sqlAddSlashes($db).'\' LIMIT 1' + ); + } + $db_collation = $result[0]['DEFAULT_COLLATION_NAME']; + $db_charset = $result[0]['DEFAULT_CHARACTER_SET_NAME']; + + $head .= ' ' . $crlf; + $head .= ' ' . $crlf; + $head .= ' ' . $crlf; + + if (count($tables) == 0) { + $tables[] = $table; + } + + foreach ($tables as $table) { + // Export tables and views + $result = PMA_DBI_fetch_result( + 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' + . PMA_backquote($table), + 0 + ); + $tbl = $result[$table][1]; + + $is_view = PMA_Table::isView($db, $table); + + if ($is_view) { + $type = 'view'; + } else { + $type = 'table'; + } + + if ($is_view && ! isset($GLOBALS['xml_export_views'])) { + continue; + } + + if (! $is_view && ! isset($GLOBALS['xml_export_tables'])) { + continue; + } + + $head .= ' ' + . $crlf; + + $tbl = " " . htmlspecialchars($tbl); + $tbl = str_replace("\n", "\n ", $tbl); + + $head .= $tbl . ';' . $crlf; + $head .= ' ' . $crlf; + + if (isset($GLOBALS['xml_export_triggers']) + && $GLOBALS['xml_export_triggers'] + ) { + // Export triggers + $triggers = PMA_DBI_get_triggers($db, $table); + if ($triggers) { + foreach ($triggers as $trigger) { + $code = $trigger['create']; + $head .= ' ' . $crlf; + + // Do some formatting + $code = substr(rtrim($code), 0, -3); + $code = " " . htmlspecialchars($code); + $code = str_replace("\n", "\n ", $code); + + $head .= $code . $crlf; + $head .= ' ' . $crlf; + } + + unset($trigger); + unset($triggers); + } + } + } + + if (isset($GLOBALS['xml_export_functions']) + && $GLOBALS['xml_export_functions'] + ) { + // Export functions + $functions = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION'); + if ($functions) { + foreach ($functions as $function) { + $head .= ' ' . $crlf; + + // Do some formatting + $sql = PMA_DBI_get_definition($db, 'FUNCTION', $function); + $sql = rtrim($sql); + $sql = " " . htmlspecialchars($sql); + $sql = str_replace("\n", "\n ", $sql); + + $head .= $sql . $crlf; + $head .= ' ' . $crlf; + } + + unset($function); + unset($functions); + } + } + + if (isset($GLOBALS['xml_export_procedures']) + && $GLOBALS['xml_export_procedures'] + ) { + // Export procedures + $procedures = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE'); + if ($procedures) { + foreach ($procedures as $procedure) { + $head .= ' ' . $crlf; + + // Do some formatting + $sql = PMA_DBI_get_definition($db, 'PROCEDURE', $procedure); + $sql = rtrim($sql); + $sql = " " . htmlspecialchars($sql); + $sql = str_replace("\n", "\n ", $sql); + + $head .= $sql . $crlf; + $head .= ' ' . $crlf; + } + + unset($procedure); + unset($procedures); + } + } + + unset($result); + + $head .= ' ' . $crlf; + $head .= ' ' . $crlf; + + if ($export_data) { + $head .= $crlf; + } + } + + return PMA_exportOutputHandler($head); + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + $foot = ''; + + return PMA_exportOutputHandler($foot); + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + $crlf = $this->getCrlf(); + + if (isset($GLOBALS['xml_export_contents']) + && $GLOBALS['xml_export_contents'] + ) { + $head = ' ' . $crlf + . ' ' . $crlf; + + return PMA_exportOutputHandler($head); + } else { + return true; + } + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + $crlf = $this->getCrlf(); + + if (isset($GLOBALS['xml_export_contents']) + && $GLOBALS['xml_export_contents'] + ) { + return PMA_exportOutputHandler(' ' . $crlf); + } else { + return true; + } + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + return true; + } + + /** + * Outputs the content of a table in XML format + * + * @param string $db database name + * @param string $table table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param string $sql_query SQL query for obtaining data + * + * @return bool Whether it succeeded + */ + public function exportData ($db, $table, $crlf, $error_url, $sql_query) + { + if (isset($GLOBALS['xml_export_contents']) + && $GLOBALS['xml_export_contents'] + ) { + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + + $columns_cnt = PMA_DBI_num_fields($result); + $columns = array(); + for ($i = 0; $i < $columns_cnt; $i++) { + $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); + } + unset($i); + + $buffer = ' ' . $crlf; + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + while ($record = PMA_DBI_fetch_row($result)) { + $buffer = ' ' . $crlf; + for ($i = 0; $i < $columns_cnt; $i++) { + // If a cell is NULL, still export it to preserve + // the XML structure + if (! isset($record[$i]) || is_null($record[$i])) { + $record[$i] = 'NULL'; + } + $buffer .= ' ' + . htmlspecialchars((string)$record[$i]) + . '' . $crlf; + } + $buffer .= '
' . $crlf; + + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + } + PMA_DBI_free_result($result); + } + + return true; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + private function getTable() + { + return $this->table; + } + + private function setTable($table) + { + $this->table = $table; + } + + private function getTables() + { + return $this->tables; + } + + private function setTables($tables) + { + $this->tables = $tables; + } +} +?> \ No newline at end of file From 54098d08ddfdd6df2fbf6b95846518cdff9102b4 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Thu, 7 Jun 2012 19:48:00 +0300 Subject: [PATCH 05/55] oop: small comment errors export xml --- libraries/plugins/export/ExportXML.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/plugins/export/ExportXML.class.php b/libraries/plugins/export/ExportXML.class.php index 6403ce7968..a51880b7bb 100644 --- a/libraries/plugins/export/ExportXML.class.php +++ b/libraries/plugins/export/ExportXML.class.php @@ -48,7 +48,7 @@ class ExportXML extends ExportPlugin } /** - * Initialize the local variables that are used specific for export SQL + * Initialize the local variables that are used specific for export XML * * @global type $table * @global type $tables @@ -171,7 +171,7 @@ class ExportXML extends ExportPlugin // initialize the general export variables $this->initExportCommonVariables(); - // initialize the specific export sql variables + // initialize the specific export xml variables $this->initLocalVariables(); $crlf = $this->getCrlf(); From 683d7677b9d60ed389c4d1efae31df968217effa Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 8 Jun 2012 11:47:36 +0300 Subject: [PATCH 06/55] oop: export codegen; camel caps export naming convention --- export.php | 35 +- libraries/plugin_interface.lib.php | 4 +- libraries/plugins/ExportPlugin.class.php | 64 ++- .../plugins/export/ExportCodegen.class.php | 532 ++++++------------ ...xportSQL.class.php => ExportSql.class.php} | 6 +- ...xportXML.class.php => ExportXml.class.php} | 2 +- .../plugins/export/TableProperty.class.php | 184 ++++++ 7 files changed, 455 insertions(+), 372 deletions(-) rename libraries/plugins/export/{ExportSQL.class.php => ExportSql.class.php} (99%) rename libraries/plugins/export/{ExportXML.class.php => ExportXml.class.php} (99%) create mode 100644 libraries/plugins/export/TableProperty.class.php diff --git a/export.php b/export.php index df182d15f9..cc9cb44671 100644 --- a/export.php +++ b/export.php @@ -124,9 +124,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 */ @@ -499,11 +496,11 @@ do { if (! $export_plugin->exportDBCreate($current_db)) { break 2; } - if (function_exists('PMA_exportRoutines') + if (function_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); @@ -520,7 +517,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 @@ -544,7 +541,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 @@ -558,7 +555,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 @@ -567,21 +564,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 (function_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; @@ -599,7 +596,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 @@ -621,7 +618,7 @@ do { // 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 (! $export_plugin->exportStructure( $db, $table, $crlf, $err_url, 'triggers', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -633,7 +630,7 @@ 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 (! $export_plugin->exportStructure( $db, $view, $crlf, $err_url, 'create_view', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -643,11 +640,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 @@ -662,7 +659,7 @@ 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 (! $export_plugin->exportStructure( $db, $table, $crlf, $err_url, $is_view ? 'create_view' : 'create_table', $export_type, $do_relation, $do_comments, $do_mime, $do_dates @@ -692,7 +689,7 @@ do { // 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 (! $export_plugin->exportStructure( $db, $table, $crlf, $err_url, 'triggers', $export_type, $do_relation, $do_comments, $do_mime, $do_dates diff --git a/libraries/plugin_interface.lib.php b/libraries/plugin_interface.lib.php index 39969001e4..fc88641ab8 100644 --- a/libraries/plugin_interface.lib.php +++ b/libraries/plugin_interface.lib.php @@ -22,7 +22,8 @@ function PMA_getPlugin($plugin_type, $plugin_format, $plugins_dir, $plugin_param // todo replace strtoupper with CamelCaps (ex: HtmlWord) $class_name = strtoupper($plugin_type[0]) . strtolower(substr($plugin_type, 1)) - . strtoupper($plugin_format); + . 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; @@ -31,6 +32,7 @@ function PMA_getPlugin($plugin_type, $plugin_format, $plugins_dir, $plugin_param return null; } + /** * Reads all plugin information from directory $plugins_dir * diff --git a/libraries/plugins/ExportPlugin.class.php b/libraries/plugins/ExportPlugin.class.php index ae845f4830..4d8ac9dd2d 100644 --- a/libraries/plugins/ExportPlugin.class.php +++ b/libraries/plugins/ExportPlugin.class.php @@ -50,6 +50,12 @@ abstract class ExportPlugin extends PluginObserver */ private $_db; + + /** + * Common methods, must be overwritten by all export plugins + */ + + /** * Outputs export header * @@ -104,6 +110,62 @@ abstract class ExportPlugin extends PluginObserver */ abstract public function exportData ($db, $table, $crlf, $error_url, $sql_query); + + /** + * The following methods are used in export.php, but they are not + * implemented by all export plugins + */ + + + /** + * Exports routines (procedures and functions) + * + * @param string $db Database + * + * @return bool Whether it succeeded + */ + public function exportRoutines($db) + { + ; + } + + /** + * Outputs table's structure + * + * @param string $db database name + * @param string $table table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param string $export_mode 'create_table','triggers','create_view', + * 'stand_in' + * @param string $export_type 'server', 'database', 'table' + * @param bool $relation whether to include relation comments + * @param bool $comments whether to include the pmadb-style column comments + * as comments in the structure; this is deprecated + * but the parameter is left here because export.php + * calls exportStructure() also for other export + * types which use this parameter + * @param bool $mime whether to include mime comments + * @param bool $dates whether to include creation/update/check dates + * + * @return bool Whether it succeeded + */ + public function exportStructure( + $db, + $table, + $crlf, + $error_url, + $export_mode, + $export_type, + $relation = false, + $comments = false, + $mime = false, + $dates = false + ) { + ; + } + + /** * Initializes the local variables with the global values. * These are variables that are used by all of the export plugins. @@ -111,7 +173,7 @@ abstract class ExportPlugin extends PluginObserver * @global String $crlf type of the newline character * @global array $cfg array with configuration settings * @global String $db database name - * + * * @return void */ protected function initExportCommonVariables() diff --git a/libraries/plugins/export/ExportCodegen.class.php b/libraries/plugins/export/ExportCodegen.class.php index 6403ce7968..7d8bb5a534 100644 --- a/libraries/plugins/export/ExportCodegen.class.php +++ b/libraries/plugins/export/ExportCodegen.class.php @@ -1,66 +1,73 @@ setProperties(); + // initialize the specific export codegen variables + $this->initLocalVariables(); + $this->setProperties(); } /** - * Initialize the local variables that are used specific for export SQL - * - * @global type $table - * @global type $tables + * Initialize the local variables that are used for export CodeGen * * @return void */ private function initLocalVariables() { - global $table; - global $tables; - $this->setTable($table); - $this->setTables($tables); + $this->setCG_FORMATS( + array( + "NHibernate C# DO", + "NHibernate XML" + ) + ); + + $this->setCG_HANDLERS( + array( + "handleNHibernateCSBody", + "handleNHibernateXMLBody" + ) + ); } /** @@ -71,9 +78,9 @@ class ExportXML extends ExportPlugin protected function setProperties() { $this->properties = array( - 'text' => __('XML'), - 'extension' => 'xml', - 'mime_type' => 'text/xml', + 'text' => 'CodeGen', + 'extension' => 'cs', + 'mime_type' => 'text/cs', 'options' => array(), 'options_text' => __('Options') ); @@ -87,64 +94,16 @@ class ExportXML extends ExportPlugin 'type' => 'hidden', 'name' => 'structure_or_data' ), + array( + 'type' => 'select', + 'name' => 'format', + 'text' => __('Format:'), + 'values' => $this->getCG_FORMATS() + ), array( 'type' => 'end_group' ) ); - - /* Export structure */ - $this->properties['options'][] = array( - 'type' => 'begin_group', - 'name' => 'structure', - 'text' => __('Object creation options (all are recommended)') - ); - if (! PMA_DRIZZLE) { - $this->properties['options'][] = array( - 'type' => 'bool', - 'name' => 'export_functions', - 'text' => __('Functions') - ); - $this->properties['options'][] = array( - 'type' => 'bool', - 'name' => 'export_procedures', - 'text' => __('Procedures') - ); - } - $this->properties['options'][] = array( - 'type' => 'bool', - 'name' => 'export_tables', - 'text' => __('Tables') - ); - if (! PMA_DRIZZLE) { - $this->properties['options'][] = array( - 'type' => 'bool', - 'name' => 'export_triggers', - 'text' => __('Triggers') - ); - $this->properties['options'][] = array( - 'type' => 'bool', - 'name' => 'export_views', - 'text' => __('Views') - ); - } - $this->properties['options'][] = array( - 'type' => 'end_group' - ); - - /* Data */ - $this->properties['options'][] = array( - 'type' => 'begin_group', - 'name' => 'data', - 'text' => __('Data dump options') - ); - $this->properties['options'][] = array( - 'type' => 'bool', - 'name' => 'export_contents', - 'text' => __('Export contents') - ); - $this->properties['options'][] = array( - 'type' => 'end_group' - ); } /** @@ -161,8 +120,7 @@ class ExportXML extends ExportPlugin } /** - * Outputs export header. It is the first method to be called, so all - * the required variables are initialized here. + * Outputs export header * * @return bool Whether it succeeded */ @@ -171,202 +129,7 @@ class ExportXML extends ExportPlugin // initialize the general export variables $this->initExportCommonVariables(); - // initialize the specific export sql variables - $this->initLocalVariables(); - - $crlf = $this->getCrlf(); - $cfg = $this->getCfg(); - $db = $this->getDb(); - $table = $this->getTable(); - $tables = $this->getTables(); - - $export_struct = isset($GLOBALS['xml_export_functions']) - || isset($GLOBALS['xml_export_procedures']) - || isset($GLOBALS['xml_export_tables']) - || isset($GLOBALS['xml_export_triggers']) - || isset($GLOBALS['xml_export_views']); - $export_data = isset($GLOBALS['xml_export_contents']) ? true : false; - - if ($GLOBALS['output_charset_conversion']) { - $charset = $GLOBALS['charset_of_file']; - } else { - $charset = 'utf-8'; - } - - $head = '' . $crlf - . '' . $crlf . $crlf; - - $head .= '' . $crlf; - - if ($export_struct) { - if (PMA_DRIZZLE) { - $result = PMA_DBI_fetch_result( - "SELECT - 'utf8' AS DEFAULT_CHARACTER_SET_NAME, - DEFAULT_COLLATION_NAME - FROM data_dictionary.SCHEMAS - WHERE SCHEMA_NAME = '" . PMA_sqlAddSlashes($db) . "'" - ); - } else { - $result = PMA_DBI_fetch_result( - 'SELECT `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`' - . ' FROM `information_schema`.`SCHEMATA` WHERE `SCHEMA_NAME`' - . ' = \''.PMA_sqlAddSlashes($db).'\' LIMIT 1' - ); - } - $db_collation = $result[0]['DEFAULT_COLLATION_NAME']; - $db_charset = $result[0]['DEFAULT_CHARACTER_SET_NAME']; - - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; - - if (count($tables) == 0) { - $tables[] = $table; - } - - foreach ($tables as $table) { - // Export tables and views - $result = PMA_DBI_fetch_result( - 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' - . PMA_backquote($table), - 0 - ); - $tbl = $result[$table][1]; - - $is_view = PMA_Table::isView($db, $table); - - if ($is_view) { - $type = 'view'; - } else { - $type = 'table'; - } - - if ($is_view && ! isset($GLOBALS['xml_export_views'])) { - continue; - } - - if (! $is_view && ! isset($GLOBALS['xml_export_tables'])) { - continue; - } - - $head .= ' ' - . $crlf; - - $tbl = " " . htmlspecialchars($tbl); - $tbl = str_replace("\n", "\n ", $tbl); - - $head .= $tbl . ';' . $crlf; - $head .= ' ' . $crlf; - - if (isset($GLOBALS['xml_export_triggers']) - && $GLOBALS['xml_export_triggers'] - ) { - // Export triggers - $triggers = PMA_DBI_get_triggers($db, $table); - if ($triggers) { - foreach ($triggers as $trigger) { - $code = $trigger['create']; - $head .= ' ' . $crlf; - - // Do some formatting - $code = substr(rtrim($code), 0, -3); - $code = " " . htmlspecialchars($code); - $code = str_replace("\n", "\n ", $code); - - $head .= $code . $crlf; - $head .= ' ' . $crlf; - } - - unset($trigger); - unset($triggers); - } - } - } - - if (isset($GLOBALS['xml_export_functions']) - && $GLOBALS['xml_export_functions'] - ) { - // Export functions - $functions = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION'); - if ($functions) { - foreach ($functions as $function) { - $head .= ' ' . $crlf; - - // Do some formatting - $sql = PMA_DBI_get_definition($db, 'FUNCTION', $function); - $sql = rtrim($sql); - $sql = " " . htmlspecialchars($sql); - $sql = str_replace("\n", "\n ", $sql); - - $head .= $sql . $crlf; - $head .= ' ' . $crlf; - } - - unset($function); - unset($functions); - } - } - - if (isset($GLOBALS['xml_export_procedures']) - && $GLOBALS['xml_export_procedures'] - ) { - // Export procedures - $procedures = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE'); - if ($procedures) { - foreach ($procedures as $procedure) { - $head .= ' ' . $crlf; - - // Do some formatting - $sql = PMA_DBI_get_definition($db, 'PROCEDURE', $procedure); - $sql = rtrim($sql); - $sql = " " . htmlspecialchars($sql); - $sql = str_replace("\n", "\n ", $sql); - - $head .= $sql . $crlf; - $head .= ' ' . $crlf; - } - - unset($procedure); - unset($procedures); - } - } - - unset($result); - - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; - - if ($export_data) { - $head .= $crlf; - } - } - - return PMA_exportOutputHandler($head); + return true; } /** @@ -376,9 +139,7 @@ class ExportXML extends ExportPlugin */ public function exportFooter () { - $foot = ''; - - return PMA_exportOutputHandler($foot); + return true; } /** @@ -388,22 +149,8 @@ class ExportXML extends ExportPlugin * * @return bool Whether it succeeded */ - public function exportDBHeader ($db) - { - $crlf = $this->getCrlf(); - - if (isset($GLOBALS['xml_export_contents']) - && $GLOBALS['xml_export_contents'] - ) { - $head = ' ' . $crlf - . ' ' . $crlf; - - return PMA_exportOutputHandler($head); - } else { - return true; - } + public function exportDBHeader ($db) { + return true; } /** @@ -415,15 +162,7 @@ class ExportXML extends ExportPlugin */ public function exportDBFooter ($db) { - $crlf = $this->getCrlf(); - - if (isset($GLOBALS['xml_export_contents']) - && $GLOBALS['xml_export_contents'] - ) { - return PMA_exportOutputHandler(' ' . $crlf); - } else { - return true; - } + return true; } /** @@ -437,9 +176,8 @@ class ExportXML extends ExportPlugin { return true; } - /** - * Outputs the content of a table in XML format + * Outputs the content of a table in NHibernate format * * @param string $db database name * @param string $table table name @@ -448,74 +186,174 @@ class ExportXML extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded + * + * @access public */ - public function exportData ($db, $table, $crlf, $error_url, $sql_query) + public function exportData($db, $table, $crlf, $error_url, $sql_query) { - if (isset($GLOBALS['xml_export_contents']) - && $GLOBALS['xml_export_contents'] - ) { - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + $CG_FORMATS = $this->getCG_FORMATS(); + $CG_HANDLERS = $this->getCG_HANDLERS(); - $columns_cnt = PMA_DBI_num_fields($result); - $columns = array(); - for ($i = 0; $i < $columns_cnt; $i++) { - $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); + $format = $GLOBALS['codegen_format']; + if (isset($CG_FORMATS[$format])) { + return PMA_exportOutputHandler( + $this->$CG_HANDLERS[$format]($db, $table, $crlf) + ); + } + return PMA_exportOutputHandler(sprintf("%s is not supported.", $format)); + } + + public static 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; + } + + private 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); } - unset($i); - - $buffer = ' ' . $crlf; - if (! PMA_exportOutputHandler($buffer)) { - return false; + PMA_DBI_free_result($result); + $lines[] = 'using System;'; + $lines[] = 'using System.Collections;'; + $lines[] = 'using System.Collections.Generic;'; + $lines[] = 'using System.Text;'; + $lines[] = 'namespace ' . ExportCodegen::cgMakeIdentifier($db); + $lines[] = '{'; + $lines[] = ' #region ' . ExportCodegen::cgMakeIdentifier($table); + $lines[] = ' public class ' . ExportCodegen::cgMakeIdentifier($table); + $lines[] = ' {'; + $lines[] = ' #region Member Variables'; + foreach ($tableProperties as $tableProperty) { + $lines[] = $tableProperty->formatCs( + ' protected #dotNetPrimitiveType# _#name#;' + ); } - - while ($record = PMA_DBI_fetch_row($result)) { - $buffer = ' ' . $crlf; - for ($i = 0; $i < $columns_cnt; $i++) { - // If a cell is NULL, still export it to preserve - // the XML structure - if (! isset($record[$i]) || is_null($record[$i])) { - $record[$i] = 'NULL'; - } - $buffer .= ' ' - . htmlspecialchars((string)$record[$i]) - . '' . $crlf; + $lines[] = ' #endregion'; + $lines[] = ' #region Constructors'; + $lines[] = ' public ' . ExportCodegen::cgMakeIdentifier($table).'() { }'; + $temp = array(); + foreach ($tableProperties as $tableProperty) { + if (! $tableProperty->isPK()) { + $temp[] = $tableProperty->formatCs( + '#dotNetPrimitiveType# #name#' + ); } - $buffer .= '
' . $crlf; + } + $lines[] = ' public ' + . ExportCodegen::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); + } - if (! PMA_exportOutputHandler($buffer)) { - return false; + 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); } - - return true; + $lines[] = ' '; + $lines[] = ''; + return implode("\n", $lines); } /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - private function getTable() + public function getCG_FORMATS() { - return $this->table; + return $this->_CG_FORMATS; } - private function setTable($table) + public function setCG_FORMATS($CG_FORMATS) { - $this->table = $table; + $this->_CG_FORMATS = $CG_FORMATS; } - private function getTables() + public function getCG_HANDLERS() { - return $this->tables; + return $this->_CG_HANDLERS; } - private function setTables($tables) + public function setCG_HANDLERS($CG_HANDLERS) { - $this->tables = $tables; + $this->_CG_HANDLERS = $CG_HANDLERS; } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportSQL.class.php b/libraries/plugins/export/ExportSql.class.php similarity index 99% rename from libraries/plugins/export/ExportSQL.class.php rename to libraries/plugins/export/ExportSql.class.php index fe04056362..b1e1c0ec9b 100644 --- a/libraries/plugins/export/ExportSQL.class.php +++ b/libraries/plugins/export/ExportSql.class.php @@ -19,7 +19,7 @@ require_once "libraries/plugins/ExportPlugin.class.php"; * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ -class ExportSQL extends ExportPlugin +class ExportSql extends ExportPlugin { /** * @@ -1428,7 +1428,7 @@ class ExportSQL extends ExportPlugin __('Table structure for table') . ' '. $formatted_table_name ); $dump .= $this->exportComment(); - $dump .= getTableDef($db, $table, $crlf, $error_url, $dates); + $dump .= $this->getTableDef($db, $table, $crlf, $error_url, $dates); $dump .= $this->getTableComments($db, $table, $crlf, $relation, $mime); break; case 'triggers': @@ -1463,7 +1463,7 @@ class ExportSQL extends ExportPlugin $dump .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table) . ';' . $crlf; } - $dump .= getTableDef( + $dump .= $this->getTableDef( $db, $table, $crlf, $error_url, $dates, true, true ); break; diff --git a/libraries/plugins/export/ExportXML.class.php b/libraries/plugins/export/ExportXml.class.php similarity index 99% rename from libraries/plugins/export/ExportXML.class.php rename to libraries/plugins/export/ExportXml.class.php index a51880b7bb..f4c120f172 100644 --- a/libraries/plugins/export/ExportXML.class.php +++ b/libraries/plugins/export/ExportXml.class.php @@ -22,7 +22,7 @@ require_once "libraries/plugins/ExportPlugin.class.php"; * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ -class ExportXML extends ExportPlugin +class ExportXml extends ExportPlugin { /** * Table name diff --git a/libraries/plugins/export/TableProperty.class.php b/libraries/plugins/export/TableProperty.class.php new file mode 100644 index 0000000000..15e8d48f6c --- /dev/null +++ b/libraries/plugins/export/TableProperty.class.php @@ -0,0 +1,184 @@ +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#", + ExportCodegen::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#", + ExportCodegen::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; + } +} +?> \ No newline at end of file From 4e764e76b86e58954f5acaf6968f3f234341215f Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 8 Jun 2012 11:52:27 +0300 Subject: [PATCH 07/55] oop: camel caps for import plugins --- libraries/plugin_interface.lib.php | 1 - .../plugins/import/{ImportSQL.class.php => ImportSql.class.php} | 2 +- .../plugins/import/{ImportXML.class.php => ImportXml.class.php} | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) rename libraries/plugins/import/{ImportSQL.class.php => ImportSql.class.php} (99%) rename libraries/plugins/import/{ImportXML.class.php => ImportXml.class.php} (99%) diff --git a/libraries/plugin_interface.lib.php b/libraries/plugin_interface.lib.php index fc88641ab8..1b5a5d0ae1 100644 --- a/libraries/plugin_interface.lib.php +++ b/libraries/plugin_interface.lib.php @@ -19,7 +19,6 @@ */ function PMA_getPlugin($plugin_type, $plugin_format, $plugins_dir, $plugin_param = false) { - // todo replace strtoupper with CamelCaps (ex: HtmlWord) $class_name = strtoupper($plugin_type[0]) . strtolower(substr($plugin_type, 1)) . strtoupper($plugin_format[0]) diff --git a/libraries/plugins/import/ImportSQL.class.php b/libraries/plugins/import/ImportSql.class.php similarity index 99% rename from libraries/plugins/import/ImportSQL.class.php rename to libraries/plugins/import/ImportSql.class.php index eb1b510af7..fcf90cfefc 100644 --- a/libraries/plugins/import/ImportSQL.class.php +++ b/libraries/plugins/import/ImportSql.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/ImportPlugin.class.php"; * * @package PhpMyAdmin-Import */ -class ImportSQL extends ImportPlugin +class ImportSql extends ImportPlugin { /** * Constructor diff --git a/libraries/plugins/import/ImportXML.class.php b/libraries/plugins/import/ImportXml.class.php similarity index 99% rename from libraries/plugins/import/ImportXML.class.php rename to libraries/plugins/import/ImportXml.class.php index 677ef8ef1d..2fc34ccaf0 100644 --- a/libraries/plugins/import/ImportXML.class.php +++ b/libraries/plugins/import/ImportXml.class.php @@ -28,7 +28,7 @@ require_once "libraries/plugins/ImportPlugin.class.php"; * @todo add descriptions * @package PhpMyAdmin-Import */ -class ImportXML extends ImportPlugin +class ImportXml extends ImportPlugin { /** * Database name From 9d6bed8d34534b97abb16899efc828a8a4d2b764 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 8 Jun 2012 15:31:16 +0300 Subject: [PATCH 08/55] oop: export csv --- libraries/plugins/export/ExportCsv.class.php | 442 +++++++++++++++++++ 1 file changed, 442 insertions(+) create mode 100644 libraries/plugins/export/ExportCsv.class.php diff --git a/libraries/plugins/export/ExportCsv.class.php b/libraries/plugins/export/ExportCsv.class.php new file mode 100644 index 0000000000..4bd406ff49 --- /dev/null +++ b/libraries/plugins/export/ExportCsv.class.php @@ -0,0 +1,442 @@ +setProperties(); + } + + /** + * Initialize the local variables that are used for export CSV + * + * @return void + */ + private function initLocalVariables() + { + global $what; + global $csv_terminated; + global $csv_separator; + global $csv_enclosed; + global $csv_escaped; + $this->setWhat($what); + $this->setCsvTerminated($csv_terminated); + $this->setCsvSeparator($csv_separator); + $this->setCsvEnclosed($csv_enclosed); + $this->setCsvEscaped($csv_escaped); + } + + /** + * Sets the export CSV properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('CSV'), + 'extension' => 'csv', + 'mime_type' => 'text/comma-separated-values', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'text', + 'name' => 'separator', + 'text' => __('Columns separated with:') + ), + array( + 'type' => 'text', + 'name' => 'enclosed', + 'text' => __('Columns enclosed with:') + ), + array( + 'type' => 'text', + 'name' => 'escaped', + 'text' => __('Columns escaped with:') + ), + array( + 'type' => 'text', + 'name' => 'terminated', + 'text' => __('Lines terminated with:') + ), + 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' => 'hidden', + 'name' => 'structure_or_data' + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + // initialize the general export variables + $this->initExportCommonVariables(); + + // initialize the specific export sql variables + $this->initLocalVariables(); + + $what = $this->getWhat(); + $csv_terminated = $this->getCsvTerminated(); + $csv_separator = $this->getCsvSeparator(); + $csv_enclosed = $this->getCsvEnclosed(); + $csv_escaped = $this->getCsvEscaped(); + + + // Here we just prepare some values for export + if ($what == 'excel') { + $csv_terminated = "\015\012"; + switch($GLOBALS['excel_edition']) { + case 'win': + // as tested on Windows with Excel 2002 and Excel 2007 + $csv_separator = ';'; + break; + case 'mac_excel2003': + $csv_separator = ';'; + break; + case 'mac_excel2008': + $csv_separator = ','; + break; + } + $csv_enclosed = '"'; + $csv_escaped = '"'; + if (isset($GLOBALS['excel_columns'])) { + $GLOBALS['csv_columns'] = 'yes'; + } + } else { + if (empty($csv_terminated) || strtolower($csv_terminated) == 'auto') { + $csv_terminated = $GLOBALS['crlf']; + } else { + $csv_terminated = str_replace('\\r', "\015", $csv_terminated); + $csv_terminated = str_replace('\\n', "\012", $csv_terminated); + $csv_terminated = str_replace('\\t', "\011", $csv_terminated); + } // end if + $csv_separator = str_replace('\\t', "\011", $csv_separator); + } + + // remember the modifications + $this->setCsvTerminated($csv_terminated); + $this->setCsvSeparator($csv_separator); + $this->setCsvEnclosed($csv_enclosed); + $this->setCsvEscaped($csv_escaped); + + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) { + return true; + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + return true; + } + + /** + * Outputs the content of a table in CSV 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $what = $this->getWhat(); + $csv_terminated = $this->getCsvTerminated(); + $csv_separator = $this->getCsvSeparator(); + $csv_enclosed = $this->getCsvEnclosed(); + $csv_escaped = $this->getCsvEscaped(); + + // Gets the data from the database + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + $fields_cnt = PMA_DBI_num_fields($result); + + // If required, get fields name at the first line + if (isset($GLOBALS['csv_columns'])) { + $schema_insert = ''; + for ($i = 0; $i < $fields_cnt; $i++) { + if ($csv_enclosed == '') { + $schema_insert .= stripslashes(PMA_DBI_field_name($result, $i)); + } else { + $schema_insert .= $csv_enclosed + . str_replace( + $csv_enclosed, + $csv_escaped . $csv_enclosed, + stripslashes(PMA_DBI_field_name($result, $i)) + ) + . $csv_enclosed; + } + $schema_insert .= $csv_separator; + } // end for + $schema_insert = trim(substr($schema_insert, 0, -1)); + if (! PMA_exportOutputHandler($schema_insert . $csv_terminated)) { + return false; + } + } // end if + + // Format the data + while ($row = PMA_DBI_fetch_row($result)) { + $schema_insert = ''; + for ($j = 0; $j < $fields_cnt; $j++) { + if (! isset($row[$j]) || is_null($row[$j])) { + $schema_insert .= $GLOBALS[$what . '_null']; + } elseif ($row[$j] == '0' || $row[$j] != '') { + // always enclose fields + if ($what == 'excel') { + $row[$j] = preg_replace("/\015(\012)?/", "\012", $row[$j]); + } + // remove CRLF characters within field + if (isset($GLOBALS[$what . '_removeCRLF']) + && $GLOBALS[$what . '_removeCRLF'] + ) { + $row[$j] = str_replace( + "\n", + "", + str_replace( + "\r", + "", + $row[$j] + ) + ); + } + if ($csv_enclosed == '') { + $schema_insert .= $row[$j]; + } else { + // also double the escape string if found in the data + if ($csv_escaped != $csv_enclosed) { + $schema_insert .= $csv_enclosed + . str_replace( + $csv_enclosed, + $csv_escaped . $csv_enclosed, + str_replace( + $csv_escaped, + $csv_escaped . $csv_escaped, + $row[$j] + ) + ) + . $csv_enclosed; + } else { + // avoid a problem when escape string equals enclose + $schema_insert .= $csv_enclosed + . str_replace( + $csv_enclosed, + $csv_escaped . $csv_enclosed, + $row[$j] + ) + . $csv_enclosed; + } + } + } else { + $schema_insert .= ''; + } + if ($j < $fields_cnt-1) { + $schema_insert .= $csv_separator; + } + } // end for + + if (! PMA_exportOutputHandler($schema_insert . $csv_terminated)) { + return false; + } + } // end while + PMA_DBI_free_result($result); + + return true; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + public function getWhat() + { + return $this->_what; + } + + public function setWhat($_what) + { + $this->_what = $_what; + } + + public function getCsvTerminated() + { + return $this->_csvTerminated; + } + + public function setCsvTerminated($_csvTerminated) + { + $this->_csvTerminated = $_csvTerminated; + } + + public function getCsvSeparator() + { + return $this->_csvSeparator; + } + + public function setCsvSeparator($_csvSeparator) + { + $this->_csvSeparator = $_csvSeparator; + } + + public function getCsvEnclosed() + { + return $this->_csvEnclosed; + } + + public function setCsvEnclosed($_csvEnclosed) + { + $this->_csvEnclosed = $_csvEnclosed; + } + + public function getCsvEscaped() + { + return $this->_csvEscaped; + } + + public function setCsvEscaped($_csvEscaped) + { + $this->_csvEscaped = $_csvEscaped; + } +} +?> \ No newline at end of file From 42360abcfb375296945bb06b0e8c3d2d4d863da2 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 8 Jun 2012 15:50:45 +0300 Subject: [PATCH 09/55] oop: export csv for excel --- libraries/plugins/export/ExportCsv.class.php | 10 +- .../plugins/export/ExportExcel.class.php | 92 +++++++++++++++++++ 2 files changed, 97 insertions(+), 5 deletions(-) create mode 100644 libraries/plugins/export/ExportExcel.class.php diff --git a/libraries/plugins/export/ExportCsv.class.php b/libraries/plugins/export/ExportCsv.class.php index 4bd406ff49..aae11d0bc4 100644 --- a/libraries/plugins/export/ExportCsv.class.php +++ b/libraries/plugins/export/ExportCsv.class.php @@ -26,35 +26,35 @@ class ExportCsv extends ExportPlugin * * @var type String */ - private $_what; + protected $_what; /** * * * @var type String */ - private $_csvTerminated; + protected $_csvTerminated; /** * * * @var type String */ - private $_csvSeparator; + protected $_csvSeparator; /** * * * @var type String */ - private $_csvEnclosed; + protected $_csvEnclosed; /** * * * @var type String */ - private $_csvEscaped; + protected $_csvEscaped; /** * Constructor diff --git a/libraries/plugins/export/ExportExcel.class.php b/libraries/plugins/export/ExportExcel.class.php new file mode 100644 index 0000000000..96bf0ba3cb --- /dev/null +++ b/libraries/plugins/export/ExportExcel.class.php @@ -0,0 +1,92 @@ +properties = array( + 'text' => __('CSV for MS Excel'), + 'extension' => 'csv', + 'mime_type' => 'text/comma-separated-values', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['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' + ) + ); + } + + /** + * 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 From 3e406e2a7676c02b770fa306403698b6243db32e Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 8 Jun 2012 15:59:12 +0300 Subject: [PATCH 10/55] oop: fix class variables names --- libraries/plugins/export/ExportCsv.class.php | 30 +++++------ libraries/plugins/export/ExportSql.class.php | 54 ++++++++++---------- libraries/plugins/export/ExportXml.class.php | 12 ++--- libraries/plugins/import/ImportXml.class.php | 18 +++---- 4 files changed, 57 insertions(+), 57 deletions(-) diff --git a/libraries/plugins/export/ExportCsv.class.php b/libraries/plugins/export/ExportCsv.class.php index aae11d0bc4..d4bdb84dcc 100644 --- a/libraries/plugins/export/ExportCsv.class.php +++ b/libraries/plugins/export/ExportCsv.class.php @@ -26,35 +26,35 @@ class ExportCsv extends ExportPlugin * * @var type String */ - protected $_what; + protected $what; /** * * * @var type String */ - protected $_csvTerminated; + protected $csvTerminated; /** * * * @var type String */ - protected $_csvSeparator; + protected $csvSeparator; /** * * * @var type String */ - protected $_csvEnclosed; + protected $csvEnclosed; /** * * * @var type String */ - protected $_csvEscaped; + protected $csvEscaped; /** * Constructor @@ -391,52 +391,52 @@ class ExportCsv extends ExportPlugin public function getWhat() { - return $this->_what; + return $this->what; } public function setWhat($_what) { - $this->_what = $_what; + $this->what = $_what; } public function getCsvTerminated() { - return $this->_csvTerminated; + return $this->csvTerminated; } public function setCsvTerminated($_csvTerminated) { - $this->_csvTerminated = $_csvTerminated; + $this->csvTerminated = $_csvTerminated; } public function getCsvSeparator() { - return $this->_csvSeparator; + return $this->csvSeparator; } public function setCsvSeparator($_csvSeparator) { - $this->_csvSeparator = $_csvSeparator; + $this->csvSeparator = $_csvSeparator; } public function getCsvEnclosed() { - return $this->_csvEnclosed; + return $this->csvEnclosed; } public function setCsvEnclosed($_csvEnclosed) { - $this->_csvEnclosed = $_csvEnclosed; + $this->csvEnclosed = $_csvEnclosed; } public function getCsvEscaped() { - return $this->_csvEscaped; + return $this->csvEscaped; } public function setCsvEscaped($_csvEscaped) { - $this->_csvEscaped = $_csvEscaped; + $this->csvEscaped = $_csvEscaped; } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportSql.class.php b/libraries/plugins/export/ExportSql.class.php index b1e1c0ec9b..9846af7603 100644 --- a/libraries/plugins/export/ExportSql.class.php +++ b/libraries/plugins/export/ExportSql.class.php @@ -26,63 +26,63 @@ class ExportSql extends ExportPlugin * * @var type */ - private $plugin_param = null; + private $_plugin_param = null; /** * * * @var type */ - private $mysql_charset_map = null; + private $_mysql_charset_map = null; /** * * * @var type */ - private $sql_drop_table; + private $_sql_drop_table; /** * * * @var type */ - private $sql_backquotes; + private $_sql_backquotes; /** * * * @var type */ - private $sql_constraints; + private $_sql_constraints; /** * Just the text of the query * * @var type string */ - private $sql_constraints_query; + private $_sql_constraints_query; /** * * * @var type */ - private $sql_drop_foreign_keys; + private $_sql_drop_foreign_keys; /** * * * @var type */ - private $cfgRelation; + private $_cfgRelation; /** * * * @var type */ - private $current_row; + private $_current_row; /** * Constructor @@ -1796,91 +1796,91 @@ class ExportSql extends ExportPlugin private function getPlugin_param() { - return $this->plugin_param; + return $this->_plugin_param; } private function setPlugin_param($plugin_param) { - $this->plugin_param = $plugin_param; + $this->_plugin_param = $plugin_param; } private function getMysql_charset_map() { - return $this->mysql_charset_map; + return $this->_mysql_charset_map; } private function setMysql_charset_map($mysql_charset_map) { - $this->mysql_charset_map = $mysql_charset_map; + $this->_mysql_charset_map = $mysql_charset_map; } private function getSql_drop_table() { - return $this->sql_drop_table; + return $this->_sql_drop_table; } private function setSql_drop_table($sql_drop_table) { - $this->sql_drop_table = $sql_drop_table; + $this->_sql_drop_table = $sql_drop_table; } private function getSql_backquotes() { - return $this->sql_backquotes; + return $this->_sql_backquotes; } private function setSql_backquotes($sql_backquotes) { - $this->sql_backquotes = $sql_backquotes; + $this->_sql_backquotes = $sql_backquotes; } private function getSql_constraints() { - return $this->sql_constraints; + return $this->_sql_constraints; } private function setSql_constraints($sql_constraints) { - $this->sql_constraints = $sql_constraints; + $this->_sql_constraints = $sql_constraints; } private function getSql_constraints_query() { - return $this->sql_constraints_query; + return $this->_sql_constraints_query; } private function setSql_constraints_query($sql_constraints_query) { - $this->sql_constraints_query = $sql_constraints_query; + $this->_sql_constraints_query = $sql_constraints_query; } private function getSql_drop_foreign_keys() { - return $this->sql_drop_foreign_keys; + return $this->_sql_drop_foreign_keys; } private function setSql_drop_foreign_keys($sql_drop_foreign_keys) { - $this->sql_drop_foreign_keys = $sql_drop_foreign_keys; + $this->_sql_drop_foreign_keys = $sql_drop_foreign_keys; } private function getCfgRelation() { - return $this->cfgRelation; + return $this->_cfgRelation; } private function setCfgRelation($cfgRelation) { - $this->cfgRelation = $cfgRelation; + $this->_cfgRelation = $cfgRelation; } private function getCurrent_row() { - return $this->current_row; + return $this->_current_row; } private function setCurrent_row($current_row) { - $this->current_row = $current_row; + $this->_current_row = $current_row; } } \ No newline at end of file diff --git a/libraries/plugins/export/ExportXml.class.php b/libraries/plugins/export/ExportXml.class.php index f4c120f172..fd8c0aee74 100644 --- a/libraries/plugins/export/ExportXml.class.php +++ b/libraries/plugins/export/ExportXml.class.php @@ -29,14 +29,14 @@ class ExportXml extends ExportPlugin * * @var type String */ - private $table; + private $_table; /** * * * @var type */ - private $tables; + private $_tables; /** * Constructor @@ -500,22 +500,22 @@ class ExportXml extends ExportPlugin private function getTable() { - return $this->table; + return $this->_table; } private function setTable($table) { - $this->table = $table; + $this->_table = $table; } private function getTables() { - return $this->tables; + return $this->_tables; } private function setTables($tables) { - $this->tables = $tables; + $this->_tables = $tables; } } ?> \ No newline at end of file diff --git a/libraries/plugins/import/ImportXml.class.php b/libraries/plugins/import/ImportXml.class.php index 2fc34ccaf0..4df3ff5740 100644 --- a/libraries/plugins/import/ImportXml.class.php +++ b/libraries/plugins/import/ImportXml.class.php @@ -35,21 +35,21 @@ class ImportXml extends ImportPlugin * * @var type String */ - private $db = null; + private $_db = null; /** * * * @var type */ - private $table = null; + private $_table = null; /** * * * @var type */ - private $tables = null; + private $_tables = null; /** * Constructor @@ -421,7 +421,7 @@ class ImportXml extends ImportPlugin */ public function getDb() { - return $this->db; + return $this->_db; } /** @@ -433,26 +433,26 @@ class ImportXml extends ImportPlugin */ public function setDb($db) { - $this->db = $db; + $this->_db = $db; } private function getTable() { - return $this->table; + return $this->_table; } private function setTable($table) { - $this->table = $table; + $this->_table = $table; } private function getTables() { - return $this->tables; + return $this->_tables; } private function setTables($tables) { - $this->tables = $tables; + $this->_tables = $tables; } } \ No newline at end of file From ff930b788ad5f066e34d1e0a214963ba143d6b3a Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 9 Jun 2012 12:38:44 +0300 Subject: [PATCH 11/55] oop: modify PMA_getTableDef and PMA_getTableDefStandIn usage --- db_operations.php | 14 +++++++++++--- libraries/Table.class.php | 23 ++++++++++++++++------- libraries/Tracker.class.php | 13 +++++++++++-- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/db_operations.php b/db_operations.php index 5a04bde59c..7253f28d4f 100644 --- a/db_operations.php +++ b/db_operations.php @@ -132,11 +132,19 @@ 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); } @@ -154,7 +162,7 @@ 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/libraries/Table.class.php b/libraries/Table.class.php index d89314ce13..53f1c3c93a 100644 --- a/libraries/Table.class.php +++ b/libraries/Table.class.php @@ -794,12 +794,21 @@ class PMA_Table // do not create the table if dataonly if ($what != 'dataonly') { - 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) + ) + ); $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); @@ -990,11 +999,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_query_as_controluser($comments_copy_query); // Write every comment as new copied entry. [MIME] diff --git a/libraries/Tracker.class.php b/libraries/Tracker.class.php index 6fe1cea524..02c784c5d1 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 From b190d924d39c9114980af4841ec2dd52fc750156 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 9 Jun 2012 13:10:09 +0300 Subject: [PATCH 12/55] oop: exportDBHeader coding style --- libraries/plugins/export/ExportCodegen.class.php | 3 ++- libraries/plugins/export/ExportCsv.class.php | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/libraries/plugins/export/ExportCodegen.class.php b/libraries/plugins/export/ExportCodegen.class.php index 7d8bb5a534..4d1813ad2b 100644 --- a/libraries/plugins/export/ExportCodegen.class.php +++ b/libraries/plugins/export/ExportCodegen.class.php @@ -149,7 +149,8 @@ class ExportCodegen extends ExportPlugin * * @return bool Whether it succeeded */ - public function exportDBHeader ($db) { + public function exportDBHeader ($db) + { return true; } diff --git a/libraries/plugins/export/ExportCsv.class.php b/libraries/plugins/export/ExportCsv.class.php index d4bdb84dcc..996893004e 100644 --- a/libraries/plugins/export/ExportCsv.class.php +++ b/libraries/plugins/export/ExportCsv.class.php @@ -240,7 +240,8 @@ class ExportCsv extends ExportPlugin * * @return bool Whether it succeeded */ - public function exportDBHeader ($db) { + public function exportDBHeader ($db) + { return true; } From 09f1ae13bd09a2731d5349ecd62dda95af0ce909 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 9 Jun 2012 13:10:46 +0300 Subject: [PATCH 13/55] oop: ExportHtmlWord --- libraries/plugins/ExportPlugin.class.php | 44 +- .../plugins/export/ExportHtmlword.class.php | 685 ++++++++++++++++++ 2 files changed, 727 insertions(+), 2 deletions(-) create mode 100644 libraries/plugins/export/ExportHtmlword.class.php diff --git a/libraries/plugins/ExportPlugin.class.php b/libraries/plugins/ExportPlugin.class.php index 4d8ac9dd2d..62bc132715 100644 --- a/libraries/plugins/ExportPlugin.class.php +++ b/libraries/plugins/ExportPlugin.class.php @@ -112,8 +112,8 @@ abstract class ExportPlugin extends PluginObserver /** - * The following methods are used in export.php, but they are not - * implemented by all export plugins + * The following methods are used in export.php or in db_operations.php, + * but they are not implemented by all export plugins */ @@ -165,6 +165,46 @@ abstract class ExportPlugin extends PluginObserver ; } + /** + * Returns a stand-in CREATE definition to resolve view dependencies + * + * @param string $db the database name + * @param string $view the view name + * @param string $crlf the end of line sequence + * + * @return string resulting definition + */ + public function getTableDefStandIn($db, $view, $crlf) + { + ; + } + + /** + * Outputs triggers + * + * @param string $db database name + * @param string $table table name + * + * @return string Formatted triggers list + */ + protected function getTriggers($db, $table) + { + ; + } + + /** + * Formats the definition for one column + * + * @param array $column info about this column + * @param array $unique_keys unique keys of the table + * + * @return string Formatted column definition + */ + protected function formatOneColumnDefinition( + $column, $unique_keys + ) { + ; + } /** * Initializes the local variables with the global values. diff --git a/libraries/plugins/export/ExportHtmlword.class.php b/libraries/plugins/export/ExportHtmlword.class.php new file mode 100644 index 0000000000..cddcbadc90 --- /dev/null +++ b/libraries/plugins/export/ExportHtmlword.class.php @@ -0,0 +1,685 @@ +setProperties(); + } + + /** + * Initialize the local variables that are used for export HTML-Word + * + * @return void + */ + private function initLocalVariables() + { + global $charset_of_file; + global $what; + + $this->setCharsetOfFile($charset_of_file); + $this->setWhat($what); + } + + /** + * Sets the export HTML-Word properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('Microsoft Word 2000'), + 'extension' => 'doc', + 'mime_type' => 'application/vnd.ms-word', + 'force_file' => true, + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + /* what to dump (structure/data/both) */ + array( + 'type' => 'begin_group', + 'name' => 'dump_what', + 'text' => __('Dump table') + ), + array( + 'type' => 'radio', + 'name' => 'structure_or_data', + 'values' => array( + 'structure' => __('structure'), + 'data' => __('data'), + 'structure_and_data' => __('structure and data') + ) + ), + array( + 'type' => 'end_group' + ), + + /* data options */ + array( + 'type' => 'begin_group', + 'name' => 'data', + 'text' => __('Data dump options'), + 'force' => 'structure' + ), + array( + 'type' => 'text', + 'name' => 'null', + 'text' => __('Replace NULL with:') + ), + array( + 'type' => 'bool', + 'name' => 'columns', + 'text' => __('Put columns names in the first row') + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + // initialize the general export variables + $this->initExportCommonVariables(); + + // initialize the specific export sql variables + $this->initLocalVariables(); + + return PMA_exportOutputHandler( + ' + + + + + + + ' + ); + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + return PMA_exportOutputHandler(''); + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + return PMA_exportOutputHandler( + '

' . __('Database') . ' ' . htmlspecialchars($db) . '

' + ); + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + return true; + } + + /** + * Outputs the content of a table in HTML-Word 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $what = $this->getWhat(); + + if (! PMA_exportOutputHandler( + '

' + . __('Dumping data for table') . ' ' . htmlspecialchars($table) + . '

' + )) { + return false; + } + if (! PMA_exportOutputHandler( + '' + )) { + return false; + } + + // Gets the data from the database + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + $fields_cnt = PMA_DBI_num_fields($result); + + // If required, get fields name at the first line + if (isset($GLOBALS['htmlword_columns'])) { + $schema_insert = ''; + for ($i = 0; $i < $fields_cnt; $i++) { + $schema_insert .= ''; + } // end for + $schema_insert .= ''; + if (! PMA_exportOutputHandler($schema_insert)) { + return false; + } + } // end if + + // Format the data + while ($row = PMA_DBI_fetch_row($result)) { + $schema_insert = ''; + for ($j = 0; $j < $fields_cnt; $j++) { + if (! isset($row[$j]) || is_null($row[$j])) { + $value = $GLOBALS[$what . '_null']; + } elseif ($row[$j] == '0' || $row[$j] != '') { + $value = $row[$j]; + } else { + $value = ''; + } + $schema_insert .= ''; + } // end for + $schema_insert .= ''; + if (! PMA_exportOutputHandler($schema_insert)) { + return false; + } + } // end while + PMA_DBI_free_result($result); + if (! PMA_exportOutputHandler('
')) { + return false; + } + + return true; + } + + /** + * Returns a stand-in CREATE definition to resolve view dependencies + * + * @param string $db the database name + * @param string $view the view name + * @param string $crlf the end of line sequence + * + * @return string resulting definition + */ + public function getTableDefStandIn($db, $view, $crlf) + { + $schema_insert = '' + . '' + . '' + . '' + . '' + . '' + . ''; + + /** + * Get the unique keys in the table + */ + $unique_keys = array(); + $keys = PMA_DBI_get_table_indexes($db, $table); + foreach ($keys as $key) { + if ($key['Non_unique'] == 0) { + $unique_keys[] = $key['Column_name']; + } + } + + $columns = PMA_DBI_get_columns($db, $view); + foreach ($columns as $column) { + $schema_insert .= $this->formatOneColumnDefinition($column, $unique_keys); + $schema_insert .= ''; + } + + $schema_insert .= '
'; + return $schema_insert; + } + + /** + * Returns $table's CREATE definition + * + * @param string $db the database name + * @param string $table the table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param bool $do_relation whether to include relation comments + * @param bool $do_comments whether to include the pmadb-style column + * comments as comments in the structure; + * this is deprecated but the parameter is + * left here because export.php calls + * PMA_exportStructure() also for other + * export types which use this parameter + * @param bool $do_mime whether to include mime comments + * @param bool $show_dates whether to include creation/update/check dates + * @param bool $add_semicolon whether to add semicolon and end-of-line + * at the end + * @param bool $view whether we're handling a view + * + * @return string resulting schema + * + * @access public + */ + function getTableDef( + $db, + $table, + $crlf, + $error_url, + $do_relation, + $do_comments, + $do_mime, + $show_dates = false, + $add_semicolon = true, + $view = false + ) { + global $cfgRelation; + + $schema_insert = ''; + + /** + * Gets fields properties + */ + PMA_DBI_select_db($db); + + // Check if we can use Relations + if ($do_relation && ! empty($cfgRelation['relation'])) { + // Find which tables are related with the current one and write it in + // an array + $res_rel = PMA_getForeigners($db, $table); + + if ($res_rel && count($res_rel) > 0) { + $have_rel = true; + } else { + $have_rel = false; + } + } else { + $have_rel = false; + } // end if + + /** + * Displays the table structure + */ + $schema_insert .= ''; + + $columns_cnt = 4; + if ($do_relation && $have_rel) { + $columns_cnt++; + } + if ($do_comments && $cfgRelation['commwork']) { + $columns_cnt++; + } + if ($do_mime && $cfgRelation['mimework']) { + $columns_cnt++; + } + + $schema_insert .= ''; + $schema_insert .= ''; + $schema_insert .= ''; + $schema_insert .= ''; + $schema_insert .= ''; + if ($do_relation && $have_rel) { + $schema_insert .= ''; + } + if ($do_comments) { + $schema_insert .= ''; + $comments = PMA_getComments($db, $table); + } + if ($do_mime && $cfgRelation['mimework']) { + $schema_insert .= ''; + $mime_map = PMA_getMIME($db, $table, true); + } + $schema_insert .= ''; + + $columns = PMA_DBI_get_columns($db, $table); + /** + * Get the unique keys in the table + */ + $unique_keys = array(); + $keys = PMA_DBI_get_table_indexes($db, $table); + foreach ($keys as $key) { + if ($key['Non_unique'] == 0) { + $unique_keys[] = $key['Column_name']; + } + } + foreach ($columns as $column) { + $schema_insert .= $this->formatOneColumnDefinition($column, $unique_keys); + $field_name = $column['Field']; + + if ($do_relation && $have_rel) { + $schema_insert .= ''; + } + if ($do_comments && $cfgRelation['commwork']) { + $schema_insert .= ''; + } + if ($do_mime && $cfgRelation['mimework']) { + $schema_insert .= ''; + } + + $schema_insert .= ''; + } // end foreach + + $schema_insert .= '
' + . (isset($res_rel[$field_name]) + ? htmlspecialchars( + $res_rel[$field_name]['foreign_table'] + . ' (' . $res_rel[$field_name]['foreign_field'] + . ')' + ) + : '') . '' + . (isset($comments[$field_name]) + ? htmlspecialchars($comments[$field_name]) + : '') . '' + . (isset($mime_map[$field_name]) ? + htmlspecialchars( + str_replace('_', '/', $mime_map[$field_name]['mimetype']) + ) + : '') . '
'; + return $schema_insert; + } // end of the 'PMA_getTableDef()' function + + /** + * Outputs triggers + * + * @param string $db database name + * @param string $table table name + * + * @return string Formatted triggers list + */ + protected function getTriggers($db, $table) + { + $dump = ''; + $dump .= ''; + $dump .= ''; + $dump .= ''; + $dump .= ''; + $dump .= ''; + $dump .= ''; + + $triggers = PMA_DBI_get_triggers($db, $table); + + foreach ($triggers as $trigger) { + $dump .= ''; + $dump .= '' + . '' + . '' + . '' + . ''; + } + + $dump .= '
'; + return $dump; + } + + /** + * 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 + */ + function exportStructure( + $db, + $table, + $crlf, + $error_url, + $export_mode, + $export_type, + $do_relation = false, + $do_comments = false, + $do_mime = false, + $dates = false + ) { + $dump = ''; + + switch($export_mode) { + case 'create_table': + $dump .= '

' + . __('Table structure for table') . ' ' . htmlspecialchars($table) + . '

'; + $dump .= $this->getTableDef( + $db, $table, $crlf, $error_url, $do_relation, $do_comments, $do_mime, + $dates + ); + break; + case 'triggers': + $dump = ''; + $triggers = PMA_DBI_get_triggers($db, $table); + if ($triggers) { + $dump .= '

' + . __('Triggers') . ' ' . htmlspecialchars($table) + . '

'; + $dump .= $this->getTriggers($db, $table); + } + break; + case 'create_view': + $dump .= '

' + . __('Structure for view') . ' ' . htmlspecialchars($table) + . '

'; + $dump .= $this->getTableDef( + $db, $table, $crlf, $error_url, $do_relation, $do_comments, $do_mime, + $dates, true, true + ); + break; + case 'stand_in': + $dump .= '

' + . __('Stand-in structure for view') . ' ' . htmlspecialchars($table) + . '

'; + // export a stand-in definition to resolve view dependencies + $dump .= $this->getTableDefStandIn($db, $table, $crlf); + } // end switch + + return PMA_exportOutputHandler($dump); + } + + /** + * Formats the definition for one column + * + * @param array $column info about this column + * @param array $unique_keys unique keys of the table + * + * @return string Formatted column definition + */ + protected function formatOneColumnDefinition( + $column, $unique_keys + ) { + $definition = ''; + $extracted_columnspec = PMA_extractColumnSpec($column['Type']); + $type = htmlspecialchars($extracted_columnspec['print_type']); + if (empty($type)) { + $type = ' '; + } + + if (! isset($column['Default'])) { + if ($column['Null'] != 'NO') { + $column['Default'] = 'NULL'; + } + } + + $fmt_pre = ''; + $fmt_post = ''; + if (in_array($column['Field'], $unique_keys)) { + $fmt_pre = '' . $fmt_pre; + $fmt_post = $fmt_post . ''; + } + if ($column['Key'] == 'PRI') { + $fmt_pre = '' . $fmt_pre; + $fmt_post = $fmt_post . ''; + } + $definition .= '' . $fmt_pre + . htmlspecialchars($column['Field']) . $fmt_post . ''; + $definition .= '' . htmlspecialchars($type) + . ''; + $definition .= '' + . (($column['Null'] == '' || $column['Null'] == 'NO') + ? __('No') + : __('Yes')) + . ''; + $definition .= '' + . htmlspecialchars( + isset($column['Default']) + ? $column['Default'] + : '' + ) + . ''; + + return $definition; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + public function getWhat() + { + return $this->_what; + } + + public function setWhat($what) + { + $this->_what = $what; + } + + public function getCharsetOfFile() + { + return $this->_charsetOfFile; + } + + public function setCharsetOfFile($charsetOfFile) + { + $this->_charsetOfFile = $charsetOfFile; + } +} +?> \ No newline at end of file From bdf17eee3286428ea96dedfb043c3b89e9c679e2 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 9 Jun 2012 16:04:36 +0300 Subject: [PATCH 14/55] oop: ExportJson --- libraries/plugins/export/ExportJson.class.php | 220 ++++++++++++++++++ 1 file changed, 220 insertions(+) create mode 100644 libraries/plugins/export/ExportJson.class.php diff --git a/libraries/plugins/export/ExportJson.class.php b/libraries/plugins/export/ExportJson.class.php new file mode 100644 index 0000000000..4fa6e19d9d --- /dev/null +++ b/libraries/plugins/export/ExportJson.class.php @@ -0,0 +1,220 @@ +setProperties(); + } + + /** + * Sets the export JSON properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => 'JSON', + 'extension' => 'json', + 'mime_type' => 'text/plain', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'hidden', + 'name' => 'structure_or_data', + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + // initialize the general export variables + $this->initExportCommonVariables(); + + PMA_exportOutputHandler( + '/**' . $GLOBALS['crlf'] + . ' Export to JSON plugin for PHPMyAdmin' . $GLOBALS['crlf'] + . ' @version 0.1' . $GLOBALS['crlf'] + . ' */' . $GLOBALS['crlf'] . $GLOBALS['crlf'] + ); + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + PMA_exportOutputHandler('// Database \'' . $db . '\'' . $GLOBALS['crlf']); + return true; + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + return true; + } + + /** + * Outputs the content of a table in CSV 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + $columns_cnt = PMA_DBI_num_fields($result); + + // Get field information + $fields_meta = PMA_DBI_get_fields_meta($result); + + for ($i = 0; $i < $columns_cnt; $i++) { + $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); + } + unset($i); + + $buffer = ''; + $record_cnt = 0; + while ($record = PMA_DBI_fetch_row($result)) { + + $record_cnt++; + + // Output table name as comment if this is the first record of the table + if ($record_cnt == 1) { + $buffer .= '// ' . $db . '.' . $table . $crlf . $crlf; + $buffer .= '[{'; + } else { + $buffer .= ', {'; + } + + for ($i = 0; $i < $columns_cnt; $i++) { + + $isLastLine = ($i + 1 >= $columns_cnt); + + $column = $columns[$i]; + + if (is_null($record[$i])) { + $buffer .= '"' . addslashes($column) + . '": null' + . (! $isLastLine ? ',' : ''); + } elseif ($fields_meta[$i]->numeric) { + $buffer .= '"' . addslashes($column) + . '": ' + . $record[$i] + . (! $isLastLine ? ',' : ''); + } else { + $buffer .= '"' . addslashes($column) + . '": "' + . addslashes($record[$i]) + . '"' + . (! $isLastLine ? ',' : ''); + } + } + + $buffer .= '}'; + } + + if ($record_cnt) { + $buffer .= ']'; + } + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + PMA_DBI_free_result($result); + + return true; + } +} +?> \ No newline at end of file From 4b0dbf6a428e710a232f91ee9f0322f689c962b1 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 15 Jun 2012 19:22:07 +0300 Subject: [PATCH 15/55] oop: ExportLatex --- export.php | 4 +- libraries/common.lib.php | 31 +- .../plugins/export/ExportCodegen.class.php | 4 +- .../plugins/export/ExportLatex.class.php | 687 ++++++++++++++++++ 4 files changed, 717 insertions(+), 9 deletions(-) create mode 100644 libraries/plugins/export/ExportLatex.class.php diff --git a/export.php b/export.php index cc9cb44671..c049a6dd1a 100644 --- a/export.php +++ b/export.php @@ -496,7 +496,7 @@ do { if (! $export_plugin->exportDBCreate($current_db)) { break 2; } - if (function_exists('$export_plugin->exportRoutines') + if (method_exists($export_plugin, 'exportRoutines') && strpos($GLOBALS['sql_structure_or_data'], 'structure') !== false && isset($GLOBALS['sql_procedure_function']) ) { @@ -574,7 +574,7 @@ do { break; } - if (function_exists('$export_plugin->exportRoutines') + if (method_exists($export_plugin, 'exportRoutines') && strpos($GLOBALS['sql_structure_or_data'], 'structure') !== false && isset($GLOBALS['sql_procedure_function']) ) { diff --git a/libraries/common.lib.php b/libraries/common.lib.php index 7f0aa5c207..8bcea0b31c 100644 --- a/libraries/common.lib.php +++ b/libraries/common.lib.php @@ -3202,13 +3202,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']; @@ -3248,7 +3254,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); + } } } @@ -3264,7 +3276,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']; } diff --git a/libraries/plugins/export/ExportCodegen.class.php b/libraries/plugins/export/ExportCodegen.class.php index 4d1813ad2b..45ac3a53f4 100644 --- a/libraries/plugins/export/ExportCodegen.class.php +++ b/libraries/plugins/export/ExportCodegen.class.php @@ -342,7 +342,7 @@ class ExportCodegen extends ExportPlugin return $this->_CG_FORMATS; } - public function setCG_FORMATS($CG_FORMATS) + private function setCG_FORMATS($CG_FORMATS) { $this->_CG_FORMATS = $CG_FORMATS; } @@ -352,7 +352,7 @@ class ExportCodegen extends ExportPlugin return $this->_CG_HANDLERS; } - public function setCG_HANDLERS($CG_HANDLERS) + private function setCG_HANDLERS($CG_HANDLERS) { $this->_CG_HANDLERS = $CG_HANDLERS; } diff --git a/libraries/plugins/export/ExportLatex.class.php b/libraries/plugins/export/ExportLatex.class.php new file mode 100644 index 0000000000..7be7ba5b5a --- /dev/null +++ b/libraries/plugins/export/ExportLatex.class.php @@ -0,0 +1,687 @@ +initLocalVariables(); + + $this->setProperties(); + } + + /** + * Initialize the local variables that are used for export Latex + * + * @return void + */ + private function initLocalVariables() + { + global $plugin_param; + global $cfgRelation; + $this->setPluginParam($plugin_param); + $this->setCfgRelation($cfgRelation); + + /* Messages used in default captions */ + $GLOBALS['strLatexContent'] = __('Content of table @TABLE@'); + $GLOBALS['strLatexContinued'] = __('(continued)'); + $GLOBALS['strLatexStructure'] = __('Structure of table @TABLE@'); + } + + /** + * Sets the export Latex properties + * + * @return void + */ + protected function setProperties() + { + $plugin_param = $this->getPluginParam(); + $hide_structure = false; + if ($plugin_param['export_type'] == 'table' + && ! $plugin_param['single_table'] + ) { + $hide_structure = true; + } + + $this->properties = array( + 'text' => __('LaTeX'), + 'extension' => 'tex', + 'mime_type' => 'application/x-tex', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'bool', + 'name' => 'caption', + 'text' => __('Include table caption') + ), + array( + 'type' => 'end_group' + ) + ); + + /* what to dump (structure/data/both) */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'dump_what', + 'text' => __('Dump table') + ); + $this->properties['options'][] = array( + 'type' => 'radio', + 'name' => 'structure_or_data', + 'values' => array( + 'structure' => __('structure'), + 'data' => __('data'), + 'structure_and_data' => __('structure and data') + ) + ); + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + + /* Structure options */ + if (! $hide_structure) { + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'structure', + 'text' => __('Object creation options'), + 'force' => 'data' + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'structure_caption', + 'text' => __('Table caption'), + 'doc' => 'faq6_27' + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'structure_continued_caption', + 'text' => __('Table caption (continued)'), + 'doc' => 'faq6_27' + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'structure_label', + 'text' => __('Label key'), + 'doc' => 'faq6_27' + ); + if (! empty($GLOBALS['cfgRelation']['relation'])) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'relation', + 'text' => __('Display foreign key relationships') + ); + } + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'comments', + 'text' => __('Display comments') + ); + if (! empty($GLOBALS['cfgRelation']['mimework'])) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'mime', + 'text' => __('Display MIME types') + ); + } + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + + /* Data */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'data', + 'text' => __('Data dump options'), + 'force' => 'structure' + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'columns', + 'text' => __('Put columns names in the first row') + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'data_caption', + 'text' => __('Table caption'), + 'doc' => 'faq6_27' + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'data_continued_caption', + 'text' => __('Table caption (continued)'), + 'doc' => 'faq6_27' + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'data_label', + 'text' => __('Label key'), + 'doc' => 'faq6_27' + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'null', + 'text' => __('Replace NULL with:') + ); + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + // initialize the general export variables + $this->initExportCommonVariables(); + + $crlf = $this->getCrlf(); + $cfg = $this->getCfg(); + + $head = '% phpMyAdmin LaTeX Dump' . $crlf + . '% version ' . PMA_VERSION . $crlf + . '% http://www.phpmyadmin.net' . $crlf + . '%' . $crlf + . '% ' . __('Host') . ': ' . $cfg['Server']['host']; + if (! empty($cfg['Server']['port'])) { + $head .= ':' . $cfg['Server']['port']; + } + $head .= $crlf + . '% ' . __('Generation Time') . ': ' . PMA_localisedDate() . $crlf + . '% ' . __('Server version') . ': ' . PMA_MYSQL_STR_VERSION . $crlf + . '% ' . __('PHP Version') . ': ' . phpversion() . $crlf; + return PMA_exportOutputHandler($head); + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + $crlf = $this->getCrlf(); + $head = '% ' . $crlf + . '% ' . __('Database') . ': ' . '\'' . $db . '\'' . $crlf + . '% ' . $crlf; + return PMA_exportOutputHandler($head); + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + return true; + } + + /** + * Outputs the content of a table in JSON 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + + $columns_cnt = PMA_DBI_num_fields($result); + for ($i = 0; $i < $columns_cnt; $i++) { + $columns[$i] = PMA_DBI_field_name($result, $i); + } + unset($i); + + $buffer = $crlf . '%' . $crlf . '% ' . __('Data') . ': ' . $table + . $crlf . '%' . $crlf . ' \\begin{longtable}{|'; + + for ($index = 0; $index < $columns_cnt; $index++) { + $buffer .= 'l|'; + } + $buffer .= '} ' . $crlf ; + + $buffer .= ' \\hline \\endhead \\hline \\endfoot \\hline ' . $crlf; + if (isset($GLOBALS['latex_caption'])) { + $buffer .= ' \\caption{' + . PMA_expandUserString( + $GLOBALS['latex_data_caption'], + 'texEscape', + get_class($this), + array('table' => $table, 'database' => $db) + ) + . '} \\label{' + . PMA_expandUserString( + $GLOBALS['latex_data_label'], + null, + null, + array('table' => $table, 'database' => $db) + ) + . '} \\\\'; + } + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + // show column names + if (isset($GLOBALS['latex_columns'])) { + $buffer = '\\hline '; + for ($i = 0; $i < $columns_cnt; $i++) { + $buffer .= '\\multicolumn{1}{|c|}{\\textbf{' + . $this::texEscape(stripslashes($columns[$i])) . '}} & '; + } + + $buffer = substr($buffer, 0, -2) . '\\\\ \\hline \hline '; + if (! PMA_exportOutputHandler($buffer . ' \\endfirsthead ' . $crlf)) { + return false; + } + if (isset($GLOBALS['latex_caption'])) { + if (! PMA_exportOutputHandler( + '\\caption{' + . PMA_expandUserString( + $GLOBALS['latex_data_continued_caption'], + 'texEscape', + get_class($this), + array('table' => $table, 'database' => $db) + ) + . '} \\\\ ' + )) { + return false; + } + } + if (! PMA_exportOutputHandler($buffer . '\\endhead \\endfoot' . $crlf)) { + return false; + } + } else { + if (! PMA_exportOutputHandler('\\\\ \hline')) { + return false; + } + } + + // print the whole table + while ($record = PMA_DBI_fetch_assoc($result)) { + + $buffer = ''; + // print each row + for ($i = 0; $i < $columns_cnt; $i++) { + if ((! function_exists('is_null') + || ! is_null($record[$columns[$i]])) + && isset($record[$columns[$i]]) + ) { + $column_value = $this::texEscape( + stripslashes($record[$columns[$i]]) + ); + } else { + $column_value = $GLOBALS['latex_null']; + } + + // last column ... no need for & character + if ($i == ($columns_cnt - 1)) { + $buffer .= $column_value; + } else { + $buffer .= $column_value . " & "; + } + } + $buffer .= ' \\\\ \\hline ' . $crlf; + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + } + + $buffer = ' \\end{longtable}' . $crlf; + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + PMA_DBI_free_result($result); + return true; + } // end getTableLaTeX + + /** + * 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 + * 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 + */ + function exportStructure( + $db, + $table, + $crlf, + $error_url, + $export_mode, + $export_type, + $do_relation = false, + $do_comments = false, + $do_mime = false, + $dates = false + ) { + global $cfgRelation; + $this->setCfgRelation($cfgRelation); + + /** + * Get the unique keys in the table + */ + $unique_keys = array(); + $keys = PMA_DBI_get_table_indexes($db, $table); + foreach ($keys as $key) { + if ($key['Non_unique'] == 0) { + $unique_keys[] = $key['Column_name']; + } + } + + /** + * Gets fields properties + */ + PMA_DBI_select_db($db); + + // Check if we can use Relations + if ($do_relation && ! empty($cfgRelation['relation'])) { + // Find which tables are related with the current one and write it in + // an array + $res_rel = PMA_getForeigners($db, $table); + + if ($res_rel && count($res_rel) > 0) { + $have_rel = true; + } else { + $have_rel = false; + } + } else { + $have_rel = false; + } // end if + + /** + * Displays the table structure + */ + $buffer = $crlf . '%' . $crlf . '% ' . __('Structure') . ': ' . $table + . $crlf . '%' . $crlf . ' \\begin{longtable}{'; + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + $columns_cnt = 4; + $alignment = '|l|c|c|c|'; + if ($do_relation && $have_rel) { + $columns_cnt++; + $alignment .= 'l|'; + } + if ($do_comments) { + $columns_cnt++; + $alignment .= 'l|'; + } + if ($do_mime && $cfgRelation['mimework']) { + $columns_cnt++; + $alignment .='l|'; + } + $buffer = $alignment . '} ' . $crlf ; + + $header = ' \\hline '; + $header .= '\\multicolumn{1}{|c|}{\\textbf{' . __('Column') + . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Type') + . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Null') + . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Default') . '}}'; + if ($do_relation && $have_rel) { + $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Links to') . '}}'; + } + if ($do_comments) { + $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Comments') . '}}'; + $comments = PMA_getComments($db, $table); + } + if ($do_mime && $cfgRelation['mimework']) { + $header .= ' & \\multicolumn{1}{|c|}{\\textbf{MIME}}'; + $mime_map = PMA_getMIME($db, $table, true); + } + + // Table caption for first page and label + if (isset($GLOBALS['latex_caption'])) { + $buffer .= ' \\caption{' + . PMA_expandUserString( + $GLOBALS['latex_structure_caption'], + 'texEscape', + get_class($this), + array('table' => $table, 'database' => $db) + ) + . '} \\label{' + . PMA_expandUserString( + $GLOBALS['latex_structure_label'], + null, + null, + array('table' => $table, 'database' => $db) + ) + . '} \\\\' . $crlf; + } + $buffer .= $header . ' \\\\ \\hline \\hline' . $crlf + . '\\endfirsthead' . $crlf; + // Table caption on next pages + if (isset($GLOBALS['latex_caption'])) { + $buffer .= ' \\caption{' + . PMA_expandUserString( + $GLOBALS['latex_structure_continued_caption'], + 'texEscape', + get_class($this), + array('table' => $table, 'database' => $db) + ) + . '} \\\\ ' . $crlf; + } + $buffer .= $header . ' \\\\ \\hline \\hline \\endhead \\endfoot ' . $crlf; + + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + $fields = PMA_DBI_get_columns($db, $table); + foreach ($fields as $row) { + $extracted_columnspec = PMA_extractColumnSpec($row['Type']); + $type = $extracted_columnspec['print_type']; + if (empty($type)) { + $type = ' '; + } + + if (! isset($row['Default'])) { + if ($row['Null'] != 'NO') { + $row['Default'] = 'NULL'; + } + } + + $field_name = $row['Field']; + + $local_buffer = $field_name . "\000" . $type . "\000" + . (($row['Null'] == '' || $row['Null'] == 'NO') + ? __('No') : __('Yes')) + . "\000" . (isset($row['Default']) ? $row['Default'] : ''); + + if ($do_relation && $have_rel) { + $local_buffer .= "\000"; + if (isset($res_rel[$field_name])) { + $local_buffer .= $res_rel[$field_name]['foreign_table'] . ' (' + . $res_rel[$field_name]['foreign_field'] . ')'; + } + } + if ($do_comments && $cfgRelation['commwork']) { + $local_buffer .= "\000"; + if (isset($comments[$field_name])) { + $local_buffer .= $comments[$field_name]; + } + } + if ($do_mime && $cfgRelation['mimework']) { + $local_buffer .= "\000"; + if (isset($mime_map[$field_name])) { + $local_buffer .= str_replace( + '_', + '/', + $mime_map[$field_name]['mimetype'] + ); + } + } + $local_buffer = $this::texEscape($local_buffer); + if ($row['Key']=='PRI') { + $pos=strpos($local_buffer, "\000"); + $local_buffer = '\\textit{' + . substr($local_buffer, 0, $pos) + . '}' . substr($local_buffer, $pos); + } + if (in_array($field_name, $unique_keys)) { + $pos=strpos($local_buffer, "\000"); + $local_buffer = '\\textbf{' + . substr($local_buffer, 0, $pos) + . '}' . substr($local_buffer, $pos); + } + $buffer = str_replace("\000", ' & ', $local_buffer); + $buffer .= ' \\\\ \\hline ' . $crlf; + + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + } // end while + + $buffer = ' \\end{longtable}' . $crlf; + return PMA_exportOutputHandler($buffer); + } // end of the 'exportStructure' method + + /** + * Escapes some special characters for use in TeX/LaTeX + * + * @param string $string the string to convert + * + * @return string the converted string with escape codes + */ + public static function texEscape($string) + { + $escape = array('$', '%', '{', '}', '&', '#', '_', '^'); + $cnt_escape = count($escape); + for ($k = 0; $k < $cnt_escape; $k++) { + $string = str_replace($escape[$k], '\\' . $escape[$k], $string); + } + return $string; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + public function getPluginParam() + { + return $this->_pluginParam; + } + + private function setPluginParam($pluginParam) + { + $this->_pluginParam = $pluginParam; + } + + public function getCfgRelation() + { + return $this->_cfgRelation; + } + + private function setCfgRelation($cfgRelation) + { + $this->_cfgRelation = $cfgRelation; + } +} +?> \ No newline at end of file From b5f2788aded7b505bbd529b36aa8b7c6424c9d54 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 15 Jun 2012 22:55:19 +0300 Subject: [PATCH 16/55] oop: ExportMediawiki --- .../plugins/export/ExportLatex.class.php | 2 +- .../plugins/export/ExportMediawiki.class.php | 359 ++++++++++++++++++ 2 files changed, 360 insertions(+), 1 deletion(-) create mode 100644 libraries/plugins/export/ExportMediawiki.class.php diff --git a/libraries/plugins/export/ExportLatex.class.php b/libraries/plugins/export/ExportLatex.class.php index 7be7ba5b5a..1ee4cc540d 100644 --- a/libraries/plugins/export/ExportLatex.class.php +++ b/libraries/plugins/export/ExportLatex.class.php @@ -463,7 +463,7 @@ class ExportLatex extends ExportPlugin ) { global $cfgRelation; $this->setCfgRelation($cfgRelation); - + /** * Get the unique keys in the table */ diff --git a/libraries/plugins/export/ExportMediawiki.class.php b/libraries/plugins/export/ExportMediawiki.class.php new file mode 100644 index 0000000000..477df634e2 --- /dev/null +++ b/libraries/plugins/export/ExportMediawiki.class.php @@ -0,0 +1,359 @@ +setProperties(); + } + + /** + * Sets the export XML properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('MediaWiki Table'), + 'extension' => 'mediawiki', + 'mime_type' => 'text/plain', + 'options' => array(), + 'options_text' => __('Options') + ); + + // general options + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ); + + // what to dump (structure/data/both) + $this->properties['options'][] = array( + 'type' => 'begin_subgroup', + 'subgroup_header' => array( + 'type' => 'message_only', + 'text' => __('Dump table') + ) + ); + $this->properties['options'][] = array( + 'type' => 'radio', + 'name' => 'structure_or_data', + 'values' => array( + 'structure' => __('structure'), + 'data' => __('data'), + 'structure_and_data' => __('structure and data') + ) + ); + $this->properties['options'][] = array( + 'type' => 'end_subgroup' + ); + + // export table name + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'caption', + 'text' => __('Export table names') + ); + + // export table headers + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'headers', + 'text' => __('Export table headers') + ); + + // end general options + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + return true; + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function 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 = $this->exportComment( + "Table structure for " + . PMA_backquote($table) + ); + + // Begin the table construction + $output .= "{| class=\"wikitable\" style=\"text-align:center;\"" + . $this->exportCRLF(); + + // Add the table name + if ($GLOBALS['mediawiki_caption']) { + $output .= "|+'''" . $table . "'''" . $this->exportCRLF(); + } + + // Add the table headers + if ($GLOBALS['mediawiki_headers']) { + $output .= "|- style=\"background:#ffdead;\"" . $this->exportCRLF(); + $output .= "! style=\"background:#ffffff\" | " . $this->exportCRLF(); + for ($i = 0; $i < $row_cnt; ++$i) { + $output .= " | " . $columns[$i]['Field']. $this->exportCRLF(); + } + } + + // Add the table structure + $output .= "|-" . $this->exportCRLF(); + $output .= "! Type" . $this->exportCRLF(); + for ($i = 0; $i < $row_cnt; ++$i) { + $output .= " | " . $columns[$i]['Type'] . $this->exportCRLF(); + } + + $output .= "|-" . $this->exportCRLF(); + $output .= "! Null" . $this->exportCRLF(); + for ($i = 0; $i < $row_cnt; ++$i) { + $output .= " | " . $columns[$i]['Null'] . $this->exportCRLF(); + } + + $output .= "|-" . $this->exportCRLF(); + $output .= "! Default" . $this->exportCRLF(); + for ($i = 0; $i < $row_cnt; ++$i) { + $output .= " | " . $columns[$i]['Default'] . $this->exportCRLF(); + } + + $output .= "|-" . $this->exportCRLF(); + $output .= "! Extra" . $this->exportCRLF(); + for ($i = 0; $i < $row_cnt; ++$i) { + $output .= " | " . $columns[$i]['Extra'] . $this->exportCRLF(); + } + + $output .= "|}" . str_repeat($this->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 exportData( + $db, + $table, + $crlf, + $error_url, + $sql_query + ) { + // Print data comment + $output = $this->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;\"" + . $this->exportCRLF(); + + // Add the table name + if ($GLOBALS['mediawiki_caption']) { + $output .= "|+'''" . $table . "'''" . $this->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 .= "|-" . $this->exportCRLF(); + + // Use '!' for separating table headers + foreach ($column_names as $column) { + $output .= " ! " . $column . "" . $this->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 .= "|-" . $this->exportCRLF(); + + // Use '|' for separating table columns + for ($i = 0; $i < $fields_cnt; ++ $i) { + $output .= " | " . $row[$i] . "" . $this->exportCRLF(); + } + } + + // End table construction + $output .= "|}" . str_repeat($this->exportCRLF(), 2); + return PMA_exportOutputHandler($output); + } + + /** + * Outputs comments containing info about the exported tables + * + * @param string $text Text of comment + * + * @return string The formatted comment + */ + private function exportComment($text = '') + { + // see http://www.mediawiki.org/wiki/Help:Formatting + $comment = $this->exportCRLF(); + $comment .= '' . str_repeat($this->exportCRLF(), 2); + + return $comment; + } + + /** + * Outputs CRLF + * + * @return string CRLF + */ + private function exportCRLF() + { + // The CRLF expected by the mediawiki format is "\n" + return "\n"; + } +} +?> \ No newline at end of file From fa004ee3c05e5670f1300ddd28594b89f6f82900 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 00:11:16 +0300 Subject: [PATCH 17/55] oop: ExportOds --- libraries/plugins/export/ExportOds.class.php | 358 +++++++++++++++++++ 1 file changed, 358 insertions(+) create mode 100644 libraries/plugins/export/ExportOds.class.php diff --git a/libraries/plugins/export/ExportOds.class.php b/libraries/plugins/export/ExportOds.class.php new file mode 100644 index 0000000000..6a94f39b85 --- /dev/null +++ b/libraries/plugins/export/ExportOds.class.php @@ -0,0 +1,358 @@ +initLocalVariables(); + + $this->setProperties(); + } + + /** + * Initialize the local variables that are used for export ODS + * + * @return void + */ + private function initLocalVariables() + { + global $what; + $this->setWhat($what); + } + + /** + * Sets the export XML properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('Open Document Spreadsheet'), + 'extension' => 'ods', + 'mime_type' => 'application/vnd.oasis.opendocument.spreadsheet', + 'force_file' => true, + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'text', + 'name' => 'null', + 'text' => __('Replace NULL with:') + ), + array( + 'type' => 'bool', + 'name' => 'columns', + 'text' => __('Put columns names in the first row') + ), + array( + 'type' => 'hidden', + 'name' => 'structure_or_data' + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + $GLOBALS['ods_buffer'] .= '' + . '' + . '' + . '' + . '' + . '/' + . '' + . '/' + . '' + . '' + . '' + . '' + . ':' + . '' + . ':' + . '' + . ' ' + . '' + . '' + . '' + . '' + . '/' + . '' + . '/' + . '' + . ' ' + . '' + . ':' + . '' + . ' ' + . '' + . '' + . '' + . '' + . '' + . '' + . '' + . ''; + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + $GLOBALS['ods_buffer'] .= '' + . '' + . ''; + if (! PMA_exportOutputHandler( + PMA_createOpenDocument( + 'application/vnd.oasis.opendocument.spreadsheet', + $GLOBALS['ods_buffer'] + ) + )) { + return false; + } + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + return true; + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $what = $this->getWhat(); + + // Gets the data from the database + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + $fields_cnt = PMA_DBI_num_fields($result); + $fields_meta = PMA_DBI_get_fields_meta($result); + $field_flags = array(); + for ($j = 0; $j < $fields_cnt; $j++) { + $field_flags[$j] = PMA_DBI_field_flags($result, $j); + } + + $GLOBALS['ods_buffer'] .= + ''; + + // If required, get fields name at the first line + if (isset($GLOBALS[$what . '_columns'])) { + $GLOBALS['ods_buffer'] .= ''; + for ($i = 0; $i < $fields_cnt; $i++) { + $GLOBALS['ods_buffer'] .= + '' + . '' + . htmlspecialchars( + stripslashes(PMA_DBI_field_name($result, $i)) + ) + . '' + . ''; + } // end for + $GLOBALS['ods_buffer'] .= ''; + } // end if + + // Format the data + while ($row = PMA_DBI_fetch_row($result)) { + $GLOBALS['ods_buffer'] .= ''; + for ($j = 0; $j < $fields_cnt; $j++) { + if (! isset($row[$j]) || is_null($row[$j])) { + $GLOBALS['ods_buffer'] .= + '' + . '' + . htmlspecialchars($GLOBALS[$what . '_null']) + . '' + . ''; + } elseif (stristr($field_flags[$j], 'BINARY') + && $fields_meta[$j]->blob + ) { + // ignore BLOB + $GLOBALS['ods_buffer'] .= + '' + . '' + . ''; + } elseif ($fields_meta[$j]->type == "date") { + $GLOBALS['ods_buffer'] .= + '' + . '' + . htmlspecialchars($row[$j]) + . '' + . ''; + } elseif ($fields_meta[$j]->type == "time") { + $GLOBALS['ods_buffer'] .= + '' + . '' + . htmlspecialchars($row[$j]) + . '' + . ''; + } elseif ($fields_meta[$j]->type == "datetime") { + $GLOBALS['ods_buffer'] .= + '' + . '' + . htmlspecialchars($row[$j]) + . '' + . ''; + } elseif ($fields_meta[$j]->numeric + && $fields_meta[$j]->type != 'timestamp' + && ! $fields_meta[$j]->blob + ) { + $GLOBALS['ods_buffer'] .= + '' + . '' + . htmlspecialchars($row[$j]) + . '' + . ''; + } else { + $GLOBALS['ods_buffer'] .= + '' + . '' + . htmlspecialchars($row[$j]) + . '' + . ''; + } + } // end for + $GLOBALS['ods_buffer'] .= ''; + } // end while + PMA_DBI_free_result($result); + + $GLOBALS['ods_buffer'] .= ''; + + return true; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + public function getWhat() + { + return $this->_what; + } + + public function setWhat($what) + { + $this->_what = $what; + } +} +?> \ No newline at end of file From 16252e4dbaee668ffae781f2028f27c263fbf20e Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 11:45:19 +0300 Subject: [PATCH 18/55] oop: ExportOdt --- libraries/plugins/ExportPlugin.class.php | 14 - libraries/plugins/export/ExportOdt.class.php | 797 +++++++++++++++++++ 2 files changed, 797 insertions(+), 14 deletions(-) create mode 100644 libraries/plugins/export/ExportOdt.class.php diff --git a/libraries/plugins/ExportPlugin.class.php b/libraries/plugins/ExportPlugin.class.php index 62bc132715..1410234dd6 100644 --- a/libraries/plugins/ExportPlugin.class.php +++ b/libraries/plugins/ExportPlugin.class.php @@ -192,20 +192,6 @@ abstract class ExportPlugin extends PluginObserver ; } - /** - * Formats the definition for one column - * - * @param array $column info about this column - * @param array $unique_keys unique keys of the table - * - * @return string Formatted column definition - */ - protected function formatOneColumnDefinition( - $column, $unique_keys - ) { - ; - } - /** * Initializes the local variables with the global values. * These are variables that are used by all of the export plugins. diff --git a/libraries/plugins/export/ExportOdt.class.php b/libraries/plugins/export/ExportOdt.class.php new file mode 100644 index 0000000000..8d2f382c38 --- /dev/null +++ b/libraries/plugins/export/ExportOdt.class.php @@ -0,0 +1,797 @@ +initLocalVariables(); + + $this->setProperties(); + } + + /** + * Initialize the local variables that are used for export ODT + * + * @return void + */ + private function initLocalVariables() + { + global $what; + global $plugin_param; + global $cfgRelation; + $this->setWhat($what); + $this->setPluginParam($plugin_param); + $this->setCfgRelation($cfgRelation); + } + + /** + * Sets the export XML properties + * + * @return void + */ + protected function setProperties() + { + $plugin_param = $this->getPluginParam(); + $hide_structure = false; + if ($plugin_param['export_type'] == 'table' + && ! $plugin_param['single_table'] + ) { + $hide_structure = true; + } + + $this->properties = array( + 'text' => __('Open Document Text'), + 'extension' => 'odt', + 'mime_type' => 'application/vnd.oasis.opendocument.text', + 'force_file' => true, + 'options' => array(), + 'options_text' => __('Options') + ); + + /* what to dump (structure/data/both) */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'text' => __('Dump table'), + 'name' => 'general_opts' + ); + $this->properties['options'][] = array( + 'type' => 'radio', + 'name' => 'structure_or_data', + 'values' => array( + 'structure' => __('structure'), + 'data' => __('data'), + 'structure_and_data' => __('structure and data') + ) + ); + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + + /* Structure options */ + if (! $hide_structure) { + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'structure', + 'text' => __('Object creation options'), + 'force' => 'data' + ); + if (! empty($GLOBALS['cfgRelation']['relation'])) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'relation', + 'text' => __('Display foreign key relationships') + ); + } + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'comments', + 'text' => __('Display comments') + ); + if (! empty($GLOBALS['cfgRelation']['mimework'])) { + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'mime', + 'text' => __('Display MIME types') + ); + } + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + + /* Data */ + $this->properties['options'][] = array( + 'type' => 'begin_group', + 'name' => 'data', + 'text' => __('Data dump options'), + 'force' => 'structure' + ); + $this->properties['options'][] = array( + 'type' => 'bool', + 'name' => 'columns', + 'text' => __('Put columns names in the first row') + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'null', + 'text' => __('Replace NULL with:') + ); + $this->properties['options'][] = array( + 'type' => 'end_group' + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + // initialize the general export variables + $this->initExportCommonVariables(); + + $GLOBALS['odt_buffer'] .= '' + . '' + . '' + . ''; + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + $GLOBALS['odt_buffer'] .= '' + . '' + . ''; + if (! PMA_exportOutputHandler( + PMA_createOpenDocument( + 'application/vnd.oasis.opendocument.text', + $GLOBALS['odt_buffer'] + ) + )) { + return false; + } + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + $GLOBALS['odt_buffer'] .= + '' + . __('Database') . ' ' . htmlspecialchars($db) + . ''; + return true; + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $what = $this->getWhat(); + + // Gets the data from the database + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + $fields_cnt = PMA_DBI_num_fields($result); + $fields_meta = PMA_DBI_get_fields_meta($result); + $field_flags = array(); + for ($j = 0; $j < $fields_cnt; $j++) { + $field_flags[$j] = PMA_DBI_field_flags($result, $j); + } + + $GLOBALS['odt_buffer'] .= + '' + . __('Dumping data for table') . ' ' . htmlspecialchars($table) + . '' + . '' + . ''; + + // If required, get fields name at the first line + if (isset($GLOBALS[$what . '_columns'])) { + $GLOBALS['odt_buffer'] .= ''; + for ($i = 0; $i < $fields_cnt; $i++) { + $GLOBALS['odt_buffer'] .= + '' + . '' + . htmlspecialchars( + stripslashes(PMA_DBI_field_name($result, $i)) + ) + . '' + . ''; + } // end for + $GLOBALS['odt_buffer'] .= ''; + } // end if + + // Format the data + while ($row = PMA_DBI_fetch_row($result)) { + $GLOBALS['odt_buffer'] .= ''; + for ($j = 0; $j < $fields_cnt; $j++) { + if (! isset($row[$j]) || is_null($row[$j])) { + $GLOBALS['odt_buffer'] .= + '' + . '' + . htmlspecialchars($GLOBALS[$what . '_null']) + . '' + . ''; + } elseif (stristr($field_flags[$j], 'BINARY') + && $fields_meta[$j]->blob + ) { + // ignore BLOB + $GLOBALS['odt_buffer'] .= + '' + . '' + . ''; + } elseif ($fields_meta[$j]->numeric + && $fields_meta[$j]->type != 'timestamp' + && ! $fields_meta[$j]->blob + ) { + $GLOBALS['odt_buffer'] .= + '' + . '' + . htmlspecialchars($row[$j]) + . '' + . ''; + } else { + $GLOBALS['odt_buffer'] .= + '' + . '' + . htmlspecialchars($row[$j]) + . '' + . ''; + } + } // end for + $GLOBALS['odt_buffer'] .= ''; + } // end while + PMA_DBI_free_result($result); + + $GLOBALS['odt_buffer'] .= ''; + + return true; + } + + /** + * Returns a stand-in CREATE definition to resolve view dependencies + * + * @param string $db the database name + * @param string $view the view name + * @param string $crlf the end of line sequence + * + * @return bool true + */ + function getTableDefStandIn($db, $view, $crlf) + { + /** + * Gets fields properties + */ + PMA_DBI_select_db($db); + + /** + * Displays the table structure + */ + $GLOBALS['odt_buffer'] .= + ''; + $columns_cnt = 4; + $GLOBALS['odt_buffer'] .= + ''; + /* Header */ + $GLOBALS['odt_buffer'] .= '' + . '' + . '' . __('Column') . '' + . '' + . '' + . '' . __('Type') . '' + . '' + . '' + . '' . __('Null') . '' + . '' + . '' + . '' . __('Default') . '' + . '' + . ''; + + $columns = PMA_DBI_get_columns($db, $view); + foreach ($columns as $column) { + $GLOBALS['odt_buffer'] .= $this->formatOneColumnDefinition($column); + $GLOBALS['odt_buffer'] .= ''; + } // end foreach + + $GLOBALS['odt_buffer'] .= ''; + return true; + } + + /** + * Returns $table's CREATE definition + * + * @param string $db the database name + * @param string $table the table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param bool $do_relation whether to include relation comments + * @param bool $do_comments whether to include the pmadb-style column + * comments as comments in the structure; + * this is deprecated but the parameter is + * left here because export.php calls + * PMA_exportStructure() also for other + * @param bool $do_mime whether to include mime comments + * @param bool $show_dates whether to include creation/update/check dates + * @param bool $add_semicolon whether to add semicolon and end-of-line at + * the end + * @param bool $view whether we're handling a view + */ + public function getTableDef( + $db, + $table, + $crlf, + $error_url, + $do_relation, + $do_comments, + $do_mime, + $show_dates = false, + $add_semicolon = true, + $view = false + ) { + $cfgRelation = $this->getCfgRelation(); + + /** + * Gets fields properties + */ + PMA_DBI_select_db($db); + + // Check if we can use Relations + if ($do_relation && ! empty($cfgRelation['relation'])) { + // Find which tables are related with the current one and write it in + // an array + $res_rel = PMA_getForeigners($db, $table); + + if ($res_rel && count($res_rel) > 0) { + $have_rel = true; + } else { + $have_rel = false; + } + } else { + $have_rel = false; + } // end if + + /** + * Displays the table structure + */ + $GLOBALS['odt_buffer'] .= ''; + $columns_cnt = 4; + if ($do_relation && $have_rel) { + $columns_cnt++; + } + if ($do_comments) { + $columns_cnt++; + } + if ($do_mime && $cfgRelation['mimework']) { + $columns_cnt++; + } + $GLOBALS['odt_buffer'] .= ''; + /* Header */ + $GLOBALS['odt_buffer'] .= '' + . '' + . '' . __('Column') . '' + . '' + . '' + . '' . __('Type') . '' + . '' + . '' + . '' . __('Null') . '' + . '' + . '' + . '' . __('Default') . '' + . ''; + if ($do_relation && $have_rel) { + $GLOBALS['odt_buffer'] .= '' + . '' . __('Links to') . '' + . ''; + } + if ($do_comments) { + $GLOBALS['odt_buffer'] .= '' + . '' . __('Comments') . '' + . ''; + $comments = PMA_getComments($db, $table); + } + if ($do_mime && $cfgRelation['mimework']) { + $GLOBALS['odt_buffer'] .= '' + . '' . __('MIME type') . '' + . ''; + $mime_map = PMA_getMIME($db, $table, true); + } + $GLOBALS['odt_buffer'] .= ''; + + $columns = PMA_DBI_get_columns($db, $table); + foreach ($columns as $column) { + $field_name = $column['Field']; + $GLOBALS['odt_buffer'] .= $this->formatOneColumnDefinition($column); + + if ($do_relation && $have_rel) { + if (isset($res_rel[$field_name])) { + $GLOBALS['odt_buffer'] .= + '' + . '' + . htmlspecialchars( + $res_rel[$field_name]['foreign_table'] + . ' (' . $res_rel[$field_name]['foreign_field'] . ')' + ) + . '' + . ''; + } + } + if ($do_comments) { + if (isset($comments[$field_name])) { + $GLOBALS['odt_buffer'] .= + '' + . '' + . htmlspecialchars($comments[$field_name]) + . '' + . ''; + } else { + $GLOBALS['odt_buffer'] .= + '' + . '' + . ''; + } + } + if ($do_mime && $cfgRelation['mimework']) { + if (isset($mime_map[$field_name])) { + $GLOBALS['odt_buffer'] .= + '' + . '' + . htmlspecialchars( + str_replace('_', '/', $mime_map[$field_name]['mimetype']) + ) + . '' + . ''; + } else { + $GLOBALS['odt_buffer'] .= + '' + . '' + . ''; + } + } + $GLOBALS['odt_buffer'] .= ''; + } // end foreach + + $GLOBALS['odt_buffer'] .= ''; + return true; + } // end of the '$this->getTableDef()' function + + /** + * Outputs triggers + * + * @param string $db database name + * @param string $table table name + * + * @return bool true + */ + function getTriggers($db, $table) + { + $GLOBALS['odt_buffer'] .= '' + . '' + . '' + . '' + . '' . __('Name') . '' + . '' + . '' + . '' . __('Time') . '' + . '' + . '' + . '' . __('Event') . '' + . '' + . '' + . '' . __('Definition') . '' + . '' + . ''; + + $triggers = PMA_DBI_get_triggers($db, $table); + + foreach ($triggers as $trigger) { + $GLOBALS['odt_buffer'] .= ''; + $GLOBALS['odt_buffer'] .= '' + . '' + . htmlspecialchars($trigger['name']) + . '' + . ''; + $GLOBALS['odt_buffer'] .= '' + . '' + . htmlspecialchars($trigger['action_timing']) + . '' + . ''; + $GLOBALS['odt_buffer'] .= '' + . '' + . htmlspecialchars($trigger['event_manipulation']) + . '' + . ''; + $GLOBALS['odt_buffer'] .= '' + . '' + . htmlspecialchars($trigger['definition']) + . '' + . ''; + $GLOBALS['odt_buffer'] .= ''; + } + + $GLOBALS['odt_buffer'] .= ''; + 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 + * @param bool $do_mime whether to include mime comments + * @param bool $dates whether to include creation/update/check dates + * + * @return bool Whether it succeeded + */ + function 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': + $GLOBALS['odt_buffer'] .= + '' + . __('Table structure for table') . ' ' . + htmlspecialchars($table) + . ''; + $this->getTableDef( + $db, $table, $crlf, $error_url, $do_relation, $do_comments, + $do_mime, $dates + ); + break; + case 'triggers': + $triggers = PMA_DBI_get_triggers($db, $table); + if ($triggers) { + $GLOBALS['odt_buffer'] .= + '' + . __('Triggers') . ' ' + . htmlspecialchars($table) + . ''; + $this->getTriggers($db, $table); + } + break; + case 'create_view': + $GLOBALS['odt_buffer'] .= + '' + . __('Structure for view') . ' ' + . htmlspecialchars($table) + . ''; + $this->getTableDef( + $db, $table, $crlf, $error_url, $do_relation, $do_comments, + $do_mime, $dates, true, true + ); + break; + case 'stand_in': + $GLOBALS['odt_buffer'] .= + '' + . __('Stand-in structure for view') . ' ' + . htmlspecialchars($table) + . ''; + // export a stand-in definition to resolve view dependencies + $this->getTableDefStandIn($db, $table, $crlf); + } // end switch + + return true; + } // end of the '$this->exportStructure' function + + /** + * Formats the definition for one column + * + * @param array $column info about this column + * + * @return string Formatted column definition + */ + protected function formatOneColumnDefinition($column) + { + $field_name = $column['Field']; + $definition = ''; + $definition .= '' + . '' . htmlspecialchars($field_name) . '' + . ''; + + $extracted_columnspec = PMA_extractColumnSpec($column['Type']); + $type = htmlspecialchars($extracted_columnspec['print_type']); + if (empty($type)) { + $type = ' '; + } + + $definition .= '' + . '' . htmlspecialchars($type) . '' + . ''; + if (! isset($column['Default'])) { + if ($column['Null'] != 'NO') { + $column['Default'] = 'NULL'; + } else { + $column['Default'] = ''; + } + } else { + $column['Default'] = $column['Default']; + } + $definition .= '' + . '' + . (($column['Null'] == '' || $column['Null'] == 'NO') + ? __('No') + : __('Yes')) + . '' + . ''; + $definition .= '' + . '' . htmlspecialchars($column['Default']) . '' + . ''; + return $definition; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + public function getWhat() + { + return $this->_what; + } + + public function setWhat($what) + { + $this->_what = $what; + } + + public function getPluginParam() + { + return $this->_pluginParam; + } + + private function setPluginParam($pluginParam) + { + $this->_pluginParam = $pluginParam; + } + + public function getCfgRelation() + { + return $this->_cfgRelation; + } + + private function setCfgRelation($cfgRelation) + { + $this->_cfgRelation = $cfgRelation; + } +} +?> \ No newline at end of file From c34d3bc003f6126b325e3df8c70e0c4c23ddd83d Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 12:34:44 +0300 Subject: [PATCH 19/55] oop: ExportPdf --- .../plugins/export/ExportMediawiki.class.php | 2 +- libraries/plugins/export/ExportOds.class.php | 2 +- libraries/plugins/export/ExportOdt.class.php | 4 +- libraries/plugins/export/ExportPdf.class.php | 224 +++++++++++ .../plugins/export/PMA_ExportPdf.class.php | 372 ++++++++++++++++++ 5 files changed, 599 insertions(+), 5 deletions(-) create mode 100644 libraries/plugins/export/ExportPdf.class.php create mode 100644 libraries/plugins/export/PMA_ExportPdf.class.php diff --git a/libraries/plugins/export/ExportMediawiki.class.php b/libraries/plugins/export/ExportMediawiki.class.php index 477df634e2..2478b99194 100644 --- a/libraries/plugins/export/ExportMediawiki.class.php +++ b/libraries/plugins/export/ExportMediawiki.class.php @@ -30,7 +30,7 @@ class ExportMediawiki extends ExportPlugin } /** - * Sets the export XML properties + * Sets the export MediaWiki properties * * @return void */ diff --git a/libraries/plugins/export/ExportOds.class.php b/libraries/plugins/export/ExportOds.class.php index 6a94f39b85..43683889ae 100644 --- a/libraries/plugins/export/ExportOds.class.php +++ b/libraries/plugins/export/ExportOds.class.php @@ -54,7 +54,7 @@ class ExportOds extends ExportPlugin } /** - * Sets the export XML properties + * Sets the export ODS properties * * @return void */ diff --git a/libraries/plugins/export/ExportOdt.class.php b/libraries/plugins/export/ExportOdt.class.php index 8d2f382c38..51c368433a 100644 --- a/libraries/plugins/export/ExportOdt.class.php +++ b/libraries/plugins/export/ExportOdt.class.php @@ -70,7 +70,7 @@ class ExportOdt extends ExportPlugin } /** - * Sets the export XML properties + * Sets the export ODT properties * * @return void */ @@ -268,8 +268,6 @@ class ExportOdt extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { diff --git a/libraries/plugins/export/ExportPdf.class.php b/libraries/plugins/export/ExportPdf.class.php new file mode 100644 index 0000000000..2f0534ad52 --- /dev/null +++ b/libraries/plugins/export/ExportPdf.class.php @@ -0,0 +1,224 @@ +initLocalVariables(); + + $this->setProperties(); + } + + /** + * Initialize the local variables that are used for export PDF + * + * @return void + */ + private function initLocalVariables() + { + global $pdf_report_title; + $this->setPdfReportTitle($pdf_report_title); + $this->setPdf(new PMA_ExportPdf('L', 'pt', 'A3')); + } + + /** + * Sets the export PDF properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('PDF'), + 'extension' => 'pdf', + 'mime_type' => 'application/pdf', + 'force_file' => true, + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['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' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + $pdf_report_title = $this->getPdfReportTitle(); + $pdf = $this->getPdf(); + $pdf->Open(); + + $attr = array('titleFontSize' => 18, 'titleText' => $pdf_report_title); + $pdf->setAttributes($attr); + $pdf->setTopMargin(30); + + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + $pdf = $this->getPdf(); + + // instead of $pdf->Output(): + if (! PMA_exportOutputHandler($pdf->getPDFData())) { + return false; + } + + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + return true; + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $pdf = $this->getPdf(); + + $attr = array('currentDb' => $db, 'currentTable' => $table); + $pdf->setAttributes($attr); + $pdf->mysqlReport($sql_query); + + return true; + } // end of the 'PMA_exportData()' function + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + public function getPdf() + { + return $this->_pdf; + } + + public function setPdf($pdf) + { + $this->_pdf = $pdf; + } + + public function getPdfReportTitle() + { + return $this->_pdfReportTitle; + } + + public function setPdfReportTitle($pdf_report_title) + { + $this->_pdfReportTitle = $pdf_report_title; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/export/PMA_ExportPdf.class.php b/libraries/plugins/export/PMA_ExportPdf.class.php new file mode 100644 index 0000000000..35c21ad08a --- /dev/null +++ b/libraries/plugins/export/PMA_ExportPdf.class.php @@ -0,0 +1,372 @@ +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 +?> From 06d6645eb346678938816d6aed10d7e4ff29bbd4 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 16:45:20 +0300 Subject: [PATCH 20/55] oop: ExportPhparray --- export.php | 23 +- libraries/plugins/export/ExportOds.class.php | 2 - .../plugins/export/ExportPhp_array.class.php | 213 ++++++++++++++++++ 3 files changed, 230 insertions(+), 8 deletions(-) create mode 100644 libraries/plugins/export/ExportPhp_array.class.php diff --git a/export.php b/export.php index c049a6dd1a..3e5ed63056 100644 --- a/export.php +++ b/export.php @@ -26,7 +26,7 @@ PMA_checkParameters(array('what', 'export_type')); // export class instance, not array of properties, as before $export_plugin = PMA_getPlugin( "export", - $what, + $what, 'libraries/plugins/export/', array( 'export_type' => $export_type, @@ -91,7 +91,7 @@ if ($_REQUEST['output_format'] == 'astext') { // Does export require to be into file? if (isset($export_plugin_properties['force_file']) && ! $asfile) { - + $message = PMA_Message::error(__('Selected export type has to be saved in file!')); include_once 'libraries/header.inc.php'; if ($export_type == 'server') { @@ -670,7 +670,13 @@ do { // If this is an export of a single view, we have to export data; // for example, a PDF report // if it is a merge table, no data is exported - if (($GLOBALS[$what . '_structure_or_data'] == 'data' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') && ! PMA_Table::isMerge($db, $table)) { + + if (($GLOBALS[$what . '_structure_or_data'] == 'data' + || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') + && ! PMA_Table::isMerge($db, $table) + ) { + echo "not server not database"; + if (!empty($sql_query)) { // only preg_replace if needed if (!empty($add_query)) { @@ -680,15 +686,20 @@ 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 (! $export_plugin->exportData($db, $table, $crlf, $err_url, $local_query)) { + if (! $export_plugin->exportData($db, $table, $crlf, $err_url, + $local_query + )) { break; } } // 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 ($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, diff --git a/libraries/plugins/export/ExportOds.class.php b/libraries/plugins/export/ExportOds.class.php index 43683889ae..9a5bf83b10 100644 --- a/libraries/plugins/export/ExportOds.class.php +++ b/libraries/plugins/export/ExportOds.class.php @@ -228,8 +228,6 @@ class ExportOds extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { diff --git a/libraries/plugins/export/ExportPhp_array.class.php b/libraries/plugins/export/ExportPhp_array.class.php new file mode 100644 index 0000000000..70e632428f --- /dev/null +++ b/libraries/plugins/export/ExportPhp_array.class.php @@ -0,0 +1,213 @@ +setProperties(); + } + + /** + * Sets the export PHP Array properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('PHP array'), + 'extension' => 'php', + 'mime_type' => 'text/plain', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'hidden', + 'name' => 'structure_or_data', + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + PMA_exportOutputHandler( + ' " . var_export($record[$i], true) + . (($i + 1 >= $columns_cnt) ? '' : ','); + } + + $buffer .= ')'; + } + + $buffer .= $crlf . ');' . $crlf; + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + + PMA_DBI_free_result($result); + return true; + } +} +?> \ No newline at end of file From 88a958828be389b4787779f5a7bc36a96cc8548c Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 17:14:55 +0300 Subject: [PATCH 21/55] oop: remove debugging echo from export.php --- export.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/export.php b/export.php index 3e5ed63056..41fdff1062 100644 --- a/export.php +++ b/export.php @@ -675,8 +675,6 @@ do { || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') && ! PMA_Table::isMerge($db, $table) ) { - echo "not server not database"; - if (!empty($sql_query)) { // only preg_replace if needed if (!empty($add_query)) { From a1cbfe7ffdc8bf032e126d7c798526efcab8b755 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 17:15:26 +0300 Subject: [PATCH 22/55] oop: ExportTexytext --- .../plugins/export/ExportTexytext.class.php | 617 ++++++++++++++++++ 1 file changed, 617 insertions(+) create mode 100644 libraries/plugins/export/ExportTexytext.class.php diff --git a/libraries/plugins/export/ExportTexytext.class.php b/libraries/plugins/export/ExportTexytext.class.php new file mode 100644 index 0000000000..0109fb46d2 --- /dev/null +++ b/libraries/plugins/export/ExportTexytext.class.php @@ -0,0 +1,617 @@ +initLocalVariables(); + + $this->setProperties(); + } + + /** + * Initialize the local variables that are used for export Texy! text + * + * @return void + */ + private function initLocalVariables() + { + global $what; + global $cfgRelation; + + $this->setWhat($what); + $this->setCfgRelation($cfgRelation); + } + + /** + * Sets the export Texy! text properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('Texy! text'), + 'extension' => 'txt', + 'mime_type' => 'text/plain', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + /* what to dump (structure/data/both) */ + array( + 'type' => 'begin_group', + 'text' => __('Dump table'), + 'name' => 'general_opts' + ), + array( + 'type' => 'radio', + 'name' => 'structure_or_data', + 'values' => array( + 'structure' => __('structure'), + 'data' => __('data'), + 'structure_and_data' => __('structure and data') + ) + ), + array( + 'type' => 'end_group' + ), + array( + 'type' => 'begin_group', + 'name' => 'data', + 'text' => __('Data dump options'), + 'force' => 'structure' + ), + array( + 'type' => 'text', + 'name' => 'null', + 'text' => __('Replace NULL by') + ), + array( + 'type' => 'bool', + 'name' => 'columns', + 'text' => __('Put columns names in the first row') + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + return PMA_exportOutputHandler( + '===' . __('Database') . ' ' . $db . "\n\n" + ); + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function 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 + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $what = $this->getWhat(); + + if (! PMA_exportOutputHandler( + '== ' . __('Dumping data for table') . ' ' . $table . "\n\n" + )) { + return false; + } + + // Gets the data from the database + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + $fields_cnt = PMA_DBI_num_fields($result); + + // If required, get fields name at the first line + if (isset($GLOBALS[$what . '_columns'])) { + $text_output = "|------\n"; + for ($i = 0; $i < $fields_cnt; $i++) { + $text_output .= '|' + . htmlspecialchars( + stripslashes(PMA_DBI_field_name($result, $i)) + ); + } // end for + $text_output .= "\n|------\n"; + if (! PMA_exportOutputHandler($text_output)) { + return false; + } + } // end if + + // Format the data + while ($row = PMA_DBI_fetch_row($result)) { + $text_output = ''; + for ($j = 0; $j < $fields_cnt; $j++) { + if (! isset($row[$j]) || is_null($row[$j])) { + $value = $GLOBALS[$what . '_null']; + } elseif ($row[$j] == '0' || $row[$j] != '') { + $value = $row[$j]; + } else { + $value = ' '; + } + $text_output .= '|' + . str_replace( + '|', '|', htmlspecialchars($value) + ); + } // end for + $text_output .= "\n"; + if (! PMA_exportOutputHandler($text_output)) { + return false; + } + } // end while + PMA_DBI_free_result($result); + + return true; + } + + /** + * Returns a stand-in CREATE definition to resolve view dependencies + * + * @param string $db the database name + * @param string $view the view name + * @param string $crlf the end of line sequence + * + * @return string resulting definition + */ + function getTableDefStandIn($db, $view, $crlf) + { + $text_output = ''; + + /** + * Get the unique keys in the table + */ + $unique_keys = array(); + $keys = PMA_DBI_get_table_indexes($db, $view); + foreach ($keys as $key) { + if ($key['Non_unique'] == 0) { + $unique_keys[] = $key['Column_name']; + } + } + + /** + * Gets fields properties + */ + PMA_DBI_select_db($db); + + /** + * Displays the table structure + */ + + $text_output .= "|------\n" + . '|' . __('Column') + . '|' . __('Type') + . '|' . __('Null') + . '|' . __('Default') + . "\n|------\n"; + + $columns = PMA_DBI_get_columns($db, $view); + foreach ($columns as $column) { + $text_output .= $this->formatOneColumnDefinition($column, $unique_keys); + $text_output .= "\n"; + } // end foreach + + return $text_output; + } + + /** + * Returns $table's CREATE definition + * + * @param string $db the database name + * @param string $table the table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param bool $do_relation whether to include relation comments + * @param bool $do_comments whether to include the pmadb-style column + * comments as comments in the structure; + * this is deprecated but the parameter is + * left here because export.php calls + * $this->exportStructure() also for other + * export types which use this parameter + * @param bool $do_mime whether to include mime comments + * @param bool $show_dates whether to include creation/update/check dates + * @param bool $add_semicolon whether to add semicolon and end-of-line + * at the end + * @param bool $view whether we're handling a view + * + * @return string resulting schema + */ + function getTableDef( + $db, + $table, + $crlf, + $error_url, + $do_relation, + $do_comments, + $do_mime, + $show_dates = false, + $add_semicolon = true, + $view = false + ) { + global $cfgRelation; + $this->setCfgRelation($cfgRelation); + + $text_output = ''; + + /** + * Get the unique keys in the table + */ + $unique_keys = array(); + $keys = PMA_DBI_get_table_indexes($db, $table); + foreach ($keys as $key) { + if ($key['Non_unique'] == 0) { + $unique_keys[] = $key['Column_name']; + } + } + + /** + * Gets fields properties + */ + PMA_DBI_select_db($db); + + // Check if we can use Relations + if ($do_relation && ! empty($cfgRelation['relation'])) { + // Find which tables are related with the current one and write it in + // an array + $res_rel = PMA_getForeigners($db, $table); + + if ($res_rel && count($res_rel) > 0) { + $have_rel = true; + } else { + $have_rel = false; + } + } else { + $have_rel = false; + } // end if + + /** + * Displays the table structure + */ + + $columns_cnt = 4; + if ($do_relation && $have_rel) { + $columns_cnt++; + } + if ($do_comments && $cfgRelation['commwork']) { + $columns_cnt++; + } + if ($do_mime && $cfgRelation['mimework']) { + $columns_cnt++; + } + + $text_output .= "|------\n"; + $text_output .= '|' . __('Column'); + $text_output .= '|' . __('Type'); + $text_output .= '|' . __('Null'); + $text_output .= '|' . __('Default'); + if ($do_relation && $have_rel) { + $text_output .= '|' . __('Links to'); + } + if ($do_comments) { + $text_output .= '|' . __('Comments'); + $comments = PMA_getComments($db, $table); + } + if ($do_mime && $cfgRelation['mimework']) { + $text_output .= '|' . htmlspecialchars('MIME'); + $mime_map = PMA_getMIME($db, $table, true); + } + $text_output .= "\n|------\n"; + + $columns = PMA_DBI_get_columns($db, $table); + foreach ($columns as $column) { + $text_output .= $this->formatOneColumnDefinition($column, $unique_keys); + $field_name = $column['Field']; + + if ($do_relation && $have_rel) { + $text_output .= '|' + . (isset($res_rel[$field_name]) + ? htmlspecialchars( + $res_rel[$field_name]['foreign_table'] + . ' (' . $res_rel[$field_name]['foreign_field'] . ')' + ) + : ''); + } + if ($do_comments && $cfgRelation['commwork']) { + $text_output .= '|' + . (isset($comments[$field_name]) + ? htmlspecialchars($comments[$field_name]) + : ''); + } + if ($do_mime && $cfgRelation['mimework']) { + $text_output .= '|' + . (isset($mime_map[$field_name]) + ? htmlspecialchars( + str_replace('_', '/', $mime_map[$field_name]['mimetype']) + ) + : ''); + } + + $text_output .= "\n"; + } // end foreach + + return $text_output; + } // end of the '$this->getTableDef()' function + + /** + * Outputs triggers + * + * @param string $db database name + * @param string $table table name + * + * @return string Formatted triggers list + */ + function getTriggers($db, $table) + { + $text_output .= "|------\n"; + $text_output .= '|' . __('Column'); + $dump = "|------\n"; + $dump .= '|' . __('Name'); + $dump .= '|' . __('Time'); + $dump .= '|' . __('Event'); + $dump .= '|' . __('Definition'); + $dump .= "\n|------\n"; + + $triggers = PMA_DBI_get_triggers($db, $table); + + foreach ($triggers as $trigger) { + $dump .= '|' . $trigger['name']; + $dump .= '|' . $trigger['action_timing']; + $dump .= '|' . $trigger['event_manipulation']; + $dump .= '|' . + str_replace( + '|', + '|', + htmlspecialchars($trigger['definition']) + ); + $dump .= "\n"; + } + + return $dump; + } + + /** + * 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 + * $this->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 + */ + function exportStructure( + $db, + $table, + $crlf, + $error_url, + $export_mode, + $export_type, + $do_relation = false, + $do_comments = false, + $do_mime = false, + $dates = false + ) { + $dump = ''; + + switch($export_mode) { + case 'create_table': + $dump .= '== ' . __('Table structure for table') . ' ' .$table . "\n\n"; + $dump .= $this->getTableDef( + $db, $table, $crlf, $error_url, $do_relation, $do_comments, + $do_mime, $dates + ); + break; + case 'triggers': + $dump = ''; + $triggers = PMA_DBI_get_triggers($db, $table); + if ($triggers) { + $dump .= '== ' . __('Triggers') . ' ' .$table . "\n\n"; + $dump .= $this->getTriggers($db, $table); + } + break; + case 'create_view': + $dump .= '== ' . __('Structure for view') . ' ' .$table . "\n\n"; + $dump .= $this->getTableDef( + $db, $table, $crlf, $error_url, $do_relation, $do_comments, + $do_mime, $dates, true, true + ); + break; + case 'stand_in': + $dump .= '== ' . __('Stand-in structure for view') + . ' ' .$table . "\n\n"; + // export a stand-in definition to resolve view dependencies + $dump .= $this->getTableDefStandIn($db, $table, $crlf); + } // end switch + + return PMA_exportOutputHandler($dump); + } + + /** + * Formats the definition for one column + * + * @param array $column info about this column + * @param array $unique_keys unique keys for this table + * + * @return string Formatted column definition + */ + function formatOneColumnDefinition( + $column, $unique_keys + ) { + $extracted_columnspec = PMA_extractColumnSpec($column['Type']); + $type = $extracted_columnspec['print_type']; + if (empty($type)) { + $type = ' '; + } + + if (! isset($column['Default'])) { + if ($column['Null'] != 'NO') { + $column['Default'] = 'NULL'; + } + } + + $fmt_pre = ''; + $fmt_post = ''; + if (in_array($column['Field'], $unique_keys)) { + $fmt_pre = '**' . $fmt_pre; + $fmt_post = $fmt_post . '**'; + } + if ($column['Key']=='PRI') { + $fmt_pre = '//' . $fmt_pre; + $fmt_post = $fmt_post . '//'; + } + $definition = '|' + . $fmt_pre . htmlspecialchars($column['Field']) . $fmt_post; + $definition .= '|' . htmlspecialchars($type); + $definition .= '|' + . (($column['Null'] == '' || $column['Null'] == 'NO') + ? __('No') : __('Yes')); + $definition .= '|' + . htmlspecialchars( + isset($column['Default']) ? $column['Default'] : '' + ); + return $definition; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + public function getWhat() + { + return $this->_what; + } + + public function setWhat($what) + { + $this->_what = $what; + } + + public function getCfgRelation() + { + return $this->_cfgRelation; + } + + private function setCfgRelation($cfgRelation) + { + $this->_cfgRelation = $cfgRelation; + } +} +?> \ No newline at end of file From 34db0b775e1513b0afbeafc77f616df5eaea42e4 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 17:16:15 +0300 Subject: [PATCH 23/55] oop: ExportHtmlword - add cfgRelation --- .../plugins/export/ExportHtmlword.class.php | 37 ++++++++++++++----- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/libraries/plugins/export/ExportHtmlword.class.php b/libraries/plugins/export/ExportHtmlword.class.php index cddcbadc90..c1dfcf3f69 100644 --- a/libraries/plugins/export/ExportHtmlword.class.php +++ b/libraries/plugins/export/ExportHtmlword.class.php @@ -35,6 +35,12 @@ class ExportHtmlword extends ExportPlugin */ private $_what; + /** + * + * @var type + */ + private $_cfgRelation; + /** * Constructor */ @@ -52,9 +58,11 @@ class ExportHtmlword extends ExportPlugin { global $charset_of_file; global $what; + global $cfgRelation; $this->setCharsetOfFile($charset_of_file); $this->setWhat($what); + $this->setCfgRelation($cfgRelation); } /** @@ -369,6 +377,7 @@ class ExportHtmlword extends ExportPlugin $view = false ) { global $cfgRelation; + $this->setCfgRelation($cfgRelation); $schema_insert = ''; @@ -481,7 +490,7 @@ class ExportHtmlword extends ExportPlugin } $schema_insert .= ''; - } // end foreach + } // end foreach $schema_insert .= ''; return $schema_insert; @@ -605,7 +614,7 @@ class ExportHtmlword extends ExportPlugin } /** - * Formats the definition for one column + * Formats the definition for one column * * @param array $column info about this column * @param array $unique_keys unique keys of the table @@ -638,16 +647,16 @@ class ExportHtmlword extends ExportPlugin $fmt_pre = '' . $fmt_pre; $fmt_post = $fmt_post . ''; } - $definition .= '' . $fmt_pre + $definition .= '' . $fmt_pre . htmlspecialchars($column['Field']) . $fmt_post . ''; $definition .= '' . htmlspecialchars($type) . ''; - $definition .= '' - . (($column['Null'] == '' || $column['Null'] == 'NO') - ? __('No') - : __('Yes')) + $definition .= '' + . (($column['Null'] == '' || $column['Null'] == 'NO') + ? __('No') + : __('Yes')) . ''; - $definition .= '' + $definition .= '' . htmlspecialchars( isset($column['Default']) ? $column['Default'] @@ -657,7 +666,7 @@ class ExportHtmlword extends ExportPlugin return $definition; } - + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ @@ -681,5 +690,15 @@ class ExportHtmlword extends ExportPlugin { $this->_charsetOfFile = $charsetOfFile; } + + public function getCfgRelation() + { + return $this->_cfgRelation; + } + + private function setCfgRelation($cfgRelation) + { + $this->_cfgRelation = $cfgRelation; + } } ?> \ No newline at end of file From 52f593c302a69c46e181bac8aacc8989c8bf2319 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sat, 16 Jun 2012 17:23:51 +0300 Subject: [PATCH 24/55] oop: ExportYaml --- libraries/plugins/export/ExportYaml.class.php | 203 ++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 libraries/plugins/export/ExportYaml.class.php diff --git a/libraries/plugins/export/ExportYaml.class.php b/libraries/plugins/export/ExportYaml.class.php new file mode 100644 index 0000000000..2ac51c6b05 --- /dev/null +++ b/libraries/plugins/export/ExportYaml.class.php @@ -0,0 +1,203 @@ +setProperties(); + } + + /** + * Sets the export YAML properties + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => 'YAML', + 'extension' => 'yml', + 'mime_type' => 'text/yaml', + 'force_file' => true, + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'hidden', + 'name' => 'structure_or_data', + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Outputs export header + * + * @return bool Whether it succeeded + */ + public function exportHeader () + { + PMA_exportOutputHandler( + '%YAML 1.1' . $GLOBALS['crlf'] . '---' . $GLOBALS['crlf'] + ); + return true; + } + + /** + * Outputs export footer + * + * @return bool Whether it succeeded + */ + public function exportFooter () + { + PMA_exportOutputHandler('...' . $GLOBALS['crlf']); + return true; + } + + /** + * Outputs database header + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBHeader ($db) + { + return true; + } + + /** + * Outputs database footer + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBFooter ($db) + { + return true; + } + + /** + * Outputs CREATE DATABASE statement + * + * @param string $db Database name + * + * @return bool Whether it succeeded + */ + public function exportDBCreate($db) + { + return true; + } + + /** + * Outputs the content of a table in JSON format + * + * @param string $db database name + * @param string $table table name + * @param string $crlf the end of line sequence + * @param string $error_url the url to go back in case of error + * @param string $sql_query SQL query for obtaining data + * + * @return bool Whether it succeeded + */ + public function exportData($db, $table, $crlf, $error_url, $sql_query) + { + $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); + + $columns_cnt = PMA_DBI_num_fields($result); + for ($i = 0; $i < $columns_cnt; $i++) { + $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); + } + unset($i); + + $buffer = ''; + $record_cnt = 0; + while ($record = PMA_DBI_fetch_row($result)) { + $record_cnt++; + + // Output table name as comment if this is the first record of the table + if ($record_cnt == 1) { + $buffer = '# ' . $db . '.' . $table . $crlf; + $buffer .= '-' . $crlf; + } else { + $buffer = '-' . $crlf; + } + + for ($i = 0; $i < $columns_cnt; $i++) { + if (! isset($record[$i])) { + continue; + } + + $column = $columns[$i]; + + if (is_null($record[$i])) { + $buffer .= ' ' . $column . ': null' . $crlf; + continue; + } + + if (is_numeric($record[$i])) { + $buffer .= ' ' . $column . ': ' . $record[$i] . $crlf; + continue; + } + + $record[$i] = str_replace( + array('\\', '"', "\n", "\r"), + array('\\\\', '\"', '\n', '\r'), + $record[$i] + ); + $buffer .= ' ' . $column . ': "' . $record[$i] . '"' . $crlf; + } + + if (! PMA_exportOutputHandler($buffer)) { + return false; + } + } + PMA_DBI_free_result($result); + + return true; + } // end getTableYAML +} +?> \ No newline at end of file From 4e93893b388c7a474224260ced30b0ec449f746a Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Sun, 17 Jun 2012 11:14:36 +0300 Subject: [PATCH 25/55] oop: ImportSql phpcs errors --- libraries/plugins/import/ImportSql.class.php | 90 +++++++++++++------- 1 file changed, 58 insertions(+), 32 deletions(-) diff --git a/libraries/plugins/import/ImportSql.class.php b/libraries/plugins/import/ImportSql.class.php index fcf90cfefc..b22a206abe 100644 --- a/libraries/plugins/import/ImportSql.class.php +++ b/libraries/plugins/import/ImportSql.class.php @@ -37,10 +37,10 @@ class ImportSql extends ImportPlugin protected function setProperties() { $this->properties = array( - 'text' => __('SQL'), - 'extension' => 'sql', + 'text' => __('SQL'), + 'extension' => 'sql', 'options' => array(), - 'options_text' => __('Options'), + 'options_text' => __('Options'), ); $compats = PMA_DBI_getCompatibilities(); @@ -52,11 +52,11 @@ class ImportSql extends ImportPlugin $this->properties['options'] = array( array('type' => 'begin_group', 'name' => 'general_opts'), array( - 'type' => 'select', - 'name' => 'compatibility', - 'text' => __('SQL compatibility mode:'), - 'values' => $values, - 'doc' => array( + 'type' => 'select', + 'name' => 'compatibility', + 'text' => __('SQL compatibility mode:'), + 'values' => $values, + 'doc' => array( 'manual_MySQL_Database_Administration', 'Server_SQL_mode', ), @@ -64,13 +64,14 @@ class ImportSql extends ImportPlugin array( 'type' => 'bool', 'name' => 'no_auto_value_on_zero', - 'text' => __('Do not use AUTO_INCREMENT for zero values'), - 'doc' => array( + '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'), ); @@ -92,6 +93,8 @@ class ImportSql extends ImportPlugin /** * Handles the whole import logic + * + * @return void */ public function doImport() { @@ -108,7 +111,8 @@ class ImportSql extends ImportPlugin $i = 0; $len= 0; $big_value = 2147483647; - $delimiter_keyword = 'DELIMITER '; // include the space because it's mandatory + // include the space because it's mandatory + $delimiter_keyword = 'DELIMITER '; $length_of_delimiter_keyword = strlen($delimiter_keyword); if (isset($_POST['sql_delimiter'])) { @@ -139,7 +143,10 @@ class ImportSql extends ImportPlugin */ $GLOBALS['finished'] = false; - while (! ($GLOBALS['finished'] && $i >= $len) && ! $error && ! $timeout_passed) { + while (! ($GLOBALS['finished'] && $i >= $len) + && ! $error + && ! $timeout_passed + ) { $data = PMA_importGetNextChunk(); if ($data === false) { // subtract data we didn't handle yet and stop processing @@ -152,7 +159,8 @@ class ImportSql extends ImportPlugin $buffer .= $data; // free memory unset($data); - // Do not parse string when we're not at the end and don't have ; inside + // 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'] ) { @@ -170,7 +178,8 @@ class ImportSql extends ImportPlugin // this is about 7 times faster that looking for each sequence i // one by one with strpos() $match = preg_match( - '/(\'|"|#|-- |\/\*|`|(?i)(? Date: Mon, 18 Jun 2012 14:22:12 +0300 Subject: [PATCH 26/55] oop: fix bugs and phpcs errors for all export plugins --- db_operations.php | 12 +- export.php | 21 +- libraries/config.default.php | 4 +- libraries/plugins/ExportPlugin.class.php | 172 ++++-- .../plugins/export/ExportCodegen.class.php | 115 ++-- libraries/plugins/export/ExportCsv.class.php | 141 +++-- .../plugins/export/ExportHtmlword.class.php | 107 +--- libraries/plugins/export/ExportJson.class.php | 10 - .../plugins/export/ExportLatex.class.php | 60 +-- .../plugins/export/ExportMediawiki.class.php | 78 ++- libraries/plugins/export/ExportOds.class.php | 42 +- libraries/plugins/export/ExportOdt.class.php | 91 +--- libraries/plugins/export/ExportPdf.class.php | 63 ++- ...ray.class.php => ExportPhparray.class.php} | 3 +- libraries/plugins/export/ExportSql.class.php | 493 ++++++++++-------- .../plugins/export/ExportTexytext.class.php | 60 +-- libraries/plugins/export/ExportXml.class.php | 72 +-- .../plugins/export/PMA_ExportPdf.class.php | 2 +- .../plugins/export/TableProperty.class.php | 105 +++- 19 files changed, 872 insertions(+), 779 deletions(-) rename libraries/plugins/export/{ExportPhp_array.class.php => ExportPhparray.class.php} (99%) diff --git a/db_operations.php b/db_operations.php index 96b0cb274a..b6b61ddbfc 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'); /** @@ -147,7 +147,9 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) { foreach ($tables_full as $each_table => $tmp) { $sql_constraints = ''; $sql_drop_foreign_keys = ''; - $sql_structure = $export_sql_plugin->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); } @@ -165,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 = $export_sql_plugin->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 b1981457f8..39d6d5db76 100644 --- a/export.php +++ b/export.php @@ -353,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); } } @@ -451,7 +459,6 @@ if (! $save_on_server) { // Fake loop just to allow skip of remain of this code by break, I'd really // need exceptions here :-) do { - // Add possibly some comments to export if (! $export_plugin->exportHeader($db)) { break; @@ -469,7 +476,7 @@ do { } // Include dates in export? - $do_dates = isset($GLOBALS[$what . '_dates']); + $do_dates = isset($GLOBALS[$what . '_dates']); /** * Builds the dump @@ -745,7 +752,7 @@ if (! empty($asfile)) { if ($compression == 'zip') { if (@function_exists('gzcompress')) { $zipfile = new zipfile(); - $zipfile -> addFile($dump_buffer, substr($filename, 0, -4)); + $zipfile->addFile($dump_buffer, substr($filename, 0, -4)); $dump_buffer = $zipfile -> file(); } } elseif ($compression == 'bzip2') { 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/plugins/ExportPlugin.class.php b/libraries/plugins/ExportPlugin.class.php index 1410234dd6..620db86a3a 100644 --- a/libraries/plugins/ExportPlugin.class.php +++ b/libraries/plugins/ExportPlugin.class.php @@ -25,31 +25,59 @@ abstract class ExportPlugin extends PluginObserver /** * Array containing the specific export plugin type properties * - * @var type array + * @var array */ protected $properties; /** * Type of the newline character * - * @var type string + * @var string */ private $_crlf; - /** - * Contains configuration settings - * - * @var type array - */ - private $_cfg; - /** * Database name * - * @var type string + * @var string */ private $_db; + /** + * Contains configuration settings + * + * @var array + */ + private $_cfg; + + + /** + * Relation configuration + * + * @var array + */ + private $_cfgRelation; + + /** + * The type of the export plugin + * + * @var string + */ + private $_what; + + /** + * Parameter to plugin by which it can decide whether it can work + * + * @var mixed + */ + private $_pluginParam; + + /** + * File Charset + * + * @var type String + */ + private $_charsetOfFile; /** * Common methods, must be overwritten by all export plugins @@ -193,23 +221,13 @@ abstract class ExportPlugin extends PluginObserver } /** - * Initializes the local variables with the global values. - * These are variables that are used by all of the export plugins. - * - * @global String $crlf type of the newline character - * @global array $cfg array with configuration settings - * @global String $db database name + * Initialize the specific variables for each export plugin * * @return void */ - protected function initExportCommonVariables() + protected function initSpecificVariables() { - global $crlf; - global $cfg; - global $db; - $this->setCrlf($crlf); - $this->setCfg($cfg); - $this->setDb($db); + ; } @@ -239,7 +257,7 @@ abstract class ExportPlugin extends PluginObserver * * @return string */ - public function getCrlf() + protected function getCrlf() { return $this->_crlf; } @@ -256,12 +274,34 @@ abstract class ExportPlugin extends PluginObserver $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 */ - public function getCfg() + protected function getCfg() { return $this->_cfg; } @@ -279,25 +319,91 @@ abstract class ExportPlugin extends PluginObserver } /** - * Gets the database name + * Gets the relation configuration * - * @return string + * @return array */ - public function getDb() + protected function getCfgRelation() { - return $this->_db; + return $this->_cfgRelation; } /** - * Sets the database name + * Sets the relation configuration * - * @param String $db database name + * @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 setDb($db) + protected function setWhat($what) { - $this->_db = $db; + $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/export/ExportCodegen.class.php b/libraries/plugins/export/ExportCodegen.class.php index 45ac3a53f4..839da90f73 100644 --- a/libraries/plugins/export/ExportCodegen.class.php +++ b/libraries/plugins/export/ExportCodegen.class.php @@ -18,33 +18,31 @@ require_once "libraries/plugins/export/TableProperty.class.php"; /** * Handles the export for the CodeGen class * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportCodegen extends ExportPlugin { /** + * CodeGen Formats * - * - * @var type array + * @var array */ - private $_CG_FORMATS; + private $_cgFormats; /** + * CodeGen Handlers * - * - * @var type array + * @var array */ - private $_CG_HANDLERS; + private $_cgHandlers; /** * Constructor */ public function __construct() { - // initialize the specific export codegen variables - $this->initLocalVariables(); - + // initialize the specific export CodeGen variables + $this->initSpecificVariables(); $this->setProperties(); } @@ -53,25 +51,25 @@ class ExportCodegen extends ExportPlugin * * @return void */ - private function initLocalVariables() + protected function initSpecificVariables() { - $this->setCG_FORMATS( + $this->_setCgFormats( array( "NHibernate C# DO", "NHibernate XML" ) ); - $this->setCG_HANDLERS( + $this->_setCgHandlers( array( - "handleNHibernateCSBody", - "handleNHibernateXMLBody" + "_handleNHibernateCSBody", + "_handleNHibernateXMLBody" ) ); } /** - * Sets the export XML properties + * Sets the export CodeGen properties * * @return void */ @@ -98,7 +96,7 @@ class ExportCodegen extends ExportPlugin 'type' => 'select', 'name' => 'format', 'text' => __('Format:'), - 'values' => $this->getCG_FORMATS() + 'values' => $this->_getCgFormats() ), array( 'type' => 'end_group' @@ -126,9 +124,6 @@ class ExportCodegen extends ExportPlugin */ public function exportHeader () { - // initialize the general export variables - $this->initExportCommonVariables(); - return true; } @@ -177,6 +172,7 @@ class ExportCodegen extends ExportPlugin { return true; } + /** * Outputs the content of a table in NHibernate format * @@ -187,13 +183,11 @@ class ExportCodegen extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { - $CG_FORMATS = $this->getCG_FORMATS(); - $CG_HANDLERS = $this->getCG_HANDLERS(); + $CG_FORMATS = $this->_getCgFormats(); + $CG_HANDLERS = $this->_getCgHandlers(); $format = $GLOBALS['codegen_format']; if (isset($CG_FORMATS[$format])) { @@ -204,6 +198,14 @@ class ExportCodegen extends ExportPlugin return PMA_exportOutputHandler(sprintf("%s is not supported.", $format)); } + /** + * Used to make identifiers (from table or database names) + * + * @param string $str name to be converted + * @param bool $ucfirst whether to make the first character uppercase + * + * @return string identifier + */ public static function cgMakeIdentifier($str, $ucfirst = true) { // remove unsafe characters @@ -218,7 +220,16 @@ class ExportCodegen extends ExportPlugin return $str; } - private function handleNHibernateCSBody($db, $table, $crlf) + /** + * C# Handler + * + * @param string $db database name + * @param string $table table name + * @param string $crlf line separator + * + * @return string containing C# code lines, separated by "\n" + */ + private function _handleNHibernateCSBody($db, $table, $crlf) { $lines = array(); $result = PMA_DBI_query( @@ -247,7 +258,8 @@ class ExportCodegen extends ExportPlugin } $lines[] = ' #endregion'; $lines[] = ' #region Constructors'; - $lines[] = ' public ' . ExportCodegen::cgMakeIdentifier($table).'() { }'; + $lines[] = ' public ' + . ExportCodegen::cgMakeIdentifier($table) . '() { }'; $temp = array(); foreach ($tableProperties as $tableProperty) { if (! $tableProperty->isPK()) { @@ -290,7 +302,16 @@ class ExportCodegen extends ExportPlugin return implode("\n", $lines); } - function handleNHibernateXMLBody($db, $table, $crlf) + /** + * XML Handler + * + * @param string $db database name + * @param string $table table name + * @param string $crlf line separator + * + * @return string containing XML code lines, separated by "\n" + */ + private function _handleNHibernateXMLBody($db, $table, $crlf) { $lines = array(); $lines[] = ''; @@ -337,24 +358,48 @@ class ExportCodegen extends ExportPlugin /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - public function getCG_FORMATS() + /** + * Getter for CodeGen formats + * + * @return array + */ + private function _getCgFormats() { - return $this->_CG_FORMATS; + return $this->_cgFormats; } - private function setCG_FORMATS($CG_FORMATS) + /** + * Setter for CodeGen formats + * + * @param array $CG_FORMATS contains CodeGen Formats + * + * @return void + */ + private function _setCgFormats($CG_FORMATS) { - $this->_CG_FORMATS = $CG_FORMATS; + $this->_cgFormats = $CG_FORMATS; } - public function getCG_HANDLERS() + /** + * Getter for CodeGen handlers + * + * @return array + */ + private function _getCgHandlers() { - return $this->_CG_HANDLERS; + return $this->_cgHandlers; } - private function setCG_HANDLERS($CG_HANDLERS) + /** + * Setter for CodeGen handlers + * + * @param array $CG_HANDLERS contains CodeGen handler methods + * + * @return void + */ + private function _setCgHandlers($CG_HANDLERS) { - $this->_CG_HANDLERS = $CG_HANDLERS; + $this->_cgHandlers = $CG_HANDLERS; } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportCsv.class.php b/libraries/plugins/export/ExportCsv.class.php index 996893004e..24af87d603 100644 --- a/libraries/plugins/export/ExportCsv.class.php +++ b/libraries/plugins/export/ExportCsv.class.php @@ -22,61 +22,54 @@ require_once "libraries/plugins/ExportPlugin.class.php"; class ExportCsv extends ExportPlugin { /** + * The string used to end lines * - * - * @var type String + * @var string */ - protected $what; + private $_csvTerminated; /** + * The string used to separate columns * - * - * @var type String + * @var string */ - protected $csvTerminated; + private $_csvSeparator; /** + * The string used to enclose columns * - * - * @var type String + * @var string */ - protected $csvSeparator; + private $_csvEnclosed; /** + * The string used to escape columns * - * - * @var type String + * @var string */ - protected $csvEnclosed; - - /** - * - * - * @var type String - */ - protected $csvEscaped; + private $_csvEscaped; /** * Constructor */ public function __construct() { + // initialize the specific export csv variables + $this->initSpecificVariables(); $this->setProperties(); } /** - * Initialize the local variables that are used for export CSV + * Initialize the variables that are used for export CSV * * @return void */ - private function initLocalVariables() + protected function initSpecificVariables() { - global $what; global $csv_terminated; global $csv_separator; global $csv_enclosed; global $csv_escaped; - $this->setWhat($what); $this->setCsvTerminated($csv_terminated); $this->setCsvSeparator($csv_separator); $this->setCsvEnclosed($csv_enclosed); @@ -170,13 +163,11 @@ class ExportCsv extends ExportPlugin */ public function exportHeader () { - // initialize the general export variables - $this->initExportCommonVariables(); + // The type of the export plugin only has to be set once and then + // it will remain unchanged. This is the first time + global $what; + $this->setWhat($what); - // initialize the specific export sql variables - $this->initLocalVariables(); - - $what = $this->getWhat(); $csv_terminated = $this->getCsvTerminated(); $csv_separator = $this->getCsvSeparator(); $csv_enclosed = $this->getCsvEnclosed(); @@ -279,8 +270,6 @@ class ExportCsv extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { @@ -390,54 +379,92 @@ class ExportCsv extends ExportPlugin /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - public function getWhat() + /** + * Gets the string used to terminate lines + * + * @return string + */ + protected function getCsvTerminated() { - return $this->what; + return $this->_csvTerminated; } - public function setWhat($_what) + /** + * Sets the string used to terminate lines + * + * @param string $csvTerminated lines terminator + * + * @return void + */ + protected function setCsvTerminated($csvTerminated) { - $this->what = $_what; + $this->_csvTerminated = $csvTerminated; } - public function getCsvTerminated() + /** + * Gets the string used to separate columns + * + * @return string + */ + protected function getCsvSeparator() { - return $this->csvTerminated; + return $this->_csvSeparator; } - public function setCsvTerminated($_csvTerminated) + /** + * Sets the string used to separate columns + * + * @param string $csvSeparator columns separator + * + * @return void + */ + protected function setCsvSeparator($csvSeparator) { - $this->csvTerminated = $_csvTerminated; + $this->_csvSeparator = $csvSeparator; } - public function getCsvSeparator() + /** + * Gets the string used to enclose columns + * + * @return string + */ + protected function getCsvEnclosed() { - return $this->csvSeparator; + return $this->_csvEnclosed; } - public function setCsvSeparator($_csvSeparator) + /** + * Sets the string used to enclose columns + * + * @param string $csvEnclosed columns encloser + * + * @return void + */ + protected function setCsvEnclosed($csvEnclosed) { - $this->csvSeparator = $_csvSeparator; + $this->_csvEnclosed = $csvEnclosed; } - public function getCsvEnclosed() + /** + * Gets the string used to escape columns + * + * @return string + */ + protected function getCsvEscaped() { - return $this->csvEnclosed; + return $this->_csvEscaped; } - public function setCsvEnclosed($_csvEnclosed) + /** + * Sets the string used to escape columns + * + * @param string $csvEscaped columns escaper + * + * @return void + */ + protected function setCsvEscaped($csvEscaped) { - $this->csvEnclosed = $_csvEnclosed; - } - - public function getCsvEscaped() - { - return $this->csvEscaped; - } - - public function setCsvEscaped($_csvEscaped) - { - $this->csvEscaped = $_csvEscaped; + $this->_csvEscaped = $csvEscaped; } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportHtmlword.class.php b/libraries/plugins/export/ExportHtmlword.class.php index c1dfcf3f69..bd9e257ee3 100644 --- a/libraries/plugins/export/ExportHtmlword.class.php +++ b/libraries/plugins/export/ExportHtmlword.class.php @@ -16,31 +16,10 @@ require_once "libraries/plugins/ExportPlugin.class.php"; /** * Handles the export for the HTML-Word format * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportHtmlword extends ExportPlugin { - /** - * File Charset - * - * @var type String - */ - private $_charsetOfFile; - - /** - * - * - * @var type String - */ - private $_what; - - /** - * - * @var type - */ - private $_cfgRelation; - /** * Constructor */ @@ -49,22 +28,6 @@ class ExportHtmlword extends ExportPlugin $this->setProperties(); } - /** - * Initialize the local variables that are used for export HTML-Word - * - * @return void - */ - private function initLocalVariables() - { - global $charset_of_file; - global $what; - global $cfgRelation; - - $this->setCharsetOfFile($charset_of_file); - $this->setWhat($what); - $this->setCfgRelation($cfgRelation); - } - /** * Sets the export HTML-Word properties * @@ -144,11 +107,8 @@ class ExportHtmlword extends ExportPlugin */ public function exportHeader () { - // initialize the general export variables - $this->initExportCommonVariables(); - - // initialize the specific export sql variables - $this->initLocalVariables(); + global $charset_of_file; + $this->setCharsetOfFile($charset_of_file); return PMA_exportOutputHandler( ' + . (isset($charsetOfFile) ? $charsetOfFile : 'utf-8') . '" /> ' ); @@ -224,12 +184,11 @@ class ExportHtmlword extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { - $what = $this->getWhat(); + global $what; + $this->setWhat($what); if (! PMA_exportOutputHandler( '

' @@ -292,7 +251,7 @@ class ExportHtmlword extends ExportPlugin return true; } - /** + /** * Returns a stand-in CREATE definition to resolve view dependencies * * @param string $db the database name @@ -332,7 +291,10 @@ class ExportHtmlword extends ExportPlugin $columns = PMA_DBI_get_columns($db, $view); foreach ($columns as $column) { - $schema_insert .= $this->formatOneColumnDefinition($column, $unique_keys); + $schema_insert .= $this->formatOneColumnDefinition( + $column, + $unique_keys + ); $schema_insert .= ''; } @@ -361,10 +323,8 @@ class ExportHtmlword extends ExportPlugin * @param bool $view whether we're handling a view * * @return string resulting schema - * - * @access public */ - function getTableDef( + public function getTableDef( $db, $table, $crlf, @@ -376,6 +336,8 @@ class ExportHtmlword extends ExportPlugin $add_semicolon = true, $view = false ) { + // set $cfgRelation here, because there is a chance that it's modified + // since the class initialization global $cfgRelation; $this->setCfgRelation($cfgRelation); @@ -454,14 +416,17 @@ class ExportHtmlword extends ExportPlugin * Get the unique keys in the table */ $unique_keys = array(); - $keys = PMA_DBI_get_table_indexes($db, $table); + $keys = PMA_DBI_get_table_indexes($db, $table); foreach ($keys as $key) { if ($key['Non_unique'] == 0) { $unique_keys[] = $key['Column_name']; } } foreach ($columns as $column) { - $schema_insert .= $this->formatOneColumnDefinition($column, $unique_keys); + $schema_insert .= $this->formatOneColumnDefinition( + $column, + $unique_keys + ); $field_name = $column['Field']; if ($do_relation && $have_rel) { @@ -559,7 +524,7 @@ class ExportHtmlword extends ExportPlugin * * @return bool Whether it succeeded */ - function exportStructure( + public function exportStructure( $db, $table, $crlf, @@ -666,39 +631,5 @@ class ExportHtmlword extends ExportPlugin return $definition; } - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - public function getWhat() - { - return $this->_what; - } - - public function setWhat($what) - { - $this->_what = $what; - } - - public function getCharsetOfFile() - { - return $this->_charsetOfFile; - } - - public function setCharsetOfFile($charsetOfFile) - { - $this->_charsetOfFile = $charsetOfFile; - } - - public function getCfgRelation() - { - return $this->_cfgRelation; - } - - private function setCfgRelation($cfgRelation) - { - $this->_cfgRelation = $cfgRelation; - } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportJson.class.php b/libraries/plugins/export/ExportJson.class.php index 4fa6e19d9d..9d13b85f5c 100644 --- a/libraries/plugins/export/ExportJson.class.php +++ b/libraries/plugins/export/ExportJson.class.php @@ -16,7 +16,6 @@ require_once "libraries/plugins/ExportPlugin.class.php"; /** * Handles the export for the JSON format * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportJson extends ExportPlugin @@ -79,9 +78,6 @@ class ExportJson extends ExportPlugin */ public function exportHeader () { - // initialize the general export variables - $this->initExportCommonVariables(); - PMA_exportOutputHandler( '/**' . $GLOBALS['crlf'] . ' Export to JSON plugin for PHPMyAdmin' . $GLOBALS['crlf'] @@ -148,8 +144,6 @@ class ExportJson extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { @@ -179,11 +173,8 @@ class ExportJson extends ExportPlugin } for ($i = 0; $i < $columns_cnt; $i++) { - $isLastLine = ($i + 1 >= $columns_cnt); - $column = $columns[$i]; - if (is_null($record[$i])) { $buffer .= '"' . addslashes($column) . '": null' @@ -213,7 +204,6 @@ class ExportJson extends ExportPlugin } PMA_DBI_free_result($result); - return true; } } diff --git a/libraries/plugins/export/ExportLatex.class.php b/libraries/plugins/export/ExportLatex.class.php index 1ee4cc540d..06fe077370 100644 --- a/libraries/plugins/export/ExportLatex.class.php +++ b/libraries/plugins/export/ExportLatex.class.php @@ -16,30 +16,17 @@ require_once "libraries/plugins/ExportPlugin.class.php"; /** * Handles the export for the Latex format * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportLatex extends ExportPlugin { - /** - * - * @var type array - */ - private $_pluginParam; - - /** - * - * @var type - */ - private $_cfgRelation; - /** * Constructor */ public function __construct() { // initialize the specific export sql variables - $this->initLocalVariables(); + $this->initSpecificVariables(); $this->setProperties(); } @@ -49,13 +36,8 @@ class ExportLatex extends ExportPlugin * * @return void */ - private function initLocalVariables() + protected function initSpecificVariables() { - global $plugin_param; - global $cfgRelation; - $this->setPluginParam($plugin_param); - $this->setCfgRelation($cfgRelation); - /* Messages used in default captions */ $GLOBALS['strLatexContent'] = __('Content of table @TABLE@'); $GLOBALS['strLatexContinued'] = __('(continued)'); @@ -229,11 +211,10 @@ class ExportLatex extends ExportPlugin */ public function exportHeader () { - // initialize the general export variables - $this->initExportCommonVariables(); - - $crlf = $this->getCrlf(); - $cfg = $this->getCfg(); + global $crlf; + global $cfg; + $this->setCrlf($crlf); + $this->setCfg($cfg); $head = '% phpMyAdmin LaTeX Dump' . $crlf . '% version ' . PMA_VERSION . $crlf @@ -310,8 +291,6 @@ class ExportLatex extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { @@ -390,7 +369,6 @@ class ExportLatex extends ExportPlugin // print the whole table while ($record = PMA_DBI_fetch_assoc($result)) { - $buffer = ''; // print each row for ($i = 0; $i < $columns_cnt; $i++) { @@ -449,7 +427,7 @@ class ExportLatex extends ExportPlugin * * @return bool Whether it succeeded */ - function exportStructure( + public function exportStructure( $db, $table, $crlf, @@ -659,29 +637,5 @@ class ExportLatex extends ExportPlugin } return $string; } - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - public function getPluginParam() - { - return $this->_pluginParam; - } - - private function setPluginParam($pluginParam) - { - $this->_pluginParam = $pluginParam; - } - - public function getCfgRelation() - { - return $this->_cfgRelation; - } - - private function setCfgRelation($cfgRelation) - { - $this->_cfgRelation = $cfgRelation; - } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportMediawiki.class.php b/libraries/plugins/export/ExportMediawiki.class.php index 2478b99194..d372a64548 100644 --- a/libraries/plugins/export/ExportMediawiki.class.php +++ b/libraries/plugins/export/ExportMediawiki.class.php @@ -16,7 +16,6 @@ require_once "libraries/plugins/ExportPlugin.class.php"; /** * Handles the export for the MediaWiki class * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportMediawiki extends ExportPlugin @@ -174,17 +173,15 @@ class ExportMediawiki extends ExportPlugin * @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() + * because export.php calls 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( + public function exportStructure( $db, $table, $crlf, @@ -203,55 +200,56 @@ class ExportMediawiki extends ExportPlugin $row_cnt = count($columns); // Print structure comment - $output = $this->exportComment( + $output = $this->_exportComment( "Table structure for " . PMA_backquote($table) ); // Begin the table construction $output .= "{| class=\"wikitable\" style=\"text-align:center;\"" - . $this->exportCRLF(); + . $this->_exportCRLF(); // Add the table name if ($GLOBALS['mediawiki_caption']) { - $output .= "|+'''" . $table . "'''" . $this->exportCRLF(); + $output .= "|+'''" . $table . "'''" . $this->_exportCRLF(); } // Add the table headers if ($GLOBALS['mediawiki_headers']) { - $output .= "|- style=\"background:#ffdead;\"" . $this->exportCRLF(); - $output .= "! style=\"background:#ffffff\" | " . $this->exportCRLF(); + $output .= "|- style=\"background:#ffdead;\"" . $this->_exportCRLF(); + $output .= "! style=\"background:#ffffff\" | " + . $this->_exportCRLF(); for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Field']. $this->exportCRLF(); + $output .= " | " . $columns[$i]['Field']. $this->_exportCRLF(); } } // Add the table structure - $output .= "|-" . $this->exportCRLF(); - $output .= "! Type" . $this->exportCRLF(); + $output .= "|-" . $this->_exportCRLF(); + $output .= "! Type" . $this->_exportCRLF(); for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Type'] . $this->exportCRLF(); + $output .= " | " . $columns[$i]['Type'] . $this->_exportCRLF(); } - $output .= "|-" . $this->exportCRLF(); - $output .= "! Null" . $this->exportCRLF(); + $output .= "|-" . $this->_exportCRLF(); + $output .= "! Null" . $this->_exportCRLF(); for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Null'] . $this->exportCRLF(); + $output .= " | " . $columns[$i]['Null'] . $this->_exportCRLF(); } - $output .= "|-" . $this->exportCRLF(); - $output .= "! Default" . $this->exportCRLF(); + $output .= "|-" . $this->_exportCRLF(); + $output .= "! Default" . $this->_exportCRLF(); for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Default'] . $this->exportCRLF(); + $output .= " | " . $columns[$i]['Default'] . $this->_exportCRLF(); } - $output .= "|-" . $this->exportCRLF(); - $output .= "! Extra" . $this->exportCRLF(); + $output .= "|-" . $this->_exportCRLF(); + $output .= "! Extra" . $this->_exportCRLF(); for ($i = 0; $i < $row_cnt; ++$i) { - $output .= " | " . $columns[$i]['Extra'] . $this->exportCRLF(); + $output .= " | " . $columns[$i]['Extra'] . $this->_exportCRLF(); } - $output .= "|}" . str_repeat($this->exportCRLF(), 2); + $output .= "|}" . str_repeat($this->_exportCRLF(), 2); break; } // end switch @@ -268,10 +266,8 @@ class ExportMediawiki extends ExportPlugin * @param string $sql_query SQL query for obtaining data * * @return bool Whether it succeeded - * - * @access public */ - function exportData( + public function exportData( $db, $table, $crlf, @@ -279,17 +275,17 @@ class ExportMediawiki extends ExportPlugin $sql_query ) { // Print data comment - $output = $this->exportComment("Table data for ". PMA_backquote($table)); + $output = $this->_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;\"" - . $this->exportCRLF(); + . $this->_exportCRLF(); // Add the table name if ($GLOBALS['mediawiki_caption']) { - $output .= "|+'''" . $table . "'''" . $this->exportCRLF(); + $output .= "|+'''" . $table . "'''" . $this->_exportCRLF(); } // Add the table headers @@ -300,11 +296,11 @@ class ExportMediawiki extends ExportPlugin // Add column names as table headers if ( ! is_null($column_names) ) { // Use '|-' for separating rows - $output .= "|-" . $this->exportCRLF(); + $output .= "|-" . $this->_exportCRLF(); // Use '!' for separating table headers foreach ($column_names as $column) { - $output .= " ! " . $column . "" . $this->exportCRLF(); + $output .= " ! " . $column . "" . $this->_exportCRLF(); } } } @@ -314,16 +310,16 @@ class ExportMediawiki extends ExportPlugin $fields_cnt = PMA_DBI_num_fields($result); while ($row = PMA_DBI_fetch_row($result)) { - $output .= "|-" . $this->exportCRLF(); + $output .= "|-" . $this->_exportCRLF(); // Use '|' for separating table columns for ($i = 0; $i < $fields_cnt; ++ $i) { - $output .= " | " . $row[$i] . "" . $this->exportCRLF(); + $output .= " | " . $row[$i] . "" . $this->_exportCRLF(); } } // End table construction - $output .= "|}" . str_repeat($this->exportCRLF(), 2); + $output .= "|}" . str_repeat($this->_exportCRLF(), 2); return PMA_exportOutputHandler($output); } @@ -334,13 +330,13 @@ class ExportMediawiki extends ExportPlugin * * @return string The formatted comment */ - private function exportComment($text = '') + private function _exportComment($text = '') { // see http://www.mediawiki.org/wiki/Help:Formatting - $comment = $this->exportCRLF(); - $comment .= '' . str_repeat($this->exportCRLF(), 2); + $comment = $this->_exportCRLF(); + $comment .= '' . str_repeat($this->_exportCRLF(), 2); return $comment; } @@ -350,7 +346,7 @@ class ExportMediawiki extends ExportPlugin * * @return string CRLF */ - private function exportCRLF() + private function _exportCRLF() { // The CRLF expected by the mediawiki format is "\n" return "\n"; diff --git a/libraries/plugins/export/ExportOds.class.php b/libraries/plugins/export/ExportOds.class.php index 9a5bf83b10..ae320cc926 100644 --- a/libraries/plugins/export/ExportOds.class.php +++ b/libraries/plugins/export/ExportOds.class.php @@ -14,45 +14,23 @@ if (! defined('PHPMYADMIN')) { require_once "libraries/plugins/ExportPlugin.class.php"; $GLOBALS['ods_buffer'] = ''; -include_once 'libraries/opendocument.lib.php'; +require_once 'libraries/opendocument.lib.php'; /** * Handles the export for the ODS class * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportOds extends ExportPlugin { - /** - * - * - * @var type string - */ - private $_what; - /** * Constructor */ public function __construct() { - // initialize the specific export ODS variables - $this->initLocalVariables(); - $this->setProperties(); } - /** - * Initialize the local variables that are used for export ODS - * - * @return void - */ - private function initLocalVariables() - { - global $what; - $this->setWhat($what); - } - /** * Sets the export ODS properties * @@ -218,6 +196,7 @@ class ExportOds extends ExportPlugin { return true; } + /** * Outputs the content of a table in NHibernate format * @@ -231,7 +210,8 @@ class ExportOds extends ExportPlugin */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { - $what = $this->getWhat(); + global $what; + $this->setWhat($what); // Gets the data from the database $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); @@ -338,19 +318,5 @@ class ExportOds extends ExportPlugin return true; } - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - public function getWhat() - { - return $this->_what; - } - - public function setWhat($what) - { - $this->_what = $what; - } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportOdt.class.php b/libraries/plugins/export/ExportOdt.class.php index 51c368433a..a6eac3b61a 100644 --- a/libraries/plugins/export/ExportOdt.class.php +++ b/libraries/plugins/export/ExportOdt.class.php @@ -14,61 +14,23 @@ if (! defined('PHPMYADMIN')) { require_once "libraries/plugins/ExportPlugin.class.php"; $GLOBALS['odt_buffer'] = ''; -include_once 'libraries/opendocument.lib.php'; +require_once 'libraries/opendocument.lib.php'; /** * Handles the export for the ODT class * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportOdt extends ExportPlugin { - /** - * - * - * @var type string - */ - private $_what; - - /** - * - * @var type array - */ - private $_pluginParam; - - /** - * - * @var type - */ - private $_cfgRelation; - /** * Constructor */ public function __construct() { - // initialize the specific export ODT variables - $this->initLocalVariables(); - $this->setProperties(); } - /** - * Initialize the local variables that are used for export ODT - * - * @return void - */ - private function initLocalVariables() - { - global $what; - global $plugin_param; - global $cfgRelation; - $this->setWhat($what); - $this->setPluginParam($plugin_param); - $this->setCfgRelation($cfgRelation); - } - /** * Sets the export ODT properties * @@ -186,9 +148,6 @@ class ExportOdt extends ExportPlugin */ public function exportHeader () { - // initialize the general export variables - $this->initExportCommonVariables(); - $GLOBALS['odt_buffer'] .= '' . '' @@ -271,7 +230,8 @@ class ExportOdt extends ExportPlugin */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { - $what = $this->getWhat(); + global $what; + $this->setWhat($what); // Gets the data from the database $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); @@ -365,7 +325,7 @@ class ExportOdt extends ExportPlugin * * @return bool true */ - function getTableDefStandIn($db, $view, $crlf) + public function getTableDefStandIn($db, $view, $crlf) { /** * Gets fields properties @@ -426,6 +386,8 @@ class ExportOdt extends ExportPlugin * @param bool $add_semicolon whether to add semicolon and end-of-line at * the end * @param bool $view whether we're handling a view + * + * @return bool true */ public function getTableDef( $db, @@ -439,7 +401,8 @@ class ExportOdt extends ExportPlugin $add_semicolon = true, $view = false ) { - $cfgRelation = $this->getCfgRelation(); + global $cfgRelation; + $this->setCfgRelation($cfgRelation); /** * Gets fields properties @@ -576,7 +539,7 @@ class ExportOdt extends ExportPlugin * * @return bool true */ - function getTriggers($db, $table) + protected function getTriggers($db, $table) { $GLOBALS['odt_buffer'] .= '' @@ -649,7 +612,7 @@ class ExportOdt extends ExportPlugin * * @return bool Whether it succeeded */ - function exportStructure( + public function exportStructure( $db, $table, $crlf, @@ -757,39 +720,5 @@ class ExportOdt extends ExportPlugin . ''; return $definition; } - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - public function getWhat() - { - return $this->_what; - } - - public function setWhat($what) - { - $this->_what = $what; - } - - public function getPluginParam() - { - return $this->_pluginParam; - } - - private function setPluginParam($pluginParam) - { - $this->_pluginParam = $pluginParam; - } - - public function getCfgRelation() - { - return $this->_cfgRelation; - } - - private function setCfgRelation($cfgRelation) - { - $this->_cfgRelation = $cfgRelation; - } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportPdf.class.php b/libraries/plugins/export/ExportPdf.class.php index 2f0534ad52..9aa41553f8 100644 --- a/libraries/plugins/export/ExportPdf.class.php +++ b/libraries/plugins/export/ExportPdf.class.php @@ -18,12 +18,22 @@ require_once 'libraries/plugins/export/PMA_ExportPdf.class.php'; /** * Handles the export for the PDF class * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportPdf extends ExportPlugin { + /** + * PMA_ExportPdf instance + * + * @var PMA_ExportPdf + */ private $_pdf; + + /** + * PDF Report Title + * + * @var string + */ private $_pdfReportTitle; /** @@ -32,7 +42,7 @@ class ExportPdf extends ExportPlugin public function __construct() { // initialize the specific export PDF variables - $this->initLocalVariables(); + $this->initSpecificVariables(); $this->setProperties(); } @@ -42,11 +52,10 @@ class ExportPdf extends ExportPlugin * * @return void */ - private function initLocalVariables() + protected function initSpecificVariables() { - global $pdf_report_title; - $this->setPdfReportTitle($pdf_report_title); - $this->setPdf(new PMA_ExportPdf('L', 'pt', 'A3')); + $this->_setPdfReportTitle(""); + $this->_setPdf(new PMA_ExportPdf('L', 'pt', 'A3')); } /** @@ -112,8 +121,8 @@ class ExportPdf extends ExportPlugin */ public function exportHeader () { - $pdf_report_title = $this->getPdfReportTitle(); - $pdf = $this->getPdf(); + $pdf_report_title = $this->_getPdfReportTitle(); + $pdf = $this->_getPdf(); $pdf->Open(); $attr = array('titleFontSize' => 18, 'titleText' => $pdf_report_title); @@ -130,7 +139,7 @@ class ExportPdf extends ExportPlugin */ public function exportFooter () { - $pdf = $this->getPdf(); + $pdf = $this->_getPdf(); // instead of $pdf->Output(): if (! PMA_exportOutputHandler($pdf->getPDFData())) { @@ -188,7 +197,7 @@ class ExportPdf extends ExportPlugin */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { - $pdf = $this->getPdf(); + $pdf = $this->_getPdf(); $attr = array('currentDb' => $db, 'currentTable' => $table); $pdf->setAttributes($attr); @@ -201,24 +210,48 @@ class ExportPdf extends ExportPlugin /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - public function getPdf() + /** + * Gets the PMA_ExportPdf instance + * + * @return PMA_ExportPdf + */ + private function _getPdf() { return $this->_pdf; } - public function setPdf($pdf) + /** + * Instantiates the PMA_ExportPdf class + * + * @param string $pdf PMA_ExportPdf instance + * + * @return void + */ + private function _setPdf($pdf) { $this->_pdf = $pdf; } - public function getPdfReportTitle() + /** + * Gets the PDF report title + * + * @return string + */ + private function _getPdfReportTitle() { return $this->_pdfReportTitle; } - public function setPdfReportTitle($pdf_report_title) + /** + * Sets the PDF report title + * + * @param string $pdfReportTitle PDF report title + * + * @return void + */ + private function _setPdfReportTitle($pdfReportTitle) { - $this->_pdfReportTitle = $pdf_report_title; + $this->_pdfReportTitle = $pdfReportTitle; } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportPhp_array.class.php b/libraries/plugins/export/ExportPhparray.class.php similarity index 99% rename from libraries/plugins/export/ExportPhp_array.class.php rename to libraries/plugins/export/ExportPhparray.class.php index 70e632428f..7046aa5ef5 100644 --- a/libraries/plugins/export/ExportPhp_array.class.php +++ b/libraries/plugins/export/ExportPhparray.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/ExportPlugin.class.php"; * * @package PhpMyAdmin-Export */ -class ExportPhp_array extends ExportPlugin +class ExportPhparray extends ExportPlugin { /** * Constructor @@ -138,6 +138,7 @@ class ExportPhp_array extends ExportPlugin { return true; } + /** * Outputs the content of a table in NHibernate format * diff --git a/libraries/plugins/export/ExportSql.class.php b/libraries/plugins/export/ExportSql.class.php index 9846af7603..6424852876 100644 --- a/libraries/plugins/export/ExportSql.class.php +++ b/libraries/plugins/export/ExportSql.class.php @@ -22,67 +22,53 @@ require_once "libraries/plugins/ExportPlugin.class.php"; class ExportSql extends ExportPlugin { /** + * MySQL charset map * - * - * @var type + * @var array */ - private $_plugin_param = null; + private $_mysqlCharsetMap; /** + * SQL for dropping a table * - * - * @var type + * @var string */ - private $_mysql_charset_map = null; + private $_sqlDropTable; /** + * SQL Backquotes * - * - * @var type + * @var bool */ - private $_sql_drop_table; + private $_sqlBackquotes; /** + * SQL Constraints * - * - * @var type + * @var string */ - private $_sql_backquotes; + private $_sqlConstraints; /** + * The text of the SQL query * - * - * @var type + * @var string */ - private $_sql_constraints; + private $_sqlConstraintsQuery; /** - * Just the text of the query + * SQL for dropping foreign keys * - * @var type string + * @var string */ - private $_sql_constraints_query; + private $_sqlDropForeignKeys; /** + * The number of the current row * - * - * @var type + * @var int */ - private $_sql_drop_foreign_keys; - - /** - * - * - * @var type - */ - private $_cfgRelation; - - /** - * - * - * @var type - */ - private $_current_row; + private $_currentRow; /** * Constructor @@ -100,48 +86,39 @@ class ExportSql extends ExportPlugin /** * Initialize the local variables that are used specific for export SQL * - * @global type $plugin_param - * @global type $mysql_charset_map - * @global type $sql_drop_table - * @global type $sql_backquotes - * @global type $sql_constraints - * @global type $sql_constraints_query - * @global type $sql_drop_foreign_keys - * @global type $cfgRelation - * @global type $current_row + * @global array $mysql_charset_map + * @global string $sql_drop_table + * @global bool $sql_backquotes + * @global string $sql_constraints + * @global string $sql_constraints_query + * @global string $sql_drop_foreign_keys + * @global int $current_row * * @return void */ - private function initLocalVariables() + protected function initSpecificVariables() { - global $plugin_param; - global $mysql_charset_map; global $sql_drop_table; global $sql_backquotes; global $sql_constraints; global $sql_constraints_query; global $sql_drop_foreign_keys; - global $cfgRelation; - global $current_row; - $this->setPlugin_param($plugin_param); - $this->setMysql_charset_map($mysql_charset_map); - $this->setSql_drop_table($sql_drop_table); - $this->setSql_backquotes($sql_backquotes); - $this->setSql_constraints($sql_constraints); - $this->setSql_constraints_query($sql_constraints_query); - $this->setSql_drop_foreign_keys($sql_drop_foreign_keys); - $this->setCfgRelation($cfgRelation); - $this->setCurrent_row($current_row); + $this->_setSqlDropTable($sql_drop_table); + $this->_setSqlBackquotes($sql_backquotes); + $this->_setSqlConstraints($sql_constraints); + $this->_setSqlConstraintsQuery($sql_constraints_query); + $this->_setSqlDropForeignKeys($sql_drop_foreign_keys); } /** - * Sets the export XML properties + * Sets the export SQL properties * * @return void */ protected function setProperties() { - $plugin_param = $this->getPlugin_param(); + global $plugin_param; + $this->setPluginParam($plugin_param); $hide_sql = false; $hide_structure = false; @@ -172,8 +149,8 @@ class ExportSql extends ExportPlugin 'type' => 'bool', 'name' => 'include_comments', 'text' => __( - 'Display comments (includes info such as export timestamp,' - . ' PHP version, and server version)' + 'Display comments (includes info such as export' + . ' timestamp, PHP version, and server version)' ) ) ); @@ -546,6 +523,9 @@ class ExportSql extends ExportPlugin */ public function exportRoutines($db) { + global $crlf; + $this->setCrlf($crlf); + $text = ''; $delimiter = '$$'; @@ -559,9 +539,9 @@ class ExportSql extends ExportPlugin if ($procedure_names) { $text .= - $this->exportComment() - . $this->exportComment(__('Procedures')) - . $this->exportComment(); + $this->_exportComment() + . $this->_exportComment(__('Procedures')) + . $this->_exportComment(); foreach ($procedure_names as $procedure_name) { if (! empty($GLOBALS['sql_drop_table'])) { @@ -576,9 +556,9 @@ class ExportSql extends ExportPlugin if ($function_names) { $text .= - $this->exportComment() - . $this->exportComment(__('Functions')) - . $this->exportComment(); + $this->_exportComment() + . $this->_exportComment(__('Functions')) + . $this->_exportComment(); foreach ($function_names as $function_name) { if (! empty($GLOBALS['sql_drop_table'])) { @@ -609,7 +589,7 @@ class ExportSql extends ExportPlugin * * @return string The formatted comment */ - private function exportComment($text = '') + private function _exportComment($text = '') { if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments'] @@ -626,7 +606,7 @@ class ExportSql extends ExportPlugin * * @return string $crlf or nothing */ - private function possibleCRLF() + private function _possibleCRLF() { if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments'] @@ -641,13 +621,12 @@ class ExportSql extends ExportPlugin * Outputs export footer * * @return bool Whether it succeeded - * - * @access public */ public function exportFooter() { - $crlf = $this->getCrlf(); - $mysql_charset_map = $this->getMysql_charset_map(); + global $crlf; + $this->setCrlf($crlf); + $mysql_charset_map = $this->_getMysqlCharsetMap(); $foot = ''; @@ -688,20 +667,14 @@ class ExportSql extends ExportPlugin * the required variables are initialized here. * * @return bool Whether it succeeded - * - * @access public */ public function exportHeader() { - // initialize the general export variables - $this->initExportCommonVariables(); - - // initialize the specific export sql variables - $this->initLocalVariables(); - - $crlf = $this->getCrlf(); - $cfg = $this->getCfg(); - $mysql_charset_map = $this->getMysql_charset_map(); + global $crlf, $cfg; + global $mysql_charset_map; + $this->setCrlf($crlf); + $this->setCfg($cfg); + $this->_setMysqlCharsetMap($mysql_charset_map); if (isset($GLOBALS['sql_compatibility'])) { $tmp_compat = $GLOBALS['sql_compatibility']; @@ -711,22 +684,24 @@ class ExportSql extends ExportPlugin PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"'); unset($tmp_compat); } - $head = $this->exportComment('phpMyAdmin SQL Dump') - . $this->exportComment('version ' . PMA_VERSION) - . $this->exportComment('http://www.phpmyadmin.net') - . $this->exportComment(); + $head = $this->_exportComment('phpMyAdmin SQL Dump') + . $this->_exportComment('version ' . PMA_VERSION) + . $this->_exportComment('http://www.phpmyadmin.net') + . $this->_exportComment(); $host_string = __('Host') . ': ' . $cfg['Server']['host']; if (! empty($cfg['Server']['port'])) { $host_string .= ':' . $cfg['Server']['port']; } - $head .= $this->exportComment($host_string); + $head .= $this->_exportComment($host_string); $head .= - $this->exportComment( + $this->_exportComment( __('Generation Time') . ': ' . PMA_localisedDate() ) - . $this->exportComment(__('Server version') . ': ' . PMA_MYSQL_STR_VERSION) - . $this->exportComment(__('PHP Version') . ': ' . phpversion()) - . $this->possibleCRLF(); + . $this->_exportComment( + __('Server version') . ': ' . PMA_MYSQL_STR_VERSION + ) + . $this->_exportComment(__('PHP Version') . ': ' . phpversion()) + . $this->_possibleCRLF(); if (isset($GLOBALS['sql_header_comment']) && ! empty($GLOBALS['sql_header_comment']) @@ -734,11 +709,11 @@ class ExportSql extends ExportPlugin // '\n' is not a newline (like "\n" would be), it's the characters // backslash and n, as explained on the export interface $lines = explode('\n', $GLOBALS['sql_header_comment']); - $head .= $this->exportComment(); + $head .= $this->_exportComment(); foreach ($lines as $one_line) { - $head .= $this->exportComment($one_line); + $head .= $this->_exportComment($one_line); } - $head .= $this->exportComment(); + $head .= $this->_exportComment(); } if (isset($GLOBALS['sql_disable_fk'])) { @@ -766,7 +741,7 @@ class ExportSql extends ExportPlugin PMA_DBI_query('SET time_zone = "+00:00"'); } - $head .= $this->possibleCRLF(); + $head .= $this->_possibleCRLF(); if (! empty($GLOBALS['asfile']) && ! PMA_DRIZZLE) { // we are saving as file, therefore we provide charset information @@ -803,7 +778,8 @@ class ExportSql extends ExportPlugin */ public function exportDBCreate($db) { - $crlf = $this->getCrlf(); + global $crlf; + $this->setCrlf($crlf); if (isset($GLOBALS['sql_drop_database'])) { if (! PMA_exportOutputHandler( 'DROP DATABASE ' @@ -856,13 +832,13 @@ class ExportSql extends ExportPlugin */ public function exportDBHeader($db) { - $head = $this->exportComment() - . $this->exportComment( + $head = $this->_exportComment() + . $this->_exportComment( __('Database') . ': ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : '\'' . $db . '\'') ) - . $this->exportComment(); + . $this->_exportComment(); return PMA_exportOutputHandler($head); } @@ -875,7 +851,8 @@ class ExportSql extends ExportPlugin */ public function exportDBFooter($db) { - $crlf = $this->getCrlf(); + global $crlf; + $this->setCrlf($crlf); $result = true; if (isset($GLOBALS['sql_constraints'])) { @@ -904,9 +881,9 @@ class ExportSql extends ExportPlugin . 'DELIMITER ' . $delimiter . $crlf; $text .= - $this->exportComment() - . $this->exportComment(__('Events')) - . $this->exportComment(); + $this->_exportComment() + . $this->_exportComment(__('Events')) + . $this->_exportComment(); foreach ($event_names as $event_name) { if (! empty($GLOBALS['sql_drop_table'])) { @@ -984,11 +961,13 @@ class ExportSql extends ExportPlugin $add_semicolon = true, $view = false ) { - $sql_drop_table = $this->getSql_drop_table(); - $sql_backquotes = $this->getSql_backquotes(); - $sql_constraints = $this->getSql_constraints(); - $sql_constraints_query = $this->getSql_constraints_query(); - $sql_drop_foreign_keys = $this->getSql_drop_foreign_keys(); + $this->initSpecificVariables(); + + $sql_drop_table = $this->_getSqlDropTable(); + $sql_backquotes = $this->_getSqlBackquotes(); + $sql_constraints = $this->_getSqlConstraints(); + $sql_constraints_query = $this->_getSqlConstraintsQuery(); + $sql_drop_foreign_keys = $this->_getSqlDropForeignKeys(); $schema_create = ''; $auto_increment = ''; @@ -1031,33 +1010,33 @@ class ExportSql extends ExportPlugin && isset($tmpres['Create_time']) && ! empty($tmpres['Create_time']) ) { - $schema_create .= $this->exportComment( + $schema_create .= $this->_exportComment( __('Creation') . ': ' . PMA_localisedDate(strtotime($tmpres['Create_time'])) ); - $new_crlf = $this->exportComment() . $crlf; + $new_crlf = $this->_exportComment() . $crlf; } if ($show_dates && isset($tmpres['Update_time']) && ! empty($tmpres['Update_time']) ) { - $schema_create .= $this->exportComment( + $schema_create .= $this->_exportComment( __('Last update') . ': ' . PMA_localisedDate(strtotime($tmpres['Update_time'])) ); - $new_crlf = $this->exportComment() . $crlf; + $new_crlf = $this->_exportComment() . $crlf; } if ($show_dates && isset($tmpres['Check_time']) && ! empty($tmpres['Check_time']) ) { - $schema_create .= $this->exportComment( + $schema_create .= $this->_exportComment( __('Last check') . ': ' . PMA_localisedDate(strtotime($tmpres['Check_time'])) ); - $new_crlf = $this->exportComment() . $crlf; + $new_crlf = $this->_exportComment() . $crlf; } } PMA_DBI_free_result($result); @@ -1098,7 +1077,7 @@ class ExportSql extends ExportPlugin // an error can happen, for example the table is crashed $tmp_error = PMA_DBI_getError(); if ($tmp_error) { - return $this->exportComment(__('in use') . '(' . $tmp_error . ')'); + return $this->_exportComment(__('in use') . '(' . $tmp_error . ')'); } if ($result != false && ($row = PMA_DBI_fetch_row($result))) { @@ -1183,24 +1162,24 @@ class ExportSql extends ExportPlugin $sql_constraints = ''; } else { $sql_constraints = $crlf - . $this->exportComment() - . $this->exportComment( + . $this->_exportComment() + . $this->_exportComment( __('Constraints for dumped tables') ) - . $this->exportComment(); + . $this->_exportComment(); } } // comments for current table if (! isset($GLOBALS['no_constraints_comments'])) { $sql_constraints .= $crlf - . $this->exportComment() - . $this->exportComment( + . $this->_exportComment() + . $this->_exportComment( __('Constraints for table') . ' ' . PMA_backquote($table) ) - . $this->exportComment(); + . $this->_exportComment(); } // let's do the work @@ -1298,16 +1277,16 @@ class ExportSql extends ExportPlugin * * @return string resulting comments */ - private function getTableComments( + private function _getTableComments( $db, $table, $crlf, $do_relation = false, $do_mime = false ) { - $cfgRelation = $this->getCfgRelation(); - $sql_backquotes = $this->getSql_backquotes(); - + global $cfgRelation; + $this->setCfgRelation($cfgRelation); + $sql_backquotes = $this->_getSqlBackquotes(); $schema_create = ''; // Check if we can use Relations @@ -1332,54 +1311,54 @@ class ExportSql extends ExportPlugin } if (isset($mime_map) && count($mime_map) > 0) { - $schema_create .= $this->possibleCRLF() - . $this->exportComment() - . $this->exportComment( + $schema_create .= $this->_possibleCRLF() + . $this->_exportComment() + . $this->_exportComment( __('MIME TYPES FOR TABLE'). ' ' . PMA_backquote($table, $sql_backquotes) . ':' ); @reset($mime_map); foreach ($mime_map AS $mime_field => $mime) { $schema_create .= - $this->exportComment( + $this->_exportComment( ' ' . PMA_backquote($mime_field, $sql_backquotes) ) - . $this->exportComment( + . $this->_exportComment( ' ' . PMA_backquote($mime['mimetype'], $sql_backquotes) ); } - $schema_create .= $this->exportComment(); + $schema_create .= $this->_exportComment(); } if ($have_rel) { - $schema_create .= $this->possibleCRLF() - . $this->exportComment() - . $this->exportComment( + $schema_create .= $this->_possibleCRLF() + . $this->_exportComment() + . $this->_exportComment( __('RELATIONS FOR TABLE') . ' ' . PMA_backquote($table, $sql_backquotes) . ':' ); foreach ($res_rel AS $rel_field => $rel) { $schema_create .= - $this->exportComment( + $this->_exportComment( ' ' . PMA_backquote($rel_field, $sql_backquotes) ) - . $this->exportComment( + . $this->_exportComment( ' ' . PMA_backquote($rel['foreign_table'], $sql_backquotes) . ' -> ' . PMA_backquote($rel['foreign_field'], $sql_backquotes) ); } - $schema_create .= $this->exportComment(); + $schema_create .= $this->_exportComment(); } return $schema_create; - } // end of the 'getTableComments()' function + } // end of the '_getTableComments()' function /** * Outputs table's structure @@ -1415,32 +1394,31 @@ class ExportSql extends ExportPlugin $dates = false ) { $formatted_table_name = (isset($GLOBALS['sql_backquotes'])) - ? PMA_backquote($table) - : '\'' . $table . '\''; - $dump = $this->possibleCRLF() - . $this->exportComment(str_repeat('-', 56)) - . $this->possibleCRLF() - . $this->exportComment(); + ? PMA_backquote($table) : '\'' . $table . '\''; + $dump = $this->_possibleCRLF() + . $this->_exportComment(str_repeat('-', 56)) + . $this->_possibleCRLF() + . $this->_exportComment(); switch($export_mode) { case 'create_table': - $dump .= $this->exportComment( + $dump .= $this->_exportComment( __('Table structure for table') . ' '. $formatted_table_name ); - $dump .= $this->exportComment(); + $dump .= $this->_exportComment(); $dump .= $this->getTableDef($db, $table, $crlf, $error_url, $dates); - $dump .= $this->getTableComments($db, $table, $crlf, $relation, $mime); + $dump .= $this->_getTableComments($db, $table, $crlf, $relation, $mime); break; case 'triggers': $dump = ''; $triggers = PMA_DBI_get_triggers($db, $table); if ($triggers) { - $dump .= $this->possibleCRLF() - . $this->exportComment() - . $this->exportComment( + $dump .= $this->_possibleCRLF() + . $this->_exportComment() + . $this->_exportComment( __('Triggers') . ' ' . $formatted_table_name ) - . $this->exportComment(); + . $this->_exportComment(); $delimiter = '//'; foreach ($triggers as $trigger) { $dump .= $trigger['drop'] . ';' . $crlf; @@ -1452,12 +1430,12 @@ class ExportSql extends ExportPlugin break; case 'create_view': $dump .= - $this->exportComment( + $this->_exportComment( __('Structure for view') . ' ' . $formatted_table_name ) - . $this->exportComment(); + . $this->_exportComment(); // delete the stand-in table previously created (if any) if ($export_type != 'table') { $dump .= 'DROP TABLE IF EXISTS ' @@ -1469,10 +1447,10 @@ class ExportSql extends ExportPlugin break; case 'stand_in': $dump .= - $this->exportComment( + $this->_exportComment( __('Stand-in structure for view') . ' ' . $formatted_table_name ) - . $this->exportComment(); + . $this->_exportComment(); // export a stand-in definition to resolve view dependencies $dump .= getTableDefStandIn($db, $table, $crlf); } // end switch @@ -1497,22 +1475,22 @@ class ExportSql extends ExportPlugin */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { - $sql_backquotes = $this->getSql_backquotes(); - $current_row = $this->getCurrent_row(); + global $current_row; + $this->_setCurrentRow($current_row); + $sql_backquotes = $this->_getSqlBackquotes(); $formatted_table_name = (isset($GLOBALS['sql_backquotes'])) - ? PMA_backquote($table) - : '\'' . $table . '\''; + ? PMA_backquote($table) : '\'' . $table . '\''; // Do not export data for a VIEW // (For a VIEW, this is called only when exporting a single VIEW) if (PMA_Table::isView($db, $table)) { - $head = $this->possibleCRLF() - . $this->exportComment() - . $this->exportComment('VIEW ' . ' ' . $formatted_table_name) - . $this->exportComment(__('Data') . ': ' . __('None')) - . $this->exportComment() - . $this->possibleCRLF(); + $head = $this->_possibleCRLF() + . $this->_exportComment() + . $this->_exportComment('VIEW ' . ' ' . $formatted_table_name) + . $this->_exportComment(__('Data') . ': ' . __('None')) + . $this->_exportComment() + . $this->_possibleCRLF(); if (! PMA_exportOutputHandler($head)) { return false; @@ -1530,7 +1508,7 @@ class ExportSql extends ExportPlugin $tmp_error = PMA_DBI_getError(); if ($tmp_error) { return PMA_exportOutputHandler( - $this->exportComment( + $this->_exportComment( __('Error reading data:') . ' (' . $tmp_error . ')' ) ); @@ -1601,13 +1579,13 @@ class ExportSql extends ExportPlugin ) { $truncate = 'TRUNCATE TABLE ' . PMA_backquote($table, $sql_backquotes) . ";"; - $truncatehead = $this->possibleCRLF() - . $this->exportComment() - . $this->exportComment( + $truncatehead = $this->_possibleCRLF() + . $this->_exportComment() + . $this->_exportComment( __('Truncate table before insert') . ' ' . $formatted_table_name ) - . $this->exportComment() + . $this->_exportComment() . $crlf; PMA_exportOutputHandler($truncatehead); PMA_exportOutputHandler($truncate); @@ -1648,13 +1626,13 @@ class ExportSql extends ExportPlugin while ($row = PMA_DBI_fetch_row($result)) { if ($current_row == 0) { - $head = $this->possibleCRLF() - . $this->exportComment() - . $this->exportComment( + $head = $this->_possibleCRLF() + . $this->_exportComment() + . $this->_exportComment( __('Dumping data for table') . ' ' . $formatted_table_name ) - . $this->exportComment() + . $this->_exportComment() . $crlf; if (! PMA_exportOutputHandler($head)) { return false; @@ -1793,94 +1771,157 @@ class ExportSql extends ExportPlugin /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - private function getPlugin_param() + /** + * Gets the MySQL charset map + * + * @return array + */ + private function _getMysqlCharsetMap() { - return $this->_plugin_param; + return $this->_mysqlCharsetMap; } - private function setPlugin_param($plugin_param) + /** + * Sets the MySQL charset map + * + * @param string $mysqlCharsetMap file charset + * + * @return void + */ + private function _setMysqlCharsetMap($mysqlCharsetMap) { - $this->_plugin_param = $plugin_param; + $this->_mysqlCharsetMap = $mysqlCharsetMap; } - private function getMysql_charset_map() + /** + * Gets the SQL for dropping a table + * + * @return string + */ + private function _getSqlDropTable() { - return $this->_mysql_charset_map; + return $this->_sqlDropTable; } - private function setMysql_charset_map($mysql_charset_map) + /** + * Sets the SQL for dropping a table + * + * @param string $sqlDropTable SQL for dropping a table + * + * @return void + */ + private function _setSqlDropTable($sqlDropTable) { - $this->_mysql_charset_map = $mysql_charset_map; + $this->_sqlDropTable = $sqlDropTable; } - private function getSql_drop_table() + /** + * Gets the SQL Backquotes + * + * @return bool + */ + private function _getSqlBackquotes() { - return $this->_sql_drop_table; + return $this->_sqlBackquotes; } - private function setSql_drop_table($sql_drop_table) + /** + * Sets the SQL Backquotes + * + * @param string $sqlBackquotes SQL Backquotes + * + * @return void + */ + private function _setSqlBackquotes($sqlBackquotes) { - $this->_sql_drop_table = $sql_drop_table; + $this->_sqlBackquotes = $sqlBackquotes; } - private function getSql_backquotes() + /** + * Gets the SQL Constraints + * + * @return void + */ + private function _getSqlConstraints() { - return $this->_sql_backquotes; + return $this->_sqlConstraints; } - private function setSql_backquotes($sql_backquotes) + /** + * Sets the SQL Constraints + * + * @param string $sqlConstraints SQL Constraints + * + * @return void + */ + private function _setSqlConstraints($sqlConstraints) { - $this->_sql_backquotes = $sql_backquotes; + $this->_sqlConstraints = $sqlConstraints; } - private function getSql_constraints() + /** + * Gets the text of the SQL constraints query + * + * @return void + */ + private function _getSqlConstraintsQuery() { - return $this->_sql_constraints; + return $this->_sqlConstraintsQuery; } - private function setSql_constraints($sql_constraints) + /** + * Sets the text of the SQL constraints query + * + * @param string $sqlConstraintsQuery text of the SQL constraints query + * + * @return void + */ + private function _setSqlConstraintsQuery($sqlConstraintsQuery) { - $this->_sql_constraints = $sql_constraints; + $this->_sqlConstraintsQuery = $sqlConstraintsQuery; } - private function getSql_constraints_query() + /** + * Gets the SQL for dropping foreign keys + * + * @return void + */ + private function _getSqlDropForeignKeys() { - return $this->_sql_constraints_query; + return $this->_sqlDropForeignKeys; } - private function setSql_constraints_query($sql_constraints_query) + /** + * Sets the SQL SQL for dropping foreign keys + * + * @param string $sqlDropForeignKeys SQL for dropping foreign keys + * + * @return void + */ + private function _setSqlDropForeignKeys($sqlDropForeignKeys) { - $this->_sql_constraints_query = $sql_constraints_query; + $this->_sqlDropForeignKeys = $sqlDropForeignKeys; } - private function getSql_drop_foreign_keys() + /** + * The number of the current row + * + * @return int + */ + private function _getCurrentRow() { - return $this->_sql_drop_foreign_keys; + return $this->_currentRow; } - private function setSql_drop_foreign_keys($sql_drop_foreign_keys) + /** + * Sets the number of the current row + * + * @param string $currentRow number of the current row + * + * @return void + */ + private function _setCurrentRow($currentRow) { - $this->_sql_drop_foreign_keys = $sql_drop_foreign_keys; - } - - private function getCfgRelation() - { - return $this->_cfgRelation; - } - - private function setCfgRelation($cfgRelation) - { - $this->_cfgRelation = $cfgRelation; - } - - private function getCurrent_row() - { - return $this->_current_row; - } - - private function setCurrent_row($current_row) - { - $this->_current_row = $current_row; + $this->_currentRow = $currentRow; } } \ No newline at end of file diff --git a/libraries/plugins/export/ExportTexytext.class.php b/libraries/plugins/export/ExportTexytext.class.php index 0109fb46d2..1cd8f23f97 100644 --- a/libraries/plugins/export/ExportTexytext.class.php +++ b/libraries/plugins/export/ExportTexytext.class.php @@ -4,7 +4,7 @@ * Export to Texy! text. * * @package PhpMyAdmin-Export - * @subpackage Texy! text + * @subpackage Texy!text */ if (! defined('PHPMYADMIN')) { exit; @@ -16,49 +16,18 @@ require_once "libraries/plugins/ExportPlugin.class.php"; /** * Handles the export for the Texy! text class * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportTexytext extends ExportPlugin { - /** - * - * - * @var type string - */ - private $_what; - - /** - * - * @var type - */ - private $_cfgRelation; - /** * Constructor */ public function __construct() { - // initialize the specific export Texy! text variables - $this->initLocalVariables(); - $this->setProperties(); } - /** - * Initialize the local variables that are used for export Texy! text - * - * @return void - */ - private function initLocalVariables() - { - global $what; - global $cfgRelation; - - $this->setWhat($what); - $this->setCfgRelation($cfgRelation); - } - /** * Sets the export Texy! text properties * @@ -198,7 +167,8 @@ class ExportTexytext extends ExportPlugin */ public function exportData($db, $table, $crlf, $error_url, $sql_query) { - $what = $this->getWhat(); + global $what; + $this->setWhat($what); if (! PMA_exportOutputHandler( '== ' . __('Dumping data for table') . ' ' . $table . "\n\n" @@ -589,29 +559,5 @@ class ExportTexytext extends ExportPlugin ); return $definition; } - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - public function getWhat() - { - return $this->_what; - } - - public function setWhat($what) - { - $this->_what = $what; - } - - public function getCfgRelation() - { - return $this->_cfgRelation; - } - - private function setCfgRelation($cfgRelation) - { - $this->_cfgRelation = $cfgRelation; - } } ?> \ No newline at end of file diff --git a/libraries/plugins/export/ExportXml.class.php b/libraries/plugins/export/ExportXml.class.php index fd8c0aee74..e2c4265349 100644 --- a/libraries/plugins/export/ExportXml.class.php +++ b/libraries/plugins/export/ExportXml.class.php @@ -19,7 +19,6 @@ require_once "libraries/plugins/ExportPlugin.class.php"; /** * Handles the export for the XML class * - * @todo add descriptions for all vars/methods * @package PhpMyAdmin-Export */ class ExportXml extends ExportPlugin @@ -27,14 +26,14 @@ class ExportXml extends ExportPlugin /** * Table name * - * @var type String + * @var string */ private $_table; /** + * Table names * - * - * @var type + * @var array */ private $_tables; @@ -44,23 +43,18 @@ class ExportXml extends ExportPlugin public function __construct() { $this->setProperties(); - } /** - * Initialize the local variables that are used specific for export XML - * - * @global type $table - * @global type $tables + * Initialize the local variables that are used for export PDF * * @return void */ - private function initLocalVariables() + protected function initSpecificVariables() { - global $table; - global $tables; - $this->setTable($table); - $this->setTables($tables); + global $table, $tables; + $this->_setTable($table); + $this->_setTables($tables); } /** @@ -168,17 +162,13 @@ class ExportXml extends ExportPlugin */ public function exportHeader () { - // initialize the general export variables - $this->initExportCommonVariables(); - - // initialize the specific export xml variables - $this->initLocalVariables(); - - $crlf = $this->getCrlf(); - $cfg = $this->getCfg(); - $db = $this->getDb(); - $table = $this->getTable(); - $tables = $this->getTables(); + $this->initSpecificVariables(); + global $crlf, $cfg, $db; + $this->setCrlf($crlf); + $this->setCfg($cfg); + $this->setDb($db); + $table = $this->_getTable(); + $tables = $this->_getTables(); $export_struct = isset($GLOBALS['xml_export_functions']) || isset($GLOBALS['xml_export_procedures']) @@ -498,22 +488,46 @@ class ExportXml extends ExportPlugin /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - private function getTable() + /** + * Gets the table name + * + * @return void + */ + private function _getTable() { return $this->_table; } - private function setTable($table) + /** + * Sets the table name + * + * @param string $table table name + * + * @return void + */ + private function _setTable($table) { $this->_table = $table; } - private function getTables() + /** + * Gets the table names + * + * @return array + */ + private function _getTables() { return $this->_tables; } - private function setTables($tables) + /** + * Sets the table names + * + * @param array $tables table names + * + * @return void + */ + private function _setTables($tables) { $this->_tables = $tables; } diff --git a/libraries/plugins/export/PMA_ExportPdf.class.php b/libraries/plugins/export/PMA_ExportPdf.class.php index 35c21ad08a..f094f8deb3 100644 --- a/libraries/plugins/export/PMA_ExportPdf.class.php +++ b/libraries/plugins/export/PMA_ExportPdf.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the PDF class */ -include_once 'libraries/PDF.class.php'; +require_once 'libraries/PDF.class.php'; /** * Adapted from a LGPL script by Philip Clarke diff --git a/libraries/plugins/export/TableProperty.class.php b/libraries/plugins/export/TableProperty.class.php index 15e8d48f6c..bc544a8774 100644 --- a/libraries/plugins/export/TableProperty.class.php +++ b/libraries/plugins/export/TableProperty.class.php @@ -10,15 +10,62 @@ if (! defined('PHPMYADMIN')) { exit; } +/** + * Holds the TableProperty class + * + * @package PhpMyAdmin-Export + */ class TableProperty { + /** + * Name + * + * @var string + */ public $name; + + /** + * Type + * + * @var string + */ public $type; + + /** + * Wheter the key is nullable or not + * + * @var bool + */ public $nullable; + + /** + * The key + * + * @var int + */ public $key; + + /** + * Default value + * + * @var mixed + */ public $defaultValue; + + /** + * Extension + * + * @var string + */ public $ext; + /** + * Constructor + * + * @param array $row table row + * + * @return void + */ function __construct($row) { $this->name = trim($row[0]); @@ -29,25 +76,45 @@ class TableProperty $this->ext = trim($row[5]); } + /** + * Gets the pure type + * + * @return string type + */ function getPureType() { - $pos=strpos($this->type, "("); + $pos = strpos($this->type, "("); if ($pos > 0) { return substr($this->type, 0, $pos); } return $this->type; } + /** + * Tells whether the key is null or not + * + * @return bool true if the key is not null, false otherwise + */ function isNotNull() { return $this->nullable == "NO" ? "true" : "false"; } + /** + * Tells whether the key is unique or not + * + * @return bool true if the key is unique, false otherwise + */ function isUnique() { return $this->key == "PRI" || $this->key == "UNI" ? "true" : "false"; } + /** + * Gets the .NET primitive type + * + * @return string type + */ function getDotNetPrimitiveType() { if (strpos($this->type, "int") === 0) { @@ -77,6 +144,11 @@ class TableProperty return "unknown"; } + /** + * Gets the .NET object type + * + * @return string type + */ function getDotNetObjectType() { if (strpos($this->type, "int") === 0) { @@ -106,6 +178,11 @@ class TableProperty return "Unknown"; } + /** + * Gets the index name + * + * @return string containing the name of the index + */ function getIndexName() { if (strlen($this->key) > 0) { @@ -116,11 +193,23 @@ class TableProperty return ""; } + /** + * Tells whether the key is primary or not + * + * @return bool true if the key is primary, false otherwise + */ function isPK() { return $this->key=="PRI"; } + /** + * Formats a string for C# + * + * @param string $text string to be formatted + * + * @return string formatted text + */ function formatCs($text) { $text = str_replace( @@ -131,6 +220,13 @@ class TableProperty return $this->format($text); } + /** + * Formats a string for XML + * + * @param string $text string to be formatted + * + * @return string formatted text + */ function formatXml($text) { $text = str_replace( @@ -146,6 +242,13 @@ class TableProperty return $this->format($text); } + /** + * Formats a string + * + * @param string $text string to be formatted + * + * @return string formatted text + */ function format($text) { $text = str_replace( From 6d852da6c1cca5580376d73620298ea73191b5fb Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 16:53:45 +0300 Subject: [PATCH 27/55] oop: fix phpcs errors for ImportSql, ImportXml and ImportPlugin --- libraries/plugins/ImportPlugin.class.php | 51 ++++++-- libraries/plugins/import/ImportSql.class.php | 9 +- libraries/plugins/import/ImportXml.class.php | 129 ++++--------------- 3 files changed, 65 insertions(+), 124 deletions(-) diff --git a/libraries/plugins/ImportPlugin.class.php b/libraries/plugins/ImportPlugin.class.php index e2a11d07ab..7bf0bf4e00 100644 --- a/libraries/plugins/ImportPlugin.class.php +++ b/libraries/plugins/ImportPlugin.class.php @@ -16,7 +16,6 @@ require_once "PluginObserver.class.php"; * Provides a common interface that will have to implemented by all of the * import plugins. * - * @todo descriptions * @package PhpMyAdmin */ abstract class ImportPlugin extends PluginObserver @@ -29,18 +28,18 @@ abstract class ImportPlugin extends PluginObserver protected $properties; /** + * Tells whether there was an error during the import * - * - * @var type + * @var bool */ private $_error; /** + * Tells whether the timeout passed before the import finished * - * - * @var type + * @var bool */ - private $_timeout_passed; + private $_timeoutPassed; /** * Handles the whole import logic @@ -55,7 +54,6 @@ abstract class ImportPlugin extends PluginObserver * * @global type $error * @global type $timeout_passed - * @global type $finished * * @return void */ @@ -64,7 +62,7 @@ abstract class ImportPlugin extends PluginObserver global $error; global $timeout_passed; $this->setError($error); - $this->setTimeout_passed($timeout_passed); + $this->setTimeoutPassed($timeout_passed); } @@ -89,24 +87,49 @@ abstract class ImportPlugin extends PluginObserver */ abstract protected function setProperties(); - public function getError() + /** + * Finds out whether there was an error during the import + * + * @return string + */ + protected function getError() { return $this->_error; } - public function setError($error) + /** + * Sets to true if there was an error during the import, false otherwise + * + * @param bool $error whether there was an error during the import + * + * @return void + */ + protected function setError($error) { $this->_error = $error; } - public function getTimeout_passed() + /** + * Finds out whether the timeout passed before the import finished + * + * @return string + */ + protected function getTimeoutPassed() { - return $this->_timeout_passed; + return $this->_timeoutPassed; } - public function setTimeout_passed($timeout_passed) + /** + * Sets to true if the timeout passed + * + * @param bool $timeoutPassed whether the timeout passed before the import + * finished + * + * @return void + */ + protected function setTimeoutPassed($timeoutPassed) { - $this->_timeout_passed = $timeout_passed; + $this->_timeoutPassed = $timeoutPassed; } } ?> \ No newline at end of file diff --git a/libraries/plugins/import/ImportSql.class.php b/libraries/plugins/import/ImportSql.class.php index b22a206abe..34ba4ac2f9 100644 --- a/libraries/plugins/import/ImportSql.class.php +++ b/libraries/plugins/import/ImportSql.class.php @@ -93,16 +93,15 @@ class ImportSql extends ImportPlugin /** * Handles the whole import logic - * + * * @return void */ public function doImport() { - // initialize the general import variables + // initialize the common import variables $this->initImportCommonVariables(); - $error = $this->getError(); - $timeout_passed = $this->getTimeout_passed(); + $timeout_passed = $this->getTimeoutPassed(); $buffer = ''; // Defaults for parser @@ -369,7 +368,7 @@ class ImportSql extends ImportPlugin } // End of SQL - if ($found_delimiter + if ($found_delimiter || ($GLOBALS['finished'] && ($i == $len - 1)) ) { diff --git a/libraries/plugins/import/ImportXml.class.php b/libraries/plugins/import/ImportXml.class.php index 4df3ff5740..7f87848dee 100644 --- a/libraries/plugins/import/ImportXml.class.php +++ b/libraries/plugins/import/ImportXml.class.php @@ -25,32 +25,10 @@ require_once "libraries/plugins/ImportPlugin.class.php"; /** * Handles the import for the XML format * - * @todo add descriptions * @package PhpMyAdmin-Import */ class ImportXml extends ImportPlugin { - /** - * Database name - * - * @var type String - */ - private $_db = null; - - /** - * - * - * @var type - */ - private $_table = null; - - /** - * - * - * @var type - */ - private $_tables = null; - /** * Constructor */ @@ -59,22 +37,6 @@ class ImportXml extends ImportPlugin $this->setProperties(); } - /** - * Initialize the local variables that are used specific for import XML - * - * @global type $table - * @global type $tables - * - * @return void - */ - private function initLocalVariables() - { - global $table; - global $tables; - $this->setTable($table); - $this->setTables($tables); - } - /** * Sets the import plugin properties. * Called in the constructor. @@ -107,20 +69,18 @@ class ImportXml extends ImportPlugin /** * Handles the whole import logic + * + * @return void */ public function doImport() { - // initialize the general import variables - $this->initImportCommonVariables(); - - // initialize the specific import xml variables - $this->initLocalVariables(); - - $error = $this->getError(); - $timeout_passed = $this->getTimeout_passed(); - $db = $this->getDb(); - // this is used in other functions while doImport() is being run global $finished; + global $db; + + // initialize the common import variables + $this->initImportCommonVariables(); + $error = $this->getError(); + $timeout_passed = $this->getTimeoutPassed(); $i = 0; $len = 0; @@ -167,10 +127,12 @@ class ImportXml extends ImportPlugin * 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(); + 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; @@ -204,7 +166,8 @@ class ImportXml extends ImportPlugin /** * Get the database name, collation and charset */ - $db_attr = $xml->children($namespaces['pma'])->{'structure_schemas'}->{'database'}; + $db_attr = $xml->children($namespaces['pma']) + ->{'structure_schemas'}->{'database'}; if ($db_attr instanceof SimpleXMLElement) { $db_attr = $db_attr->attributes(); @@ -226,10 +189,12 @@ class ImportXml extends ImportPlugin * 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(); + 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; @@ -248,8 +213,8 @@ class ImportXml extends ImportPlugin foreach ($struct as $tier1 => $val1) { foreach ($val1 as $tier2 => $val2) { - // Need to select the correct database for the creation of tables, - // views, triggers, etc. + // 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. @@ -409,50 +374,4 @@ class ImportXml extends ImportPlugin /* Commit any possible data in buffers */ PMA_importRunQuery(); } - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - /** - * Gets the database name - * - * @return string - */ - public function getDb() - { - return $this->_db; - } - - /** - * Sets the database name - * - * @param String $db database name - * - * @return void - */ - public function setDb($db) - { - $this->_db = $db; - } - - private function getTable() - { - return $this->_table; - } - - private function setTable($table) - { - $this->_table = $table; - } - - private function getTables() - { - return $this->_tables; - } - - private function setTables($tables) - { - $this->_tables = $tables; - } } \ No newline at end of file From 02e4babdb45cd9e47dc9c8f473ace3d0b3d2feff Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 17:37:39 +0300 Subject: [PATCH 28/55] oop: ImportCsv --- libraries/plugins/import/ImportCsv.class.php | 629 +++++++++++++++++++ 1 file changed, 629 insertions(+) create mode 100644 libraries/plugins/import/ImportCsv.class.php diff --git a/libraries/plugins/import/ImportCsv.class.php b/libraries/plugins/import/ImportCsv.class.php new file mode 100644 index 0000000000..570d69ad11 --- /dev/null +++ b/libraries/plugins/import/ImportCsv.class.php @@ -0,0 +1,629 @@ +setProperties(); + } + + /** + * Sets the import plugin properties. + * Called in the constructor. + * + * @return void + */ + protected function setProperties() + { + global $plugin_param; + $this->_setAnalyze(false); + + if ($plugin_param !== 'table') { + $this->_setAnalyze(true); + } + + $this->properties = array( + 'text' => __('CSV'), + 'extension' => 'csv', + 'options' => array(), + 'options_text' => __('Options') + ); + + $this->properties['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') { + $this->properties['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.' + ) + ); + $this->properties['options'][] = array( + 'type' => 'text', + 'name' => 'columns', + 'text' => __('Column names: ') . PMA_showHint($hint) + ); + } + + $this->properties['options'][] = array('type' => 'end_group'); + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + * + * @return void + */ + public function doImport() + { + global $finished, $db; + global $csv_terminated, $csv_enclosed, $csv_escaped, $csv_new_line; + + // initialize the common import variables + $this->initImportCommonVariables(); + $error = $this->getError(); + $timeout_passed = $this->getTimeoutPassed(); + + $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 (! $this->_getAnalyze()) { + 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 ($this->_getAnalyze()) { + foreach ($values as $ley => $val) { + $tempRow[] = $val; + ++$col_count; + } + + if ($col_count > $max_cols) { + $max_cols = $col_count; + } + $col_count = 0; + + $rows[] = $tempRow; + $tempRow = array(); + } else { + // Do we have correct count of values? + if (count($values) != $required_fields) { + + // Hack for excel + if ($values[count($values) - 1] == ';') { + unset($values[count($values) - 1]); + } else { + $message = PMA_Message::error( + __('Invalid column count in CSV input on line %d.') + ); + $message->addParam($line); + $error = true; + break; + } + } + + $first = true; + $sql = $sql_template; + foreach ($values as $key => $val) { + if (! $first) { + $sql .= ', '; + } + if ($val === null) { + $sql .= 'NULL'; + } else { + $sql .= '\'' . 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 ($this->_getAnalyze()) { + /* Fill out all rows */ + $num_rows = count($rows); + for ($i = 0; $i < $num_rows; ++$i) { + for ($j = count($rows[$i]); $j < $max_cols; ++$j) { + $rows[$i][] = 'NULL'; + } + } + + if (isset($_REQUEST['csv_col_names'])) { + $col_names = array_splice($rows, 0, 1); + $col_names = $col_names[0]; + } + + if ((isset($col_names) && count($col_names) != $max_cols) + || ! isset($col_names) + ) { + // Fill out column names + for ($i = 0; $i < $max_cols; ++$i) { + $col_names[] = 'COL '.($i+1); + } + } + + if (strlen($db)) { + $result = PMA_DBI_fetch_result('SHOW TABLES'); + $tbl_name = 'TABLE '.(count($result) + 1); + } else { + $tbl_name = 'TBL_NAME'; + } + + $tables[] = array($tbl_name, $col_names, $rows); + + /* Obtain the best-fit MySQL types for each column */ + $analyses = array(); + $analyses[] = PMA_analyzeTable($tables[0]); + + /** + * string $db_name (no backquotes) + * + * array $table = array(table_name, array() column_names, array()() rows) + * array $tables = array of "$table"s + * + * array $analysis = array(array() column_types, array() column_sizes) + * array $analyses = array of "$analysis"s + * + * array $create = array of SQL strings + * + * array $options = an associative array of options + */ + + /* Set database name to the currently selected one, if applicable */ + if (strlen($db)) { + $db_name = $db; + $options = array('create_db' => false); + } else { + $db_name = 'CSV_DB'; + $options = null; + } + + /* Non-applicable parameters */ + $create = null; + + /* Created and execute necessary SQL statements from data */ + PMA_buildSQL($db_name, $tables, $analyses, $create, $options); + + unset($tables); + unset($analyses); + } + + // Commit any possible data in buffers + PMA_importRunQuery(); + + if (count($values) != 0 && ! $error) { + $message = PMA_Message::error( + __('Invalid format of CSV input on line %d.') + ); + $message->addParam($line); + $error = true; + } + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Returns true if the table should be analyzed, false otherwise + * + * @return bool + */ + private function _getAnalyze() + { + return $this->_analyze; + } + + /** + * Sets to true if the table should be analyzed, false otherwise + * + * @param bool $analyze status + * + * @return void + */ + private function _setAnalyze($analyze) + { + $this->_analyze = $analyze; + } +} \ No newline at end of file From f21dfd6646e12cbd215e7b94f427629354aa2dba Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 17:57:55 +0300 Subject: [PATCH 29/55] oop: ImportDocsql --- libraries/plugins/import/ImportCsv.class.php | 1 - .../plugins/import/ImportDocsql.class.php | 206 ++++++++++++++++++ 2 files changed, 206 insertions(+), 1 deletion(-) create mode 100644 libraries/plugins/import/ImportDocsql.class.php diff --git a/libraries/plugins/import/ImportCsv.class.php b/libraries/plugins/import/ImportCsv.class.php index 570d69ad11..478379f830 100644 --- a/libraries/plugins/import/ImportCsv.class.php +++ b/libraries/plugins/import/ImportCsv.class.php @@ -7,7 +7,6 @@ * @package PhpMyAdmin-Import * @subpackage CSV */ - if (! defined('PHPMYADMIN')) { exit; } diff --git a/libraries/plugins/import/ImportDocsql.class.php b/libraries/plugins/import/ImportDocsql.class.php new file mode 100644 index 0000000000..c39da54ef1 --- /dev/null +++ b/libraries/plugins/import/ImportDocsql.class.php @@ -0,0 +1,206 @@ +setProperties(); + } + + /** + * Sets the import plugin properties. + * Called in the constructor. + * + * @return void + */ + protected function setProperties() + { + global $plugin_param; + $this->_setCfgRelation(PMA_getRelationsParam()); + $cfgRelation = $this->_getCfgRelation(); + + // We need relations enabled and we work only on database + if ($plugin_param !== 'database' + || $GLOBALS['num_tables'] < 1 + || ! $cfgRelation['relwork'] + || ! $cfgRelation['commwork'] + ) { + return; + } + + $this->properties = array( + 'text' => __('DocSQL'), + 'extension' => '', + 'options' => array( ), + 'options_text' => __('Options'), + ); + + $this->properties['options'] = array( + array( + 'type' => 'begin_group', + 'name' => 'general_opts' + ), + array( + 'type' => 'text', + 'name' => 'table', + 'text' => __('Table name') + ), + array( + 'type' => 'end_group' + ) + ); + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + * + * @return void + */ + public function doImport() + { + global $finished; + + // initialize the common import variables + $this->initImportCommonVariables(); + $error = $this->getError(); + $timeout_passed = $this->getTimeoutPassed(); + + $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(); + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Gets relation configuration + * + * @return array + */ + private function _getCfgRelation() + { + return $this->_cfgRelation; + } + + /** + * Sets relation configuration + * + * @param array $cfgRelation relation configuration + * + * @return void + */ + private function _setCfgRelation($cfgRelation) + { + $this->_cfgRelation = $cfgRelation; + } +} \ No newline at end of file From f6c7bac2c793945562d5a52c06ab648c8af7c787 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 19:23:53 +0300 Subject: [PATCH 30/55] oop: import - remove getters and setters for globals --- libraries/plugins/ImportPlugin.class.php | 76 ------------------- libraries/plugins/import/ImportCsv.class.php | 9 +-- .../plugins/import/ImportDocsql.class.php | 8 +- libraries/plugins/import/ImportSql.class.php | 5 +- libraries/plugins/import/ImportXml.class.php | 10 +-- 5 files changed, 7 insertions(+), 101 deletions(-) diff --git a/libraries/plugins/ImportPlugin.class.php b/libraries/plugins/ImportPlugin.class.php index 7bf0bf4e00..018f3a60a0 100644 --- a/libraries/plugins/ImportPlugin.class.php +++ b/libraries/plugins/ImportPlugin.class.php @@ -27,20 +27,6 @@ abstract class ImportPlugin extends PluginObserver */ protected $properties; - /** - * Tells whether there was an error during the import - * - * @var bool - */ - private $_error; - - /** - * Tells whether the timeout passed before the import finished - * - * @var bool - */ - private $_timeoutPassed; - /** * Handles the whole import logic * @@ -48,23 +34,6 @@ abstract class ImportPlugin extends PluginObserver */ abstract public function doImport(); - /** - * Initializes the local variables with the global values. - * These are variables that are used by all of the import plugins. - * - * @global type $error - * @global type $timeout_passed - * - * @return void - */ - protected function initImportCommonVariables() - { - global $error; - global $timeout_passed; - $this->setError($error); - $this->setTimeoutPassed($timeout_passed); - } - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ @@ -86,50 +55,5 @@ abstract class ImportPlugin extends PluginObserver * @return void */ abstract protected function setProperties(); - - /** - * Finds out whether there was an error during the import - * - * @return string - */ - protected function getError() - { - return $this->_error; - } - - /** - * Sets to true if there was an error during the import, false otherwise - * - * @param bool $error whether there was an error during the import - * - * @return void - */ - protected function setError($error) - { - $this->_error = $error; - } - - /** - * Finds out whether the timeout passed before the import finished - * - * @return string - */ - protected function getTimeoutPassed() - { - return $this->_timeoutPassed; - } - - /** - * Sets to true if the timeout passed - * - * @param bool $timeoutPassed whether the timeout passed before the import - * finished - * - * @return void - */ - protected function setTimeoutPassed($timeoutPassed) - { - $this->_timeoutPassed = $timeoutPassed; - } } ?> \ No newline at end of file diff --git a/libraries/plugins/import/ImportCsv.class.php b/libraries/plugins/import/ImportCsv.class.php index 478379f830..1b29646a5e 100644 --- a/libraries/plugins/import/ImportCsv.class.php +++ b/libraries/plugins/import/ImportCsv.class.php @@ -151,13 +151,8 @@ class ImportCsv extends ImportPlugin */ public function doImport() { - global $finished, $db; - global $csv_terminated, $csv_enclosed, $csv_escaped, $csv_new_line; - - // initialize the common import variables - $this->initImportCommonVariables(); - $error = $this->getError(); - $timeout_passed = $this->getTimeoutPassed(); + global $db, $csv_terminated, $csv_enclosed, $csv_escaped, $csv_new_line; + global $error, $timeout_passed, $finished; $replacements = array( '\\n' => "\n", diff --git a/libraries/plugins/import/ImportDocsql.class.php b/libraries/plugins/import/ImportDocsql.class.php index c39da54ef1..8f48723893 100644 --- a/libraries/plugins/import/ImportDocsql.class.php +++ b/libraries/plugins/import/ImportDocsql.class.php @@ -99,12 +99,8 @@ class ImportDocsql extends ImportPlugin */ public function doImport() { - global $finished; - - // initialize the common import variables - $this->initImportCommonVariables(); - $error = $this->getError(); - $timeout_passed = $this->getTimeoutPassed(); + global $error, $timeout_passed, $finished; + $cfgRelation = $this->_getCfgRelation(); $tab = $_POST['docsql_table']; $buffer = ''; diff --git a/libraries/plugins/import/ImportSql.class.php b/libraries/plugins/import/ImportSql.class.php index 34ba4ac2f9..d25ea2396e 100644 --- a/libraries/plugins/import/ImportSql.class.php +++ b/libraries/plugins/import/ImportSql.class.php @@ -98,10 +98,7 @@ class ImportSql extends ImportPlugin */ public function doImport() { - // initialize the common import variables - $this->initImportCommonVariables(); - $error = $this->getError(); - $timeout_passed = $this->getTimeoutPassed(); + global $error, $timeout_passed; $buffer = ''; // Defaults for parser diff --git a/libraries/plugins/import/ImportXml.class.php b/libraries/plugins/import/ImportXml.class.php index 7f87848dee..e162984196 100644 --- a/libraries/plugins/import/ImportXml.class.php +++ b/libraries/plugins/import/ImportXml.class.php @@ -69,18 +69,12 @@ class ImportXml extends ImportPlugin /** * Handles the whole import logic - * + * * @return void */ public function doImport() { - global $finished; - global $db; - - // initialize the common import variables - $this->initImportCommonVariables(); - $error = $this->getError(); - $timeout_passed = $this->getTimeoutPassed(); + global $error, $timeout_passed, $finished, $db; $i = 0; $len = 0; From 9abc518e9e370e5a8c51480512d334534601c8a1 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 19:33:15 +0300 Subject: [PATCH 31/55] oop: ImportLdi --- libraries/plugins/import/ImportLdi.class.php | 210 +++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 libraries/plugins/import/ImportLdi.class.php diff --git a/libraries/plugins/import/ImportLdi.class.php b/libraries/plugins/import/ImportLdi.class.php new file mode 100644 index 0000000000..421d11509c --- /dev/null +++ b/libraries/plugins/import/ImportLdi.class.php @@ -0,0 +1,210 @@ +setProperties(); + } + + /** + * Sets the import plugin properties. + * Called in the constructor. + * + * @return void + */ + protected function setProperties() + { + global $plugin_param; + if ($plugin_param !== 'table') { + return; + } + + if ($GLOBALS['cfg']['Import']['ldi_local_option'] == 'auto') { + $GLOBALS['cfg']['Import']['ldi_local_option'] = false; + + $result = PMA_DBI_try_query('SHOW VARIABLES LIKE \'local\\_infile\';'); + if ($result != false && PMA_DBI_num_rows($result) > 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); + } + + $this->properties = array( + 'text' => __('CSV using LOAD DATA'), + // Following is nonsense, however we want to default to our + // parser for csv + 'extension' => 'ldi', + 'options' => array(), + 'options_text' => __('Options'), + ); + + $this->properties['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' + ) + ); + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + * + * @return void + */ + public function doImport() + { + global $finished, $error, $import_file, $compression, $charset_conversion; + global $ldi_local_option, $ldi_replace, $ldi_terminated, $ldi_enclosed, + $ldi_escaped, $ldi_new_line, $skip_queries, $ldi_columns; + + 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; + } +} \ No newline at end of file From 1df80ed79adc98a2c197045317af48cd1f0414ea Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 19:34:22 +0300 Subject: [PATCH 32/55] oop: ImportDocsql clear spaces --- libraries/plugins/import/ImportDocsql.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/plugins/import/ImportDocsql.class.php b/libraries/plugins/import/ImportDocsql.class.php index 8f48723893..262c5d28af 100644 --- a/libraries/plugins/import/ImportDocsql.class.php +++ b/libraries/plugins/import/ImportDocsql.class.php @@ -59,7 +59,7 @@ class ImportDocsql extends ImportPlugin $this->properties = array( 'text' => __('DocSQL'), 'extension' => '', - 'options' => array( ), + 'options' => array(), 'options_text' => __('Options'), ); @@ -127,7 +127,7 @@ class ImportDocsql extends ImportPlugin $lines = explode("\n", $buffer); foreach ($lines AS $lkey => $line) { //echo '

' . $line . '

'; - $inf = explode('|', $line); + $inf = explode('|', $line); if (!empty($inf[1]) && strlen(trim($inf[1])) > 0) { $qry = ' INSERT INTO From 7248bf87fad6f371943c7b26c3a597bc04265dc7 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 19:49:00 +0300 Subject: [PATCH 33/55] oop: ImportMediawiki --- .../plugins/import/ImportMediawiki.class.php | 569 ++++++++++++++++++ 1 file changed, 569 insertions(+) create mode 100644 libraries/plugins/import/ImportMediawiki.class.php diff --git a/libraries/plugins/import/ImportMediawiki.class.php b/libraries/plugins/import/ImportMediawiki.class.php new file mode 100644 index 0000000000..be8049a3b6 --- /dev/null +++ b/libraries/plugins/import/ImportMediawiki.class.php @@ -0,0 +1,569 @@ +setProperties(); + } + + /** + * Sets the import plugin properties. + * Called in the constructor. + * + * @return void + */ + protected function setProperties() + { + global $plugin_param; + $this->_setAnalyze(false); + if ($plugin_param !== 'table') { + $this->_setAnalyze(true); + } + + $this->properties = array( + 'text' => __('MediaWiki Table'), + 'extension' => 'txt', + 'mime_type' => 'text/plain', + 'options' => array(), + 'options_text' => __('Options'), + ); + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + * + * @return void + */ + public function doImport() + { + global $error, $timeout_passed, $finished; + + // 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 + $this->_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 = $this->_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 + */ + private function _importDataOneTable ($table) + { + $analyze = $this->_getAnalyze(); + if ($analyze) { + // Set the table name + $this->_setTableName($table[0]); + + // Set generic names for table headers if they don't exist + $this->_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]); + + $this->_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 + */ + private function _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 + */ + private function _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 $this->_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 + */ + private function _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 + */ + private function _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 + */ + private function _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 = $this->_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; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Returns true if the table should be analyzed, false otherwise + * + * @return bool + */ + private function _getAnalyze() + { + return $this->_analyze; + } + + /** + * Sets to true if the table should be analyzed, false otherwise + * + * @param bool $analyze status + * + * @return void + */ + private function _setAnalyze($analyze) + { + $this->_analyze = $analyze; + } +} \ No newline at end of file From a62dda15f6cb7245a654ead54442ca067b63e33f Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 20:18:20 +0300 Subject: [PATCH 34/55] oop: ImportOds --- libraries/plugins/import/ImportOds.class.php | 386 +++++++++++++++++++ 1 file changed, 386 insertions(+) create mode 100644 libraries/plugins/import/ImportOds.class.php diff --git a/libraries/plugins/import/ImportOds.class.php b/libraries/plugins/import/ImportOds.class.php new file mode 100644 index 0000000000..c275de6491 --- /dev/null +++ b/libraries/plugins/import/ImportOds.class.php @@ -0,0 +1,386 @@ +setProperties(); + } + + /** + * Sets the import plugin properties. + * Called in the constructor. + * + * @return void + */ + protected function setProperties() + { + $this->properties = array( + 'text' => __('Open Document Spreadsheet'), + 'extension' => 'ods', + 'options' => array(), + 'options_text' => __('Options'), + ); + + $this->properties['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') + ); + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + * + * @return void + */ + public function doImport() + { + global $db, $error, $timeout_passed, $finished; + + $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(); + } +} \ No newline at end of file From 0cfb03331c62864d5690299a9b28f5fb1d6748b7 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Mon, 18 Jun 2012 20:40:48 +0300 Subject: [PATCH 35/55] oop: ImportShp --- libraries/plugins/import/ImportShp.class.php | 325 ++++++++++++++++++ .../plugins/import/PMA_ShapeFile.class.php | 102 ++++++ .../plugins/import/PMA_ShapeRecord.class.php | 161 +++++++++ 3 files changed, 588 insertions(+) create mode 100644 libraries/plugins/import/ImportShp.class.php create mode 100644 libraries/plugins/import/PMA_ShapeFile.class.php create mode 100644 libraries/plugins/import/PMA_ShapeRecord.class.php diff --git a/libraries/plugins/import/ImportShp.class.php b/libraries/plugins/import/ImportShp.class.php new file mode 100644 index 0000000000..bc56195380 --- /dev/null +++ b/libraries/plugins/import/ImportShp.class.php @@ -0,0 +1,325 @@ +properties = array( + 'text' => __('ESRI Shape File'), + 'extension' => 'shp', + 'options' => array(), + 'options_text' => __('Options'), + ); + } + + /** + * 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) + { + } + + /** + * Handles the whole import logic + * + * @return void + */ + public function doImport() + { + global $db, $error, $finished; + + if ((int) ini_get('memory_limit') < 512) { + @ini_set('memory_limit', '512M'); + } + @set_time_limit(300); + + $GLOBALS['finished'] = false; + $buffer = ''; + $eof = false; + + + $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(); + } + + /** + * 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. + * + * @param int $length number of bytes + * + * @return string + */ + public static 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; + } +} \ No newline at end of file diff --git a/libraries/plugins/import/PMA_ShapeFile.class.php b/libraries/plugins/import/PMA_ShapeFile.class.php new file mode 100644 index 0000000000..121bf124d2 --- /dev/null +++ b/libraries/plugins/import/PMA_ShapeFile.class.php @@ -0,0 +1,102 @@ +_loadHeaders(); + $this->_loadRecords(); + if ($this->_isDbaseLoaded()) { + $this->_closeDBFFile(); + } + } + + /** + * Loads metadata from the ESRI shape file header + * + * @return void + * @see ShapeFile::_loadHeaders() + */ + function _loadHeaders() + { + ImportShp::readFromBuffer(24); + $this->fileLength = loadData("N", ImportShp::readFromBuffer(4)); + + ImportShp::readFromBuffer(4); + $this->shapeType = loadData("V", ImportShp::readFromBuffer(4)); + + $this->boundingBox = array(); + $this->boundingBox["xmin"] = loadData("d", ImportShp::readFromBuffer(8)); + $this->boundingBox["ymin"] = loadData("d", ImportShp::readFromBuffer(8)); + $this->boundingBox["xmax"] = loadData("d", ImportShp::readFromBuffer(8)); + $this->boundingBox["ymax"] = loadData("d", ImportShp::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; + ImportShp::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; + } + } +} +?> diff --git a/libraries/plugins/import/PMA_ShapeRecord.class.php b/libraries/plugins/import/PMA_ShapeRecord.class.php new file mode 100644 index 0000000000..efefd0c806 --- /dev/null +++ b/libraries/plugins/import/PMA_ShapeRecord.class.php @@ -0,0 +1,161 @@ +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", ImportShp::readFromBuffer(4)); + ImportShp::readFromBuffer(4); + $this->shapeType = loadData("V", ImportShp::readFromBuffer(4)); + } + + /** + * Loads data from a point record + * + * @return void + * @see ShapeRecord::_loadPoint() + */ + function _loadPoint() + { + $data = array(); + + $data["x"] = loadData("d", ImportShp::readFromBuffer(8)); + $data["y"] = loadData("d", ImportShp::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", ImportShp::readFromBuffer(8)); + $this->SHPData["ymin"] = loadData("d", ImportShp::readFromBuffer(8)); + $this->SHPData["xmax"] = loadData("d", ImportShp::readFromBuffer(8)); + $this->SHPData["ymax"] = loadData("d", ImportShp::readFromBuffer(8)); + + $this->SHPData["numpoints"] = loadData("V", ImportShp::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", ImportShp::readFromBuffer(8)); + $this->SHPData["ymin"] = loadData("d", ImportShp::readFromBuffer(8)); + $this->SHPData["xmax"] = loadData("d", ImportShp::readFromBuffer(8)); + $this->SHPData["ymax"] = loadData("d", ImportShp::readFromBuffer(8)); + + $this->SHPData["numparts"] = loadData("V", ImportShp::readFromBuffer(4)); + $this->SHPData["numpoints"] = loadData("V", ImportShp::readFromBuffer(4)); + + for ($i = 0; $i < $this->SHPData["numparts"]; $i++) { + $this->SHPData["parts"][$i] = loadData( + "V", ImportShp::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++; + } + } + } +} +?> From ab436a573c7193f6bf06a9360e9ff53bdcc0de15 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Tue, 19 Jun 2012 14:53:04 +0300 Subject: [PATCH 36/55] oop: fix display import plugins list bug --- libraries/plugin_interface.lib.php | 17 +++++++++++++---- libraries/plugins/import/ImportCsv.class.php | 5 ++--- libraries/plugins/import/ImportDocsql.class.php | 12 +++++++----- libraries/plugins/import/ImportLdi.class.php | 11 ++++++----- .../plugins/import/ImportMediawiki.class.php | 3 +-- libraries/plugins/import/ImportShp.class.php | 10 +++++++++- 6 files changed, 38 insertions(+), 20 deletions(-) diff --git a/libraries/plugin_interface.lib.php b/libraries/plugin_interface.lib.php index 1b5a5d0ae1..b659af3475 100644 --- a/libraries/plugin_interface.lib.php +++ b/libraries/plugin_interface.lib.php @@ -17,8 +17,13 @@ * * @return new plugin instance */ -function PMA_getPlugin($plugin_type, $plugin_format, $plugins_dir, $plugin_param = false) -{ +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]) @@ -44,6 +49,7 @@ function PMA_getPlugin($plugin_type, $plugin_format, $plugins_dir, $plugin_param */ 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)) { @@ -61,9 +67,12 @@ function PMA_getPlugins($plugin_type, $plugins_dir, $plugin_param) $matches ) ) { + $GLOBALS['skip_import'] = false; include_once $plugins_dir . $file; - $class_name = $class_type . $matches[1]; - $plugin_list [] = new $class_name; + if (! $GLOBALS['skip_import']) { + $class_name = $class_type . $matches[1]; + $plugin_list [] = new $class_name; + } } } } diff --git a/libraries/plugins/import/ImportCsv.class.php b/libraries/plugins/import/ImportCsv.class.php index 1b29646a5e..abcddac717 100644 --- a/libraries/plugins/import/ImportCsv.class.php +++ b/libraries/plugins/import/ImportCsv.class.php @@ -44,10 +44,9 @@ class ImportCsv extends ImportPlugin */ protected function setProperties() { - global $plugin_param; $this->_setAnalyze(false); - if ($plugin_param !== 'table') { + if ($GLOBALS['plugin_param'] !== 'table') { $this->_setAnalyze(true); } @@ -102,7 +101,7 @@ class ImportCsv extends ImportPlugin ) ); - if ($plugin_param !== 'table') { + if ($GLOBALS['plugin_param'] !== 'table') { $this->properties['options'][] = array( 'type' => 'bool', 'name' => 'col_names', diff --git a/libraries/plugins/import/ImportDocsql.class.php b/libraries/plugins/import/ImportDocsql.class.php index 262c5d28af..4a374beede 100644 --- a/libraries/plugins/import/ImportDocsql.class.php +++ b/libraries/plugins/import/ImportDocsql.class.php @@ -13,6 +13,12 @@ if (! defined('PHPMYADMIN')) { /* Get the import interface */ require_once "libraries/plugins/ImportPlugin.class.php"; +// We need relations enabled and we work only on database +if ($GLOBALS['plugin_param'] !== 'database') { + $GLOBALS['skip_import'] = true; + return; +} + /** * Handles the import for the DocSQL format * @@ -43,13 +49,9 @@ class ImportDocsql extends ImportPlugin */ protected function setProperties() { - global $plugin_param; $this->_setCfgRelation(PMA_getRelationsParam()); $cfgRelation = $this->_getCfgRelation(); - - // We need relations enabled and we work only on database - if ($plugin_param !== 'database' - || $GLOBALS['num_tables'] < 1 + if ( $GLOBALS['num_tables'] < 1 || ! $cfgRelation['relwork'] || ! $cfgRelation['commwork'] ) { diff --git a/libraries/plugins/import/ImportLdi.class.php b/libraries/plugins/import/ImportLdi.class.php index 421d11509c..d99e326925 100644 --- a/libraries/plugins/import/ImportLdi.class.php +++ b/libraries/plugins/import/ImportLdi.class.php @@ -13,6 +13,12 @@ if (! defined('PHPMYADMIN')) { /* Get the import interface */ require_once "libraries/plugins/ImportPlugin.class.php"; +// We need relations enabled and we work only on database +if ($GLOBALS['plugin_param'] !== 'table') { + $GLOBALS['skip_import'] = true; + return; +} + /** * Handles the import for the CSV format using load data * @@ -36,11 +42,6 @@ class ImportLdi extends ImportPlugin */ protected function setProperties() { - global $plugin_param; - if ($plugin_param !== 'table') { - return; - } - if ($GLOBALS['cfg']['Import']['ldi_local_option'] == 'auto') { $GLOBALS['cfg']['Import']['ldi_local_option'] = false; diff --git a/libraries/plugins/import/ImportMediawiki.class.php b/libraries/plugins/import/ImportMediawiki.class.php index be8049a3b6..8ed5e52be7 100644 --- a/libraries/plugins/import/ImportMediawiki.class.php +++ b/libraries/plugins/import/ImportMediawiki.class.php @@ -43,9 +43,8 @@ class ImportMediawiki extends ImportPlugin */ protected function setProperties() { - global $plugin_param; $this->_setAnalyze(false); - if ($plugin_param !== 'table') { + if ($GLOBALS['plugin_param'] !== 'table') { $this->_setAnalyze(true); } diff --git a/libraries/plugins/import/ImportShp.class.php b/libraries/plugins/import/ImportShp.class.php index bc56195380..1d239f0c9a 100644 --- a/libraries/plugins/import/ImportShp.class.php +++ b/libraries/plugins/import/ImportShp.class.php @@ -28,7 +28,15 @@ require_once "libraries/plugins/import/PMA_ShapeRecord.class.php"; * @package PhpMyAdmin-Import */ class ImportShp extends ImportPlugin -{ +{ + /** + * Constructor + */ + public function __construct() + { + $this->setProperties(); + } + /** * Sets the import plugin properties. * Called in the constructor. From 507be981fee972cb559d986787b44e8702b97de7 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Tue, 19 Jun 2012 16:52:23 +0300 Subject: [PATCH 37/55] oop: transformations rename classes --- libraries/plugins/TransformationsPlugin.class.php | 4 ++-- ....class.php => Application_Octetstream_Download.class.php} | 3 +-- ...amHex.class.php => Application_Octetstream_Hex.class.php} | 3 +-- ...ImageJPEGInline.class.php => Image_JPEG_Inline.class.php} | 3 +-- ...tionImageJPEGLink.class.php => Image_JPEG_Link.class.php} | 3 +-- ...onImagePNGInline.class.php => Image_PNG_Inline.class.php} | 3 +-- ...TextPlainAppend.class.php => Text_Plain_Append.class.php} | 3 +-- ...nDateFormat.class.php => Text_Plain_Dateformat.class.php} | 5 ++--- ...PlainExternal.class.php => Text_Plain_External.class.php} | 3 +-- ...ainFormatted.class.php => Text_Plain_Formatted.class.php} | 3 +-- ...ainImageLink.class.php => Text_Plain_Imagelink.class.php} | 5 ++--- ...tionTextPlainLink.class.php => Text_Plain_Link.class.php} | 3 +-- ...nLongToIPv4.class.php => Text_Plain_Longtoipv4.class.php} | 5 ++--- ...mationTextPlainSQL.class.php => Text_Plain_Sql.class.php} | 3 +-- ...ainSubstring.class.php => Text_Plain_Substring.class.php} | 3 +-- .../abstract/DateFormatTransformationsPlugin.class.php | 2 +- .../abstract/ImageLinkTransformationsPlugin.class.php | 2 +- .../abstract/LongToIPv4TransformationsPlugin.class.php | 2 +- 18 files changed, 22 insertions(+), 36 deletions(-) rename libraries/plugins/transformations/{TransformationApplicationOctetStreamDownload.class.php => Application_Octetstream_Download.class.php} (93%) rename libraries/plugins/transformations/{TransformationApplicationOctetStreamHex.class.php => Application_Octetstream_Hex.class.php} (93%) rename libraries/plugins/transformations/{TransformationImageJPEGInline.class.php => Image_JPEG_Inline.class.php} (93%) rename libraries/plugins/transformations/{TransformationImageJPEGLink.class.php => Image_JPEG_Link.class.php} (92%) rename libraries/plugins/transformations/{TransformationImagePNGInline.class.php => Image_PNG_Inline.class.php} (93%) rename libraries/plugins/transformations/{TransformationTextPlainAppend.class.php => Text_Plain_Append.class.php} (93%) rename libraries/plugins/transformations/{TransformationTextPlainDateFormat.class.php => Text_Plain_Dateformat.class.php} (93%) rename libraries/plugins/transformations/{TransformationTextPlainExternal.class.php => Text_Plain_External.class.php} (95%) rename libraries/plugins/transformations/{TransformationTextPlainFormatted.class.php => Text_Plain_Formatted.class.php} (93%) rename libraries/plugins/transformations/{TransformationTextPlainImageLink.class.php => Text_Plain_Imagelink.class.php} (91%) rename libraries/plugins/transformations/{TransformationTextPlainLink.class.php => Text_Plain_Link.class.php} (93%) rename libraries/plugins/transformations/{TransformationTextPlainLongToIPv4.class.php => Text_Plain_Longtoipv4.class.php} (90%) rename libraries/plugins/transformations/{TransformationTextPlainSQL.class.php => Text_Plain_Sql.class.php} (93%) rename libraries/plugins/transformations/{TransformationTextPlainSubstring.class.php => Text_Plain_Substring.class.php} (94%) diff --git a/libraries/plugins/TransformationsPlugin.class.php b/libraries/plugins/TransformationsPlugin.class.php index be17845425..48ac4f92b7 100644 --- a/libraries/plugins/TransformationsPlugin.class.php +++ b/libraries/plugins/TransformationsPlugin.class.php @@ -47,14 +47,14 @@ abstract class TransformationsPlugin extends PluginObserver * * @return string */ - abstract public function getMimeType(); + abstract public function getMIMEType(); /** * Gets the specific MIME subtype * * @return string */ - abstract public function getMimeSubType(); + abstract public function getMIMESubtype(); /** * Gets the transformation name of the specific plugin diff --git a/libraries/plugins/transformations/TransformationApplicationOctetStreamDownload.class.php b/libraries/plugins/transformations/Application_Octetstream_Download.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationApplicationOctetStreamDownload.class.php rename to libraries/plugins/transformations/Application_Octetstream_Download.class.php index 369bc850b8..1e411e0ef7 100644 --- a/libraries/plugins/transformations/TransformationApplicationOctetStreamDownload.class.php +++ b/libraries/plugins/transformations/Application_Octetstream_Download.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/DownloadTransformationsPlugin.class.php * * @package PhpMyAdmin */ -class TransformationApplicationOctetStreamDownload - extends DownloadTransformationsPlugin +class Application_Octetstream_Download extends DownloadTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationApplicationOctetStreamHex.class.php b/libraries/plugins/transformations/Application_Octetstream_Hex.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationApplicationOctetStreamHex.class.php rename to libraries/plugins/transformations/Application_Octetstream_Hex.class.php index 89e5e3d06f..8d9d68741e 100644 --- a/libraries/plugins/transformations/TransformationApplicationOctetStreamHex.class.php +++ b/libraries/plugins/transformations/Application_Octetstream_Hex.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/HexTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -class TransformationApplicationOctetStreamHex - extends HexTransformationsPlugin +class Application_Octetstream_Hex extends HexTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationImageJPEGInline.class.php b/libraries/plugins/transformations/Image_JPEG_Inline.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationImageJPEGInline.class.php rename to libraries/plugins/transformations/Image_JPEG_Inline.class.php index 1ea682980c..900590f69a 100644 --- a/libraries/plugins/transformations/TransformationImageJPEGInline.class.php +++ b/libraries/plugins/transformations/Image_JPEG_Inline.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/InlineTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -class TransformationImageJPEGInline - extends InlineTransformationsPlugin +class Image_JPEG_Inline extends InlineTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationImageJPEGLink.class.php b/libraries/plugins/transformations/Image_JPEG_Link.class.php similarity index 92% rename from libraries/plugins/transformations/TransformationImageJPEGLink.class.php rename to libraries/plugins/transformations/Image_JPEG_Link.class.php index 4b62deb82e..2c58b00d50 100644 --- a/libraries/plugins/transformations/TransformationImageJPEGLink.class.php +++ b/libraries/plugins/transformations/Image_JPEG_Link.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/LinkTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -class TransformationImageJPEGLink - extends LinkTransformationsPlugin +class Image_JPEG_Link extends LinkTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationImagePNGInline.class.php b/libraries/plugins/transformations/Image_PNG_Inline.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationImagePNGInline.class.php rename to libraries/plugins/transformations/Image_PNG_Inline.class.php index 5a056ad179..a11a8ab61a 100644 --- a/libraries/plugins/transformations/TransformationImagePNGInline.class.php +++ b/libraries/plugins/transformations/Image_PNG_Inline.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/InlineTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -class TransformationImagePNGInline - extends InlineTransformationsPlugin +class Image_PNG_Inline extends InlineTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainAppend.class.php b/libraries/plugins/transformations/Text_Plain_Append.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationTextPlainAppend.class.php rename to libraries/plugins/transformations/Text_Plain_Append.class.php index 3287dd0032..184d059f28 100644 --- a/libraries/plugins/transformations/TransformationTextPlainAppend.class.php +++ b/libraries/plugins/transformations/Text_Plain_Append.class.php @@ -19,8 +19,7 @@ require_once "libraries/plugins/abstract/AppendTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -class TransformationTextPlainAppend - extends AppendTransformationsPlugin +class Text_Plain_Append extends AppendTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainDateFormat.class.php b/libraries/plugins/transformations/Text_Plain_Dateformat.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationTextPlainDateFormat.class.php rename to libraries/plugins/transformations/Text_Plain_Dateformat.class.php index 6319fefbc6..36f2a518bf 100644 --- a/libraries/plugins/transformations/TransformationTextPlainDateFormat.class.php +++ b/libraries/plugins/transformations/Text_Plain_Dateformat.class.php @@ -4,7 +4,7 @@ * Text Plain Date Format Transformations plugin for phpMyAdmin * * @package PhpMyAdmin-Transformations - * @subpackage Date Format + * @subpackage DateFormat */ if (! defined('PHPMYADMIN')) { exit; @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/DateFormatTransformationsPlugin.class.p * * @package PhpMyAdmin */ -class TransformationTextPlainDateFormat - extends DateFormatTransformationsPlugin +class Text_Plain_Dateformat extends DateFormatTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainExternal.class.php b/libraries/plugins/transformations/Text_Plain_External.class.php similarity index 95% rename from libraries/plugins/transformations/TransformationTextPlainExternal.class.php rename to libraries/plugins/transformations/Text_Plain_External.class.php index a1c5a5ffb6..6ea114887a 100644 --- a/libraries/plugins/transformations/TransformationTextPlainExternal.class.php +++ b/libraries/plugins/transformations/Text_Plain_External.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/ExternalTransformationsPlugin.class.php * * @package PhpMyAdmin */ -class TransformationTextPlainExternal - extends ExternalTransformationsPlugin +class Text_Plain_External extends ExternalTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainFormatted.class.php b/libraries/plugins/transformations/Text_Plain_Formatted.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationTextPlainFormatted.class.php rename to libraries/plugins/transformations/Text_Plain_Formatted.class.php index 795a1fc597..5a5d2a8fee 100644 --- a/libraries/plugins/transformations/TransformationTextPlainFormatted.class.php +++ b/libraries/plugins/transformations/Text_Plain_Formatted.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/FormattedTransformationsPlugin.class.ph * * @package PhpMyAdmin */ -class TransformationTextPlainFormatted - extends FormattedTransformationsPlugin +class Text_Plain_Formatted extends FormattedTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainImageLink.class.php b/libraries/plugins/transformations/Text_Plain_Imagelink.class.php similarity index 91% rename from libraries/plugins/transformations/TransformationTextPlainImageLink.class.php rename to libraries/plugins/transformations/Text_Plain_Imagelink.class.php index 5356c8700c..0b3bd9e7fa 100644 --- a/libraries/plugins/transformations/TransformationTextPlainImageLink.class.php +++ b/libraries/plugins/transformations/Text_Plain_Imagelink.class.php @@ -4,7 +4,7 @@ * Text Plain Image Link Transformations plugin for phpMyAdmin * * @package PhpMyAdmin-Transformations - * @subpackage Image Link + * @subpackage ImageLink */ if (! defined('PHPMYADMIN')) { exit; @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/ImageLinkTransformationsPlugin.class.ph * * @package PhpMyAdmin */ -class TransformationTextPlainImageLink - extends ImageLinkTransformationsPlugin +class Text_Plain_Imagelink extends ImageLinkTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainLink.class.php b/libraries/plugins/transformations/Text_Plain_Link.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationTextPlainLink.class.php rename to libraries/plugins/transformations/Text_Plain_Link.class.php index 87350f077b..c3e08b37ce 100644 --- a/libraries/plugins/transformations/TransformationTextPlainLink.class.php +++ b/libraries/plugins/transformations/Text_Plain_Link.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/LinkTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -class TransformationTextPlainLink - extends LinkTransformationsPlugin +class Text_Plain_Link extends LinkTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainLongToIPv4.class.php b/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php similarity index 90% rename from libraries/plugins/transformations/TransformationTextPlainLongToIPv4.class.php rename to libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php index 22b690c406..c2e8e56d34 100644 --- a/libraries/plugins/transformations/TransformationTextPlainLongToIPv4.class.php +++ b/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php @@ -4,7 +4,7 @@ * Text Plain Long To IPv4 Transformations plugin for phpMyAdmin * * @package PhpMyAdmin-Transformations - * @subpackage Long To IPv4 + * @subpackage LongToIPv4 */ if (! defined('PHPMYADMIN')) { exit; @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/LongToIPv4TransformationsPlugin.class.p * * @package PhpMyAdmin */ -class TransformationTextPlainLongToIPv4 - extends LongToIPv4TransformationsPlugin +class Text_Plain_Longtoipv4 extends LongToIPv4TransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainSQL.class.php b/libraries/plugins/transformations/Text_Plain_Sql.class.php similarity index 93% rename from libraries/plugins/transformations/TransformationTextPlainSQL.class.php rename to libraries/plugins/transformations/Text_Plain_Sql.class.php index 62fc3dace6..d7052610bb 100644 --- a/libraries/plugins/transformations/TransformationTextPlainSQL.class.php +++ b/libraries/plugins/transformations/Text_Plain_Sql.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/SQLTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -class TransformationTextPlainSQL - extends SQLTransformationsPlugin +class Text_Plain_Sql extends SQLTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/TransformationTextPlainSubstring.class.php b/libraries/plugins/transformations/Text_Plain_Substring.class.php similarity index 94% rename from libraries/plugins/transformations/TransformationTextPlainSubstring.class.php rename to libraries/plugins/transformations/Text_Plain_Substring.class.php index de118cfdfe..f1de2a2132 100644 --- a/libraries/plugins/transformations/TransformationTextPlainSubstring.class.php +++ b/libraries/plugins/transformations/Text_Plain_Substring.class.php @@ -18,8 +18,7 @@ require_once "libraries/plugins/abstract/SubstringTransformationsPlugin.class.ph * * @package PhpMyAdmin */ -class TransformationTextPlainSubstring - extends SubstringTransformationsPlugin +class Text_Plain_Substring extends SubstringTransformationsPlugin { /** * Gets the transformation description of the specific plugin diff --git a/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php index cc0c000ea1..a482cc8943 100644 --- a/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php @@ -4,7 +4,7 @@ * Abstract class for the date format transformations plugins * * @package PhpMyAdmin-Transformations - * @subpackage Date Format + * @subpackage DateFormat */ if (! defined('PHPMYADMIN')) { exit; diff --git a/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php index 2cb6b4c6e6..cef2c80f88 100644 --- a/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php @@ -4,7 +4,7 @@ * Abstract class for the image link transformations plugins * * @package PhpMyAdmin-Transformations - * @subpackage Image Link + * @subpackage ImageLink */ if (! defined('PHPMYADMIN')) { exit; diff --git a/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php index 0b968b97e1..d01e0ef6b8 100644 --- a/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php @@ -4,7 +4,7 @@ * Abstract class for the long to IPv4 transformations plugins * * @package PhpMyAdmin-Transformations - * @subpackage Long To IPv4 + * @subpackage LongToIPv4 */ if (! defined('PHPMYADMIN')) { exit; From 1ad049d8239853516d7c007e98a2fee09ac9115c Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Tue, 19 Jun 2012 23:55:15 +0300 Subject: [PATCH 38/55] oop: transformations - fix classes, add interface and use descriptions --- .../plugins/TransformationsInterface.int.php | 48 +++++++++++ .../plugins/TransformationsPlugin.class.php | 41 ++------- ...Application_Octetstream_Download.class.php | 9 +- .../Application_Octetstream_Hex.class.php | 8 +- .../Image_JPEG_Inline.class.php | 8 +- .../transformations/Image_JPEG_Link.class.php | 8 +- .../Image_PNG_Inline.class.php | 8 +- .../Text_Plain_Append.class.php | 8 +- .../Text_Plain_Dateformat.class.php | 8 +- .../Text_Plain_External.class.php | 8 +- .../Text_Plain_Formatted.class.php | 8 +- .../Text_Plain_Imagelink.class.php | 8 +- .../transformations/Text_Plain_Link.class.php | 8 +- .../Text_Plain_Longtoipv4.class.php | 8 +- .../transformations/Text_Plain_Sql.class.php | 8 +- .../Text_Plain_Substring.class.php | 8 +- .../AppendTransformationsPlugin.class.php | 4 +- .../DateFormatTransformationsPlugin.class.php | 4 +- .../DownloadTransformationsPlugin.class.php | 4 +- .../ExternalTransformationsPlugin.class.php | 4 +- .../FormattedTransformationsPlugin.class.php | 4 +- ...php => HexTransformationsPlugin.class.php} | 4 +- .../ImageLinkTransformationsPlugin.class.php | 4 +- ... => InlineTransformationsPlugin.class.php} | 4 +- .../LinkTransformationsPlugin.class.php | 4 +- .../LongToIPv4TransformationsPlugin.class.php | 4 +- .../SQLTransformationsPlugin.class.php | 4 +- .../SubstringTransformationsPlugin.class.php | 4 +- libraries/transformations.lib.php | 84 +++++++++---------- transformation_overview.php | 5 -- 30 files changed, 176 insertions(+), 163 deletions(-) create mode 100644 libraries/plugins/TransformationsInterface.int.php rename libraries/plugins/transformations/abstract/{HexTransformationsPlugin.class.php.php => HexTransformationsPlugin.class.php} (92%) rename libraries/plugins/transformations/abstract/{InlineTransformationsPlugin.class.php.php => InlineTransformationsPlugin.class.php} (92%) diff --git a/libraries/plugins/TransformationsInterface.int.php b/libraries/plugins/TransformationsInterface.int.php new file mode 100644 index 0000000000..291ba8b51c --- /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 index 48ac4f92b7..a9bb5bd9a6 100644 --- a/libraries/plugins/TransformationsPlugin.class.php +++ b/libraries/plugins/TransformationsPlugin.class.php @@ -9,16 +9,19 @@ if (! defined('PHPMYADMIN')) { exit; } -/* This class extends the PluginObserver class */ +/* It extends the PluginObserver abstract class */ require_once "PluginObserver.class.php"; +/* It also implements the transformations interface */ +require_once "TransformationsInterface.int.php"; /** - * Provides a common interface that will have to implemented by all of the - * transformations plugins. + * Extends PluginObserver and provides a common interface that will have to + * be implemented by all of the transformations plugins. * * @package PhpMyAdmin */ abstract class TransformationsPlugin extends PluginObserver + implements TransformationsInterface { /** * Does the actual work of each specific transformations plugin. @@ -30,37 +33,5 @@ abstract class TransformationsPlugin extends PluginObserver * @return void */ abstract public function applyTransformation($buffer, $options, $meta); - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - /** - * Gets the transformation description - * - * @return string - */ - abstract public function getInfo(); - - /** - * Gets the specific MIME type - * - * @return string - */ - abstract public function getMIMEType(); - - /** - * Gets the specific MIME subtype - * - * @return string - */ - abstract public function getMIMESubtype(); - - /** - * Gets the transformation name of the specific plugin - * - * @return string - */ - abstract public function getName(); } ?> \ No newline at end of file diff --git a/libraries/plugins/transformations/Application_Octetstream_Download.class.php b/libraries/plugins/transformations/Application_Octetstream_Download.class.php index 1e411e0ef7..e986631c6e 100644 --- a/libraries/plugins/transformations/Application_Octetstream_Download.class.php +++ b/libraries/plugins/transformations/Application_Octetstream_Download.class.php @@ -9,9 +9,8 @@ if (! defined('PHPMYADMIN')) { exit; } - /* Get the download transformations interface */ -require_once "libraries/plugins/abstract/DownloadTransformationsPlugin.class.php"; +require_once "abstract/DownloadTransformationsPlugin.class.php"; /** * Handles the download transformation for application octetstream @@ -25,7 +24,7 @@ class Application_Octetstream_Download extends DownloadTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays a link to download the binary data of the column. You can' @@ -41,7 +40,7 @@ class Application_Octetstream_Download extends DownloadTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Application"; } @@ -51,7 +50,7 @@ class Application_Octetstream_Download extends DownloadTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "OctetStream"; } diff --git a/libraries/plugins/transformations/Application_Octetstream_Hex.class.php b/libraries/plugins/transformations/Application_Octetstream_Hex.class.php index 8d9d68741e..121548374c 100644 --- a/libraries/plugins/transformations/Application_Octetstream_Hex.class.php +++ b/libraries/plugins/transformations/Application_Octetstream_Hex.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the hex transformations interface */ -require_once "libraries/plugins/abstract/HexTransformationsPlugin.class.php"; +require_once "abstract/HexTransformationsPlugin.class.php"; /** * Handles the hex transformation for application octetstream @@ -25,7 +25,7 @@ class Application_Octetstream_Hex extends HexTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays hexadecimal representation of data. Optional first' @@ -39,7 +39,7 @@ class Application_Octetstream_Hex extends HexTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Application"; } @@ -49,7 +49,7 @@ class Application_Octetstream_Hex extends HexTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "OctetStream"; } diff --git a/libraries/plugins/transformations/Image_JPEG_Inline.class.php b/libraries/plugins/transformations/Image_JPEG_Inline.class.php index 900590f69a..41d481da01 100644 --- a/libraries/plugins/transformations/Image_JPEG_Inline.class.php +++ b/libraries/plugins/transformations/Image_JPEG_Inline.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the inline transformations interface */ -require_once "libraries/plugins/abstract/InlineTransformationsPlugin.class.php"; +require_once "abstract/InlineTransformationsPlugin.class.php"; /** * Handles the inline transformation for image jpeg @@ -25,7 +25,7 @@ class Image_JPEG_Inline extends InlineTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays a clickable thumbnail. The options are the maximum width' @@ -38,7 +38,7 @@ class Image_JPEG_Inline extends InlineTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Image"; } @@ -48,7 +48,7 @@ class Image_JPEG_Inline extends InlineTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "JPEG"; } diff --git a/libraries/plugins/transformations/Image_JPEG_Link.class.php b/libraries/plugins/transformations/Image_JPEG_Link.class.php index 2c58b00d50..0f5258072e 100644 --- a/libraries/plugins/transformations/Image_JPEG_Link.class.php +++ b/libraries/plugins/transformations/Image_JPEG_Link.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the link transformations interface */ -require_once "libraries/plugins/abstract/LinkTransformationsPlugin.class.php"; +require_once "abstract/LinkTransformationsPlugin.class.php"; /** * Handles the link transformation for image jpeg @@ -25,7 +25,7 @@ class Image_JPEG_Link extends LinkTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays a link to download this image.' @@ -37,7 +37,7 @@ class Image_JPEG_Link extends LinkTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Image"; } @@ -47,7 +47,7 @@ class Image_JPEG_Link extends LinkTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "JPEG"; } diff --git a/libraries/plugins/transformations/Image_PNG_Inline.class.php b/libraries/plugins/transformations/Image_PNG_Inline.class.php index a11a8ab61a..6a722d305c 100644 --- a/libraries/plugins/transformations/Image_PNG_Inline.class.php +++ b/libraries/plugins/transformations/Image_PNG_Inline.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the inline transformations interface */ -require_once "libraries/plugins/abstract/InlineTransformationsPlugin.class.php"; +require_once "abstract/InlineTransformationsPlugin.class.php"; /** * Handles the inline transformation for image png @@ -25,7 +25,7 @@ class Image_PNG_Inline extends InlineTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays a clickable thumbnail. The options are the maximum width' @@ -38,7 +38,7 @@ class Image_PNG_Inline extends InlineTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Image"; } @@ -48,7 +48,7 @@ class Image_PNG_Inline extends InlineTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "PNG"; } diff --git a/libraries/plugins/transformations/Text_Plain_Append.class.php b/libraries/plugins/transformations/Text_Plain_Append.class.php index 184d059f28..b2f914ec48 100644 --- a/libraries/plugins/transformations/Text_Plain_Append.class.php +++ b/libraries/plugins/transformations/Text_Plain_Append.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the append transformations interface */ -require_once "libraries/plugins/abstract/AppendTransformationsPlugin.class.php"; +require_once "abstract/AppendTransformationsPlugin.class.php"; /** * Handles the append transformation for text plain. @@ -26,7 +26,7 @@ class Text_Plain_Append extends AppendTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Appends text to a string. The only option is the text to be appended' @@ -39,7 +39,7 @@ class Text_Plain_Append extends AppendTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -49,7 +49,7 @@ class Text_Plain_Append extends AppendTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_Dateformat.class.php b/libraries/plugins/transformations/Text_Plain_Dateformat.class.php index 36f2a518bf..d76c612183 100644 --- a/libraries/plugins/transformations/Text_Plain_Dateformat.class.php +++ b/libraries/plugins/transformations/Text_Plain_Dateformat.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the date format transformations interface */ -require_once "libraries/plugins/abstract/DateFormatTransformationsPlugin.class.php"; +require_once "abstract/DateFormatTransformationsPlugin.class.php"; /** * Handles the date format transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_Dateformat extends DateFormatTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays a TIME, TIMESTAMP, DATETIME or numeric unix timestamp' @@ -45,7 +45,7 @@ class Text_Plain_Dateformat extends DateFormatTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -55,7 +55,7 @@ class Text_Plain_Dateformat extends DateFormatTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_External.class.php b/libraries/plugins/transformations/Text_Plain_External.class.php index 6ea114887a..b7155485d5 100644 --- a/libraries/plugins/transformations/Text_Plain_External.class.php +++ b/libraries/plugins/transformations/Text_Plain_External.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the external transformations interface */ -require_once "libraries/plugins/abstract/ExternalTransformationsPlugin.class.php"; +require_once "abstract/ExternalTransformationsPlugin.class.php"; /** * Handles the external transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_External extends ExternalTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'LINUX ONLY: Launches an external application and feeds it the column' @@ -48,7 +48,7 @@ class Text_Plain_External extends ExternalTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -58,7 +58,7 @@ class Text_Plain_External extends ExternalTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_Formatted.class.php b/libraries/plugins/transformations/Text_Plain_Formatted.class.php index 5a5d2a8fee..2865323719 100644 --- a/libraries/plugins/transformations/Text_Plain_Formatted.class.php +++ b/libraries/plugins/transformations/Text_Plain_Formatted.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the formatted transformations interface */ -require_once "libraries/plugins/abstract/FormattedTransformationsPlugin.class.php"; +require_once "abstract/FormattedTransformationsPlugin.class.php"; /** * Handles the formatted transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_Formatted extends FormattedTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays the contents of the column as-is, without running it' @@ -39,7 +39,7 @@ class Text_Plain_Formatted extends FormattedTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -49,7 +49,7 @@ class Text_Plain_Formatted extends FormattedTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_Imagelink.class.php b/libraries/plugins/transformations/Text_Plain_Imagelink.class.php index 0b3bd9e7fa..3d23824900 100644 --- a/libraries/plugins/transformations/Text_Plain_Imagelink.class.php +++ b/libraries/plugins/transformations/Text_Plain_Imagelink.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the image link transformations interface */ -require_once "libraries/plugins/abstract/ImageLinkTransformationsPlugin.class.php"; +require_once "abstract/ImageLinkTransformationsPlugin.class.php"; /** * Handles the image link transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_Imagelink extends ImageLinkTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays an image and a link; the column contains the filename. The' @@ -39,7 +39,7 @@ class Text_Plain_Imagelink extends ImageLinkTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -49,7 +49,7 @@ class Text_Plain_Imagelink extends ImageLinkTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_Link.class.php b/libraries/plugins/transformations/Text_Plain_Link.class.php index c3e08b37ce..1ed058bb34 100644 --- a/libraries/plugins/transformations/Text_Plain_Link.class.php +++ b/libraries/plugins/transformations/Text_Plain_Link.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the link transformations interface */ -require_once "libraries/plugins/abstract/LinkTransformationsPlugin.class.php"; +require_once "abstract/LinkTransformationsPlugin.class.php"; /** * Handles the link transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_Link extends LinkTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays a link; the column contains the filename. The first option' @@ -39,7 +39,7 @@ class Text_Plain_Link extends LinkTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -49,7 +49,7 @@ class Text_Plain_Link extends LinkTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php b/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php index c2e8e56d34..32373ad7f3 100644 --- a/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php +++ b/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the long to ipv4 transformations interface */ -require_once "libraries/plugins/abstract/LongToIPv4TransformationsPlugin.class.php"; +require_once "abstract/LongToIPv4TransformationsPlugin.class.php"; /** * Handles the long to ipv4 transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_Longtoipv4 extends LongToIPv4TransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Converts an (IPv4) Internet network address into a string in' @@ -38,7 +38,7 @@ class Text_Plain_Longtoipv4 extends LongToIPv4TransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -48,7 +48,7 @@ class Text_Plain_Longtoipv4 extends LongToIPv4TransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_Sql.class.php b/libraries/plugins/transformations/Text_Plain_Sql.class.php index d7052610bb..816069faab 100644 --- a/libraries/plugins/transformations/Text_Plain_Sql.class.php +++ b/libraries/plugins/transformations/Text_Plain_Sql.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the sql transformations interface */ -require_once "libraries/plugins/abstract/SQLTransformationsPlugin.class.php"; +require_once "abstract/SQLTransformationsPlugin.class.php"; /** * Handles the sql transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_Sql extends SQLTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Formats text as SQL query with syntax highlighting.' @@ -37,7 +37,7 @@ class Text_Plain_Sql extends SQLTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -47,7 +47,7 @@ class Text_Plain_Sql extends SQLTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/Text_Plain_Substring.class.php b/libraries/plugins/transformations/Text_Plain_Substring.class.php index f1de2a2132..187e5fdbb8 100644 --- a/libraries/plugins/transformations/Text_Plain_Substring.class.php +++ b/libraries/plugins/transformations/Text_Plain_Substring.class.php @@ -11,7 +11,7 @@ if (! defined('PHPMYADMIN')) { } /* Get the substring transformations interface */ -require_once "libraries/plugins/abstract/SubstringTransformationsPlugin.class.php"; +require_once "abstract/SubstringTransformationsPlugin.class.php"; /** * Handles the substring transformation for text plain @@ -25,7 +25,7 @@ class Text_Plain_Substring extends SubstringTransformationsPlugin * * @return string */ - public function getInfo() + public static function getInfo() { return __( 'Displays a part of a string. The first option is the number of' @@ -41,7 +41,7 @@ class Text_Plain_Substring extends SubstringTransformationsPlugin * * @return string */ - public function getMIMEType() + public static function getMIMEType() { return "Text"; } @@ -51,7 +51,7 @@ class Text_Plain_Substring extends SubstringTransformationsPlugin * * @return string */ - public function getMIMESubtype() + public static function getMIMESubtype() { return "Plain"; } diff --git a/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php index c3f323d64e..9b811a057d 100644 --- a/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class AppendTransformationsPlugin extends PluginObserver +abstract class AppendTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class AppendTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Append"; } diff --git a/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php index a482cc8943..bd4d82d67c 100644 --- a/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class DateFormatTransformationsPlugin extends PluginObserver +abstract class DateFormatTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class DateFormatTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Date Format"; } diff --git a/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php index f6ff46d787..77bd39ecda 100644 --- a/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class DownloadTransformationsPlugin extends PluginObserver +abstract class DownloadTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class DownloadTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Download"; } diff --git a/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php index 0adf1a5d50..2a7c495584 100644 --- a/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class ExternalTransformationsPlugin extends PluginObserver +abstract class ExternalTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class ExternalTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "External"; } diff --git a/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php index a9431f137c..e089fac77a 100644 --- a/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class FormattedTransformationsPlugin extends PluginObserver +abstract class FormattedTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class FormattedTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Formatted"; } diff --git a/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php.php b/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php similarity index 92% rename from libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php.php rename to libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php index 63b8e96360..76ff6741ae 100644 --- a/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php.php +++ b/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class HexTransformationsPlugin extends PluginObserver +abstract class HexTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class HexTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Hex"; } diff --git a/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php index cef2c80f88..c98568a579 100644 --- a/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class ImageLinkTransformationsPlugin extends PluginObserver +abstract class ImageLinkTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class ImageLinkTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Image Link"; } diff --git a/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php.php b/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php similarity index 92% rename from libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php.php rename to libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php index 8fcdec25b3..16683b92c4 100644 --- a/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php.php +++ b/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class InlineTransformationsPlugin extends PluginObserver +abstract class InlineTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class InlineTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Inline"; } diff --git a/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php index b1dd95d705..d655ea2b17 100644 --- a/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class LinkTransformationsPlugin extends PluginObserver +abstract class LinkTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class LinkTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Link"; } diff --git a/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php index d01e0ef6b8..53f1180f59 100644 --- a/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class LongToIPv4TransformationsPlugin extends PluginObserver +abstract class LongToIPv4TransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class LongToIPv4TransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Long To IPv4"; } diff --git a/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php index ae51182abb..32cd9b889d 100644 --- a/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class SQLTransformationsPlugin extends PluginObserver +abstract class SQLTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class SQLTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "SQL"; } diff --git a/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php index 33eab316ec..de0e794989 100644 --- a/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class SubstringTransformationsPlugin extends PluginObserver +abstract class SubstringTransformationsPlugin extends TransformationsPlugin { /** * Does the actual work of each specific transformations plugin. @@ -59,7 +59,7 @@ abstract class SubstringTransformationsPlugin extends PluginObserver * * @return string */ - public function getName() + public static function getName() { return "Substring"; } diff --git a/libraries/transformations.lib.php b/libraries/transformations.lib.php index a6517df8ce..ec8b97fcc4 100644 --- a/libraries/transformations.lib.php +++ b/libraries/transformations.lib.php @@ -93,7 +93,7 @@ function PMA_getAvailableMIMEtypes() $stack = array(); $filestack = array(); - $handle = opendir('./libraries/transformations'); + $handle = opendir('./libraries/plugins/transformations'); if (! $handle) { return $stack; @@ -107,18 +107,17 @@ function PMA_getAvailableMIMEtypes() sort($filestack); foreach ($filestack as $file) { - if (preg_match('|^.*__.*\.inc\.php$|', $file)) { + if (preg_match('|^.*_.*_.*\.class\.php$|', $file)) { // File contains transformation functions. - $base = explode('__', str_replace('.inc.php', '', $file)); - $mimetype = str_replace('_', '/', $base[0]); + $parts = explode('_', str_replace('.class.php', '', $file)); + $mimetype = $parts[0] . "/" . $parts[1]; $stack['mimetype'][$mimetype] = $mimetype; - - $stack['transformation'][] = $mimetype . ': ' . $base[1]; + $stack['transformation'][] = $mimetype . ': ' . $parts[2]; $stack['transformation_file'][] = $file; - } elseif (preg_match('|^.*\.inc\.php$|', $file)) { + } elseif (preg_match('|^.*\.class.php$|', $file)) { // File is a plain mimetype, no functions. - $base = str_replace('.inc.php', '', $file); + $base = str_replace('.class.php', '', $file); if ($base != 'global') { $mimetype = str_replace('_', '/', $base); @@ -135,29 +134,20 @@ function PMA_getAvailableMIMEtypes() * Returns the description of the transformation * * @param string $file transformation file - * @param string $html_formatted whether the description should be formatted as HTML + * @param string $html_formatted whether the description should be formatted + * as HTML * * @return the description of the transformation */ function PMA_getTransformationDescription($file, $html_formatted = true) { - include_once './libraries/transformations/' . $file; - $func = strtolower(str_replace('.inc.php', '', $file)); - $funcname = 'PMA_transformation_' . $func . '_info'; + // get the transformation class name + $class_name = explode(".class.php", $file); + $class_name = $class_name[0]; - $desc = sprintf(__('No description is available for this transformation.
Please ask the author what %s does.'), 'PMA_transformation_' . $func . '()'); - if ($html_formatted) { - $desc = '' . $desc . ''; - } else { - $desc = str_replace('
', ' ', $desc); - } - if (function_exists($funcname)) { - $desc_arr = $funcname(); - if (isset($desc_arr['info'])) { - $desc = $desc_arr['info']; - } - } - return $desc; + // include and instantiate the class + require_once 'libraries/plugins/transformations/' . $file; + return $class_name::getInfo(); } /** @@ -184,7 +174,8 @@ function PMA_getMIME($db, $table, $strict = false) `mimetype`, `transformation`, `transformation_options` - FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' + FROM ' . PMA_backquote($cfgRelation['db']) . '.' + . PMA_backquote($cfgRelation['column_info']) . ' WHERE `db_name` = \'' . PMA_sqlAddSlashes($db) . '\' AND `table_name` = \'' . PMA_sqlAddSlashes($table) . '\' AND ( `mimetype` != \'\'' . (!$strict ? ' @@ -223,7 +214,8 @@ function PMA_setMIME($db, $table, $key, $mimetype, $transformation, $test_qry = ' SELECT `mimetype`, `comment` - FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' + FROM ' . PMA_backquote($cfgRelation['db']) . '.' + . PMA_backquote($cfgRelation['column_info']) . ' WHERE `db_name` = \'' . PMA_sqlAddSlashes($db) . '\' AND `table_name` = \'' . PMA_sqlAddSlashes($table) . '\' AND `column_name` = \'' . PMA_sqlAddSlashes($key) . '\''; @@ -238,12 +230,17 @@ function PMA_setMIME($db, $table, $key, $mimetype, $transformation, || strlen($transformation_options) || strlen($row['comment'])) ) { $upd_query = ' - UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' - SET `mimetype` = \'' . PMA_sqlAddSlashes($mimetype) . '\', - `transformation` = \'' . PMA_sqlAddSlashes($transformation) . '\', - `transformation_options` = \'' . PMA_sqlAddSlashes($transformation_options) . '\''; + UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' + . PMA_backquote($cfgRelation['column_info']) . ' + SET `mimetype` = \'' + . PMA_sqlAddSlashes($mimetype) . '\', + `transformation` = \'' + . PMA_sqlAddSlashes($transformation) . '\', + `transformation_options` = \'' + . PMA_sqlAddSlashes($transformation_options) . '\''; } else { - $upd_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']); + $upd_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' + . PMA_backquote($cfgRelation['column_info']); } $upd_query .= ' WHERE `db_name` = \'' . PMA_sqlAddSlashes($db) . '\' @@ -251,15 +248,17 @@ function PMA_setMIME($db, $table, $key, $mimetype, $transformation, AND `column_name` = \'' . PMA_sqlAddSlashes($key) . '\''; } elseif (strlen($mimetype) || strlen($transformation) || strlen($transformation_options)) { - $upd_query = 'INSERT INTO ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) - . ' (db_name, table_name, column_name, mimetype, transformation, transformation_options) ' - . ' VALUES(' - . '\'' . PMA_sqlAddSlashes($db) . '\',' - . '\'' . PMA_sqlAddSlashes($table) . '\',' - . '\'' . PMA_sqlAddSlashes($key) . '\',' - . '\'' . PMA_sqlAddSlashes($mimetype) . '\',' - . '\'' . PMA_sqlAddSlashes($transformation) . '\',' - . '\'' . PMA_sqlAddSlashes($transformation_options) . '\')'; + $upd_query = 'INSERT INTO ' . PMA_backquote($cfgRelation['db']) + . '.' . PMA_backquote($cfgRelation['column_info']) + . ' (db_name, table_name, column_name, mimetype, transformation,' + . ' transformation_options) ' + . ' VALUES(' + . '\'' . PMA_sqlAddSlashes($db) . '\',' + . '\'' . PMA_sqlAddSlashes($table) . '\',' + . '\'' . PMA_sqlAddSlashes($key) . '\',' + . '\'' . PMA_sqlAddSlashes($mimetype) . '\',' + . '\'' . PMA_sqlAddSlashes($transformation) . '\',' + . '\'' . PMA_sqlAddSlashes($transformation_options) . '\')'; } if (isset($upd_query)) { @@ -286,7 +285,8 @@ function PMA_setMIME($db, $table, $key, $mimetype, $transformation, * = array ( * 'string' => 'string', // text containing "[__BUFFER__]" * 'regex' => 'mixed', // the pattern to search for - * 'regex_replace' => 'mixed', // string or array of strings to replace with + * 'regex_replace' => 'mixed', // string or array of strings to replace + * // with * ); * * @return string containing the text with all the replacements diff --git a/transformation_overview.php b/transformation_overview.php index 50a3ab8e9c..d47c5e8c84 100644 --- a/transformation_overview.php +++ b/transformation_overview.php @@ -31,11 +31,6 @@ foreach ($types['mimetype'] as $key => $mimetype) { } ?>
-() - -
-
-

From 02dbd14fc7a212b591ae050998c6eebf60298b00 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Wed, 20 Jun 2012 16:28:10 +0300 Subject: [PATCH 39/55] oop: integrate transformations - no errors, but not working. --- libraries/DisplayResults.class.php | 530 ++++++++++-------- libraries/insert_edit.lib.php | 2 +- .../plugins/TransformationsPlugin.class.php | 13 + ...Application_Octetstream_Download.class.php | 16 - .../Application_Octetstream_Hex.class.php | 14 - .../Image_JPEG_Inline.class.php | 13 - .../transformations/Image_JPEG_Link.class.php | 16 +- .../Image_PNG_Inline.class.php | 13 - .../Text_Plain_Append.class.php | 13 - .../Text_Plain_Dateformat.class.php | 20 - .../Text_Plain_External.class.php | 23 - .../Text_Plain_Formatted.class.php | 14 - .../Text_Plain_Imagelink.class.php | 18 +- .../transformations/Text_Plain_Link.class.php | 18 +- .../Text_Plain_Longtoipv4.class.php | 13 - .../transformations/Text_Plain_Sql.class.php | 12 - .../Text_Plain_Substring.class.php | 16 - .../AppendTransformationsPlugin.class.php | 24 +- .../DateFormatTransformationsPlugin.class.php | 114 +++- .../DownloadTransformationsPlugin.class.php | 49 +- .../ExternalTransformationsPlugin.class.php | 121 +++- .../FormattedTransformationsPlugin.class.php | 19 +- .../HexTransformationsPlugin.class.php | 30 +- .../ImageLinkTransformationsPlugin.class.php | 34 +- .../InlineTransformationsPlugin.class.php | 40 +- .../LongToIPv4TransformationsPlugin.class.php | 22 +- .../SQLTransformationsPlugin.class.php | 20 +- .../SubstringTransformationsPlugin.class.php | 55 +- ...xtImageLinkTransformationsPlugin.class.php | 94 ++++ ...> TextLinkTransformationsPlugin.class.php} | 33 +- tbl_replace.php | 51 +- 31 files changed, 960 insertions(+), 510 deletions(-) create mode 100644 libraries/plugins/transformations/abstract/TextImageLinkTransformationsPlugin.class.php rename libraries/plugins/transformations/abstract/{LinkTransformationsPlugin.class.php => TextLinkTransformationsPlugin.class.php} (57%) diff --git a/libraries/DisplayResults.class.php b/libraries/DisplayResults.class.php index 0061047fb2..003d9e79a8 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,51 +2156,50 @@ 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'] && $GLOBALS['cfg']['BrowseMIME'] ) { - if (isset($GLOBALS['mime_map'][$meta->name]['mimetype']) && isset($GLOBALS['mime_map'][$meta->name]['transformation']) && !empty($GLOBALS['mime_map'][$meta->name]['transformation']) ) { + $file = $GLOBALS['mime_map'][$meta->name]['transformation']; + $file = PMA_securePath( + str_replace( + ".inc.php", + ".class.php", + str_replace( + "__", + "_", + $file + ) + ) + ); + $file_parts = explode("_", $file); + $file = strtoupper($file_parts[0]) . "_" + . strtoupper($file_parts[1]) . "_" + . strtoupper($file_parts[2]); - $include_file - = './libraries/transformations/' . PMA_securePath( - $GLOBALS['mime_map'][$meta->name]['transformation'] - ); - + $include_file = 'libraries/transformations/plugins/' . $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); + $transformation_plugin = new $class_name; + $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 +2229,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 +2244,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 +2258,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 +2269,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 +2396,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 +2435,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 +2464,7 @@ class PMA_DisplayResults * @param boolean $directionCondition the directional condition * * @return string $vertical_disp_html html content - * + * * @access private * * @see _getTableBody() @@ -2516,7 +2519,7 @@ class PMA_DisplayResults * * @return array 5 element array - $edit_url, $copy_url, * $edit_str, $copy_str, $edit_anchor_class - * + * * @access private * * @see _getTableBody() @@ -2568,7 +2571,7 @@ class PMA_DisplayResults * * @return array 4 element array - $del_query, * $del_url, $del_str, $js_conf - * + * * @access private * * @see _getTableBody() @@ -2662,7 +2665,7 @@ class PMA_DisplayResults * @param string $js_conf text for the JS confirmation * * @return string html content - * + * * @access private * * @see _getTableBody() @@ -2698,7 +2701,7 @@ class PMA_DisplayResults * @param integer $row_no the row index * * @return string $class the resetted class - * + * * @access private * * @see _getTableBody() @@ -2736,7 +2739,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,28 +2762,31 @@ 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 * - * @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)) { $cell = $this->_buildNullDisplay( @@ -2795,7 +2801,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 +2820,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 +2859,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 +2889,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 +2916,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 +2951,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 +2979,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 +3013,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 +3042,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 +3081,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 +3124,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 +3141,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 +3158,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 ); @@ -3322,7 +3338,7 @@ class PMA_DisplayResults * @param string $operation edit/copy/delete * * @return string $links_html html content - * + * * @access private * * @see _getVerticalTable() @@ -3364,7 +3380,7 @@ class PMA_DisplayResults * @param string $dir _left / _right * * @return $checkBoxes_html html content - * + * * @access private * * @see _getVerticalTable() @@ -3408,9 +3424,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 +3901,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 +3937,7 @@ class PMA_DisplayResults * * @return array 3 element array: $sort_expression, * $sort_expression_nodirection, $sort_direction - * + * * @access private * * @see getTable() @@ -3969,10 +3985,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 +4028,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 +4039,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 +4063,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 +4107,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 +4219,7 @@ class PMA_DisplayResults * @param string $del_link the display element - 'del_link' * * @return string $links_html html content - * + * * @access private * * @see getTable() @@ -4490,25 +4508,27 @@ class PMA_DisplayResults * Verifies what to do with non-printable contents (binary or BLOB) * in Browse mode. * - * @param string $category BLOB|BINARY|GEOMETRY - * @param string $content the binary content - * @param string $transform_function transformation function - * @param string $transform_options transformation parameters - * @param string $default_function default transformation function - * @param object $meta the meta-information about this field - * @param array $url_params parameters that should go to the - * download link + * @param string $category BLOB|BINARY|GEOMETRY + * @param string $content the binary content + * @param string $transformation_plugin transformation plugin. + * Can also be the default function: + * PMA_mimeDefaultFunction + * @param string $transform_options transformation parameters + * @param string $default_function default transformation function + * @param object $meta the meta-information about the field + * @param array $url_params parameters that should go to the + * download link * * @return mixed string or float - * + * * @access private - * + * * @see _getDataCellForBlobColumns(), _getDataCellForGeometryColumns(), * _getDataCellForNonNumericAndNonBlobColumns(), * _getSortedColumnMessage() */ private function _handleNonPrintableContents( - $category, $content, $transform_function, $transform_options, + $category, $content, $transformation_plugin, $transform_options, $default_function, $meta, $url_params = array() ) { @@ -4529,14 +4549,18 @@ class PMA_DisplayResults $result .= ']'; - if (strpos($transform_function, 'octetstream')) { + if (strpos($transformation_plugin, 'Octetstream')) { $result = $content; } if ($size > 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); @@ -4565,39 +4589,41 @@ 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 cluase - * @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 cluase + * @param array $transform_options array of options for transformation + * @param bool $is_field_truncated whether the field is truncated * * @return string formatted data - * + * * @access private - * + * * @see _getDataCellForNumericColumns(), _getDataCellForGeometryColumns(), * _getDataCellForNonNumericAndNonBlobColumns(), - * + * */ 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 = '
'; @@ -4653,10 +4679,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 { @@ -4686,19 +4717,31 @@ 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 .= $transformation_plugin->applyTransformation( + $dispval, + array(), + $meta + ); } else { // otherwise display data in the cell - $result .= $transform_function($data, array(), $meta); + $result .= $transformation_plugin->applyTransformation( + $data, + array(), + $meta + ); } } @@ -4706,9 +4749,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 @@ -4754,9 +4802,9 @@ class PMA_DisplayResults * @param string $class css classes for the td element * * @return string the generated HTML - * + * * @access private - * + * * @see _getTableBody(), _getCheckboxAndLinks() */ private function _getCheckboxForMultiRowSubmissions( @@ -4803,9 +4851,9 @@ class PMA_DisplayResults * @param string $where_clause_html url encoded where cluase * * @return string the generated HTML - * + * * @access private - * + * * @see _getTableBody(), _getCheckboxAndLinks() */ private function _getEditLink( @@ -4843,9 +4891,9 @@ class PMA_DisplayResults * @param string $class css classes for the td element * * @return string the generated HTML - * + * * @access private - * + * * @see _getTableBody(), _getCheckboxAndLinks() */ private function _getCopyLink( @@ -4888,9 +4936,9 @@ class PMA_DisplayResults * @param string $class css classes for the td element * * @return string the generated HTML - * + * * @access private - * + * * @see _getTableBody(), _getCheckboxAndLinks() */ private function _getDeleteLink($del_url, $del_str, $js_conf, $class) @@ -4937,9 +4985,9 @@ class PMA_DisplayResults * @param string $js_conf text for the JS confirmation * * @return string the generated HTML - * + * * @access private - * + * * @see _getPlacedLinks() */ private function _getCheckboxAndLinks( @@ -4995,6 +5043,6 @@ class PMA_DisplayResults return $ret; } // end of the '_getCheckboxAndLinks()' function - + } ?> diff --git a/libraries/insert_edit.lib.php b/libraries/insert_edit.lib.php index 2c8148f762..bc2dd90351 100644 --- a/libraries/insert_edit.lib.php +++ b/libraries/insert_edit.lib.php @@ -97,7 +97,7 @@ function PMA_getWhereClauseArray($where_clause) * * @return array $where_clauses, $result, $rows */ -function PMA_analyzeWhereClauses(\ +function PMA_analyzeWhereClauses( $where_clause_array, $table, $db, $found_unique_key ) { $rows = array(); diff --git a/libraries/plugins/TransformationsPlugin.class.php b/libraries/plugins/TransformationsPlugin.class.php index a9bb5bd9a6..6f59c02896 100644 --- a/libraries/plugins/TransformationsPlugin.class.php +++ b/libraries/plugins/TransformationsPlugin.class.php @@ -23,6 +23,19 @@ require_once "TransformationsInterface.int.php"; abstract class TransformationsPlugin extends PluginObserver implements TransformationsInterface { + /** + * Does the actual work of each specific transformations plugin. + * + * @param array $options transformation options + * + * @todo implement + * @return void + */ + public function applyTransformationNoWrap($options = array()) + { + ; + } + /** * Does the actual work of each specific transformations plugin. * diff --git a/libraries/plugins/transformations/Application_Octetstream_Download.class.php b/libraries/plugins/transformations/Application_Octetstream_Download.class.php index e986631c6e..e88e34386f 100644 --- a/libraries/plugins/transformations/Application_Octetstream_Download.class.php +++ b/libraries/plugins/transformations/Application_Octetstream_Download.class.php @@ -19,22 +19,6 @@ require_once "abstract/DownloadTransformationsPlugin.class.php"; */ class Application_Octetstream_Download extends DownloadTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays a link to download the binary data of the column. You can' - . ' use the first option to specify the filename, or use the second' - . ' option as the name of a column which contains the filename. If' - . ' you use the second option, you need to set the first option to' - . ' the empty string.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Application_Octetstream_Hex.class.php b/libraries/plugins/transformations/Application_Octetstream_Hex.class.php index 121548374c..09c87ed74a 100644 --- a/libraries/plugins/transformations/Application_Octetstream_Hex.class.php +++ b/libraries/plugins/transformations/Application_Octetstream_Hex.class.php @@ -20,20 +20,6 @@ require_once "abstract/HexTransformationsPlugin.class.php"; */ class Application_Octetstream_Hex extends HexTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays hexadecimal representation of data. Optional first' - . ' parameter specifies how often space will be added (defaults' - . ' to 2 nibbles).' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Image_JPEG_Inline.class.php b/libraries/plugins/transformations/Image_JPEG_Inline.class.php index 41d481da01..5db7fe9f1e 100644 --- a/libraries/plugins/transformations/Image_JPEG_Inline.class.php +++ b/libraries/plugins/transformations/Image_JPEG_Inline.class.php @@ -20,19 +20,6 @@ require_once "abstract/InlineTransformationsPlugin.class.php"; */ class Image_JPEG_Inline extends InlineTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays a clickable thumbnail. The options are the maximum width' - . ' and height in pixels. The original aspect ratio is preserved.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Image_JPEG_Link.class.php b/libraries/plugins/transformations/Image_JPEG_Link.class.php index 0f5258072e..1f9577667f 100644 --- a/libraries/plugins/transformations/Image_JPEG_Link.class.php +++ b/libraries/plugins/transformations/Image_JPEG_Link.class.php @@ -11,27 +11,15 @@ if (! defined('PHPMYADMIN')) { } /* Get the link transformations interface */ -require_once "abstract/LinkTransformationsPlugin.class.php"; +require_once "abstract/ImageLinkTransformationsPlugin.class.php"; /** * Handles the link transformation for image jpeg * * @package PhpMyAdmin */ -class Image_JPEG_Link extends LinkTransformationsPlugin + class Image_JPEG_Link extends ImageLinkTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays a link to download this image.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Image_PNG_Inline.class.php b/libraries/plugins/transformations/Image_PNG_Inline.class.php index 6a722d305c..af60e315ee 100644 --- a/libraries/plugins/transformations/Image_PNG_Inline.class.php +++ b/libraries/plugins/transformations/Image_PNG_Inline.class.php @@ -20,19 +20,6 @@ require_once "abstract/InlineTransformationsPlugin.class.php"; */ class Image_PNG_Inline extends InlineTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays a clickable thumbnail. The options are the maximum width' - . ' and height in pixels. The original aspect ratio is preserved.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Append.class.php b/libraries/plugins/transformations/Text_Plain_Append.class.php index b2f914ec48..50072baa43 100644 --- a/libraries/plugins/transformations/Text_Plain_Append.class.php +++ b/libraries/plugins/transformations/Text_Plain_Append.class.php @@ -21,19 +21,6 @@ require_once "abstract/AppendTransformationsPlugin.class.php"; */ class Text_Plain_Append extends AppendTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Appends text to a string. The only option is the text to be appended' - . ' (enclosed in single quotes, default empty string).' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Dateformat.class.php b/libraries/plugins/transformations/Text_Plain_Dateformat.class.php index d76c612183..3d2c912b15 100644 --- a/libraries/plugins/transformations/Text_Plain_Dateformat.class.php +++ b/libraries/plugins/transformations/Text_Plain_Dateformat.class.php @@ -20,26 +20,6 @@ require_once "abstract/DateFormatTransformationsPlugin.class.php"; */ class Text_Plain_Dateformat extends DateFormatTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays a TIME, TIMESTAMP, DATETIME or numeric unix timestamp' - . ' column as formatted date. The first option is the offset (in' - . ' hours) which will be added to the timestamp (Default: 0). Use' - . ' second option to specify a different date/time format string.' - . ' Third option determines whether you want to see local date or' - . ' UTC one (use "local" or "utc" strings) for that. According to' - . ' that, date format has different value - for "local" see the' - . ' documentation for PHP\'s strftime() function and for "utc" it' - . ' is done using gmdate() function.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_External.class.php b/libraries/plugins/transformations/Text_Plain_External.class.php index b7155485d5..2fbc3ce4d0 100644 --- a/libraries/plugins/transformations/Text_Plain_External.class.php +++ b/libraries/plugins/transformations/Text_Plain_External.class.php @@ -20,29 +20,6 @@ require_once "abstract/ExternalTransformationsPlugin.class.php"; */ class Text_Plain_External extends ExternalTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'LINUX ONLY: Launches an external application and feeds it the column' - . ' data via standard input. Returns the standard output of the' - . ' application. The default is Tidy, to pretty-print HTML code.' - . ' For security reasons, you have to manually edit the file' - . ' libraries/plugins/transformations/TransformationTextPlainExternal' - . '.class.php and list the tools you want to make available.' - . ' The first option is then the number of the program you want to' - . ' use and the second option is the parameters for the program.' - . ' The third option, if set to 1, will convert the output using' - . ' htmlspecialchars() (Default 1). The fourth option, if set to 1,' - . ' will prevent wrapping and ensure that the output appears all on' - . ' one line (Default 1).' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Formatted.class.php b/libraries/plugins/transformations/Text_Plain_Formatted.class.php index 2865323719..714d808890 100644 --- a/libraries/plugins/transformations/Text_Plain_Formatted.class.php +++ b/libraries/plugins/transformations/Text_Plain_Formatted.class.php @@ -20,20 +20,6 @@ require_once "abstract/FormattedTransformationsPlugin.class.php"; */ class Text_Plain_Formatted extends FormattedTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays the contents of the column as-is, without running it' - . ' through htmlspecialchars(). That is, the column is assumed' - . ' to contain valid HTML.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Imagelink.class.php b/libraries/plugins/transformations/Text_Plain_Imagelink.class.php index 3d23824900..d9e0110afb 100644 --- a/libraries/plugins/transformations/Text_Plain_Imagelink.class.php +++ b/libraries/plugins/transformations/Text_Plain_Imagelink.class.php @@ -11,29 +11,15 @@ if (! defined('PHPMYADMIN')) { } /* Get the image link transformations interface */ -require_once "abstract/ImageLinkTransformationsPlugin.class.php"; +require_once "abstract/TextImageLinkTransformationsPlugin.class.php"; /** * Handles the image link transformation for text plain * * @package PhpMyAdmin */ -class Text_Plain_Imagelink extends ImageLinkTransformationsPlugin +class Text_Plain_Imagelink extends TextImageLinkTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays an image and a link; the column contains the filename. The' - . ' first option is a URL prefix like "http://www.example.com/". The' - . ' second and third options are the width and the height in pixels.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Link.class.php b/libraries/plugins/transformations/Text_Plain_Link.class.php index 1ed058bb34..da93d3c00a 100644 --- a/libraries/plugins/transformations/Text_Plain_Link.class.php +++ b/libraries/plugins/transformations/Text_Plain_Link.class.php @@ -11,29 +11,15 @@ if (! defined('PHPMYADMIN')) { } /* Get the link transformations interface */ -require_once "abstract/LinkTransformationsPlugin.class.php"; +require_once "abstract/TextLinkTransformationsPlugin.class.php"; /** * Handles the link transformation for text plain * * @package PhpMyAdmin */ -class Text_Plain_Link extends LinkTransformationsPlugin +class Text_Plain_Link extends TextLinkTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays a link; the column contains the filename. The first option' - . ' is a URL prefix like "http://www.example.com/". The second option' - . ' is a title for the link.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php b/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php index 32373ad7f3..202b0c73bf 100644 --- a/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php +++ b/libraries/plugins/transformations/Text_Plain_Longtoipv4.class.php @@ -20,19 +20,6 @@ require_once "abstract/LongToIPv4TransformationsPlugin.class.php"; */ class Text_Plain_Longtoipv4 extends LongToIPv4TransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Converts an (IPv4) Internet network address into a string in' - . ' Internet standard dotted format.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Sql.class.php b/libraries/plugins/transformations/Text_Plain_Sql.class.php index 816069faab..3b892b2827 100644 --- a/libraries/plugins/transformations/Text_Plain_Sql.class.php +++ b/libraries/plugins/transformations/Text_Plain_Sql.class.php @@ -20,18 +20,6 @@ require_once "abstract/SQLTransformationsPlugin.class.php"; */ class Text_Plain_Sql extends SQLTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Formats text as SQL query with syntax highlighting.' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/Text_Plain_Substring.class.php b/libraries/plugins/transformations/Text_Plain_Substring.class.php index 187e5fdbb8..3f28c987e4 100644 --- a/libraries/plugins/transformations/Text_Plain_Substring.class.php +++ b/libraries/plugins/transformations/Text_Plain_Substring.class.php @@ -20,22 +20,6 @@ require_once "abstract/SubstringTransformationsPlugin.class.php"; */ class Text_Plain_Substring extends SubstringTransformationsPlugin { - /** - * Gets the transformation description of the specific plugin - * - * @return string - */ - public static function getInfo() - { - return __( - 'Displays a part of a string. The first option is the number of' - . ' characters to skip from the beginning of the string (Default 0).' - . ' The second option is the number of characters to return (Default:' - . ' until end of string). The third option is the string to append' - . ' and/or prepend when truncation occurs (Default: "...").' - ); - } - /** * Gets the plugin`s MIME type * diff --git a/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php index 9b811a057d..bd0661f805 100644 --- a/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/AppendTransformationsPlugin.class.php @@ -20,6 +20,19 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class AppendTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Appends text to a string. The only option is the text to be appended' + . ' (enclosed in single quotes, default empty string).' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +40,17 @@ abstract class AppendTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + if (! isset($options[0]) || $options[0] == '') { + $options[0] = ''; + } + //just append the option to the original text + $newtext = $buffer . htmlspecialchars($options[0]); + + return $newtext; } /** diff --git a/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php index bd4d82d67c..03b96657c6 100644 --- a/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/DateFormatTransformationsPlugin.class.php @@ -20,6 +20,26 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class DateFormatTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Displays a TIME, TIMESTAMP, DATETIME or numeric unix timestamp' + . ' column as formatted date. The first option is the offset (in' + . ' hours) which will be added to the timestamp (Default: 0). Use' + . ' second option to specify a different date/time format string.' + . ' Third option determines whether you want to see local date or' + . ' UTC one (use "local" or "utc" strings) for that. According to' + . ' that, date format has different value - for "local" see the' + . ' documentation for PHP\'s strftime() function and for "utc" it' + . ' is done using gmdate() function.' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +47,100 @@ abstract class DateFormatTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + // possibly use a global transform and feed it with special options + + // further operations on $buffer using the $options[] array. + if (empty($options[0])) { + $options[0] = 0; + } + + if (empty($options[2])) { + $options[2] = 'local'; + } else { + $options[2] = strtolower($options[2]); + } + + if (empty($options[1])) { + if ($options[2] == 'local') { + $options[1] = __('%B %d, %Y at %I:%M %p'); + } else { + $options[1] = 'Y-m-d H:i:s'; + } + } + + $timestamp = -1; + + // INT columns will be treated as UNIX timestamps + // and need to be detected before the verification for + // MySQL TIMESTAMP + if ($meta->type == 'int') { + $timestamp = $buffer; + + // Detect TIMESTAMP(6 | 8 | 10 | 12 | 14) + // TIMESTAMP (2 | 4) not supported here. + // (Note: prior to MySQL 4.1, TIMESTAMP has a display size + // for example TIMESTAMP(8) means YYYYMMDD) + } else if (preg_match('/^(\d{2}){3,7}$/', $buffer)) { + + if (strlen($buffer) == 14 || strlen($buffer) == 8) { + $offset = 4; + } else { + $offset = 2; + } + + $d = array(); + $d['year'] = substr($buffer, 0, $offset); + $d['month'] = substr($buffer, $offset, 2); + $d['day'] = substr($buffer, $offset + 2, 2); + $d['hour'] = substr($buffer, $offset + 4, 2); + $d['minute'] = substr($buffer, $offset + 6, 2); + $d['second'] = substr($buffer, $offset + 8, 2); + + if (checkdate($d['month'], $d['day'], $d['year'])) { + $timestamp = mktime( + $d['hour'], + $d['minute'], + $d['second'], + $d['month'], + $d['day'], + $d['year'] + ); + } + // If all fails, assume one of the dozens of valid strtime() syntaxes + // (http://www.gnu.org/manual/tar-1.12/html_chapter/tar_7.html) + } else { + if (preg_match('/^[0-9]\d{1,9}$/', $buffer)) { + $timestamp = (int)$buffer; + } else { + $timestamp = strtotime($buffer); + } + } + + // If all above failed, maybe it's a Unix timestamp already? + if ($timestamp < 0 && preg_match('/^[1-9]\d{1,9}$/', $buffer)) { + $timestamp = $buffer; + } + + // Reformat a valid timestamp + if ($timestamp >= 0) { + $timestamp -= $options[0] * 60 * 60; + $source = $buffer; + if ($options[2] == 'local') { + $text = PMA_localisedDate($timestamp, $options[1]); + } elseif ($options[2] == 'utc') { + $text = gmdate($options[1], $timestamp); + } else { + $text = 'INVALID DATE TYPE'; + } + $buffer = '' . $text . ''; + } + + return $buffer; } /** diff --git a/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php index 77bd39ecda..3f081c3895 100644 --- a/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/DownloadTransformationsPlugin.class.php @@ -20,6 +20,22 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class DownloadTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Displays a link to download the binary data of the column. You can' + . ' use the first option to specify the filename, or use the second' + . ' option as the name of a column which contains the filename. If' + . ' you use the second option, you need to set the first option to' + . ' the empty string.' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +43,39 @@ abstract class DownloadTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + global $row, $fields_meta; + + if (isset($options[0]) && !empty($options[0])) { + $cn = $options[0]; // filename + } else { + if (isset($options[1]) && !empty($options[1])) { + foreach ($fields_meta as $key => $val) { + if ($val->name == $options[1]) { + $pos = $key; + break; + } + } + if (isset($pos)) { + $cn = $row[$pos]; + } + } + if (empty($cn)) { + $cn = 'binary_file.dat'; + } + } + + return sprintf( + '%s', + $options['wrapper_link'], + urlencode($cn), + htmlspecialchars($cn), + htmlspecialchars($cn) + ); } /** diff --git a/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php index 2a7c495584..d2ceea5885 100644 --- a/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php @@ -20,6 +20,49 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class ExternalTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'LINUX ONLY: Launches an external application and feeds it the column' + . ' data via standard input. Returns the standard output of the' + . ' application. The default is Tidy, to pretty-print HTML code.' + . ' For security reasons, you have to manually edit the file' + . ' libraries/plugins/transformations/Text_Plain_External' + . '.class.php and list the tools you want to make available.' + . ' The first option is then the number of the program you want to' + . ' use and the second option is the parameters for the program.' + . ' The third option, if set to 1, will convert the output using' + . ' htmlspecialchars() (Default 1). The fourth option, if set to 1,' + . ' will prevent wrapping and ensure that the output appears all on' + . ' one line (Default 1).' + ); + } + + /** + * Enables no-wrapping + * + * @param array $options transformation options + * + * @return bool + */ + public function applyTransformationNoWrap($options = array()) + { + if (! isset($options[3]) || $options[3] == '') { + $nowrap = true; + } elseif ($options[3] == '1' || $options[3] == 1) { + $nowrap = true; + } else { + $nowrap = false; + } + + return $nowrap; + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +70,84 @@ abstract class ExternalTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + // possibly use a global transform and feed it with special options + + // further operations on $buffer using the $options[] array. + + $allowed_programs = array(); + + // + // WARNING: + // + // It's up to administrator to allow anything here. Note that users may + // specify any parameters, so when programs allow output redirection or + // any other possibly dangerous operations, you should write wrapper + // script that will publish only functions you really want. + // + // Add here program definitions like (note that these are NOT safe + // programs): + // + //$allowed_programs[0] = '/usr/local/bin/tidy'; + //$allowed_programs[1] = '/usr/local/bin/validate'; + + // no-op when no allowed programs + if (count($allowed_programs) == 0) { + return $buffer; + } + + if (! isset($options[0]) + || $options[0] == '' + || ! isset($allowed_programs[$options[0]]) + ) { + $program = $allowed_programs[0]; + } else { + $program = $allowed_programs[$options[0]]; + } + + if (!isset($options[1]) || $options[1] == '') { + $poptions = '-f /dev/null -i -wrap -q'; + } else { + $poptions = $options[1]; + } + + if (!isset($options[2]) || $options[2] == '') { + $options[2] = 1; + } + + if (!isset($options[3]) || $options[3] == '') { + $options[3] = 1; + } + + // needs PHP >= 4.3.0 + $newstring = ''; + $descriptorspec = array( + 0 => array("pipe", "r"), + 1 => array("pipe", "w") + ); + $process = proc_open($program . ' ' . $poptions, $descriptorspec, $pipes); + if (is_resource($process)) { + fwrite($pipes[0], $buffer); + fclose($pipes[0]); + + while (!feof($pipes[1])) { + $newstring .= fgets($pipes[1], 1024); + } + fclose($pipes[1]); + // we don't currently use the return value + proc_close($process); + } + + if ($options[2] == 1 || $options[2] == '2') { + $retstring = htmlspecialchars($newstring); + } else { + $retstring = $newstring; + } + + return $retstring; } /** diff --git a/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php index e089fac77a..0e93835380 100644 --- a/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/FormattedTransformationsPlugin.class.php @@ -20,6 +20,20 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class FormattedTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Displays the contents of the column as-is, without running it' + . ' through htmlspecialchars(). That is, the column is assumed' + . ' to contain valid HTML.' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +41,11 @@ abstract class FormattedTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + return $buffer; } /** diff --git a/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php index 76ff6741ae..9bb14475ad 100644 --- a/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/HexTransformationsPlugin.class.php @@ -20,6 +20,20 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class HexTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Displays hexadecimal representation of data. Optional first' + . ' parameter specifies how often space will be added (defaults' + . ' to 2 nibbles).' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +41,22 @@ abstract class HexTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + // possibly use a global transform and feed it with special options + if (!isset($options[0])) { + $options[0] = 2; + } else { + $options[0] = (int)$options[0]; + } + + if ($options[0] < 1) { + return bin2hex($buffer); + } else { + return chunk_split(bin2hex($buffer), $options[0], ' '); + } } /** diff --git a/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php index c98568a579..99e28e4698 100644 --- a/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/ImageLinkTransformationsPlugin.class.php @@ -1,10 +1,10 @@ '[BLOB]' + ); + $buffer = PMA_transformation_global_html_replace( + $buffer, + $transform_options + ); + + return $buffer; } /** @@ -61,7 +81,7 @@ abstract class ImageLinkTransformationsPlugin extends TransformationsPlugin */ public static function getName() { - return "Image Link"; + return "Link"; } } ?> \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php index 16683b92c4..0b7452911b 100644 --- a/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/InlineTransformationsPlugin.class.php @@ -20,6 +20,19 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class InlineTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Displays a clickable thumbnail. The options are the maximum width' + . ' and height in pixels. The original aspect ratio is preserved.' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +40,33 @@ abstract class InlineTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + if (PMA_IS_GD2) { + $transform_options = array ( + 'string' => '[__BUFFER__]' + ); + } else { + $transform_options = array ( + 'string' => '[__BUFFER__]' + ); + } + $buffer = PMA_transformation_global_html_replace( + $buffer, + $transform_options + ); + + return $buffer; } /** diff --git a/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php index 53f1180f59..e7b2ddb33d 100644 --- a/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/LongToIPv4TransformationsPlugin.class.php @@ -20,6 +20,19 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class LongToIPv4TransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Converts an (IPv4) Internet network address into a string in' + . ' Internet standard dotted format.' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +40,15 @@ abstract class LongToIPv4TransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + if ($buffer < 0 || $buffer > 4294967295) { + return $buffer; + } + + return long2ip($buffer); } /** diff --git a/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php index 32cd9b889d..c6d8e6513f 100644 --- a/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/SQLTransformationsPlugin.class.php @@ -20,6 +20,18 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class SQLTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Formats text as SQL query with syntax highlighting.' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +39,14 @@ abstract class SQLTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + $result = PMA_SQP_formatHtml(PMA_SQP_parse($buffer)); + // Need to clear error state not to break subsequent queries display. + PMA_SQP_resetError(); + return $result; } /** diff --git a/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php index de0e794989..03e7639651 100644 --- a/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/SubstringTransformationsPlugin.class.php @@ -20,6 +20,22 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; */ abstract class SubstringTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Displays a part of a string. The first option is the number of' + . ' characters to skip from the beginning of the string (Default 0).' + . ' The second option is the number of characters to return (Default:' + . ' until end of string). The third option is the string to append' + . ' and/or prepend when truncation occurs (Default: "...").' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +43,45 @@ abstract class SubstringTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + // possibly use a global transform and feed it with special options + + // further operations on $buffer using the $options[] array. + if (!isset($options[0]) || $options[0] == '') { + $options[0] = 0; + } + + if (!isset($options[1]) || $options[1] == '') { + $options[1] = 'all'; + } + + if (!isset($options[2]) || $options[2] == '') { + $options[2] = '...'; + } + + $newtext = ''; + if ($options[1] != 'all') { + $newtext = PMA_substr($buffer, $options[0], $options[1]); + } else { + $newtext = PMA_substr($buffer, $options[0]); + } + + $length = strlen($newtext); + $baselength = strlen($buffer); + if ($length != $baselength) { + if ($options[0] != 0) { + $newtext = $options[2] . $newtext; + } + + if (($length + $options[0]) != $baselength) { + $newtext .= $options[2]; + } + } + + return $newtext; } /** diff --git a/libraries/plugins/transformations/abstract/TextImageLinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/TextImageLinkTransformationsPlugin.class.php new file mode 100644 index 0000000000..772e412cbc --- /dev/null +++ b/libraries/plugins/transformations/abstract/TextImageLinkTransformationsPlugin.class.php @@ -0,0 +1,94 @@ + '' + . $buffer . '' + ); + + $buffer = PMA_transformation_global_html_replace( + $buffer, + $transform_options + ); + + return $buffer; + } + + /** + * 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. + * + * @todo implement + * @return void + */ + public function update (SplSubject $subject) + { + ; + } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Gets the transformation name of the specific plugin + * + * @return string + */ + public static function getName() + { + return "Image Link"; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/TextLinkTransformationsPlugin.class.php similarity index 57% rename from libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php rename to libraries/plugins/transformations/abstract/TextLinkTransformationsPlugin.class.php index d655ea2b17..43bc65792d 100644 --- a/libraries/plugins/transformations/abstract/LinkTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/TextLinkTransformationsPlugin.class.php @@ -18,8 +18,22 @@ require_once "libraries/plugins/TransformationsPlugin.class.php"; * * @package PhpMyAdmin */ -abstract class LinkTransformationsPlugin extends TransformationsPlugin +abstract class TextLinkTransformationsPlugin extends TransformationsPlugin { + /** + * Gets the transformation description of the specific plugin + * + * @return string + */ + public static function getInfo() + { + return __( + 'Displays a link; the column contains the filename. The first option' + . ' is a URL prefix like "http://www.example.com/". The second option' + . ' is a title for the link.' + ); + } + /** * Does the actual work of each specific transformations plugin. * @@ -27,12 +41,23 @@ abstract class LinkTransformationsPlugin extends TransformationsPlugin * @param array $options transformation options * @param string $meta meta information * - * @todo implement * @return void */ - public function applyTransformation($buffer, $options, $meta) + public function applyTransformation($buffer, $options = array(), $meta = '') { - ; + $transform_options = array ( + 'string' => '' . (isset($options[1]) ? $options[1] : $buffer) . '' + ); + + $buffer = PMA_transformation_global_html_replace( + $buffer, + $transform_options + ); + + return $buffer; } /** diff --git a/tbl_replace.php b/tbl_replace.php index ef6c39e4c3..38d737a2f4 100644 --- a/tbl_replace.php +++ b/tbl_replace.php @@ -371,7 +371,9 @@ if ($GLOBALS['is_ajax_request'] == true) { } // end of loop for each relation cell } - if (isset($_REQUEST['do_transformations']) && $_REQUEST['do_transformations'] == true ) { + if (isset($_REQUEST['do_transformations']) + && $_REQUEST['do_transformations'] == true + ) { include_once 'libraries/transformations.lib.php'; //if some posted fields need to be transformed, generate them here. $mime_map = PMA_getMIME($db, $table); @@ -384,9 +386,27 @@ if ($GLOBALS['is_ajax_request'] == true) { parse_str($_REQUEST['transform_fields_list'], $edited_values); foreach ($mime_map as $transformation) { - $include_file = PMA_securePath($transformation['transformation']); $column_name = $transformation['column_name']; + $include_file = $transformation['transformation']; + $include_file = PMA_securePath( + str_replace( + ".inc.php", + ".class.php", + str_replace( + "__", + "_", + $include_file + ) + ) + ); + $file_parts = explode("_", $include_file); + $include_file = strtoupper($file_parts[0]) . "_" + . strtoupper($file_parts[1]) . "_" + . strtoupper($file_parts[2]); + + $include_file = 'libraries/transformations/plugins/' . $include_file; + foreach ($edited_values as $cell_index => $curr_cell_edited_values) { if (isset($curr_cell_edited_values[$column_name])) { $column_data = $curr_cell_edited_values[$column_name]; @@ -398,21 +418,24 @@ if ($GLOBALS['is_ajax_request'] == true) { 'transform_key' => $column_name, ); - if (file_exists('libraries/transformations/' . $include_file)) { - $transformfunction_name = str_replace('.inc.php', '', $transformation['transformation']); + if (file_exists($include_file)) { + include_once $include_file; + $class_name = str_replace('.class.php', '', $file); + $transformation_plugin = new $class_name; - include_once 'libraries/transformations/' . $include_file; - - if (function_exists('PMA_transformation_' . $transformfunction_name)) { - $transform_function = 'PMA_transformation_' . $transformfunction_name; - $transform_options = PMA_transformation_getOptions( - isset($transformation['transformation_options']) ? $transformation['transformation_options'] : '' - ); - $transform_options['wrapper_link'] = PMA_generate_common_url($_url_params); - } + $transform_options = PMA_transformation_getOptions( + isset($transformation['transformation_options']) + ? $transformation['transformation_options'] : '' + ); + $transform_options['wrapper_link'] = + PMA_generate_common_url($_url_params); } - $extra_data['transformations'][$cell_index] = $transform_function($column_data, $transform_options); + $extra_data['transformations'][$cell_index] = + $transformation_plugin->applyTransformation( + $column_data, + $transform_options + ); } } // end of loop for each transformation cell } // end of loop for each $mime_map From b0248d0e4d786aa5f943d3464e0b4e2180534a9d Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Wed, 20 Jun 2012 20:24:07 +0300 Subject: [PATCH 40/55] oop: fix transformations bug --- libraries/DisplayResults.class.php | 30 +++--------------------------- tbl_replace.php | 18 +----------------- 2 files changed, 4 insertions(+), 44 deletions(-) diff --git a/libraries/DisplayResults.class.php b/libraries/DisplayResults.class.php index 003d9e79a8..d48af75380 100644 --- a/libraries/DisplayResults.class.php +++ b/libraries/DisplayResults.class.php @@ -2167,23 +2167,7 @@ class PMA_DisplayResults && !empty($GLOBALS['mime_map'][$meta->name]['transformation']) ) { $file = $GLOBALS['mime_map'][$meta->name]['transformation']; - $file = PMA_securePath( - str_replace( - ".inc.php", - ".class.php", - str_replace( - "__", - "_", - $file - ) - ) - ); - $file_parts = explode("_", $file); - $file = strtoupper($file_parts[0]) . "_" - . strtoupper($file_parts[1]) . "_" - . strtoupper($file_parts[2]); - - $include_file = 'libraries/transformations/plugins/' . $file; + $include_file = 'libraries/plugins/transformations/' . $file; if (file_exists($include_file)) { include_once $include_file; $class_name = str_replace('.class.php', '', $file); @@ -4730,18 +4714,10 @@ class PMA_DisplayResults 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 .= $transformation_plugin->applyTransformation( - $dispval, - array(), - $meta - ); + $result .= $default_function($dispval); } else { // otherwise display data in the cell - $result .= $transformation_plugin->applyTransformation( - $data, - array(), - $meta - ); + $result .= $default_function($data); } } diff --git a/tbl_replace.php b/tbl_replace.php index d59a8163b0..b0e47d55ad 100644 --- a/tbl_replace.php +++ b/tbl_replace.php @@ -414,23 +414,7 @@ if ($GLOBALS['is_ajax_request'] == true) { $column_name = $transformation['column_name']; $include_file = $transformation['transformation']; - $include_file = PMA_securePath( - str_replace( - ".inc.php", - ".class.php", - str_replace( - "__", - "_", - $include_file - ) - ) - ); - $file_parts = explode("_", $include_file); - $include_file = strtoupper($file_parts[0]) . "_" - . strtoupper($file_parts[1]) . "_" - . strtoupper($file_parts[2]); - - $include_file = 'libraries/transformations/plugins/' . $include_file; + $include_file = 'libraries/plugins/transformations/' . $include_file; foreach ($edited_values as $cell_index => $curr_cell_edited_values) { if (isset($curr_cell_edited_values[$column_name])) { From 6efd5422f7e37375063a16a92518b940712922ea Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Wed, 20 Jun 2012 20:26:39 +0300 Subject: [PATCH 41/55] oop: transformations phpcs errors --- .../transformations/Image_JPEG_Link.class.php | 2 +- .../ExternalTransformationsPlugin.class.php | 2 +- libraries/tbl_properties.inc.php | 17 +++++++++++++---- tbl_alter.php | 2 +- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/libraries/plugins/transformations/Image_JPEG_Link.class.php b/libraries/plugins/transformations/Image_JPEG_Link.class.php index 1f9577667f..e2f018fd36 100644 --- a/libraries/plugins/transformations/Image_JPEG_Link.class.php +++ b/libraries/plugins/transformations/Image_JPEG_Link.class.php @@ -18,7 +18,7 @@ require_once "abstract/ImageLinkTransformationsPlugin.class.php"; * * @package PhpMyAdmin */ - class Image_JPEG_Link extends ImageLinkTransformationsPlugin +class Image_JPEG_Link extends ImageLinkTransformationsPlugin { /** * Gets the plugin`s MIME type diff --git a/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php index d2ceea5885..807ee36a6c 100644 --- a/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php +++ b/libraries/plugins/transformations/abstract/ExternalTransformationsPlugin.class.php @@ -46,7 +46,7 @@ abstract class ExternalTransformationsPlugin extends TransformationsPlugin /** * Enables no-wrapping * - * @param array $options transformation options + * @param array $options transformation options * * @return bool */ diff --git a/libraries/tbl_properties.inc.php b/libraries/tbl_properties.inc.php index dadf08f4c5..dc6d352a9b 100644 --- a/libraries/tbl_properties.inc.php +++ b/libraries/tbl_properties.inc.php @@ -95,7 +95,7 @@ $header_cells[] = __('Null'); // editable. However, for this to work, tbl_alter must be modified to use the // key fields, as tbl_addfield does. -if (!$is_backup) { +if (! $is_backup) { $header_cells[] = __('Index'); } @@ -127,9 +127,12 @@ if ($cfgRelation['mimework'] && $cfg['BrowseMIME']) { $hint = '
' . sprintf( - __('For a list of available transformation options and their MIME type transformations, click on %stransformation descriptions%s'), + __('For a list of available transformation options and their MIME' + . ' type transformations, click on %stransformation descriptions%s' + ), '', + . PMA_generate_common_url($db, $table) + . '" target="_blank">', '' ); @@ -137,7 +140,13 @@ if ($cfgRelation['mimework'] && $cfg['BrowseMIME']) { $header_cells[] = __('MIME type'); $header_cells[] = __('Browser transformation'); $header_cells[] = __('Transformation options') - . PMA_showHint(__('Please enter the values for transformation options using this format: \'a\', 100, b,\'c\'...
If you ever need to put a backslash ("\") or a single quote ("\'") amongst those values, precede it with a backslash (for example \'\\\\xyz\' or \'a\\\'b\').') . $hint); + . PMA_showHint( + __('Please enter the values for transformation options using this' + . ' format: \'a\', 100, b,\'c\'...
If you ever need to put' + . ' a backslash ("\") or a single quote ("\'") amongst those' + . ' values, precede it with a backslash (for example \'\\\\xyz\'' + . ' or \'a\\\'b\').' + ) . $hint); } // workaround for field_fulltext, because its submitted indizes contain diff --git a/tbl_alter.php b/tbl_alter.php index b7e1d74b91..b29e54e9b8 100644 --- a/tbl_alter.php +++ b/tbl_alter.php @@ -221,7 +221,7 @@ if (isset($_REQUEST['do_save_data'])) { */ include_once 'libraries/transformations.lib.php'; - // updaet field names in relation + // update field names in relation if (isset($_REQUEST['field_orig']) && is_array($_REQUEST['field_orig'])) { foreach ($_REQUEST['field_orig'] as $fieldindex => $fieldcontent) { if ($_REQUEST['field_name'][$fieldindex] != $fieldcontent) { From aad914f7b8dfc0d95b49dff54ee87a4f479768ee Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 09:22:37 +0300 Subject: [PATCH 42/55] oop: AuthenticationConfig --- .../auth/AuthenticationConfig.class.php | 85 +++++++++++++++++-- 1 file changed, 78 insertions(+), 7 deletions(-) diff --git a/libraries/plugins/auth/AuthenticationConfig.class.php b/libraries/plugins/auth/AuthenticationConfig.class.php index d9837db1eb..dbe7f7cb48 100644 --- a/libraries/plugins/auth/AuthenticationConfig.class.php +++ b/libraries/plugins/auth/AuthenticationConfig.class.php @@ -21,39 +21,110 @@ require_once "libraries/plugins/AuthenticationPlugin.class.php"; class AuthenticationConfig extends AuthenticationPlugin { /** + * Displays authentication form * - * - * @return void + * @return boolean always true */ public function auth() { + return true; } /** + * Gets advanced authentication settings * - * - * @return void + * @return boolean always true */ public function authCheck() { + return true; } /** + * Set the user and password after last checkings if required * - * - * @return void + * @return boolean always true */ public function authSetUser() { + return true; } /** + * User is not allowed to login to MySQL -> authentication failed * + * @global string the MySQL error message PHP returns + * @global string the connection type (persistent or not) + * @global string the MySQL server port to use + * @global string the MySQL socket port to use + * @global array the current server settings + * @global string the font face to use in case of failure + * @global string the default font size to use in case of failure + * @global string the big font size to use in case of failure + * @global boolean tell the "PMA_mysqlDie()" function headers have been + * sent * - * @return void + * @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_select_server(true, true); + echo '
' . "\n"; + exit; + return true; } /** From c91e80b6ca98aed4eaa8ab5fda006c3f4c54d890 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 10:10:05 +0300 Subject: [PATCH 43/55] oop: AuthenticationCookie --- libraries/blowfish.php | 54 -- .../auth/AuthenticationCookie.class.php | 616 +++++++++++++++++- .../HordeCipherBlowfishOperations.class.php | 67 ++ 3 files changed, 675 insertions(+), 62 deletions(-) create mode 100644 libraries/plugins/auth/HordeCipherBlowfishOperations.class.php 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/plugins/auth/AuthenticationCookie.class.php b/libraries/plugins/auth/AuthenticationCookie.class.php index 2733135bea..9c15c77ca9 100644 --- a/libraries/plugins/auth/AuthenticationCookie.class.php +++ b/libraries/plugins/auth/AuthenticationCookie.class.php @@ -13,6 +13,19 @@ if (! defined('PHPMYADMIN')) { /* Get the authentication interface */ require_once "libraries/plugins/AuthenticationPlugin.class.php"; +/** + * Remember where to redirect the user + * in case of an expired session. + */ +if (! empty($_REQUEST['target'])) { + $GLOBALS['target'] = $_REQUEST['target']; +} + +/** + * Swekey authentication functions. + */ +require './libraries/plugins/auth/swekey/swekey.auth.lib.php'; + /** * Handles the cookie authentication method * @@ -21,57 +34,618 @@ require_once "libraries/plugins/AuthenticationPlugin.class.php"; class AuthenticationCookie extends AuthenticationPlugin { /** + * Initialization vector * + * @var array + */ + private $_iv; + + /** + * Constructor + */ + function __construct() { + /** + * Initialization + * Store the initialization vector because it will be needed for + * further decryption. I don't think necessary to have one iv + * per server so I don't put the server number in the cookie name. + */ + if (empty($_COOKIE['pma_mcrypt_iv']) + || false === ($this->_setIv(base64_decode($_COOKIE['pma_mcrypt_iv'], true))) + ) { + srand((double) microtime() * 1000000); + $td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, ''); + if ($td === false) { + PMA_fatalError(__('Failed to use Blowfish from mcrypt!')); + } + $this->_setIv(mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND)); + $GLOBALS['PMA_Config']->setCookie('pma_mcrypt_iv', base64_encode($this->_getIv())); + } + } + + /** + * 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; + } + ?> + +
+ +

+ 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; } /** + * Set the user and password after last checkings if required * - * - * @return void + * @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'], + 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; + } /** + * 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() * * @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'); + + PMA_auth(); } /** + * Returns blowfish secret or generates one if needed. * - * - * @return void + * @return string */ - private function blowfishEncrypt() + public 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 void + * @return string the encrypted result */ - private function blowfishDecrypt() + public function blowfishEncrypt($data, $secret) { + 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, $this->_getIv()) + ); + } + + /** + * Decryption using blowfish algorithm (mcrypt) + * + * @param string $encdata encrypted data + * @param string $secret the secret + * + * @return string original data + */ + public function blowfishDecrypt($encdata, $secret) + { + 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, + $this->_getIv() + ); + return trim($decrypted); } /** @@ -86,4 +660,30 @@ class AuthenticationCookie extends AuthenticationPlugin public function update (SplSubject $subject) { } + + + /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ + + + /** + * Get the initialization vector + * + * @return array + */ + private function _getIv() + { + return $this->_iv; + } + + /** + * Set the initialization vector + * + * @param array $iv the initialization vector + * + * @return void + */ + private function _setIv($iv) + { + $this->_iv = $iv; + } } \ 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..8b6447008d --- /dev/null +++ b/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php @@ -0,0 +1,67 @@ + 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); + } +} +?> From 6d1f1132dae70360f16e1d04b9dd2ca8d181192e Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 10:16:15 +0300 Subject: [PATCH 44/55] oop: AuthenticationHTTP --- .../plugins/auth/AuthenticationHTTP.class.php | 192 +++++++++++++++++- 1 file changed, 184 insertions(+), 8 deletions(-) diff --git a/libraries/plugins/auth/AuthenticationHTTP.class.php b/libraries/plugins/auth/AuthenticationHTTP.class.php index 0c11b7457b..a52f0a580b 100644 --- a/libraries/plugins/auth/AuthenticationHTTP.class.php +++ b/libraries/plugins/auth/AuthenticationHTTP.class.php @@ -1,10 +1,11 @@ getFooter()->setMinimal(); + $header = $response->getHeader(); + $header->setTitle(__('Access denied')); + $header->disableMenu(); + + ?> +

+
+

+
+
+ + 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 void + * @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 void + * @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 void + * @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; + } } /** From 096a0a224f59da82942460be0367a17ba75abda8 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 10:22:24 +0300 Subject: [PATCH 45/55] oop: AuthenticationSignon --- .../auth/AuthenticationSIgnOn.class.php | 71 ----- .../auth/AuthenticationSignOn.class.php | 272 ++++++++++++++++++ 2 files changed, 272 insertions(+), 71 deletions(-) delete mode 100644 libraries/plugins/auth/AuthenticationSIgnOn.class.php create mode 100644 libraries/plugins/auth/AuthenticationSignOn.class.php diff --git a/libraries/plugins/auth/AuthenticationSIgnOn.class.php b/libraries/plugins/auth/AuthenticationSIgnOn.class.php deleted file mode 100644 index 8b33399280..0000000000 --- a/libraries/plugins/auth/AuthenticationSIgnOn.class.php +++ /dev/null @@ -1,71 +0,0 @@ - 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 From 2640b1399f8c82f7dc7c02e10bbb0d8513377035 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 10:30:23 +0300 Subject: [PATCH 46/55] oop: AuthenticationCookie bug --- .../auth/AuthenticationCookie.class.php | 50 +++++++++++++------ 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/libraries/plugins/auth/AuthenticationCookie.class.php b/libraries/plugins/auth/AuthenticationCookie.class.php index 9c15c77ca9..bfdac06792 100644 --- a/libraries/plugins/auth/AuthenticationCookie.class.php +++ b/libraries/plugins/auth/AuthenticationCookie.class.php @@ -274,11 +274,11 @@ class AuthenticationCookie extends AuthenticationPlugin * usually with PMA_DBI_connect() * * it returns false if something is missing - which usually leads to - * PMA_auth() which displays login form + * auth() which displays login form * - * it returns true if all seems ok which usually leads to PMA_auth_set_user() + * it returns true if all seems ok which usually leads to auth_set_user() * - * it directly switches to PMA_auth_fails() if user inactivity timout is reached + * 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 @@ -365,9 +365,9 @@ class AuthenticationCookie extends AuthenticationPlugin return false; } - $GLOBALS['PHP_AUTH_USER'] = PMA_blowfish_decrypt( + $GLOBALS['PHP_AUTH_USER'] = $this->blowfishDecrypt( $_COOKIE['pmaUser-' . $GLOBALS['server']], - PMA_get_blowfish_secret() + $this->getBlowfishSecret() ); // user was never logged in since session start @@ -383,7 +383,7 @@ class AuthenticationCookie extends AuthenticationPlugin PMA_cacheUnset('db_to_create', true); PMA_cacheUnset('dbs_where_create_table_allowed', true); $GLOBALS['no_activity'] = true; - PMA_auth_fails(); + $this->authFails(); exit; } @@ -392,9 +392,9 @@ class AuthenticationCookie extends AuthenticationPlugin return false; } - $GLOBALS['PHP_AUTH_PW'] = PMA_blowfish_decrypt( + $GLOBALS['PHP_AUTH_PW'] = $this->blowfishDecrypt( $_COOKIE['pmaPass-' . $GLOBALS['server']], - PMA_get_blowfish_secret() + $this->getBlowfishSecret() ); if ($GLOBALS['PHP_AUTH_PW'] == "\xff(blank)") { @@ -466,17 +466,18 @@ class AuthenticationCookie extends AuthenticationPlugin // Duration = one month for username $GLOBALS['PMA_Config']->setCookie( 'pmaUser-' . $GLOBALS['server'], - PMA_blowfish_encrypt( - $cfg['Server']['user'], PMA_get_blowfish_secret() + $this->blowfishEncrypt( + $cfg['Server']['user'], + $this->getBlowfishSecret() ) ); // Duration = as configured $GLOBALS['PMA_Config']->setCookie( 'pmaPass-' . $GLOBALS['server'], - PMA_blowfish_encrypt( + $this->blowfishEncrypt( ! empty($cfg['Server']['password']) ? $cfg['Server']['password'] : "\xff(blank)", - PMA_get_blowfish_secret() + $this->getBlowfishSecret() ), null, $GLOBALS['cfg']['LoginCookieStore'] @@ -537,11 +538,11 @@ class AuthenticationCookie extends AuthenticationPlugin /** * User is not allowed to login to MySQL -> authentication failed * - * prepares error message and switches to PMA_auth() which display the error + * 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 PMA_auth() + * currently doen by call to auth() * * @return void */ @@ -577,7 +578,7 @@ class AuthenticationCookie extends AuthenticationPlugin header('Cache-Control: no-store, no-cache, must-revalidate'); header('Pragma: no-cache'); - PMA_auth(); + $this->auth(); } /** @@ -619,6 +620,25 @@ class AuthenticationCookie extends AuthenticationPlugin ); } + /** + * 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']); + } + } + /** * Decryption using blowfish algorithm (mcrypt) * From 29cb9811d33c10b1c50ace568f37fa76041f2c75 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 11:00:53 +0300 Subject: [PATCH 47/55] oop: Auth - phpcs errors; remove php+html mix --- .../auth/AuthenticationConfig.class.php | 52 +++-- .../auth/AuthenticationCookie.class.php | 219 ++++++++++-------- .../plugins/auth/AuthenticationHTTP.class.php | 15 +- .../auth/AuthenticationSignOn.class.php | 28 ++- .../HordeCipherBlowfishOperations.class.php | 6 +- 5 files changed, 185 insertions(+), 135 deletions(-) diff --git a/libraries/plugins/auth/AuthenticationConfig.class.php b/libraries/plugins/auth/AuthenticationConfig.class.php index dbe7f7cb48..93f2015004 100644 --- a/libraries/plugins/auth/AuthenticationConfig.class.php +++ b/libraries/plugins/auth/AuthenticationConfig.class.php @@ -53,16 +53,16 @@ class AuthenticationConfig extends AuthenticationPlugin /** * User is not allowed to login to MySQL -> authentication failed * - * @global string the MySQL error message PHP returns - * @global string the connection type (persistent or not) - * @global string the MySQL server port to use - * @global string the MySQL socket port to use - * @global array the current server settings - * @global string the font face to use in case of failure - * @global string the default font size to use in case of failure - * @global string the big font size to use in case of failure - * @global boolean tell the "PMA_mysqlDie()" function headers have been - * sent + * @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) */ @@ -89,24 +89,42 @@ class AuthenticationConfig extends AuthenticationPlugin '; - $extracted_columnspec = PMA_extractColumnSpec($column['Type']); - $type = htmlspecialchars($extracted_columnspec['print_type']); - if (empty($type)) { - $type = ' '; - } - - if (! isset($column['Default'])) { - if ($column['Null'] != 'NO') { - $column['Default'] = 'NULL'; - } - } - - $fmt_pre = ''; - $fmt_post = ''; - if (in_array($column['Field'], $unique_keys)) { - $fmt_pre = '' . $fmt_pre; - $fmt_post = $fmt_post . ''; - } - if ($column['Key'] == 'PRI') { - $fmt_pre = '' . $fmt_pre; - $fmt_post = $fmt_post . ''; - } - $definition .= ''; - $definition .= ''; - $definition .= ''; - $definition .= ''; - - return $definition; - } -} -?> diff --git a/libraries/export/json.php b/libraries/export/json.php deleted file mode 100644 index df4a33ec85..0000000000 --- a/libraries/export/json.php +++ /dev/null @@ -1,197 +0,0 @@ - 'JSON', - 'extension' => 'json', - 'mime_type' => 'text/plain', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['json']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data', - ), - 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() - { - PMA_exportOutputHandler( - '/**' . $GLOBALS['crlf'] - . ' Export to JSON plugin for PHPMyAdmin' . $GLOBALS['crlf'] - . ' @version 0.1' . $GLOBALS['crlf'] - . ' */' . $GLOBALS['crlf'] . $GLOBALS['crlf'] - ); - return true; - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - PMA_exportOutputHandler('// Database \'' . $db . '\'' . $GLOBALS['crlf']); - 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 JSON 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) - { - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - - $columns_cnt = PMA_DBI_num_fields($result); - - // Get field information - $fields_meta = PMA_DBI_get_fields_meta($result); - - for ($i = 0; $i < $columns_cnt; $i++) { - $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); - } - unset($i); - - $buffer = ''; - $record_cnt = 0; - while ($record = PMA_DBI_fetch_row($result)) { - - $record_cnt++; - - // Output table name as comment if this is the first record of the table - if ($record_cnt == 1) { - $buffer .= '// ' . $db . '.' . $table . $crlf . $crlf; - $buffer .= '[{'; - } else { - $buffer .= ', {'; - } - - for ($i = 0; $i < $columns_cnt; $i++) { - - $isLastLine = ($i + 1 >= $columns_cnt); - - $column = $columns[$i]; - - if (is_null($record[$i])) { - $buffer .= '"' . addslashes($column) - . '": null' - . (! $isLastLine ? ',' : ''); - } elseif ($fields_meta[$i]->numeric) { - $buffer .= '"' . addslashes($column) - . '": ' - . $record[$i] - . (! $isLastLine ? ',' : ''); - } else { - $buffer .= '"' . addslashes($column) - . '": "' - . addslashes($record[$i]) - . '"' - . (! $isLastLine ? ',' : ''); - } - } - - $buffer .= '}'; - } - - if ($record_cnt) { - $buffer .= ']'; - } - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - - PMA_DBI_free_result($result); - - return true; - } - -} diff --git a/libraries/export/latex.php b/libraries/export/latex.php deleted file mode 100644 index 8164cef416..0000000000 --- a/libraries/export/latex.php +++ /dev/null @@ -1,601 +0,0 @@ - __('LaTeX'), - 'extension' => 'tex', - 'mime_type' => 'application/x-tex', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['latex']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'bool', - 'name' => 'caption', - 'text' => __('Include table caption') - ), - array( - 'type' => 'end_group' - ) - ); - /* what to dump (structure/data/both) */ - $plugin_list['latex']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'dump_what', - 'text' => __('Dump table') - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'radio', - 'name' => 'structure_or_data', - 'values' => array( - 'structure' => __('structure'), - 'data' => __('data'), - 'structure_and_data' => __('structure and data') - ) - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'end_group' - ); - - /* Structure options */ - if (! $hide_structure) { - $plugin_list['latex']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'structure', - 'text' => __('Object creation options'), - 'force' => 'data' - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'text', - 'name' => 'structure_caption', - 'text' => __('Table caption'), - 'doc' => 'faq6_27' - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'text', - 'name' => 'structure_continued_caption', - 'text' => __('Table caption (continued)'), - 'doc' => 'faq6_27' - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'text', - 'name' => 'structure_label', - 'text' => __('Label key'), - 'doc' => 'faq6_27' - ); - if (! empty($GLOBALS['cfgRelation']['relation'])) { - $plugin_list['latex']['options'][] = array( - 'type' => 'bool', - 'name' => 'relation', - 'text' => __('Display foreign key relationships') - ); - } - $plugin_list['latex']['options'][] = array( - 'type' => 'bool', - 'name' => 'comments', - 'text' => __('Display comments') - ); - if (! empty($GLOBALS['cfgRelation']['mimework'])) { - $plugin_list['latex']['options'][] = array( - 'type' => 'bool', - 'name' => 'mime', - 'text' => __('Display MIME types') - ); - } - $plugin_list['latex']['options'][] = array( - 'type' => 'end_group' - ); - } - - /* Data */ - $plugin_list['latex']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'data', - 'text' => __('Data dump options'), - 'force' => 'structure' - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'bool', - 'name' => 'columns', - 'text' => __('Put columns names in the first row') - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'text', - 'name' => 'data_caption', - 'text' => __('Table caption'), - 'doc' => 'faq6_27' - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'text', - 'name' => 'data_continued_caption', - 'text' => __('Table caption (continued)'), - 'doc' => 'faq6_27' - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'text', - 'name' => 'data_label', - 'text' => __('Label key'), - 'doc' => 'faq6_27' - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'text', - 'name' => 'null', - 'text' => __('Replace NULL with:') - ); - $plugin_list['latex']['options'][] = array( - 'type' => 'end_group' - ); -} else { - - /** - * Escapes some special characters for use in TeX/LaTeX - * - * @param string $string the string to convert - * - * @return string the converted string with escape codes - * - * @access private - */ - function PMA_texEscape($string) - { - $escape = array('$', '%', '{', '}', '&', '#', '_', '^'); - $cnt_escape = count($escape); - for ($k = 0; $k < $cnt_escape; $k++) { - $string = str_replace($escape[$k], '\\' . $escape[$k], $string); - } - return $string; - } - - /** - * 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() - { - global $crlf; - global $cfg; - - $head = '% phpMyAdmin LaTeX Dump' . $crlf - . '% version ' . PMA_VERSION . $crlf - . '% http://www.phpmyadmin.net' . $crlf - . '%' . $crlf - . '% ' . __('Host') . ': ' . $cfg['Server']['host']; - if (! empty($cfg['Server']['port'])) { - $head .= ':' . $cfg['Server']['port']; - } - $head .= $crlf - . '% ' . __('Generation Time') . ': ' . PMA_localisedDate() . $crlf - . '% ' . __('Server version') . ': ' . PMA_MYSQL_STR_VERSION . $crlf - . '% ' . __('PHP Version') . ': ' . phpversion() . $crlf; - return PMA_exportOutputHandler($head); - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - global $crlf; - $head = '% ' . $crlf - . '% ' . __('Database') . ': ' . '\'' . $db . '\'' . $crlf - . '% ' . $crlf; - return PMA_exportOutputHandler($head); - } - - /** - * 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 LaTeX table/sideways table environment - * - * @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) - { - $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - - $columns_cnt = PMA_DBI_num_fields($result); - for ($i = 0; $i < $columns_cnt; $i++) { - $columns[$i] = PMA_DBI_field_name($result, $i); - } - unset($i); - - $buffer = $crlf . '%' . $crlf . '% ' . __('Data') . ': ' . $table - . $crlf . '%' . $crlf . ' \\begin{longtable}{|'; - - for ($index = 0; $index < $columns_cnt; $index++) { - $buffer .= 'l|'; - } - $buffer .= '} ' . $crlf ; - - $buffer .= ' \\hline \\endhead \\hline \\endfoot \\hline ' . $crlf; - if (isset($GLOBALS['latex_caption'])) { - $buffer .= ' \\caption{' - . PMA_expandUserString( - $GLOBALS['latex_data_caption'], - 'PMA_texEscape', - array('table' => $table, 'database' => $db) - ) - . '} \\label{' - . PMA_expandUserString( - $GLOBALS['latex_data_label'], - null, - array('table' => $table, 'database' => $db) - ) - . '} \\\\'; - } - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - - // show column names - if (isset($GLOBALS['latex_columns'])) { - $buffer = '\\hline '; - for ($i = 0; $i < $columns_cnt; $i++) { - $buffer .= '\\multicolumn{1}{|c|}{\\textbf{' - . PMA_texEscape(stripslashes($columns[$i])) . '}} & '; - } - - $buffer = substr($buffer, 0, -2) . '\\\\ \\hline \hline '; - if (! PMA_exportOutputHandler($buffer . ' \\endfirsthead ' . $crlf)) { - return false; - } - if (isset($GLOBALS['latex_caption'])) { - if (! PMA_exportOutputHandler( - '\\caption{' - . PMA_expandUserString( - $GLOBALS['latex_data_continued_caption'], - 'PMA_texEscape', - array('table' => $table, 'database' => $db) - ) - . '} \\\\ ' - )) { - return false; - } - } - if (! PMA_exportOutputHandler($buffer . '\\endhead \\endfoot' . $crlf)) { - return false; - } - } else { - if (! PMA_exportOutputHandler('\\\\ \hline')) { - return false; - } - } - - // print the whole table - while ($record = PMA_DBI_fetch_assoc($result)) { - - $buffer = ''; - // print each row - for ($i = 0; $i < $columns_cnt; $i++) { - if ((! function_exists('is_null') - || ! is_null($record[$columns[$i]])) - && isset($record[$columns[$i]]) - ) { - $column_value = PMA_texEscape( - stripslashes($record[$columns[$i]]) - ); - } else { - $column_value = $GLOBALS['latex_null']; - } - - // last column ... no need for & character - if ($i == ($columns_cnt - 1)) { - $buffer .= $column_value; - } else { - $buffer .= $column_value . " & "; - } - } - $buffer .= ' \\\\ \\hline ' . $crlf; - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - } - - $buffer = ' \\end{longtable}' . $crlf; - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - - PMA_DBI_free_result($result); - return true; - - } // end getTableLaTeX - - /** - * 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 - ) { - global $cfgRelation; - - /** - * Get the unique keys in the table - */ - $unique_keys = array(); - $keys = PMA_DBI_get_table_indexes($db, $table); - foreach ($keys as $key) { - if ($key['Non_unique'] == 0) { - $unique_keys[] = $key['Column_name']; - } - } - - /** - * Gets fields properties - */ - PMA_DBI_select_db($db); - - // Check if we can use Relations - if ($do_relation && ! empty($cfgRelation['relation'])) { - // Find which tables are related with the current one and write it in - // an array - $res_rel = PMA_getForeigners($db, $table); - - if ($res_rel && count($res_rel) > 0) { - $have_rel = true; - } else { - $have_rel = false; - } - } else { - $have_rel = false; - } // end if - - /** - * Displays the table structure - */ - $buffer = $crlf . '%' . $crlf . '% ' . __('Structure') . ': ' . $table - . $crlf . '%' . $crlf . ' \\begin{longtable}{'; - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - - $columns_cnt = 4; - $alignment = '|l|c|c|c|'; - if ($do_relation && $have_rel) { - $columns_cnt++; - $alignment .= 'l|'; - } - if ($do_comments) { - $columns_cnt++; - $alignment .= 'l|'; - } - if ($do_mime && $cfgRelation['mimework']) { - $columns_cnt++; - $alignment .='l|'; - } - $buffer = $alignment . '} ' . $crlf ; - - $header = ' \\hline '; - $header .= '\\multicolumn{1}{|c|}{\\textbf{' . __('Column') - . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Type') - . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Null') - . '}} & \\multicolumn{1}{|c|}{\\textbf{' . __('Default') . '}}'; - if ($do_relation && $have_rel) { - $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Links to') . '}}'; - } - if ($do_comments) { - $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . __('Comments') . '}}'; - $comments = PMA_getComments($db, $table); - } - if ($do_mime && $cfgRelation['mimework']) { - $header .= ' & \\multicolumn{1}{|c|}{\\textbf{MIME}}'; - $mime_map = PMA_getMIME($db, $table, true); - } - - // Table caption for first page and label - if (isset($GLOBALS['latex_caption'])) { - $buffer .= ' \\caption{' - . PMA_expandUserString( - $GLOBALS['latex_structure_caption'], - 'PMA_texEscape', - array('table' => $table, 'database' => $db) - ) - . '} \\label{' - . PMA_expandUserString( - $GLOBALS['latex_structure_label'], - null, - array('table' => $table, 'database' => $db) - ) - . '} \\\\' . $crlf; - } - $buffer .= $header . ' \\\\ \\hline \\hline' . $crlf - . '\\endfirsthead' . $crlf; - // Table caption on next pages - if (isset($GLOBALS['latex_caption'])) { - $buffer .= ' \\caption{' - . PMA_expandUserString( - $GLOBALS['latex_structure_continued_caption'], - 'PMA_texEscape', - array('table' => $table, 'database' => $db) - ) - . '} \\\\ ' . $crlf; - } - $buffer .= $header . ' \\\\ \\hline \\hline \\endhead \\endfoot ' . $crlf; - - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - - $fields = PMA_DBI_get_columns($db, $table); - foreach ($fields as $row) { - $extracted_columnspec = PMA_extractColumnSpec($row['Type']); - $type = $extracted_columnspec['print_type']; - if (empty($type)) { - $type = ' '; - } - - if (! isset($row['Default'])) { - if ($row['Null'] != 'NO') { - $row['Default'] = 'NULL'; - } - } - - $field_name = $row['Field']; - - $local_buffer = $field_name . "\000" . $type . "\000" - . (($row['Null'] == '' || $row['Null'] == 'NO') - ? __('No') : __('Yes')) - . "\000" . (isset($row['Default']) ? $row['Default'] : ''); - - if ($do_relation && $have_rel) { - $local_buffer .= "\000"; - if (isset($res_rel[$field_name])) { - $local_buffer .= $res_rel[$field_name]['foreign_table'] . ' (' - . $res_rel[$field_name]['foreign_field'] . ')'; - } - } - if ($do_comments && $cfgRelation['commwork']) { - $local_buffer .= "\000"; - if (isset($comments[$field_name])) { - $local_buffer .= $comments[$field_name]; - } - } - if ($do_mime && $cfgRelation['mimework']) { - $local_buffer .= "\000"; - if (isset($mime_map[$field_name])) { - $local_buffer .= str_replace( - '_', - '/', - $mime_map[$field_name]['mimetype'] - ); - } - } - $local_buffer = PMA_texEscape($local_buffer); - if ($row['Key']=='PRI') { - $pos=strpos($local_buffer, "\000"); - $local_buffer = '\\textit{' - . substr($local_buffer, 0, $pos) - . '}' . substr($local_buffer, $pos); - } - if (in_array($field_name, $unique_keys)) { - $pos=strpos($local_buffer, "\000"); - $local_buffer = '\\textbf{' - . substr($local_buffer, 0, $pos) - . '}' . substr($local_buffer, $pos); - } - $buffer = str_replace("\000", ' & ', $local_buffer); - $buffer .= ' \\\\ \\hline ' . $crlf; - - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - } // end while - - $buffer = ' \\end{longtable}' . $crlf; - return PMA_exportOutputHandler($buffer); - } // end of the 'PMA_exportStructure' function - -} // end else -?> 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/ods.php b/libraries/export/ods.php deleted file mode 100644 index 5128363d8a..0000000000 --- a/libraries/export/ods.php +++ /dev/null @@ -1,300 +0,0 @@ - __('Open Document Spreadsheet'), - 'extension' => 'ods', - 'mime_type' => 'application/vnd.oasis.opendocument.spreadsheet', - 'force_file' => true, - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['ods']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'text', - 'name' => 'null', - 'text' => __('Replace NULL with:') - ), - array( - 'type' => 'bool', - 'name' => 'columns', - 'text' => __('Put columns names in the first row') - ), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data' - ), - array( - 'type' => 'end_group' - ) - ); -} else { - - $GLOBALS['ods_buffer'] = ''; - include_once './libraries/opendocument.lib.php'; - - /** - * Outputs export footer - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - $GLOBALS['ods_buffer'] .= '' - . '' - . ''; - if (! PMA_exportOutputHandler( - PMA_createOpenDocument( - 'application/vnd.oasis.opendocument.spreadsheet', - $GLOBALS['ods_buffer'] - ) - )) { - return false; - } - return true; - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - $GLOBALS['ods_buffer'] .= '' - . '' - . '' - . '' - . '' - . '/' - . '' - . '/' - . '' - . '' - . '' - . '' - . ':' - . '' - . ':' - . '' - . ' ' - . '' - . '' - . '' - . '' - . '/' - . '' - . '/' - . '' - . ' ' - . '' - . ':' - . '' - . ' ' - . '' - . '' - . '' - . '' - . '' - . '' - . '' - . ''; - 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 ODS 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 $what; - - // Gets the data from the database - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - $fields_cnt = PMA_DBI_num_fields($result); - $fields_meta = PMA_DBI_get_fields_meta($result); - $field_flags = array(); - for ($j = 0; $j < $fields_cnt; $j++) { - $field_flags[$j] = PMA_DBI_field_flags($result, $j); - } - - $GLOBALS['ods_buffer'] .= - ''; - - // If required, get fields name at the first line - if (isset($GLOBALS[$what . '_columns'])) { - $GLOBALS['ods_buffer'] .= ''; - for ($i = 0; $i < $fields_cnt; $i++) { - $GLOBALS['ods_buffer'] .= - '' - . '' - . htmlspecialchars( - stripslashes(PMA_DBI_field_name($result, $i)) - ) - . '' - . ''; - } // end for - $GLOBALS['ods_buffer'] .= ''; - } // end if - - // Format the data - while ($row = PMA_DBI_fetch_row($result)) { - $GLOBALS['ods_buffer'] .= ''; - for ($j = 0; $j < $fields_cnt; $j++) { - if (! isset($row[$j]) || is_null($row[$j])) { - $GLOBALS['ods_buffer'] .= - '' - . '' - . htmlspecialchars($GLOBALS[$what . '_null']) - . '' - . ''; - } elseif (stristr($field_flags[$j], 'BINARY') - && $fields_meta[$j]->blob - ) { - // ignore BLOB - $GLOBALS['ods_buffer'] .= - '' - . '' - . ''; - } elseif ($fields_meta[$j]->type == "date") { - $GLOBALS['ods_buffer'] .= - '' - . '' - . htmlspecialchars($row[$j]) - . '' - . ''; - } elseif ($fields_meta[$j]->type == "time") { - $GLOBALS['ods_buffer'] .= - '' - . '' - . htmlspecialchars($row[$j]) - . '' - . ''; - } elseif ($fields_meta[$j]->type == "datetime") { - $GLOBALS['ods_buffer'] .= - '' - . '' - . htmlspecialchars($row[$j]) - . '' - . ''; - } elseif ($fields_meta[$j]->numeric - && $fields_meta[$j]->type != 'timestamp' - && ! $fields_meta[$j]->blob - ) { - $GLOBALS['ods_buffer'] .= - '' - . '' - . htmlspecialchars($row[$j]) - . '' - . ''; - } else { - $GLOBALS['ods_buffer'] .= - '' - . '' - . htmlspecialchars($row[$j]) - . '' - . ''; - } - } // end for - $GLOBALS['ods_buffer'] .= ''; - } // end while - PMA_DBI_free_result($result); - - $GLOBALS['ods_buffer'] .= ''; - - return true; - } - -} -?> diff --git a/libraries/export/odt.php b/libraries/export/odt.php deleted file mode 100644 index 49da5d0a76..0000000000 --- a/libraries/export/odt.php +++ /dev/null @@ -1,709 +0,0 @@ - __('Open Document Text'), - 'extension' => 'odt', - 'mime_type' => 'application/vnd.oasis.opendocument.text', - 'force_file' => true, - 'options' => array(), - 'options_text' => __('Options') - ); - - /* what to dump (structure/data/both) */ - $plugin_list['odt']['options'][] = array( - 'type' => 'begin_group', - 'text' => __('Dump table'), - 'name' => 'general_opts' - ); - $plugin_list['odt']['options'][] = array( - 'type' => 'radio', - 'name' => 'structure_or_data', - 'values' => array( - 'structure' => __('structure'), - 'data' => __('data'), - 'structure_and_data' => __('structure and data') - ) - ); - $plugin_list['odt']['options'][] = array( - 'type' => 'end_group' - ); - - /* Structure options */ - if (! $hide_structure) { - $plugin_list['odt']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'structure', - 'text' => __('Object creation options'), - 'force' => 'data' - ); - if (! empty($GLOBALS['cfgRelation']['relation'])) { - $plugin_list['odt']['options'][] = array( - 'type' => 'bool', - 'name' => 'relation', - 'text' => __('Display foreign key relationships') - ); - } - $plugin_list['odt']['options'][] = array( - 'type' => 'bool', - 'name' => 'comments', - 'text' => __('Display comments') - ); - if (! empty($GLOBALS['cfgRelation']['mimework'])) { - $plugin_list['odt']['options'][] = array( - 'type' => 'bool', - 'name' => 'mime', - 'text' => __('Display MIME types') - ); - } - $plugin_list['odt']['options'][] = array( - 'type' => 'end_group' - ); - } - - /* Data */ - $plugin_list['odt']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'data', - 'text' => __('Data dump options'), - 'force' => 'structure' - ); - $plugin_list['odt']['options'][] = array( - 'type' => 'bool', - 'name' => 'columns', - 'text' => __('Put columns names in the first row') - ); - $plugin_list['odt']['options'][] = array( - 'type' => 'text', - 'name' => 'null', - 'text' => __('Replace NULL with:') - ); - $plugin_list['odt']['options'][] = array( - 'type' => 'end_group' - ); -} else { - - $GLOBALS['odt_buffer'] = ''; - include_once './libraries/opendocument.lib.php'; - - /** - * Outputs export footer - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - $GLOBALS['odt_buffer'] .= '' - . '' - . ''; - if (! PMA_exportOutputHandler( - PMA_createOpenDocument( - 'application/vnd.oasis.opendocument.text', - $GLOBALS['odt_buffer'] - ) - )) { - return false; - } - return true; - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - $GLOBALS['odt_buffer'] .= '' - . '' - . '' - . ''; - return true; - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - $GLOBALS['odt_buffer'] .= - '' - . __('Database') . ' ' . htmlspecialchars($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 ODT 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 $what; - - // Gets the data from the database - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - $fields_cnt = PMA_DBI_num_fields($result); - $fields_meta = PMA_DBI_get_fields_meta($result); - $field_flags = array(); - for ($j = 0; $j < $fields_cnt; $j++) { - $field_flags[$j] = PMA_DBI_field_flags($result, $j); - } - - $GLOBALS['odt_buffer'] .= - '' - . __('Dumping data for table') . ' ' . htmlspecialchars($table) - . '' - . '' - . ''; - - // If required, get fields name at the first line - if (isset($GLOBALS[$what . '_columns'])) { - $GLOBALS['odt_buffer'] .= ''; - for ($i = 0; $i < $fields_cnt; $i++) { - $GLOBALS['odt_buffer'] .= - '' - . '' - . htmlspecialchars( - stripslashes(PMA_DBI_field_name($result, $i)) - ) - . '' - . ''; - } // end for - $GLOBALS['odt_buffer'] .= ''; - } // end if - - // Format the data - while ($row = PMA_DBI_fetch_row($result)) { - $GLOBALS['odt_buffer'] .= ''; - for ($j = 0; $j < $fields_cnt; $j++) { - if (! isset($row[$j]) || is_null($row[$j])) { - $GLOBALS['odt_buffer'] .= - '' - . '' - . htmlspecialchars($GLOBALS[$what . '_null']) - . '' - . ''; - } elseif (stristr($field_flags[$j], 'BINARY') - && $fields_meta[$j]->blob - ) { - // ignore BLOB - $GLOBALS['odt_buffer'] .= - '' - . '' - . ''; - } elseif ($fields_meta[$j]->numeric - && $fields_meta[$j]->type != 'timestamp' - && ! $fields_meta[$j]->blob - ) { - $GLOBALS['odt_buffer'] .= - '' - . '' - . htmlspecialchars($row[$j]) - . '' - . ''; - } else { - $GLOBALS['odt_buffer'] .= - '' - . '' - . htmlspecialchars($row[$j]) - . '' - . ''; - } - } // end for - $GLOBALS['odt_buffer'] .= ''; - } // end while - PMA_DBI_free_result($result); - - $GLOBALS['odt_buffer'] .= ''; - - return true; - } - - /** - * Returns a stand-in CREATE definition to resolve view dependencies - * - * @param string $db the database name - * @param string $view the view name - * @param string $crlf the end of line sequence - * - * @return bool true - * - * @access public - */ - function PMA_getTableDefStandIn($db, $view, $crlf) - { - /** - * Gets fields properties - */ - PMA_DBI_select_db($db); - - /** - * Displays the table structure - */ - $GLOBALS['odt_buffer'] .= - ''; - $columns_cnt = 4; - $GLOBALS['odt_buffer'] .= - ''; - /* Header */ - $GLOBALS['odt_buffer'] .= '' - . '' - . '' . __('Column') . '' - . '' - . '' - . '' . __('Type') . '' - . '' - . '' - . '' . __('Null') . '' - . '' - . '' - . '' . __('Default') . '' - . '' - . ''; - - $columns = PMA_DBI_get_columns($db, $view); - foreach ($columns as $column) { - $GLOBALS['odt_buffer'] .= PMA_formatOneColumnDefinition($column); - $GLOBALS['odt_buffer'] .= ''; - } // end foreach - - $GLOBALS['odt_buffer'] .= ''; - return true; - } - - /** - * Returns $table's CREATE definition - * - * @param string $db the database name - * @param string $table the table name - * @param string $crlf the end of line sequence - * @param string $error_url the url to go back in case of error - * @param bool $do_relation whether to include relation comments - * @param bool $do_comments whether to include the pmadb-style column - * comments as comments in the structure; - * this is deprecated but the parameter is - * left here because export.php calls - * PMA_exportStructure() also for other - * @param bool $do_mime whether to include mime comments - * @param bool $show_dates whether to include creation/update/check dates - * @param bool $add_semicolon whether to add semicolon and end-of-line at - * the end - * @param bool $view whether we're handling a view - * - * @return bool true - * - * @access public - */ - function PMA_getTableDef( - $db, - $table, - $crlf, - $error_url, - $do_relation, - $do_comments, - $do_mime, - $show_dates = false, - $add_semicolon = true, - $view = false - ) { - global $cfgRelation; - - /** - * Gets fields properties - */ - PMA_DBI_select_db($db); - - // Check if we can use Relations - if ($do_relation && ! empty($cfgRelation['relation'])) { - // Find which tables are related with the current one and write it in - // an array - $res_rel = PMA_getForeigners($db, $table); - - if ($res_rel && count($res_rel) > 0) { - $have_rel = true; - } else { - $have_rel = false; - } - } else { - $have_rel = false; - } // end if - - /** - * Displays the table structure - */ - $GLOBALS['odt_buffer'] .= ''; - $columns_cnt = 4; - if ($do_relation && $have_rel) { - $columns_cnt++; - } - if ($do_comments) { - $columns_cnt++; - } - if ($do_mime && $cfgRelation['mimework']) { - $columns_cnt++; - } - $GLOBALS['odt_buffer'] .= ''; - /* Header */ - $GLOBALS['odt_buffer'] .= '' - . '' - . '' . __('Column') . '' - . '' - . '' - . '' . __('Type') . '' - . '' - . '' - . '' . __('Null') . '' - . '' - . '' - . '' . __('Default') . '' - . ''; - if ($do_relation && $have_rel) { - $GLOBALS['odt_buffer'] .= '' - . '' . __('Links to') . '' - . ''; - } - if ($do_comments) { - $GLOBALS['odt_buffer'] .= '' - . '' . __('Comments') . '' - . ''; - $comments = PMA_getComments($db, $table); - } - if ($do_mime && $cfgRelation['mimework']) { - $GLOBALS['odt_buffer'] .= '' - . '' . __('MIME type') . '' - . ''; - $mime_map = PMA_getMIME($db, $table, true); - } - $GLOBALS['odt_buffer'] .= ''; - - $columns = PMA_DBI_get_columns($db, $table); - foreach ($columns as $column) { - $field_name = $column['Field']; - $GLOBALS['odt_buffer'] .= PMA_formatOneColumnDefinition($column); - - if ($do_relation && $have_rel) { - if (isset($res_rel[$field_name])) { - $GLOBALS['odt_buffer'] .= - '' - . '' - . htmlspecialchars( - $res_rel[$field_name]['foreign_table'] - . ' (' . $res_rel[$field_name]['foreign_field'] . ')' - ) - . '' - . ''; - } - } - if ($do_comments) { - if (isset($comments[$field_name])) { - $GLOBALS['odt_buffer'] .= - '' - . '' - . htmlspecialchars($comments[$field_name]) - . '' - . ''; - } else { - $GLOBALS['odt_buffer'] .= - '' - . '' - . ''; - } - } - if ($do_mime && $cfgRelation['mimework']) { - if (isset($mime_map[$field_name])) { - $GLOBALS['odt_buffer'] .= - '' - . '' - . htmlspecialchars( - str_replace('_', '/', $mime_map[$field_name]['mimetype']) - ) - . '' - . ''; - } else { - $GLOBALS['odt_buffer'] .= - '' - . '' - . ''; - } - } - $GLOBALS['odt_buffer'] .= ''; - } // end foreach - - $GLOBALS['odt_buffer'] .= ''; - return true; - } // end of the 'PMA_getTableDef()' function - - /** - * Outputs triggers - * - * @param string $db database name - * @param string $table table name - * - * @return bool true - * - * @access public - */ - function PMA_getTriggers($db, $table) - { - $GLOBALS['odt_buffer'] .= '' - . '' - . '' - . '' - . '' . __('Name') . '' - . '' - . '' - . '' . __('Time') . '' - . '' - . '' - . '' . __('Event') . '' - . '' - . '' - . '' . __('Definition') . '' - . '' - . ''; - - $triggers = PMA_DBI_get_triggers($db, $table); - - foreach ($triggers as $trigger) { - $GLOBALS['odt_buffer'] .= ''; - $GLOBALS['odt_buffer'] .= '' - . '' - . htmlspecialchars($trigger['name']) - . '' - . ''; - $GLOBALS['odt_buffer'] .= '' - . '' - . htmlspecialchars($trigger['action_timing']) - . '' - . ''; - $GLOBALS['odt_buffer'] .= '' - . '' - . htmlspecialchars($trigger['event_manipulation']) - . '' - . ''; - $GLOBALS['odt_buffer'] .= '' - . '' - . htmlspecialchars($trigger['definition']) - . '' - . ''; - $GLOBALS['odt_buffer'] .= ''; - } - - $GLOBALS['odt_buffer'] .= ''; - 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 - * @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': - $GLOBALS['odt_buffer'] .= - '' - . __('Table structure for table') . ' ' . - htmlspecialchars($table) - . ''; - PMA_getTableDef( - $db, $table, $crlf, $error_url, $do_relation, $do_comments, - $do_mime, $dates - ); - break; - case 'triggers': - $triggers = PMA_DBI_get_triggers($db, $table); - if ($triggers) { - $GLOBALS['odt_buffer'] .= - '' - . __('Triggers') . ' ' - . htmlspecialchars($table) - . ''; - PMA_getTriggers($db, $table); - } - break; - case 'create_view': - $GLOBALS['odt_buffer'] .= - '' - . __('Structure for view') . ' ' - . htmlspecialchars($table) - . ''; - PMA_getTableDef( - $db, $table, $crlf, $error_url, $do_relation, $do_comments, - $do_mime, $dates, true, true - ); - break; - case 'stand_in': - $GLOBALS['odt_buffer'] .= - '' - . __('Stand-in structure for view') . ' ' - . htmlspecialchars($table) - . ''; - // export a stand-in definition to resolve view dependencies - PMA_getTableDefStandIn($db, $table, $crlf); - } // end switch - - return true; - } // end of the 'PMA_exportStructure' function - - /** - * Formats the definition for one column - * - * @param array $column info about this column - * - * @return string Formatted column definition - * - * @access public - */ - function PMA_formatOneColumnDefinition($column) - { - $field_name = $column['Field']; - $definition = ''; - $definition .= '' - . '' . htmlspecialchars($field_name) . '' - . ''; - - $extracted_columnspec = PMA_extractColumnSpec($column['Type']); - $type = htmlspecialchars($extracted_columnspec['print_type']); - if (empty($type)) { - $type = ' '; - } - - $definition .= '' - . '' . htmlspecialchars($type) . '' - . ''; - if (! isset($column['Default'])) { - if ($column['Null'] != 'NO') { - $column['Default'] = 'NULL'; - } else { - $column['Default'] = ''; - } - } else { - $column['Default'] = $column['Default']; - } - $definition .= '' - . '' - . (($column['Null'] == '' || $column['Null'] == 'NO') - ? __('No') - : __('Yes')) - . '' - . ''; - $definition .= '' - . '' . htmlspecialchars($column['Default']) . '' - . ''; - return $definition; - } -} // end else -?> 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/export/php_array.php b/libraries/export/php_array.php deleted file mode 100644 index 336d1ec19d..0000000000 --- a/libraries/export/php_array.php +++ /dev/null @@ -1,198 +0,0 @@ - __('PHP array'), - 'extension' => 'php', - 'mime_type' => 'text/plain', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['php_array']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data', - ), - 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() - { - PMA_exportOutputHandler( - ' " . var_export($record[$i], true) - . (($i + 1 >= $columns_cnt) ? '' : ','); - } - - $buffer .= ')'; - } - - $buffer .= $crlf . ');' . $crlf; - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - - PMA_DBI_free_result($result); - - return true; - } - -} diff --git a/libraries/export/sql.php b/libraries/export/sql.php deleted file mode 100644 index 8466a76586..0000000000 --- a/libraries/export/sql.php +++ /dev/null @@ -1,1675 +0,0 @@ - __('SQL'), - 'extension' => 'sql', - 'mime_type' => 'text/x-sql', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ); - - /* comments */ - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_subgroup', - 'subgroup_header' => array( - 'type' => 'bool', - 'name' => 'include_comments', - 'text' => __( - 'Display comments (includes info such as export timestamp,' - . ' PHP version, and server version)' - ) - ) - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'text', - 'name' => 'header_comment', - 'text' => __('Additional custom header comment (\n splits lines):') - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'dates', - 'text' => __( - 'Include a timestamp of when databases were created, last' - . ' updated, and last checked' - ) - ); - if (! empty($GLOBALS['cfgRelation']['relation'])) { - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'relation', - 'text' => __('Display foreign key relationships') - ); - } - if (! empty($GLOBALS['cfgRelation']['mimework'])) { - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'mime', - 'text' => __('Display MIME types') - ); - } - $plugin_list['sql']['options'][] = array( - 'type' => 'end_subgroup' - ); - /* end comments */ - - /* enclose in a transaction */ - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'use_transaction', - 'text' => __('Enclose export in a transaction'), - 'doc' => array( - 'programs', - 'mysqldump', - 'option_mysqldump_single-transaction' - ) - ); - - /* disable foreign key checks */ - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'disable_fk', - 'text' => __('Disable foreign key checks'), - 'doc' => array( - 'manual_MySQL_Database_Administration', - 'server-system-variables', - 'sysvar_foreign_key_checks' - ) - ); - - /* compatibility maximization */ - $compats = PMA_DBI_getCompatibilities(); - if (count($compats) > 0) { - $values = array(); - foreach ($compats as $val) { - $values[$val] = $val; - } - $plugin_list['sql']['options'][] = array( - 'type' => 'select', - 'name' => 'compatibility', - 'text' => __( - 'Database system or older MySQL server to maximize output' - . ' compatibility with:' - ), - 'values' => $values, - 'doc' => array( - 'manual_MySQL_Database_Administration', - 'Server_SQL_mode' - ) - ); - unset($values); - } - - /* server export options */ - if ($plugin_param['export_type'] == 'server') { - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'drop_database', - 'text' => sprintf( - __('Add %s statement'), 'DROP DATABASE' - ) - ); - } - - /* what to dump (structure/data/both) */ - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_subgroup', - 'subgroup_header' => array( - 'type' => 'message_only', - 'text' => __('Dump table') - ) - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'radio', - 'name' => 'structure_or_data', - 'values' => array( - 'structure' => __('structure'), - 'data' => __('data'), - 'structure_and_data' => __('structure and data') - ) - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'end_subgroup' - ); - - $plugin_list['sql']['options'][] = array( - 'type' => 'end_group' - ); - - /* begin Structure options */ - if (! $hide_structure) { - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'structure', - 'text' => __('Object creation options'), - 'force' => 'data' - ); - - /* begin SQL Statements */ - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_subgroup', - 'subgroup_header' => array( - 'type' => 'message_only', - 'name' => 'add_statements', - 'text' => __('Add statements:') - ) - ); - if ($plugin_param['export_type'] == 'table') { - if (PMA_Table::isView($GLOBALS['db'], $GLOBALS['table'])) { - $drop_clause = 'DROP VIEW'; - } else { - $drop_clause = 'DROP TABLE'; - } - } else { - if (PMA_DRIZZLE) { - $drop_clause = 'DROP TABLE'; - } else { - $drop_clause = 'DROP TABLE / VIEW / PROCEDURE' - . ' / FUNCTION'; - if (PMA_MYSQL_INT_VERSION > 50100) { - $drop_clause .= ' / EVENT'; - } - } - } - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'drop_table', - 'text' => sprintf(__('Add %s statement'), $drop_clause) - ); - // Drizzle doesn't support procedures and functions - if (! PMA_DRIZZLE) { - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'procedure_function', - 'text' => sprintf( - __('Add %s statement'), - 'CREATE PROCEDURE / FUNCTION' - . (PMA_MYSQL_INT_VERSION > 50100 - ? ' / EVENT' : '') - ) - ); - } - - /* begin CREATE TABLE statements*/ - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_subgroup', - 'subgroup_header' => array( - 'type' => 'bool', - 'name' => 'create_table_statements', - 'text' => __('CREATE TABLE options:') - ) - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'if_not_exists', - 'text' => 'IF NOT EXISTS' - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'auto_increment', - 'text' => 'AUTO_INCREMENT' - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'end_subgroup' - ); - /* end CREATE TABLE statements */ - - $plugin_list['sql']['options'][] = array( - 'type' => 'end_subgroup' - ); - /* end SQL statements */ - - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'backquotes', - 'text' => __( - 'Enclose table and column names with backquotes ' - . '(Protects column and table names formed with' - . ' special characters or keywords)' - ) - ); - - $plugin_list['sql']['options'][] = array( - 'type' => 'end_group' - ); - } - /* end Structure options */ - - /* begin Data options */ - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'data', - 'text' => __('Data dump options'), - 'force' => 'structure' - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'truncate', - 'text' => __('Truncate table before insert') - ); - /* begin SQL statements */ - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_subgroup', - 'subgroup_header' => array( - 'type' => 'message_only', - 'text' => __('Instead of INSERT statements, use:') - ) - ); - // Not supported in Drizzle - if (! PMA_DRIZZLE) { - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'delayed', - 'text' => __('INSERT DELAYED statements'), - 'doc' => array( - 'manual_MySQL_Database_Administration', - 'insert_delayed' - ) - ); - } - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'ignore', - 'text' => __('INSERT IGNORE statements'), - 'doc' => array( - 'manual_MySQL_Database_Administration', - 'insert' - ) - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'end_subgroup' - ); - /* end SQL statements */ - - /* Function to use when dumping data */ - $plugin_list['sql']['options'][] = array( - 'type' => 'select', - 'name' => 'type', - 'text' => __('Function to use when dumping data:'), - 'values' => array( - 'INSERT' => 'INSERT', - 'UPDATE' => 'UPDATE', - 'REPLACE' => 'REPLACE' - ) - ); - - /* Syntax to use when inserting data */ - $plugin_list['sql']['options'][] = array( - 'type' => 'begin_subgroup', - 'subgroup_header' => array( - 'type' => 'message_only', - 'text' => __('Syntax to use when inserting data:') - ) - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'radio', - 'name' => 'insert_syntax', - 'values' => array( - 'complete' => __( - 'include column names in every INSERT statement' - . '
      Example: INSERT INTO' - . ' tbl_name (col_A,col_B,col_C) VALUES (1,2,3)' - ), - 'extended' => __( - 'insert multiple rows in every INSERT statement' - . '
      Example: INSERT INTO' - . ' tbl_name VALUES (1,2,3), (4,5,6), (7,8,9)' - ), - 'both' => __( - 'both of the above
      Example:' - . ' INSERT INTO tbl_name (col_A,col_B) VALUES (1,2,3),' - . ' (4,5,6), (7,8,9)' - ), - 'none' => __( - 'neither of the above
      Example:' - . ' INSERT INTO tbl_name VALUES (1,2,3)' - ) - ) - ); - $plugin_list['sql']['options'][] = array( - 'type' => 'end_subgroup' - ); - - /* Max length of query */ - $plugin_list['sql']['options'][] = array( - 'type' => 'text', - 'name' => 'max_query_size', - 'text' => __('Maximal length of created query') - ); - - /* Dump binary columns in hexadecimal */ - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'hex_for_blob', - 'text' => __( - 'Dump binary columns in hexadecimal notation' - . ' (for example, "abc" becomes 0x616263)' - ) - ); - - // Drizzle works only with UTC timezone - if (! PMA_DRIZZLE) { - /* Dump time in UTC */ - $plugin_list['sql']['options'][] = array( - 'type' => 'bool', - 'name' => 'utc_time', - 'text' => __( - 'Dump TIMESTAMP columns in UTC (enables TIMESTAMP columns' - . ' to be dumped and reloaded between servers in different' - . ' time zones)' - ) - ); - } - - $plugin_list['sql']['options'][] = array( - 'type' => 'end_group' - ); - /* end Data options */ - } -} else { - - /** - * Avoids undefined variables, use NULL so isset() returns false - */ - if (! isset($GLOBALS['sql_backquotes'])) { - $GLOBALS['sql_backquotes'] = null; - } - - /** - * Exports routines (procedures and functions) - * - * @param string $db Database - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportRoutines($db) - { - global $crlf; - - $text = ''; - $delimiter = '$$'; - - $procedure_names = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE'); - $function_names = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION'); - - if ($procedure_names || $function_names) { - $text .= $crlf - . 'DELIMITER ' . $delimiter . $crlf; - } - - if ($procedure_names) { - $text .= - PMA_exportComment() - . PMA_exportComment(__('Procedures')) - . PMA_exportComment(); - - foreach ($procedure_names as $procedure_name) { - if (! empty($GLOBALS['sql_drop_table'])) { - $text .= 'DROP PROCEDURE IF EXISTS ' - . PMA_backquote($procedure_name) - . $delimiter . $crlf; - } - $text .= PMA_DBI_get_definition($db, 'PROCEDURE', $procedure_name) - . $delimiter . $crlf . $crlf; - } - } - - if ($function_names) { - $text .= - PMA_exportComment() - . PMA_exportComment(__('Functions')) - . PMA_exportComment(); - - foreach ($function_names as $function_name) { - if (! empty($GLOBALS['sql_drop_table'])) { - $text .= 'DROP FUNCTION IF EXISTS ' - . PMA_backquote($function_name) - . $delimiter . $crlf; - } - $text .= PMA_DBI_get_definition($db, 'FUNCTION', $function_name) - . $delimiter . $crlf . $crlf; - } - } - - if ($procedure_names || $function_names) { - $text .= 'DELIMITER ;' . $crlf; - } - - if (! empty($text)) { - return PMA_exportOutputHandler($text); - } else { - return false; - } - } - - /** - * Possibly outputs comment - * - * @param string $text Text of comment - * - * @return string The formatted comment - * - * @access private - */ - function PMA_exportComment($text = '') - { - if (isset($GLOBALS['sql_include_comments']) - && $GLOBALS['sql_include_comments'] - ) { - // see http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html - return '--' . (empty($text) ? '' : ' ') . $text . $GLOBALS['crlf']; - } else { - return ''; - } - } - - /** - * Possibly outputs CRLF - * - * @return string $crlf or nothing - * - * @access private - */ - function PMA_possibleCRLF() - { - if (isset($GLOBALS['sql_include_comments']) - && $GLOBALS['sql_include_comments'] - ) { - return $GLOBALS['crlf']; - } else { - return ''; - } - } - - /** - * Outputs export footer - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - global $crlf; - global $mysql_charset_map; - - $foot = ''; - - if (isset($GLOBALS['sql_disable_fk'])) { - $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf; - } - - if (isset($GLOBALS['sql_use_transaction'])) { - $foot .= 'COMMIT;' . $crlf; - } - - // restore connection settings - $charset_of_file = isset($GLOBALS['charset_of_file']) - ? $GLOBALS['charset_of_file'] : ''; - if (! empty($GLOBALS['asfile']) - && isset($mysql_charset_map[$charset_of_file]) - && ! PMA_DRIZZLE - ) { - $foot .= $crlf - . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' - . $crlf - . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' - . $crlf - . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' - . $crlf; - } - - /* Restore timezone */ - if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) { - PMA_DBI_query('SET time_zone = "' . $GLOBALS['old_tz'] . '"'); - } - - return PMA_exportOutputHandler($foot); - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - global $crlf; - global $cfg; - global $mysql_charset_map; - - if (isset($GLOBALS['sql_compatibility'])) { - $tmp_compat = $GLOBALS['sql_compatibility']; - if ($tmp_compat == 'NONE') { - $tmp_compat = ''; - } - PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"'); - unset($tmp_compat); - } - $head = PMA_exportComment('phpMyAdmin SQL Dump') - . PMA_exportComment('version ' . PMA_VERSION) - . PMA_exportComment('http://www.phpmyadmin.net') - . PMA_exportComment(); - $host_string = __('Host') . ': ' . $cfg['Server']['host']; - if (! empty($cfg['Server']['port'])) { - $host_string .= ':' . $cfg['Server']['port']; - } - $head .= PMA_exportComment($host_string); - $head .= - PMA_exportComment( - __('Generation Time') . ': ' . PMA_localisedDate() - ) - . PMA_exportComment(__('Server version') . ': ' . PMA_MYSQL_STR_VERSION) - . PMA_exportComment(__('PHP Version') . ': ' . phpversion()) - . PMA_possibleCRLF(); - - if (isset($GLOBALS['sql_header_comment']) - && ! empty($GLOBALS['sql_header_comment']) - ) { - // '\n' is not a newline (like "\n" would be), it's the characters - // backslash and n, as explained on the export interface - $lines = explode('\n', $GLOBALS['sql_header_comment']); - $head .= PMA_exportComment(); - foreach ($lines as $one_line) { - $head .= PMA_exportComment($one_line); - } - $head .= PMA_exportComment(); - } - - if (isset($GLOBALS['sql_disable_fk'])) { - $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf; - } - - // We want exported AUTO_INCREMENT columns to have still same value, - // do this only for recent MySQL exports - if ((! isset($GLOBALS['sql_compatibility']) - || $GLOBALS['sql_compatibility'] == 'NONE') - && ! PMA_DRIZZLE - ) { - $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $crlf; - } - - if (isset($GLOBALS['sql_use_transaction'])) { - $head .= 'SET AUTOCOMMIT = 0;' . $crlf - . 'START TRANSACTION;' . $crlf; - } - - /* Change timezone if we should export timestamps in UTC */ - if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) { - $head .= 'SET time_zone = "+00:00";' . $crlf; - $GLOBALS['old_tz'] = PMA_DBI_fetch_value('SELECT @@session.time_zone'); - PMA_DBI_query('SET time_zone = "+00:00"'); - } - - $head .= PMA_possibleCRLF(); - - if (! empty($GLOBALS['asfile']) && ! PMA_DRIZZLE) { - // we are saving as file, therefore we provide charset information - // so that a utility like the mysql client can interpret - // the file correctly - if (isset($GLOBALS['charset_of_file']) - && isset($mysql_charset_map[$GLOBALS['charset_of_file']]) - ) { - // we got a charset from the export dialog - $set_names = $mysql_charset_map[$GLOBALS['charset_of_file']]; - } else { - // by default we use the connection charset - $set_names = $mysql_charset_map['utf-8']; - } - $head .= $crlf - . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=' - . '@@CHARACTER_SET_CLIENT */;' . $crlf - . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=' - . '@@CHARACTER_SET_RESULTS */;' . $crlf - . '/*!40101 SET @OLD_COLLATION_CONNECTION=' - . '@@COLLATION_CONNECTION */;'. $crlf - . '/*!40101 SET NAMES ' . $set_names . ' */;' . $crlf . $crlf; - } - - return PMA_exportOutputHandler($head); - } - - /** - * Outputs CREATE DATABASE statement - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBCreate($db) - { - global $crlf; - if (isset($GLOBALS['sql_drop_database'])) { - if (! PMA_exportOutputHandler( - 'DROP DATABASE ' - . (isset($GLOBALS['sql_backquotes']) - ? PMA_backquote($db) : $db) - . ';' . $crlf - )) { - return false; - } - } - $create_query = 'CREATE DATABASE ' - . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db); - $collation = PMA_getDbCollation($db); - if (PMA_DRIZZLE) { - $create_query .= ' COLLATE ' . $collation; - } else { - if (strpos($collation, '_')) { - $create_query .= ' DEFAULT CHARACTER SET ' - . substr($collation, 0, strpos($collation, '_')) - . ' COLLATE ' . $collation; - } else { - $create_query .= ' DEFAULT CHARACTER SET ' . $collation; - } - } - $create_query .= ';' . $crlf; - if (! PMA_exportOutputHandler($create_query)) { - return false; - } - if (isset($GLOBALS['sql_backquotes']) - && ((isset($GLOBALS['sql_compatibility']) - && $GLOBALS['sql_compatibility'] == 'NONE') - || PMA_DRIZZLE) - ) { - $result = PMA_exportOutputHandler( - 'USE ' . PMA_backquote($db) . ';' . $crlf - ); - } else { - $result = PMA_exportOutputHandler('USE ' . $db . ';' . $crlf); - } - - return $result; - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - $head = PMA_exportComment() - . PMA_exportComment( - __('Database') . ': ' - . (isset($GLOBALS['sql_backquotes']) - ? PMA_backquote($db) : '\'' . $db . '\'') - ) - . PMA_exportComment(); - return PMA_exportOutputHandler($head); - } - - /** - * Outputs database footer - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBFooter($db) - { - global $crlf; - - $result = true; - if (isset($GLOBALS['sql_constraints'])) { - $result = PMA_exportOutputHandler($GLOBALS['sql_constraints']); - unset($GLOBALS['sql_constraints']); - } - - if (($GLOBALS['sql_structure_or_data'] == 'structure' - || $GLOBALS['sql_structure_or_data'] == 'structure_and_data') - && isset($GLOBALS['sql_procedure_function']) - ) { - $text = ''; - $delimiter = '$$'; - - if (PMA_MYSQL_INT_VERSION > 50100) { - $event_names = PMA_DBI_fetch_result( - 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE' - . ' EVENT_SCHEMA= \'' . PMA_sqlAddSlashes($db, true) . '\';' - ); - } else { - $event_names = array(); - } - - if ($event_names) { - $text .= $crlf - . 'DELIMITER ' . $delimiter . $crlf; - - $text .= - PMA_exportComment() - . PMA_exportComment(__('Events')) - . PMA_exportComment(); - - foreach ($event_names as $event_name) { - if (! empty($GLOBALS['sql_drop_table'])) { - $text .= 'DROP EVENT ' . PMA_backquote($event_name) - . $delimiter . $crlf; - } - $text .= PMA_DBI_get_definition($db, 'EVENT', $event_name) - . $delimiter . $crlf . $crlf; - } - - $text .= 'DELIMITER ;' . $crlf; - } - - if (! empty($text)) { - $result = PMA_exportOutputHandler($text); - } - } - return $result; - } - - /** - * Returns a stand-in CREATE definition to resolve view dependencies - * - * @param string $db the database name - * @param string $view the view name - * @param string $crlf the end of line sequence - * - * @return string resulting definition - * - * @access public - */ - function PMA_getTableDefStandIn($db, $view, $crlf) - { - $create_query = ''; - if (! empty($GLOBALS['sql_drop_table'])) { - $create_query .= 'DROP VIEW IF EXISTS ' . PMA_backquote($view) - . ';' . $crlf; - } - - $create_query .= 'CREATE TABLE '; - - if (isset($GLOBALS['sql_if_not_exists']) - && $GLOBALS['sql_if_not_exists'] - ) { - $create_query .= 'IF NOT EXISTS '; - } - $create_query .= PMA_backquote($view) . ' (' . $crlf; - $tmp = array(); - $columns = PMA_DBI_get_columns_full($db, $view); - foreach ($columns as $column_name => $definition) { - $tmp[] = PMA_backquote($column_name) . ' ' . $definition['Type'] . $crlf; - } - $create_query .= implode(',', $tmp) . ');'; - return($create_query); - } - - /** - * Returns $table's CREATE definition - * - * @param string $db the database name - * @param string $table the table name - * @param string $crlf the end of line sequence - * @param string $error_url the url to go back in case of error - * @param bool $show_dates whether to include creation/update/check dates - * @param bool $add_semicolon whether to add semicolon and end-of-line at - * the end - * @param bool $view whether we're handling a view - * - * @return string resulting schema - * - * @access public - */ - function PMA_getTableDef( - $db, - $table, - $crlf, - $error_url, - $show_dates = false, - $add_semicolon = true, - $view = false - ) { - global $sql_drop_table; - global $sql_backquotes; - global $sql_constraints; - global $sql_constraints_query; // just the text of the query - global $sql_drop_foreign_keys; - - $schema_create = ''; - $auto_increment = ''; - $new_crlf = $crlf; - - // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli - $result = PMA_DBI_query( - 'SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' - . PMA_sqlAddSlashes($table, true) . '\'', - null, - PMA_DBI_QUERY_STORE - ); - if ($result != false) { - if (PMA_DBI_num_rows($result) > 0) { - $tmpres = PMA_DBI_fetch_assoc($result); - if (PMA_DRIZZLE && $show_dates) { - // Drizzle doesn't give Create_time and Update_time in - // SHOW TABLE STATUS, add it - $sql ="SELECT - TABLE_CREATION_TIME AS Create_time, - TABLE_UPDATE_TIME AS Update_time - FROM data_dictionary.TABLES - WHERE TABLE_SCHEMA = '" . PMA_sqlAddSlashes($db) . "' - AND TABLE_NAME = '" . PMA_sqlAddSlashes($table) . "'"; - $tmpres = array_merge(PMA_DBI_fetch_single_row($sql), $tmpres); - } - // Here we optionally add the AUTO_INCREMENT next value, - // but starting with MySQL 5.0.24, the clause is already included - // in SHOW CREATE TABLE so we'll remove it below - // It's required for Drizzle because SHOW CREATE TABLE uses - // the value from table's creation time - if (isset($GLOBALS['sql_auto_increment']) - && ! empty($tmpres['Auto_increment']) - ) { - $auto_increment .= ' AUTO_INCREMENT=' - . $tmpres['Auto_increment'] . ' '; - } - - if ($show_dates - && isset($tmpres['Create_time']) - && ! empty($tmpres['Create_time']) - ) { - $schema_create .= PMA_exportComment( - __('Creation') . ': ' - . PMA_localisedDate(strtotime($tmpres['Create_time'])) - ); - $new_crlf = PMA_exportComment() . $crlf; - } - - if ($show_dates - && isset($tmpres['Update_time']) - && ! empty($tmpres['Update_time']) - ) { - $schema_create .= PMA_exportComment( - __('Last update') . ': ' - . PMA_localisedDate(strtotime($tmpres['Update_time'])) - ); - $new_crlf = PMA_exportComment() . $crlf; - } - - if ($show_dates - && isset($tmpres['Check_time']) - && ! empty($tmpres['Check_time']) - ) { - $schema_create .= PMA_exportComment( - __('Last check') . ': ' - . PMA_localisedDate(strtotime($tmpres['Check_time'])) - ); - $new_crlf = PMA_exportComment() . $crlf; - } - } - PMA_DBI_free_result($result); - } - - $schema_create .= $new_crlf; - - // no need to generate a DROP VIEW here, it was done earlier - if (! empty($sql_drop_table) && ! PMA_Table::isView($db, $table)) { - $schema_create .= 'DROP TABLE IF EXISTS ' - . PMA_backquote($table, $sql_backquotes) . ';' . $crlf; - } - - // Complete table dump, - // Whether to quote table and column names or not - // Drizzle always quotes names - if (! PMA_DRIZZLE) { - if ($sql_backquotes) { - PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1'); - } else { - PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0'); - } - } - - // I don't see the reason why this unbuffered query could cause problems, - // because SHOW CREATE TABLE returns only one row, and we free the - // results below. Nonetheless, we got 2 user reports about this - // (see bug 1562533) so I removed the unbuffered mode. - // $result = PMA_DBI_query('SHOW CREATE TABLE ' . PMA_backquote($db) - // . '.' . PMA_backquote($table), null, PMA_DBI_QUERY_UNBUFFERED); - // - // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not - // produce a displayable result for the default value of a BIT - // column, nor does the mysqldump command. See MySQL bug 35796 - $result = PMA_DBI_try_query( - 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table) - ); - // an error can happen, for example the table is crashed - $tmp_error = PMA_DBI_getError(); - if ($tmp_error) { - return PMA_exportComment(__('in use') . '(' . $tmp_error . ')'); - } - - if ($result != false && ($row = PMA_DBI_fetch_row($result))) { - $create_query = $row[1]; - unset($row); - - // Convert end of line chars to one that we want (note that MySQL - // doesn't return query it will accept in all cases) - if (strpos($create_query, "(\r\n ")) { - $create_query = str_replace("\r\n", $crlf, $create_query); - } elseif (strpos($create_query, "(\n ")) { - $create_query = str_replace("\n", $crlf, $create_query); - } elseif (strpos($create_query, "(\r ")) { - $create_query = str_replace("\r", $crlf, $create_query); - } - - /* - * Drop database name from VIEW creation. - * - * This is a bit tricky, but we need to issue SHOW CREATE TABLE with - * database name, but we don't want name to show up in CREATE VIEW - * statement. - */ - if ($view) { - $create_query = preg_replace( - '/' . PMA_backquote($db) . '\./', - '', - $create_query - ); - } - - // Should we use IF NOT EXISTS? - if (isset($GLOBALS['sql_if_not_exists'])) { - $create_query = preg_replace( - '/^CREATE TABLE/', - 'CREATE TABLE IF NOT EXISTS', - $create_query - ); - } - - // Drizzle (checked on 2011.03.13) returns ROW_FORMAT surrounded - // with quotes, which is not accepted by parser - if (PMA_DRIZZLE) { - $create_query = preg_replace( - '/ROW_FORMAT=\'(\S+)\'/', - 'ROW_FORMAT=$1', - $create_query - ); - } - - // are there any constraints to cut out? - if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) { - - // Split the query into lines, so we can easily handle it. - // We know lines are separated by $crlf (done few lines above). - $sql_lines = explode($crlf, $create_query); - $sql_count = count($sql_lines); - - // lets find first line with constraints - for ($i = 0; $i < $sql_count; $i++) { - if (preg_match( - '@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@', - $sql_lines[$i] - )) { - break; - } - } - - // If we really found a constraint - if ($i != $sql_count) { - - // remove, from the end of create statement - $sql_lines[$i - 1] = preg_replace( - '@,$@', - '', - $sql_lines[$i - 1] - ); - - // prepare variable for constraints - if (! isset($sql_constraints)) { - if (isset($GLOBALS['no_constraints_comments'])) { - $sql_constraints = ''; - } else { - $sql_constraints = $crlf - . PMA_exportComment() - . PMA_exportComment( - __('Constraints for dumped tables') - ) - . PMA_exportComment(); - } - } - - // comments for current table - if (! isset($GLOBALS['no_constraints_comments'])) { - $sql_constraints .= $crlf - . PMA_exportComment() - . PMA_exportComment( - __('Constraints for table') - . ' ' - . PMA_backquote($table) - ) - . PMA_exportComment(); - } - - // let's do the work - $sql_constraints_query .= 'ALTER TABLE ' - . PMA_backquote($table) . $crlf; - $sql_constraints .= 'ALTER TABLE ' - . PMA_backquote($table) . $crlf; - $sql_drop_foreign_keys .= 'ALTER TABLE ' - . PMA_backquote($db) . '.' - . PMA_backquote($table) . $crlf; - - $first = true; - for ($j = $i; $j < $sql_count; $j++) { - if (preg_match( - '@CONSTRAINT|FOREIGN[\s]+KEY@', - $sql_lines[$j] - )) { - if (! $first) { - $sql_constraints .= $crlf; - } - if (strpos($sql_lines[$j], 'CONSTRAINT') === false) { - $tmp_str = preg_replace( - '/(FOREIGN[\s]+KEY)/', - 'ADD \1', - $sql_lines[$j] - ); - $sql_constraints_query .= $tmp_str; - $sql_constraints .= $tmp_str; - } else { - $tmp_str = preg_replace( - '/(CONSTRAINT)/', - 'ADD \1', - $sql_lines[$j] - ); - $sql_constraints_query .= $tmp_str; - $sql_constraints .= $tmp_str; - preg_match( - '/(CONSTRAINT)([\s])([\S]*)([\s])/', - $sql_lines[$j], - $matches - ); - if (! $first) { - $sql_drop_foreign_keys .= ', '; - } - $sql_drop_foreign_keys .= 'DROP FOREIGN KEY ' - . $matches[3]; - } - $first = false; - } else { - break; - } - } - $sql_constraints .= ';' . $crlf; - $sql_constraints_query .= ';'; - - $create_query = implode( - $crlf, - array_slice($sql_lines, 0, $i) - ) - . $crlf - . implode( - $crlf, - array_slice($sql_lines, $j, $sql_count - 1) - ); - unset($sql_lines); - } - } - $schema_create .= $create_query; - } - - // remove a possible "AUTO_INCREMENT = value" clause - // that could be there starting with MySQL 5.0.24 - // in Drizzle it's useless as it contains the value given at table - // creation time - $schema_create = preg_replace( - '/AUTO_INCREMENT\s*=\s*([0-9])+/', - '', - $schema_create - ); - - $schema_create .= $auto_increment; - - PMA_DBI_free_result($result); - return $schema_create . ($add_semicolon ? ';' . $crlf : ''); - } // end of the 'PMA_getTableDef()' function - - /** - * Returns $table's comments, relations etc. - * - * @param string $db database name - * @param string $table table name - * @param string $crlf end of line sequence - * @param bool $do_relation whether to include relation comments - * @param bool $do_mime whether to include mime comments - * - * @return string resulting comments - * - * @access private - */ - function PMA_getTableComments( - $db, - $table, - $crlf, - $do_relation = false, - $do_mime = false - ) { - global $cfgRelation; - global $sql_backquotes; - - $schema_create = ''; - - // Check if we can use Relations - if ($do_relation && ! empty($cfgRelation['relation'])) { - // Find which tables are related with the current one and write it in - // an array - $res_rel = PMA_getForeigners($db, $table); - - if ($res_rel && count($res_rel) > 0) { - $have_rel = true; - } else { - $have_rel = false; - } - } else { - $have_rel = false; - } // end if - - if ($do_mime && $cfgRelation['mimework']) { - if (! ($mime_map = PMA_getMIME($db, $table, true))) { - unset($mime_map); - } - } - - if (isset($mime_map) && count($mime_map) > 0) { - $schema_create .= PMA_possibleCRLF() - . PMA_exportComment() - . PMA_exportComment( - __('MIME TYPES FOR TABLE'). ' ' - . PMA_backquote($table, $sql_backquotes) . ':' - ); - @reset($mime_map); - foreach ($mime_map AS $mime_field => $mime) { - $schema_create .= - PMA_exportComment( - ' ' - . PMA_backquote($mime_field, $sql_backquotes) - ) - . PMA_exportComment( - ' ' - . PMA_backquote($mime['mimetype'], $sql_backquotes) - ); - } - $schema_create .= PMA_exportComment(); - } - - if ($have_rel) { - $schema_create .= PMA_possibleCRLF() - . PMA_exportComment() - . PMA_exportComment( - __('RELATIONS FOR TABLE') . ' ' - . PMA_backquote($table, $sql_backquotes) - . ':' - ); - foreach ($res_rel AS $rel_field => $rel) { - $schema_create .= - PMA_exportComment( - ' ' - . PMA_backquote($rel_field, $sql_backquotes) - ) - . PMA_exportComment( - ' ' - . PMA_backquote($rel['foreign_table'], $sql_backquotes) - . ' -> ' - . PMA_backquote($rel['foreign_field'], $sql_backquotes) - ); - } - $schema_create .= PMA_exportComment(); - } - - return $schema_create; - - } // end of the 'PMA_getTableComments()' function - - /** - * Outputs table's structure - * - * @param string $db database name - * @param string $table table name - * @param string $crlf the end of line sequence - * @param string $error_url the url to go back in case of error - * @param string $export_mode 'create_table','triggers','create_view', - * 'stand_in' - * @param string $export_type 'server', 'database', 'table' - * @param bool $relation whether to include relation comments - * @param bool $comments whether to include the pmadb-style column comments - * as comments in the structure; this is deprecated - * but the parameter is left here because export.php - * calls PMA_exportStructure() also for other export - * types which use this parameter - * @param bool $mime whether to include mime comments - * @param bool $dates whether to include creation/update/check dates - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportStructure( - $db, - $table, - $crlf, - $error_url, - $export_mode, - $export_type, - $relation = false, - $comments = false, - $mime = false, - $dates = false - ) { - $formatted_table_name = (isset($GLOBALS['sql_backquotes'])) - ? PMA_backquote($table) - : '\'' . $table . '\''; - $dump = PMA_possibleCRLF() - . PMA_exportComment(str_repeat('-', 56)) - . PMA_possibleCRLF() - . PMA_exportComment(); - - switch($export_mode) { - case 'create_table': - $dump .= PMA_exportComment( - __('Table structure for table') . ' '. $formatted_table_name - ); - $dump .= PMA_exportComment(); - $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates); - $dump .= PMA_getTableComments($db, $table, $crlf, $relation, $mime); - break; - case 'triggers': - $dump = ''; - $triggers = PMA_DBI_get_triggers($db, $table); - if ($triggers) { - $dump .= PMA_possibleCRLF() - . PMA_exportComment() - . PMA_exportComment( - __('Triggers') . ' ' . $formatted_table_name - ) - . PMA_exportComment(); - $delimiter = '//'; - foreach ($triggers as $trigger) { - $dump .= $trigger['drop'] . ';' . $crlf; - $dump .= 'DELIMITER ' . $delimiter . $crlf; - $dump .= $trigger['create']; - $dump .= 'DELIMITER ;' . $crlf; - } - } - break; - case 'create_view': - $dump .= - PMA_exportComment( - __('Structure for view') - . ' ' - . $formatted_table_name - ) - . PMA_exportComment(); - // delete the stand-in table previously created (if any) - if ($export_type != 'table') { - $dump .= 'DROP TABLE IF EXISTS ' - . PMA_backquote($table) . ';' . $crlf; - } - $dump .= PMA_getTableDef( - $db, $table, $crlf, $error_url, $dates, true, true - ); - break; - case 'stand_in': - $dump .= - PMA_exportComment( - __('Stand-in structure for view') . ' ' . $formatted_table_name - ) - . PMA_exportComment(); - // export a stand-in definition to resolve view dependencies - $dump .= PMA_getTableDefStandIn($db, $table, $crlf); - } // end switch - - // this one is built by PMA_getTableDef() to use in table copy/move - // but not in the case of export - unset($GLOBALS['sql_constraints_query']); - - return PMA_exportOutputHandler($dump); - } - - /** - * Outputs the content of a table in SQL format - * - * @param string $db database name - * @param string $table table name - * @param string $crlf the end of line sequence - * @param string $error_url the url to go back in case of error - * @param string $sql_query SQL query for obtaining data - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportData($db, $table, $crlf, $error_url, $sql_query) - { - global $sql_backquotes; - global $current_row; - - $formatted_table_name = (isset($GLOBALS['sql_backquotes'])) - ? PMA_backquote($table) - : '\'' . $table . '\''; - - // Do not export data for a VIEW - // (For a VIEW, this is called only when exporting a single VIEW) - if (PMA_Table::isView($db, $table)) { - $head = PMA_possibleCRLF() - . PMA_exportComment() - . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name) - . PMA_exportComment(__('Data') . ': ' . __('None')) - . PMA_exportComment() - . PMA_possibleCRLF(); - - if (! PMA_exportOutputHandler($head)) { - return false; - } - return true; - } - - // analyze the query to get the true column names, not the aliases - // (this fixes an undefined index, also if Complete inserts - // are used, we did not get the true column name in case of aliases) - $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query)); - - $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - // a possible error: the table has crashed - $tmp_error = PMA_DBI_getError(); - if ($tmp_error) { - return PMA_exportOutputHandler( - PMA_exportComment( - __('Error reading data:') . ' (' . $tmp_error . ')' - ) - ); - } - - if ($result != false) { - $fields_cnt = PMA_DBI_num_fields($result); - - // Get field information - $fields_meta = PMA_DBI_get_fields_meta($result); - $field_flags = array(); - for ($j = 0; $j < $fields_cnt; $j++) { - $field_flags[$j] = PMA_DBI_field_flags($result, $j); - } - - for ($j = 0; $j < $fields_cnt; $j++) { - if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) { - $field_set[$j] = PMA_backquote( - $analyzed_sql[0]['select_expr'][$j]['column'], - $sql_backquotes - ); - } else { - $field_set[$j] = PMA_backquote( - $fields_meta[$j]->name, - $sql_backquotes - ); - } - } - - if (isset($GLOBALS['sql_type']) - && $GLOBALS['sql_type'] == 'UPDATE' - ) { - // update - $schema_insert = 'UPDATE '; - if (isset($GLOBALS['sql_ignore'])) { - $schema_insert .= 'IGNORE '; - } - // avoid EOL blank - $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET'; - } else { - // insert or replace - if (isset($GLOBALS['sql_type']) - && $GLOBALS['sql_type'] == 'REPLACE' - ) { - $sql_command = 'REPLACE'; - } else { - $sql_command = 'INSERT'; - } - - // delayed inserts? - if (isset($GLOBALS['sql_delayed'])) { - $insert_delayed = ' DELAYED'; - } else { - $insert_delayed = ''; - } - - // insert ignore? - if (isset($GLOBALS['sql_type']) - && $GLOBALS['sql_type'] == 'INSERT' - && isset($GLOBALS['sql_ignore']) - ) { - $insert_delayed .= ' IGNORE'; - } - //truncate table before insert - if (isset($GLOBALS['sql_truncate']) - && $GLOBALS['sql_truncate'] - && $sql_command == 'INSERT' - ) { - $truncate = 'TRUNCATE TABLE ' - . PMA_backquote($table, $sql_backquotes) . ";"; - $truncatehead = PMA_possibleCRLF() - . PMA_exportComment() - . PMA_exportComment( - __('Truncate table before insert') . ' ' - . $formatted_table_name - ) - . PMA_exportComment() - . $crlf; - PMA_exportOutputHandler($truncatehead); - PMA_exportOutputHandler($truncate); - } else { - $truncate = ''; - } - // scheme for inserting fields - if ($GLOBALS['sql_insert_syntax'] == 'complete' - || $GLOBALS['sql_insert_syntax'] == 'both' - ) { - $fields = implode(', ', $field_set); - $schema_insert = $sql_command . $insert_delayed .' INTO ' - . PMA_backquote($table, $sql_backquotes) - // avoid EOL blank - . ' (' . $fields . ') VALUES'; - } else { - $schema_insert = $sql_command . $insert_delayed .' INTO ' - . PMA_backquote($table, $sql_backquotes) - . ' VALUES'; - } - } - - //\x08\\x09, not required - $search = array("\x00", "\x0a", "\x0d", "\x1a"); - $replace = array('\0', '\n', '\r', '\Z'); - $current_row = 0; - $query_size = 0; - if (($GLOBALS['sql_insert_syntax'] == 'extended' - || $GLOBALS['sql_insert_syntax'] == 'both') - && (! isset($GLOBALS['sql_type']) - || $GLOBALS['sql_type'] != 'UPDATE') - ) { - $separator = ','; - $schema_insert .= $crlf; - } else { - $separator = ';'; - } - - while ($row = PMA_DBI_fetch_row($result)) { - if ($current_row == 0) { - $head = PMA_possibleCRLF() - . PMA_exportComment() - . PMA_exportComment( - __('Dumping data for table') . ' ' - . $formatted_table_name - ) - . PMA_exportComment() - . $crlf; - if (! PMA_exportOutputHandler($head)) { - return false; - } - } - $current_row++; - for ($j = 0; $j < $fields_cnt; $j++) { - // NULL - if (! isset($row[$j]) || is_null($row[$j])) { - $values[] = 'NULL'; - } elseif ($fields_meta[$j]->numeric - && $fields_meta[$j]->type != 'timestamp' - && ! $fields_meta[$j]->blob - ) { - // a number - // timestamp is numeric on some MySQL 4.1, BLOBs are - // sometimes numeric - $values[] = $row[$j]; - } elseif (stristr($field_flags[$j], 'BINARY') - && $fields_meta[$j]->blob - && isset($GLOBALS['sql_hex_for_blob']) - ) { - // a true BLOB - // - mysqldump only generates hex data when the --hex-blob - // option is used, for fields having the binary attribute - // no hex is generated - // - a TEXT field returns type blob but a real blob - // returns also the 'binary' flag - - // empty blobs need to be different, but '0' is also empty - // :-( - if (empty($row[$j]) && $row[$j] != '0') { - $values[] = '\'\''; - } else { - $values[] = '0x' . bin2hex($row[$j]); - } - } elseif ($fields_meta[$j]->type == 'bit') { - // detection of 'bit' works only on mysqli extension - $values[] = "b'" . PMA_sqlAddSlashes( - PMA_printableBitValue( - $row[$j], $fields_meta[$j]->length - ) - ) - . "'"; - } else { - // something else -> treat as a string - $values[] = '\'' - . str_replace( - $search, $replace, PMA_sqlAddSlashes($row[$j]) - ) - . '\''; - } // end if - } // end for - - // should we make update? - if (isset($GLOBALS['sql_type']) - && $GLOBALS['sql_type'] == 'UPDATE' - ) { - - $insert_line = $schema_insert; - for ($i = 0; $i < $fields_cnt; $i++) { - if (0 == $i) { - $insert_line .= ' '; - } - if ($i > 0) { - // avoid EOL blank - $insert_line .= ','; - } - $insert_line .= $field_set[$i] . ' = ' . $values[$i]; - } - - list($tmp_unique_condition, $tmp_clause_is_unique) - = PMA_getUniqueCondition( - $result, - $fields_cnt, - $fields_meta, - $row - ); - $insert_line .= ' WHERE ' . $tmp_unique_condition; - unset($tmp_unique_condition, $tmp_clause_is_unique); - - } else { - - // Extended inserts case - if ($GLOBALS['sql_insert_syntax'] == 'extended' - || $GLOBALS['sql_insert_syntax'] == 'both' - ) { - if ($current_row == 1) { - $insert_line = $schema_insert . '(' - . implode(', ', $values) . ')'; - } else { - $insert_line = '(' . implode(', ', $values) . ')'; - $sql_max_size = $GLOBALS['sql_max_query_size']; - if (isset($sql_max_size) - && $sql_max_size > 0 - && $query_size + strlen($insert_line) > $sql_max_size - ) { - if (! PMA_exportOutputHandler(';' . $crlf)) { - return false; - } - $query_size = 0; - $current_row = 1; - $insert_line = $schema_insert . $insert_line; - } - } - $query_size += strlen($insert_line); - // Other inserts case - } else { - $insert_line = $schema_insert - . '(' - . implode(', ', $values) - . ')'; - } - } - unset($values); - - if (! PMA_exportOutputHandler( - ($current_row == 1 ? '' : $separator . $crlf) - . $insert_line - )) { - return false; - } - - } // end while - if ($current_row > 0) { - if (! PMA_exportOutputHandler(';' . $crlf)) { - return false; - } - } - } // end if ($result != false) - PMA_DBI_free_result($result); - - return true; - } // end of the 'PMA_exportData()' function -} -?> diff --git a/libraries/export/texytext.php b/libraries/export/texytext.php deleted file mode 100644 index fd53b05a11..0000000000 --- a/libraries/export/texytext.php +++ /dev/null @@ -1,550 +0,0 @@ - __('Texy! text'), - 'extension' => 'txt', - 'mime_type' => 'text/plain', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['texytext']['options'] = array( - /* what to dump (structure/data/both) */ - array( - 'type' => 'begin_group', - 'text' => __('Dump table'), - 'name' => 'general_opts' - ), - array( - 'type' => 'radio', - 'name' => 'structure_or_data', - 'values' => array( - 'structure' => __('structure'), - 'data' => __('data'), - 'structure_and_data' => __('structure and data') - ) - ), - array( - 'type' => 'end_group' - ), - array( - 'type' => 'begin_group', - 'name' => 'data', - 'text' => __('Data dump options'), - 'force' => 'structure' - ), - array( - 'type' => 'text', - 'name' => 'null', - 'text' => __('Replace NULL by') - ), - array( - 'type' => 'bool', - 'name' => 'columns', - 'text' => __('Put columns names in the first row') - ), - array( - 'type' => 'end_group' - ) - ); -} else { - - /** - * 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 PMA_exportOutputHandler( - '===' . __('Database') . ' ' . $db . "\n\n" - ); - } - - /** - * 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 Texy 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 $what; - - if (! PMA_exportOutputHandler( - '== ' . __('Dumping data for table') . ' ' . $table . "\n\n" - )) { - return false; - } - - // Gets the data from the database - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - $fields_cnt = PMA_DBI_num_fields($result); - - // If required, get fields name at the first line - if (isset($GLOBALS[$what . '_columns'])) { - $text_output = "|------\n"; - for ($i = 0; $i < $fields_cnt; $i++) { - $text_output .= '|' - . htmlspecialchars( - stripslashes(PMA_DBI_field_name($result, $i)) - ); - } // end for - $text_output .= "\n|------\n"; - if (! PMA_exportOutputHandler($text_output)) { - return false; - } - } // end if - - // Format the data - while ($row = PMA_DBI_fetch_row($result)) { - $text_output = ''; - for ($j = 0; $j < $fields_cnt; $j++) { - if (! isset($row[$j]) || is_null($row[$j])) { - $value = $GLOBALS[$what . '_null']; - } elseif ($row[$j] == '0' || $row[$j] != '') { - $value = $row[$j]; - } else { - $value = ' '; - } - $text_output .= '|' - . str_replace( - '|', '|', htmlspecialchars($value) - ); - } // end for - $text_output .= "\n"; - if (! PMA_exportOutputHandler($text_output)) { - return false; - } - } // end while - PMA_DBI_free_result($result); - - return true; - } - - /** - * Returns a stand-in CREATE definition to resolve view dependencies - * - * @param string $db the database name - * @param string $view the view name - * @param string $crlf the end of line sequence - * - * @return string resulting definition - * - * @access public - */ - function PMA_getTableDefStandIn($db, $view, $crlf) - { - $text_output = ''; - - /** - * Get the unique keys in the table - */ - $unique_keys = array(); - $keys = PMA_DBI_get_table_indexes($db, $view); - foreach ($keys as $key) { - if ($key['Non_unique'] == 0) { - $unique_keys[] = $key['Column_name']; - } - } - - /** - * Gets fields properties - */ - PMA_DBI_select_db($db); - - /** - * Displays the table structure - */ - - $text_output .= "|------\n"; - $text_output .= '|' . __('Column'); - $text_output .= '|' . __('Type'); - $text_output .= '|' . __('Null'); - $text_output .= '|' . __('Default'); - $text_output .= "\n|------\n"; - - $columns = PMA_DBI_get_columns($db, $view); - foreach ($columns as $column) { - $text_output .= PMA_formatOneColumnDefinition($column, $unique_keys); - $text_output .= "\n"; - } // end foreach - - return $text_output; - } - - /** - * Returns $table's CREATE definition - * - * @param string $db the database name - * @param string $table the table name - * @param string $crlf the end of line sequence - * @param string $error_url the url to go back in case of error - * @param bool $do_relation whether to include relation comments - * @param bool $do_comments whether to include the pmadb-style column - * comments as comments in the structure; - * this is deprecated but the parameter is - * left here because export.php calls - * PMA_exportStructure() also for other - * export types which use this parameter - * @param bool $do_mime whether to include mime comments - * @param bool $show_dates whether to include creation/update/check dates - * @param bool $add_semicolon whether to add semicolon and end-of-line - * at the end - * @param bool $view whether we're handling a view - * - * @return string resulting schema - * - * @access public - */ - function PMA_getTableDef( - $db, - $table, - $crlf, - $error_url, - $do_relation, - $do_comments, - $do_mime, - $show_dates = false, - $add_semicolon = true, - $view = false - ) { - global $cfgRelation; - - $text_output = ''; - - /** - * Get the unique keys in the table - */ - $unique_keys = array(); - $keys = PMA_DBI_get_table_indexes($db, $table); - foreach ($keys as $key) { - if ($key['Non_unique'] == 0) { - $unique_keys[] = $key['Column_name']; - } - } - - /** - * Gets fields properties - */ - PMA_DBI_select_db($db); - - // Check if we can use Relations - if ($do_relation && ! empty($cfgRelation['relation'])) { - // Find which tables are related with the current one and write it in - // an array - $res_rel = PMA_getForeigners($db, $table); - - if ($res_rel && count($res_rel) > 0) { - $have_rel = true; - } else { - $have_rel = false; - } - } else { - $have_rel = false; - } // end if - - /** - * Displays the table structure - */ - - $columns_cnt = 4; - if ($do_relation && $have_rel) { - $columns_cnt++; - } - if ($do_comments && $cfgRelation['commwork']) { - $columns_cnt++; - } - if ($do_mime && $cfgRelation['mimework']) { - $columns_cnt++; - } - - $text_output .= "|------\n"; - $text_output .= '|' . __('Column'); - $text_output .= '|' . __('Type'); - $text_output .= '|' . __('Null'); - $text_output .= '|' . __('Default'); - if ($do_relation && $have_rel) { - $text_output .= '|' . __('Links to'); - } - if ($do_comments) { - $text_output .= '|' . __('Comments'); - $comments = PMA_getComments($db, $table); - } - if ($do_mime && $cfgRelation['mimework']) { - $text_output .= '|' . htmlspecialchars('MIME'); - $mime_map = PMA_getMIME($db, $table, true); - } - $text_output .= "\n|------\n"; - - $columns = PMA_DBI_get_columns($db, $table); - foreach ($columns as $column) { - $text_output .= PMA_formatOneColumnDefinition($column, $unique_keys); - $field_name = $column['Field']; - - if ($do_relation && $have_rel) { - $text_output .= '|' - . (isset($res_rel[$field_name]) - ? htmlspecialchars( - $res_rel[$field_name]['foreign_table'] - . ' (' . $res_rel[$field_name]['foreign_field'] . ')' - ) - : ''); - } - if ($do_comments && $cfgRelation['commwork']) { - $text_output .= '|' - . (isset($comments[$field_name]) - ? htmlspecialchars($comments[$field_name]) - : ''); - } - if ($do_mime && $cfgRelation['mimework']) { - $text_output .= '|' - . (isset($mime_map[$field_name]) - ? htmlspecialchars( - str_replace('_', '/', $mime_map[$field_name]['mimetype']) - ) - : ''); - } - - $text_output .= "\n"; - } // end foreach - - return $text_output; - } // end of the 'PMA_getTableDef()' function - - /** - * Outputs triggers - * - * @param string $db database name - * @param string $table table name - * - * @return string Formatted triggers list - * - * @access public - */ - function PMA_getTriggers($db, $table) - { - $text_output .= "|------\n"; - $text_output .= '|' . __('Column'); - $dump = "|------\n"; - $dump .= '|' . __('Name'); - $dump .= '|' . __('Time'); - $dump .= '|' . __('Event'); - $dump .= '|' . __('Definition'); - $dump .= "\n|------\n"; - - $triggers = PMA_DBI_get_triggers($db, $table); - - foreach ($triggers as $trigger) { - $dump .= '|' . $trigger['name']; - $dump .= '|' . $trigger['action_timing']; - $dump .= '|' . $trigger['event_manipulation']; - $dump .= '|' . - str_replace( - '|', - '|', - htmlspecialchars($trigger['definition']) - ); - $dump .= "\n"; - } - - return $dump; - } - - /** - * 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 - ) { - $dump = ''; - - switch($export_mode) { - case 'create_table': - $dump .= '== ' . __('Table structure for table') . ' ' .$table . "\n\n"; - $dump .= PMA_getTableDef( - $db, $table, $crlf, $error_url, $do_relation, $do_comments, - $do_mime, $dates - ); - break; - case 'triggers': - $dump = ''; - $triggers = PMA_DBI_get_triggers($db, $table); - if ($triggers) { - $dump .= '== ' . __('Triggers') . ' ' .$table . "\n\n"; - $dump .= PMA_getTriggers($db, $table); - } - break; - case 'create_view': - $dump .= '== ' . __('Structure for view') . ' ' .$table . "\n\n"; - $dump .= PMA_getTableDef( - $db, $table, $crlf, $error_url, $do_relation, $do_comments, - $do_mime, $dates, true, true - ); - break; - case 'stand_in': - $dump .= '== ' . __('Stand-in structure for view') - . ' ' .$table . "\n\n"; - // export a stand-in definition to resolve view dependencies - $dump .= PMA_getTableDefStandIn($db, $table, $crlf); - } // end switch - - return PMA_exportOutputHandler($dump); - } - - /** - * Formats the definition for one column - * - * @param array $column info about this column - * @param array $unique_keys unique keys for this table - * - * @return string Formatted column definition - * - * @access public - */ - function PMA_formatOneColumnDefinition( - $column, $unique_keys - ) { - $extracted_columnspec = PMA_extractColumnSpec($column['Type']); - $type = $extracted_columnspec['print_type']; - if (empty($type)) { - $type = ' '; - } - - if (! isset($column['Default'])) { - if ($column['Null'] != 'NO') { - $column['Default'] = 'NULL'; - } - } - - $fmt_pre = ''; - $fmt_post = ''; - if (in_array($column['Field'], $unique_keys)) { - $fmt_pre = '**' . $fmt_pre; - $fmt_post = $fmt_post . '**'; - } - if ($column['Key']=='PRI') { - $fmt_pre = '//' . $fmt_pre; - $fmt_post = $fmt_post . '//'; - } - $definition = '|' - . $fmt_pre . htmlspecialchars($column['Field']) . $fmt_post; - $definition .= '|' . htmlspecialchars($type); - $definition .= '|' - . (($column['Null'] == '' || $column['Null'] == 'NO') - ? __('No') : __('Yes')); - $definition .= '|' - . htmlspecialchars( - isset($column['Default']) ? $column['Default'] : '' - ); - return $definition; - } -} -?> diff --git a/libraries/export/xml.php b/libraries/export/xml.php deleted file mode 100644 index 7192d8c082..0000000000 --- a/libraries/export/xml.php +++ /dev/null @@ -1,434 +0,0 @@ - __('XML'), - 'extension' => 'xml', - 'mime_type' => 'text/xml', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['xml']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data' - ), - array( - 'type' => 'end_group' - ) - ); - - /* Export structure */ - $plugin_list['xml']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'structure', - 'text' => __('Object creation options (all are recommended)') - ); - if (! PMA_DRIZZLE) { - $plugin_list['xml']['options'][] = array( - 'type' => 'bool', - 'name' => 'export_functions', - 'text' => __('Functions') - ); - $plugin_list['xml']['options'][] = array( - 'type' => 'bool', - 'name' => 'export_procedures', - 'text' => __('Procedures') - ); - } - $plugin_list['xml']['options'][] = array( - 'type' => 'bool', - 'name' => 'export_tables', - 'text' => __('Tables') - ); - if (! PMA_DRIZZLE) { - $plugin_list['xml']['options'][] = array( - 'type' => 'bool', - 'name' => 'export_triggers', - 'text' => __('Triggers') - ); - $plugin_list['xml']['options'][] = array( - 'type' => 'bool', - 'name' => 'export_views', - 'text' => __('Views') - ); - } - $plugin_list['xml']['options'][] = array( - 'type' => 'end_group' - ); - - /* Data */ - $plugin_list['xml']['options'][] = array( - 'type' => 'begin_group', - 'name' => 'data', - 'text' => __('Data dump options') - ); - $plugin_list['xml']['options'][] = array( - 'type' => 'bool', - 'name' => 'export_contents', - 'text' => __('Export contents') - ); - $plugin_list['xml']['options'][] = array( - 'type' => 'end_group' - ); -} else { - - /** - * Outputs export footer - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - $foot = ''; - - return PMA_exportOutputHandler($foot); - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - global $crlf; - global $cfg; - global $db; - global $table; - global $tables; - - $export_struct = isset($GLOBALS['xml_export_functions']) - || isset($GLOBALS['xml_export_procedures']) - || isset($GLOBALS['xml_export_tables']) - || isset($GLOBALS['xml_export_triggers']) - || isset($GLOBALS['xml_export_views']); - $export_data = isset($GLOBALS['xml_export_contents']) ? true : false; - - if ($GLOBALS['output_charset_conversion']) { - $charset = $GLOBALS['charset_of_file']; - } else { - $charset = 'utf-8'; - } - - $head = '' . $crlf - . '' . $crlf . $crlf; - - $head .= '' . $crlf; - - if ($export_struct) { - if (PMA_DRIZZLE) { - $result = PMA_DBI_fetch_result( - "SELECT - 'utf8' AS DEFAULT_CHARACTER_SET_NAME, - DEFAULT_COLLATION_NAME - FROM data_dictionary.SCHEMAS - WHERE SCHEMA_NAME = '" . PMA_sqlAddSlashes($db) . "'" - ); - } else { - $result = PMA_DBI_fetch_result( - 'SELECT `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`' - . ' FROM `information_schema`.`SCHEMATA` WHERE `SCHEMA_NAME`' - . ' = \''.PMA_sqlAddSlashes($db).'\' LIMIT 1' - ); - } - $db_collation = $result[0]['DEFAULT_COLLATION_NAME']; - $db_charset = $result[0]['DEFAULT_CHARACTER_SET_NAME']; - - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; - - if (count($tables) == 0) { - $tables[] = $table; - } - - foreach ($tables as $table) { - // Export tables and views - $result = PMA_DBI_fetch_result( - 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' - . PMA_backquote($table), - 0 - ); - $tbl = $result[$table][1]; - - $is_view = PMA_Table::isView($db, $table); - - if ($is_view) { - $type = 'view'; - } else { - $type = 'table'; - } - - if ($is_view && ! isset($GLOBALS['xml_export_views'])) { - continue; - } - - if (! $is_view && ! isset($GLOBALS['xml_export_tables'])) { - continue; - } - - $head .= ' ' - . $crlf; - - $tbl = " " . htmlspecialchars($tbl); - $tbl = str_replace("\n", "\n ", $tbl); - - $head .= $tbl . ';' . $crlf; - $head .= ' ' . $crlf; - - if (isset($GLOBALS['xml_export_triggers']) - && $GLOBALS['xml_export_triggers'] - ) { - // Export triggers - $triggers = PMA_DBI_get_triggers($db, $table); - if ($triggers) { - foreach ($triggers as $trigger) { - $code = $trigger['create']; - $head .= ' ' . $crlf; - - // Do some formatting - $code = substr(rtrim($code), 0, -3); - $code = " " . htmlspecialchars($code); - $code = str_replace("\n", "\n ", $code); - - $head .= $code . $crlf; - $head .= ' ' . $crlf; - } - - unset($trigger); - unset($triggers); - } - } - } - - if (isset($GLOBALS['xml_export_functions']) - && $GLOBALS['xml_export_functions'] - ) { - // Export functions - $functions = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION'); - if ($functions) { - foreach ($functions as $function) { - $head .= ' ' . $crlf; - - // Do some formatting - $sql = PMA_DBI_get_definition($db, 'FUNCTION', $function); - $sql = rtrim($sql); - $sql = " " . htmlspecialchars($sql); - $sql = str_replace("\n", "\n ", $sql); - - $head .= $sql . $crlf; - $head .= ' ' . $crlf; - } - - unset($function); - unset($functions); - } - } - - if (isset($GLOBALS['xml_export_procedures']) - && $GLOBALS['xml_export_procedures'] - ) { - // Export procedures - $procedures = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE'); - if ($procedures) { - foreach ($procedures as $procedure) { - $head .= ' ' . $crlf; - - // Do some formatting - $sql = PMA_DBI_get_definition($db, 'PROCEDURE', $procedure); - $sql = rtrim($sql); - $sql = " " . htmlspecialchars($sql); - $sql = str_replace("\n", "\n ", $sql); - - $head .= $sql . $crlf; - $head .= ' ' . $crlf; - } - - unset($procedure); - unset($procedures); - } - } - - unset($result); - - $head .= ' ' . $crlf; - $head .= ' ' . $crlf; - - if ($export_data) { - $head .= $crlf; - } - } - - return PMA_exportOutputHandler($head); - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - global $crlf; - - if (isset($GLOBALS['xml_export_contents']) - && $GLOBALS['xml_export_contents'] - ) { - $head = ' ' . $crlf - . ' ' . $crlf; - - return PMA_exportOutputHandler($head); - } else { - return true; - } - } - - /** - * Outputs database footer - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBFooter($db) - { - global $crlf; - - if (isset($GLOBALS['xml_export_contents']) - && $GLOBALS['xml_export_contents'] - ) { - return PMA_exportOutputHandler(' ' . $crlf); - } else { - 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 XML 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) - { - if (isset($GLOBALS['xml_export_contents']) - && $GLOBALS['xml_export_contents'] - ) { - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - - $columns_cnt = PMA_DBI_num_fields($result); - $columns = array(); - for ($i = 0; $i < $columns_cnt; $i++) { - $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); - } - unset($i); - - $buffer = ' ' . $crlf; - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - - while ($record = PMA_DBI_fetch_row($result)) { - $buffer = '
'; - if (isset($GLOBALS['allowDeny_forbidden']) && $GLOBALS['allowDeny_forbidden']) { + 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"; + 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 + // 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); + 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); } diff --git a/libraries/plugins/auth/AuthenticationCookie.class.php b/libraries/plugins/auth/AuthenticationCookie.class.php index bfdac06792..7cbfc9cbc0 100644 --- a/libraries/plugins/auth/AuthenticationCookie.class.php +++ b/libraries/plugins/auth/AuthenticationCookie.class.php @@ -43,7 +43,8 @@ class AuthenticationCookie extends AuthenticationPlugin /** * Constructor */ - function __construct() { + function __construct() + { /** * Initialization * Store the initialization vector because it will be needed for @@ -51,15 +52,20 @@ class AuthenticationCookie extends AuthenticationPlugin * per server so I don't put the server number in the cookie name. */ if (empty($_COOKIE['pma_mcrypt_iv']) - || false === ($this->_setIv(base64_decode($_COOKIE['pma_mcrypt_iv'], true))) + || ! ($this->_setIv(base64_decode($_COOKIE['pma_mcrypt_iv'], true))) ) { srand((double) microtime() * 1000000); $td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, ''); if ($td === false) { PMA_fatalError(__('Failed to use Blowfish from mcrypt!')); } - $this->_setIv(mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND)); - $GLOBALS['PMA_Config']->setCookie('pma_mcrypt_iv', base64_encode($this->_getIv())); + $this->_setIv( + mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND) + ); + $GLOBALS['PMA_Config']->setCookie( + 'pma_mcrypt_iv', + base64_encode($this->_getIv()) + ); } } @@ -82,7 +88,12 @@ class AuthenticationCookie extends AuthenticationPlugin if (! empty($conn_error)) { $response->addJSON('message', $conn_error); } else { - $response->addJSON('message', PMA_Message::error(__('Your session has expired. Please login again.'))); + $response->addJSON( + 'message', + PMA_Message::error( + __('Your session has expired. Please login again.') + ) + ); } exit; } @@ -95,7 +106,8 @@ class AuthenticationCookie extends AuthenticationPlugin exit; } - /* No recall if blowfish secret is not configured as it would produce garbage */ + // No recall if blowfish secret is not configured as it would produce + // garbage if ($GLOBALS['cfg']['LoginCookieRecall'] && ! empty($GLOBALS['cfg']['blowfish_secret']) ) { @@ -121,10 +133,11 @@ class AuthenticationCookie extends AuthenticationPlugin if (file_exists(CUSTOM_HEADER_FILE)) { include CUSTOM_HEADER_FILE; } - ?> - + echo '
- -

- +

'; echo sprintf( __('Welcome to %s'), 'phpMyAdmin' ); - ?> -

- "; // Show error message if (! empty($conn_error)) { @@ -151,7 +161,9 @@ class AuthenticationCookie extends AuthenticationPlugin } echo "\n"; echo "
"; @@ -161,43 +173,53 @@ class AuthenticationCookie extends AuthenticationPlugin // use fieldset, don't show doc link PMA_select_language(true, false); } - echo "
"; - - ?> + echo '

-
target="_top" class="login hide js-show"> +
- - '; echo __('Log in'); echo PMA_showDocu(''); - ?> - - - + echo ''; + if ($GLOBALS['cfg']['AllowArbitraryServer']) { + echo '
- - -
- -
- - + + +
'; + } + echo '
+ +
- - -
- ' . __('Password:') . ' + + '; if (count($GLOBALS['cfg']['Servers']) > 1) { - ?> -
- - '; @@ -206,13 +228,13 @@ class AuthenticationCookie extends AuthenticationPlugin echo '
'; } else { - echo ' '; + echo ' '; } // end if (server choice) - ?> -
+ + echo '
- - '; $_form_params = array(); if (! empty($GLOBALS['target'])) { $_form_params['target'] = $GLOBALS['target']; @@ -226,11 +248,8 @@ class AuthenticationCookie extends AuthenticationPlugin // 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'); - ?> -
-
- - + '; // BEGIN Swekey Integration Swekey_login('input_username', 'input_go'); @@ -246,24 +265,20 @@ class AuthenticationCookie extends AuthenticationPlugin $GLOBALS['error_handler']->dispErrors(); echo ''; } - ?> - - '; if (file_exists(CUSTOM_FOOTER_FILE)) { include CUSTOM_FOOTER_FILE; } - ?> + echo ' - '; exit; - } /** @@ -281,8 +296,8 @@ class AuthenticationCookie extends AuthenticationPlugin * 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 + * 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 */ @@ -290,7 +305,8 @@ class AuthenticationCookie extends AuthenticationPlugin { // Initialization /** - * @global $GLOBALS['pma_auth_server'] the user provided server to connect to + * @global $GLOBALS['pma_auth_server'] the user provided server to + * connect to */ $GLOBALS['pma_auth_server'] = ''; @@ -329,7 +345,9 @@ class AuthenticationCookie extends AuthenticationPlugin } } } else { - $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']); + $GLOBALS['PMA_Config']->removeCookie( + 'pmaPass-' . $GLOBALS['server'] + ); if (isset($_COOKIE['pmaPass-' . $GLOBALS['server']])) { unset($_COOKIE['pmaPass-' . $GLOBALS['server']]); } @@ -357,7 +375,8 @@ class AuthenticationCookie extends AuthenticationPlugin if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($_COOKIE['pmaServer-' . $GLOBALS['server']]) ) { - $GLOBALS['pma_auth_server'] = $_COOKIE['pmaServer-' . $GLOBALS['server']]; + $GLOBALS['pma_auth_server'] + = $_COOKIE['pmaServer-' . $GLOBALS['server']]; } // username @@ -367,7 +386,7 @@ class AuthenticationCookie extends AuthenticationPlugin $GLOBALS['PHP_AUTH_USER'] = $this->blowfishDecrypt( $_COOKIE['pmaUser-' . $GLOBALS['server']], - $this->getBlowfishSecret() + $this->_getBlowfishSecret() ); // user was never logged in since session start @@ -376,7 +395,9 @@ class AuthenticationCookie extends AuthenticationPlugin } // User inactive too long - if ($_SESSION['last_access_time'] < time() - $GLOBALS['cfg']['LoginCookieValidity']) { + $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); @@ -394,7 +415,7 @@ class AuthenticationCookie extends AuthenticationPlugin $GLOBALS['PHP_AUTH_PW'] = $this->blowfishDecrypt( $_COOKIE['pmaPass-' . $GLOBALS['server']], - $this->getBlowfishSecret() + $this->_getBlowfishSecret() ); if ($GLOBALS['PHP_AUTH_PW'] == "\xff(blank)") { @@ -468,7 +489,7 @@ class AuthenticationCookie extends AuthenticationPlugin 'pmaUser-' . $GLOBALS['server'], $this->blowfishEncrypt( $cfg['Server']['user'], - $this->getBlowfishSecret() + $this->_getBlowfishSecret() ) ); @@ -476,15 +497,16 @@ class AuthenticationCookie extends AuthenticationPlugin $GLOBALS['PMA_Config']->setCookie( 'pmaPass-' . $GLOBALS['server'], $this->blowfishEncrypt( - ! empty($cfg['Server']['password']) ? $cfg['Server']['password'] : "\xff(blank)", - $this->getBlowfishSecret() + ! 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 + // 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'])) { @@ -513,7 +535,9 @@ class AuthenticationCookie extends AuthenticationPlugin $url_params['table'] = $GLOBALS['table']; } // any target to pass? - if (! empty($GLOBALS['target']) && $GLOBALS['target'] != 'index.php') { + if (! empty($GLOBALS['target']) + && $GLOBALS['target'] != 'index.php' + ) { $url_params['target'] = $GLOBALS['target']; } @@ -554,11 +578,17 @@ class AuthenticationCookie extends AuthenticationPlugin $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)'); + $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']); + $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')); @@ -586,7 +616,7 @@ class AuthenticationCookie extends AuthenticationPlugin * * @return string */ - public function getBlowfishSecret () + private function _getBlowfishSecret() { if (empty($GLOBALS['cfg']['blowfish_secret'])) { if (empty($_SESSION['auto_blowfish_secret'])) { @@ -611,34 +641,21 @@ class AuthenticationCookie extends AuthenticationPlugin public function blowfishEncrypt($data, $secret) { if (! function_exists('mcrypt_encrypt')) { - include_once("HordeCipherBlowfishOperations.class.php"); + include_once "HordeCipherBlowfishOperations.class.php"; return HordeCipherBlowfishOperations::blowfishEncrypt($data, $secret); } return base64_encode( - mcrypt_encrypt(MCRYPT_BLOWFISH, $secret, $data, MCRYPT_MODE_CBC, $this->_getIv()) + mcrypt_encrypt( + MCRYPT_BLOWFISH, + $secret, + $data, + MCRYPT_MODE_CBC, + $this->_getIv() + ) ); } - /** - * 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']); - } - } - /** * Decryption using blowfish algorithm (mcrypt) * @@ -648,9 +665,9 @@ class AuthenticationCookie extends AuthenticationPlugin * @return string original data */ public function blowfishDecrypt($encdata, $secret) - { + { if (! function_exists('mcrypt_encrypt')) { - include_once("HordeCipherBlowfishOperations.class.php"); + include_once "HordeCipherBlowfishOperations.class.php"; return HordeCipherBlowfishOperations::blowfishDecrypt( $encdata, $secret diff --git a/libraries/plugins/auth/AuthenticationHTTP.class.php b/libraries/plugins/auth/AuthenticationHTTP.class.php index a52f0a580b..3cfe3fe335 100644 --- a/libraries/plugins/auth/AuthenticationHTTP.class.php +++ b/libraries/plugins/auth/AuthenticationHTTP.class.php @@ -64,16 +64,17 @@ class AuthenticationHTTP extends AuthenticationPlugin $header = $response->getHeader(); $header->setTitle(__('Access denied')); $header->disableMenu(); - - ?> + echo '

-

+

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

-
- - display(); +
' . + PMA_Message::error( + __('Wrong username/password. Access denied.') + )->display(); if (file_exists(CUSTOM_FOOTER_FILE)) { include CUSTOM_FOOTER_FILE; diff --git a/libraries/plugins/auth/AuthenticationSignOn.class.php b/libraries/plugins/auth/AuthenticationSignOn.class.php index b4f93b5ad0..463da00086 100644 --- a/libraries/plugins/auth/AuthenticationSignOn.class.php +++ b/libraries/plugins/auth/AuthenticationSignOn.class.php @@ -67,8 +67,9 @@ class AuthenticationSignOn extends AuthenticationPlugin global $PHP_AUTH_USER, $PHP_AUTH_PW; /* Check if we're using same sigon server */ + $signon_url = $GLOBALS['cfg']['Server']['SignonURL']; if (isset($_SESSION['LAST_SIGNON_URL']) - && $_SESSION['LAST_SIGNON_URL'] != $GLOBALS['cfg']['Server']['SignonURL'] + && $_SESSION['LAST_SIGNON_URL'] != $signon_url ) { return false; } @@ -98,7 +99,8 @@ class AuthenticationSignOn extends AuthenticationPlugin if (!empty($script_name)) { if (! file_exists($script_name)) { PMA_fatalError( - __('Can not find signon authentication script:') . ' ' . $script_name + __('Can not find signon authentication script:') + . ' '. $script_name ); } include $script_name; @@ -196,7 +198,7 @@ class AuthenticationSignOn extends AuthenticationPlugin return true; } } - + /** * Set the user and password after last checkings if required * @@ -243,15 +245,25 @@ class AuthenticationSignOn extends AuthenticationPlugin /* 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)'); + $_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']); + $_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()); + $_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'); + $_SESSION['PMA_single_signon_error_message'] = __( + 'Cannot log in to the MySQL server' + ); } } $this->auth(); @@ -264,7 +276,7 @@ class AuthenticationSignOn extends AuthenticationPlugin * @param SplSubject $subject The PluginManager notifying the observer * of an update. * - * @return void + * @return void */ public function update (SplSubject $subject) { diff --git a/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php b/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php index 8b6447008d..ac1f728742 100644 --- a/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php +++ b/libraries/plugins/auth/HordeCipherBlowfishOperations.class.php @@ -2,7 +2,7 @@ /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Auxiliary functions for cookie authentication - * + * * @package PhpMyAdmin-Auth * @subpackage Cookie */ @@ -12,10 +12,12 @@ if (! defined('PHPMYADMIN')) { /* Get the Horde_Cipher_blowfish class */ require_once './libraries/blowfish.php'; - + /** * The HordeCipherBlowfishOperations provides encrypt and decrypt functions * using the Horde_Cipher_blowfish class + * + * @package PhpMyAdmin-Auth */ class HordeCipherBlowfishOperations { From 1df5cc8eae24a6f45707fc43939de2ab07ac4063 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 11:05:53 +0300 Subject: [PATCH 48/55] oop: remake PMA_blowfish_test --- test/libraries/PMA_blowfish_test.php | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/test/libraries/PMA_blowfish_test.php b/test/libraries/PMA_blowfish_test.php index f24d07c722..f3ff4093e7 100644 --- a/test/libraries/PMA_blowfish_test.php +++ b/test/libraries/PMA_blowfish_test.php @@ -10,6 +10,7 @@ * Include to test. */ require_once 'libraries/blowfish.php'; +require_once 'libraries/plugins/auth/HordeCipherBlowfishOperations.class.php'; class PMA_blowfish_test extends PHPUnit_Framework_TestCase { @@ -19,7 +20,10 @@ class PMA_blowfish_test extends PHPUnit_Framework_TestCase $string = '12345678'; $this->assertEquals( $string, - PMA_blowfish_decrypt(PMA_blowfish_encrypt($string, $secret), $secret) + HordeCipherBlowfishOperations::blowfishDecrypt( + HordeCipherBlowfishOperations::blowfishEncrypt($string, $secret), + $secret + ) ); } @@ -29,7 +33,10 @@ class PMA_blowfish_test extends PHPUnit_Framework_TestCase $string = 'abcDEF012!"§$%&/()=?`´"\',.;:-_#+*~öäüÖÄÜ^°²³'; $this->assertEquals( $string, - PMA_blowfish_decrypt(PMA_blowfish_encrypt($string, $secret), $secret) + HordeCipherBlowfishOperations::blowfishDecrypt( + HordeCipherBlowfishOperations::blowfishEncrypt($string, $secret), + $secret + ) ); } @@ -39,7 +46,10 @@ class PMA_blowfish_test extends PHPUnit_Framework_TestCase $secret = '$%ÄüfuDFRR'; $decrypted = '12345678'; $encrypted = 'kO/kc4j/nyk='; - $this->assertEquals($encrypted, PMA_blowfish_encrypt($decrypted, $secret)); + $this->assertEquals( + $encrypted, + HordeCipherBlowfishOperations::blowfishEncrypt($decrypted, $secret) + ); } public function testDecrypt() @@ -47,9 +57,12 @@ class PMA_blowfish_test extends PHPUnit_Framework_TestCase $secret = '$%ÄüfuDFRR'; $encrypted = 'kO/kc4j/nyk='; $decrypted = '12345678'; - $this->assertEquals($decrypted, PMA_blowfish_decrypt($encrypted, $secret)); + $this->assertEquals( + $decrypted, + HordeCipherBlowfishOperations::blowfishDecrypt($encrypted, $secret) + ); } */ } -?> +?> \ No newline at end of file From 0565b0e12aef4456f0172669659d63ebb1659c4f Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 11:43:54 +0300 Subject: [PATCH 49/55] oop: integrate authentication plugins --- libraries/common.inc.php | 19 ++++++++----- libraries/dbi/drizzle.dbi.lib.php | 3 ++- libraries/dbi/mysql.dbi.lib.php | 3 ++- libraries/dbi/mysqli.dbi.lib.php | 3 ++- ...class.php => AuthenticationHttp.class.php} | 2 +- ...ass.php => AuthenticationSignon.class.php} | 2 +- user_password.php | 27 ++++++++++++++----- 7 files changed, 41 insertions(+), 18 deletions(-) rename libraries/plugins/auth/{AuthenticationHTTP.class.php => AuthenticationHttp.class.php} (99%) rename libraries/plugins/auth/{AuthenticationSignOn.class.php => AuthenticationSignon.class.php} (99%) diff --git a/libraries/common.inc.php b/libraries/common.inc.php index e0eb6e786c..dd79390e26 100644 --- a/libraries/common.inc.php +++ b/libraries/common.inc.php @@ -847,13 +847,18 @@ if (! defined('PMA_MINIMUM_COMMON')) { /** * the required auth type plugin */ - include_once './libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php'; - if (! PMA_auth_check()) { + $auth_class = "Authentication" + . strtoupper(substr($cfg['Server']['auth_type'], 0, 1)) + . strtolower(substr($cfg['Server']['auth_type'], 1)); + include_once './libraries/plugins/auth/' . $auth_class . '.class.php'; + $auth_plugin = new $auth_class; + + 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 +902,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 +910,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/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/plugins/auth/AuthenticationHTTP.class.php b/libraries/plugins/auth/AuthenticationHttp.class.php similarity index 99% rename from libraries/plugins/auth/AuthenticationHTTP.class.php rename to libraries/plugins/auth/AuthenticationHttp.class.php index 3cfe3fe335..89eeab9a5f 100644 --- a/libraries/plugins/auth/AuthenticationHTTP.class.php +++ b/libraries/plugins/auth/AuthenticationHttp.class.php @@ -19,7 +19,7 @@ require_once "libraries/plugins/AuthenticationPlugin.class.php"; * * @package PhpMyAdmin-Authentication */ -class AuthenticationHTTP extends AuthenticationPlugin +class AuthenticationHttp extends AuthenticationPlugin { /** * Displays authentication form diff --git a/libraries/plugins/auth/AuthenticationSignOn.class.php b/libraries/plugins/auth/AuthenticationSignon.class.php similarity index 99% rename from libraries/plugins/auth/AuthenticationSignOn.class.php rename to libraries/plugins/auth/AuthenticationSignon.class.php index 463da00086..ba109d1850 100644 --- a/libraries/plugins/auth/AuthenticationSignOn.class.php +++ b/libraries/plugins/auth/AuthenticationSignon.class.php @@ -18,7 +18,7 @@ require_once "libraries/plugins/AuthenticationPlugin.class.php"; * * @package PhpMyAdmin-Authentication */ -class AuthenticationSignOn extends AuthenticationPlugin +class AuthenticationSignon extends AuthenticationPlugin { /** * Displays authentication form diff --git a/user_password.php b/user_password.php index 69086d7e5b..1dc9145a07 100644 --- a/user_password.php +++ b/user_password.php @@ -25,7 +25,9 @@ if (! $cfg['ShowChgPassword']) { $cfg['ShowChgPassword'] = PMA_DBI_select_db('mysql'); } if ($cfg['Server']['auth_type'] == 'config' || ! $cfg['ShowChgPassword']) { - PMA_Message::error(__('You don\'t have sufficient privileges to be here right now!'))->display(); + PMA_Message::error( + __('You don\'t have sufficient privileges to be here right now!') + )->display(); exit; } // end if @@ -164,7 +166,9 @@ function PMA_changePassHashingFunction() function PMA_ChangePassUrlParamsAndSubmitQuery($password, $_url_params, $sql_query, $hashing_function) { $err_url = 'user_password.php' . PMA_generate_common_url($_url_params); - $local_query = 'SET password = ' . (($password == '') ? '\'\'' : $hashing_function . '(\'' . PMA_sqlAddSlashes($password) . '\')'); + $local_query = 'SET password = ' . (($password == '') + ? '\'\'' + : $hashing_function . '(\'' . PMA_sqlAddSlashes($password) . '\')'); $result = @PMA_DBI_try_query($local_query) or PMA_mysqlDie(PMA_DBI_getError(), $sql_query, false, $err_url); } @@ -181,12 +185,22 @@ function PMA_changePassAuthType($_url_params, $password) { /** * Changes password cookie if required - * Duration = till the browser is closed for password (we don't want this to be saved) + * Duration = till the browser is closed for password + * (we don't want this to be saved) */ + + // include_once "libraries/plugins/auth/AuthenticationCookie.class.php"; + // $auth_plugin = new AuthenticationCookie(); + // the $auth_plugin is already defined in common.lib.php when this is used + global $auth_plugin; + if ($GLOBALS['cfg']['Server']['auth_type'] == 'cookie') { $GLOBALS['PMA_Config']->setCookie( 'pmaPass-' . $GLOBALS['server'], - PMA_blowfish_encrypt($password, $GLOBALS['cfg']['blowfish_secret']) + $auth_plugin->blowfishEncrypt( + $password, + $GLOBALS['cfg']['blowfish_secret'] + ) ); } /** @@ -212,8 +226,9 @@ function PMA_changePassDisplayPage($message, $sql_query, $_url_params) { echo '

' . __('Change password') . '

' . "\n\n"; echo PMA_getMessage($message, $sql_query, 'success'); - echo ''. "\n" - .''.__('Back').''; + echo ''. "\n" + .''.__('Back').''; exit; } ?> From 65467e9c77a7ca91c462bfcac91efc56423e9324 Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 15:38:54 +0300 Subject: [PATCH 50/55] oop: AuthenticationCookie bug --- libraries/common.inc.php | 4 +- .../auth/AuthenticationCookie.class.php | 91 ++++++------------- 2 files changed, 30 insertions(+), 65 deletions(-) diff --git a/libraries/common.inc.php b/libraries/common.inc.php index dd79390e26..be92bc925f 100644 --- a/libraries/common.inc.php +++ b/libraries/common.inc.php @@ -851,7 +851,9 @@ if (! defined('PMA_MINIMUM_COMMON')) { . strtoupper(substr($cfg['Server']['auth_type'], 0, 1)) . strtolower(substr($cfg['Server']['auth_type'], 1)); include_once './libraries/plugins/auth/' . $auth_class . '.class.php'; - $auth_plugin = new $auth_class; + // 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 */ diff --git a/libraries/plugins/auth/AuthenticationCookie.class.php b/libraries/plugins/auth/AuthenticationCookie.class.php index 7cbfc9cbc0..e745cba39a 100644 --- a/libraries/plugins/auth/AuthenticationCookie.class.php +++ b/libraries/plugins/auth/AuthenticationCookie.class.php @@ -26,6 +26,29 @@ if (! empty($_REQUEST['target'])) { */ require './libraries/plugins/auth/swekey/swekey.auth.lib.php'; +/** + * Initialization + * Store the initialization vector because it will be needed for + * further decryption. I don't think necessary to have one iv + * per server so I don't put the server number in the cookie name. + */ +if (function_exists('mcrypt_encrypt')) { + if (empty($_COOKIE['pma_mcrypt_iv']) + || ! ($iv = base64_decode($_COOKIE['pma_mcrypt_iv'], true)) + ) { + srand((double) microtime() * 1000000); + $td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, ''); + if ($td === false) { + PMA_fatalError(__('Failed to use Blowfish from mcrypt!')); + } + $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); + $GLOBALS['PMA_Config']->setCookie( + 'pma_mcrypt_iv', + base64_encode($iv) + ); + } +} + /** * Handles the cookie authentication method * @@ -33,42 +56,6 @@ require './libraries/plugins/auth/swekey/swekey.auth.lib.php'; */ class AuthenticationCookie extends AuthenticationPlugin { - /** - * Initialization vector - * - * @var array - */ - private $_iv; - - /** - * Constructor - */ - function __construct() - { - /** - * Initialization - * Store the initialization vector because it will be needed for - * further decryption. I don't think necessary to have one iv - * per server so I don't put the server number in the cookie name. - */ - if (empty($_COOKIE['pma_mcrypt_iv']) - || ! ($this->_setIv(base64_decode($_COOKIE['pma_mcrypt_iv'], true))) - ) { - srand((double) microtime() * 1000000); - $td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, ''); - if ($td === false) { - PMA_fatalError(__('Failed to use Blowfish from mcrypt!')); - } - $this->_setIv( - mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND) - ); - $GLOBALS['PMA_Config']->setCookie( - 'pma_mcrypt_iv', - base64_encode($this->_getIv()) - ); - } - } - /** * Displays authentication form * @@ -640,6 +627,7 @@ class AuthenticationCookie extends AuthenticationPlugin */ public function blowfishEncrypt($data, $secret) { + global $iv; if (! function_exists('mcrypt_encrypt')) { include_once "HordeCipherBlowfishOperations.class.php"; return HordeCipherBlowfishOperations::blowfishEncrypt($data, $secret); @@ -651,7 +639,7 @@ class AuthenticationCookie extends AuthenticationPlugin $secret, $data, MCRYPT_MODE_CBC, - $this->_getIv() + $iv ) ); } @@ -666,6 +654,7 @@ class AuthenticationCookie extends AuthenticationPlugin */ public function blowfishDecrypt($encdata, $secret) { + global $iv; if (! function_exists('mcrypt_encrypt')) { include_once "HordeCipherBlowfishOperations.class.php"; return HordeCipherBlowfishOperations::blowfishDecrypt( @@ -680,7 +669,7 @@ class AuthenticationCookie extends AuthenticationPlugin $secret, $data, MCRYPT_MODE_CBC, - $this->_getIv() + $iv ); return trim($decrypted); } @@ -697,30 +686,4 @@ class AuthenticationCookie extends AuthenticationPlugin public function update (SplSubject $subject) { } - - - /* ~~~~~~~~~~~~~~~~~~~~ Getters and Setters ~~~~~~~~~~~~~~~~~~~~ */ - - - /** - * Get the initialization vector - * - * @return array - */ - private function _getIv() - { - return $this->_iv; - } - - /** - * Set the initialization vector - * - * @param array $iv the initialization vector - * - * @return void - */ - private function _setIv($iv) - { - $this->_iv = $iv; - } } \ No newline at end of file From 89570a547573df90e0c0830bb78e8ea810ed83bb Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 18:22:25 +0300 Subject: [PATCH 51/55] oop: import/upload interface and classes --- libraries/display_import.lib.php | 8 +- libraries/display_import_ajax.lib.php | 13 +-- libraries/plugins/PluginManager.class.php | 1 + .../plugins/TransformationsInterface.int.php | 2 +- .../plugins/TransformationsPlugin.class.php | 1 - libraries/plugins/UploadInterface.int.php | 35 +++++++ libraries/plugins/import/ImportShp.class.php | 2 +- .../plugins/import/upload/UploadApc.class.php | 84 ++++++++++++++++ .../import/upload/UploadNoplugin.class.php | 64 +++++++++++++ .../import/upload/UploadProgress.class.php | 94 ++++++++++++++++++ .../import/upload/UploadSession.class.php | 96 +++++++++++++++++++ 11 files changed, 388 insertions(+), 12 deletions(-) create mode 100644 libraries/plugins/UploadInterface.int.php create mode 100644 libraries/plugins/import/upload/UploadApc.class.php create mode 100644 libraries/plugins/import/upload/UploadNoplugin.class.php create mode 100644 libraries/plugins/import/upload/UploadProgress.class.php create mode 100644 libraries/plugins/import/upload/UploadSession.class.php diff --git a/libraries/display_import.lib.php b/libraries/display_import.lib.php index 310e08092a..abfee40275 100644 --- a/libraries/display_import.lib.php +++ b/libraries/display_import.lib.php @@ -44,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; @@ -161,10 +161,12 @@ if ($_SESSION[$SESSION_KEY]["handler"]!="noplugin") {
> - + " value="" /> 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 + * + * @return array|null + */ + public static function getUploadStatus(); +} +?> \ No newline at end of file diff --git a/libraries/plugins/import/ImportShp.class.php b/libraries/plugins/import/ImportShp.class.php index 1d239f0c9a..7f35135e03 100644 --- a/libraries/plugins/import/ImportShp.class.php +++ b/libraries/plugins/import/ImportShp.class.php @@ -28,7 +28,7 @@ require_once "libraries/plugins/import/PMA_ShapeRecord.class.php"; * @package PhpMyAdmin-Import */ class ImportShp extends ImportPlugin -{ +{ /** * Constructor */ diff --git a/libraries/plugins/import/upload/UploadApc.class.php b/libraries/plugins/import/upload/UploadApc.class.php new file mode 100644 index 0000000000..7f480f6a55 --- /dev/null +++ b/libraries/plugins/import/upload/UploadApc.class.php @@ -0,0 +1,84 @@ + $id, + 'finished' => false, + 'percent' => 0, + 'total' => 0, + 'complete' => 0, + 'plugin' => UploadApc::getIdKey() + ); + } + $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; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/import/upload/UploadNoplugin.class.php b/libraries/plugins/import/upload/UploadNoplugin.class.php new file mode 100644 index 0000000000..84453fab49 --- /dev/null +++ b/libraries/plugins/import/upload/UploadNoplugin.class.php @@ -0,0 +1,64 @@ + $id, + 'finished' => false, + 'percent' => 0, + 'total' => 0, + 'complete' => 0, + 'plugin' => UploadNoplugin::getIdKey() + ); + } + $ret = $_SESSION[$SESSION_KEY][$id]; + + return $ret; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/import/upload/UploadProgress.class.php b/libraries/plugins/import/upload/UploadProgress.class.php new file mode 100644 index 0000000000..8264c96c91 --- /dev/null +++ b/libraries/plugins/import/upload/UploadProgress.class.php @@ -0,0 +1,94 @@ + $id, + 'finished' => false, + 'percent' => 0, + 'total' => 0, + 'complete' => 0, + 'plugin' => UploadProgress::getIdKey() + ); + } + $ret = $_SESSION[$SESSION_KEY][$id]; + + if (! PMA_import_progressCheck() || $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' => UploadProgress::getIdKey() + ); + } + + $_SESSION[$SESSION_KEY][$id] = $ret; + return $ret; + } +} +?> \ No newline at end of file diff --git a/libraries/plugins/import/upload/UploadSession.class.php b/libraries/plugins/import/upload/UploadSession.class.php new file mode 100644 index 0000000000..d2464a043a --- /dev/null +++ b/libraries/plugins/import/upload/UploadSession.class.php @@ -0,0 +1,96 @@ + $id, + 'finished' => false, + 'percent' => 0, + 'total' => 0, + 'complete' => 0, + 'plugin' => UploadSession::getIdKey() + ); + } + $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' => UploadSession::getIdKey() + ); + } + + $_SESSION[$SESSION_KEY][$id] = $ret; + + return $ret; + } +} +?> \ No newline at end of file From c9218f08a6db138100053c78b760f1332b38f3bf Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 18:35:15 +0300 Subject: [PATCH 52/55] oop: plugins bugs --- libraries/DisplayResults.class.php | 4 +++- libraries/display_import_ajax.lib.php | 2 +- libraries/plugins/UploadInterface.int.php | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/libraries/DisplayResults.class.php b/libraries/DisplayResults.class.php index 490bd5de11..6dbad94d8c 100644 --- a/libraries/DisplayResults.class.php +++ b/libraries/DisplayResults.class.php @@ -2172,7 +2172,9 @@ class PMA_DisplayResults if (file_exists($include_file)) { include_once $include_file; $class_name = str_replace('.class.php', '', $file); - $transformation_plugin = new $class_name; + // 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'] diff --git a/libraries/display_import_ajax.lib.php b/libraries/display_import_ajax.lib.php index 7147a4790b..b0a6c7ea64 100644 --- a/libraries/display_import_ajax.lib.php +++ b/libraries/display_import_ajax.lib.php @@ -44,7 +44,7 @@ foreach ($plugins as $plugin) { if ($check()) { $upload_class = "Upload" . ucwords($plugin); $_SESSION[$SESSION_KEY]["handler"] = $upload_class; - include_once "import/upload/" . $plugin . ".class.php"; + include_once "plugins/import/upload/" . $upload_class . ".class.php"; break; } } diff --git a/libraries/plugins/UploadInterface.int.php b/libraries/plugins/UploadInterface.int.php index 4adced136b..35444420a8 100644 --- a/libraries/plugins/UploadInterface.int.php +++ b/libraries/plugins/UploadInterface.int.php @@ -26,10 +26,10 @@ interface UploadInterface { /** * Returns upload status. * - * @param string $id + * @param string $id upload id * * @return array|null */ - public static function getUploadStatus(); + public static function getUploadStatus($id); } ?> \ No newline at end of file From 415bd34b1cb6bac37397dc11c9663dd75ecbadfe Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Fri, 22 Jun 2012 19:13:33 +0300 Subject: [PATCH 53/55] oop: change include locations for plugins --- libraries/auth/cookie.auth.lib.php | 2 +- libraries/check_user_privileges.lib.php | 3 ++- libraries/common.inc.php | 16 ++++++++-------- .../plugins/auth/swekey/swekey.auth.lib.php | 4 ++-- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/libraries/auth/cookie.auth.lib.php b/libraries/auth/cookie.auth.lib.php index c4f5d2fc35..b5d8ce3321 100644 --- a/libraries/auth/cookie.auth.lib.php +++ b/libraries/auth/cookie.auth.lib.php @@ -22,7 +22,7 @@ if (! empty($_REQUEST['target'])) { /** * Swekey authentication functions. */ -require './libraries/auth/swekey/swekey.auth.lib.php'; +require './libraries/plugins/auth/swekey/swekey.auth.lib.php'; if (function_exists('mcrypt_encrypt')) { /** 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 be92bc925f..c60a783b17 100644 --- a/libraries/common.inc.php +++ b/libraries/common.inc.php @@ -839,17 +839,17 @@ 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 */ - $auth_class = "Authentication" - . strtoupper(substr($cfg['Server']['auth_type'], 0, 1)) - . strtolower(substr($cfg['Server']['auth_type'], 1)); + $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; diff --git a/libraries/plugins/auth/swekey/swekey.auth.lib.php b/libraries/plugins/auth/swekey/swekey.auth.lib.php index 29d4a7f72b..def135d3ae 100644 --- a/libraries/plugins/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'; ?> - $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/auth/swekey/authentication.inc.php b/libraries/auth/swekey/authentication.inc.php deleted file mode 100644 index 1977f883e1..0000000000 --- a/libraries/auth/swekey/authentication.inc.php +++ /dev/null @@ -1,172 +0,0 @@ - - - diff --git a/libraries/auth/swekey/musbe-ca.crt b/libraries/auth/swekey/musbe-ca.crt deleted file mode 100644 index 2a31ad18f9..0000000000 --- a/libraries/auth/swekey/musbe-ca.crt +++ /dev/null @@ -1,25 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEKjCCAxKgAwIBAgIJAMjw7QcLWCd6MA0GCSqGSIb3DQEBBQUAMGsxCzAJBgNV -BAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQKEwtNdXNiZSwgSW5j -LjESMBAGA1UEAxMJbXVzYmUuY29tMR0wGwYJKoZIhvcNAQkBFg5pbmZvQG11c2Jl -LmNvbTAeFw0wODA5MDQxNDE2MTNaFw0zNzEyMjExNDE2MTNaMGsxCzAJBgNVBAYT -AlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQKEwtNdXNiZSwgSW5jLjES -MBAGA1UEAxMJbXVzYmUuY29tMR0wGwYJKoZIhvcNAQkBFg5pbmZvQG11c2JlLmNv -bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOBhOljxVzQfK4gted2I -d3BemcjW4abAUOzn3KYWXpPO5xIfVeXNDGkDbyH+X+7fo94sX25/ewuKNFDSOcvo -tXHq7uQenTHB35r+a+LY81KceUHgW90a3XsqPAkwAjyYcgo3zmM2DtLvw+5Yod8T -wAHk9m3qavnQ1uk99jBTwL7RZ9jIZHh9pFCL93uJc2obtd8O96Iycbn2q0w/AWbb -+eUVWIHzvLtfPvROeL3lJzr/Uz5LjKapxJ3qyqASflfHpnj9pU8l6g2TQ6Hg5KT5 -tLFkRe7uGhOfRtOQ/+NjaWrEuNCFnpyN4Q5Fv+5qA1Ip1IpH0200sWbAf/k2u0Qp -Sx0CAwEAAaOB0DCBzTAdBgNVHQ4EFgQUczJrQ7hCvtsnzcqiDIZ/GSn/CiwwgZ0G -A1UdIwSBlTCBkoAUczJrQ7hCvtsnzcqiDIZ/GSn/Ciyhb6RtMGsxCzAJBgNVBAYT -AlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQKEwtNdXNiZSwgSW5jLjES -MBAGA1UEAxMJbXVzYmUuY29tMR0wGwYJKoZIhvcNAQkBFg5pbmZvQG11c2JlLmNv -bYIJAMjw7QcLWCd6MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAGxk -8xzIljeBDQWWVRr0NEALVSv3i09V4jAKkyEOfmZ8lKMKJi0atwbtjrXTzLnNYj+Q -pyUbyY/8ItWvV7pnVxMiF9qcer7e9X4vw358GZuMVE/da1nWxz+CwzTm5oO30RzA -antM9bISFFr9lJq69bDWOnCUi1IG8DSL3TxtlABso7S4vqiZ+sB33l6k1K4a/Njb -QkU9UejKhKkVVZTsOrumfnOJ4MCmPfX8Y/AY2o670y5HnzpxerIYziCVzApPVrW7 -sKH0tuVGturMfQOKgstYe4/m9glBTeTLMkjD+6MJC2ONBD7GAiOO95gNl5M1fzJQ -FEe5CJ7DCYl0GdmLXXw= ------END CERTIFICATE----- diff --git a/libraries/auth/swekey/swekey.auth.lib.php b/libraries/auth/swekey/swekey.auth.lib.php deleted file mode 100644 index 29d4a7f72b..0000000000 --- a/libraries/auth/swekey/swekey.auth.lib.php +++ /dev/null @@ -1,291 +0,0 @@ - - - \n"; -// if (file_exists($caFile)) -// echo "\n"; - } - - if (file_exists($caFile)) { - Swekey_SetCAFile($caFile); - } elseif (! empty($caFile) && (substr($_SESSION['SWEKEY']['CONF_SERVER_CHECK'], 0, 8) == "https://")) { - return "Internal Error: CA File $caFile not found"; - } - - $result = null; - $swekey_id = $_GET['swekey_id']; - $swekey_otp = $_GET['swekey_otp']; - - if (isset($swekey_id)) { - unset($_SESSION['SWEKEY']['AUTHENTICATED_SWEKEY']); - if (! isset($_SESSION['SWEKEY']['RND_TOKEN'])) { - unset($swekey_id); - } else { - if (strlen($swekey_id) == 32) { - $res = Swekey_CheckOtp($swekey_id, $_SESSION['SWEKEY']['RND_TOKEN'], $swekey_otp); - unset($_SESSION['SWEKEY']['RND_TOKEN']); - if (! $res) { - $result = __('Hardware authentication failed') . ' (' . Swekey_GetLastError() . ')'; - } else { - $_SESSION['SWEKEY']['AUTHENTICATED_SWEKEY'] = $swekey_id; - $_SESSION['SWEKEY']['FORCE_USER'] = $_SESSION['SWEKEY']['VALID_SWEKEYS'][$swekey_id]; - return null; - } - } else { - $result = __('No valid authentication key plugged'); - if ($_SESSION['SWEKEY']['CONF_DEBUG']) { - $result .= "
" . htmlspecialchars($swekey_id); - } - unset($_SESSION['SWEKEY']['CONF_LOADED']); // reload the conf file - } - } - } else { - unset($_SESSION['SWEKEY']); - } - - $_SESSION['SWEKEY']['RND_TOKEN'] = Swekey_GetFastRndToken(); - if (strlen($_SESSION['SWEKEY']['RND_TOKEN']) != 64) { - $result = __('Hardware authentication failed') . ' (' . Swekey_GetLastError() . ')'; - unset($_SESSION['SWEKEY']['CONF_LOADED']); // reload the conf file - } - - if (! isset($swekey_id)) { - ?> - - display(); - if ($GLOBALS['error_handler']->hasDisplayErrors()) { - echo '
'; - $GLOBALS['error_handler']->dispErrors(); - echo '
'; - } - } - - if (isset($_SESSION['SWEKEY']) && $_SESSION['SWEKEY']['ENABLED']) { - echo ''; - } -} - -if (!empty($_GET['session_to_unset'])) { - session_write_close(); - session_id($_GET['session_to_unset']); - session_start(); - $_SESSION = array(); - session_write_close(); - session_destroy(); - exit; -} - -if (isset($_GET['swekey_reset'])) { - unset($_SESSION['SWEKEY']); -} - -?> diff --git a/libraries/auth/swekey/swekey.php b/libraries/auth/swekey/swekey.php deleted file mode 100644 index 0f49732101..0000000000 --- a/libraries/auth/swekey/swekey.php +++ /dev/null @@ -1,517 +0,0 @@ -"; - -/** - * Servers addresses - * Use the Swekey_SetXxxServer($server) functions to set them - */ - -global $gSwekeyCheckServer; -if (! isset($gSwekeyCheckServer)) { - $gSwekeyCheckServer = SWEKEY_DEFAULT_CHECK_SERVER; -} - -global $gSwekeyRndTokenServer; -if (! isset($gSwekeyRndTokenServer)) { - $gSwekeyRndTokenServer = SWEKEY_DEFAULT_RND_SERVER; -} - -global $gSwekeyStatusServer; -if (! isset($gSwekeyStatusServer)) { - $gSwekeyStatusServer = SWEKEY_DEFAULT_STATUS_SERVER; -} - -global $gSwekeyCA; - -global $gSwekeyTokenCacheEnabled; -if (! isset($gSwekeyTokenCacheEnabled)) { - $gSwekeyTokenCacheEnabled = true; -} - -/** - * Change the address of the Check server. - * If $server is empty the default value 'http://auth-check.musbe.net' will be used - * - * @param server The protocol and hostname to use - * @access public - */ -function Swekey_SetCheckServer($server) -{ - global $gSwekeyCheckServer; - if (empty($server)) { - $gSwekeyCheckServer = SWEKEY_DEFAULT_CHECK_SERVER; - } else { - $gSwekeyCheckServer = $server; - } -} - -/** - * Change the address of the Random Token Generator server. - * If $server is empty the default value 'http://auth-rnd-gen.musbe.net' will be used - * - * @param server The protocol and hostname to use - * @access public - */ -function Swekey_SetRndTokenServer($server) -{ - global $gSwekeyRndTokenServer; - if (empty($server)) { - $gSwekeyRndTokenServer = SWEKEY_DEFAULT_RND_SERVER; - } else { - $gSwekeyRndTokenServer = $server; - } -} - -/** - * Change the address of the Satus server. - * If $server is empty the default value 'http://auth-status.musbe.net' will be used - * - * @param server The protocol and hostname to use - * @access public - */ -function Swekey_SetStatusServer($server) -{ - global $gSwekeyStatusServer; - if (empty($server)) { - $gSwekeyStatusServer = SWEKEY_DEFAULT_STATUS_SERVER; - } else { - $gSwekeyStatusServer = $server; - } -} - -/** - * Change the certificat file in case of the the severs use https instead of http - * - * @param cafile The path of the crt file to use - * @access public - */ -function Swekey_SetCAFile($cafile) -{ - global $gSwekeyCA; - $gSwekeyCA = $cafile; -} - -/** - * Enable or disable the random token caching - * Because everybody has full access to the cache file, it can be a DOS vulnerability - * So disable it if you are running in a non secure enviromnement - * - * @param $enable - * @access public - */ -function Swekey_EnableTokenCache($enable) -{ - global $gSwekeyTokenCacheEnabled; - $gSwekeyTokenCacheEnabled = ! empty($enable); -} - - -/** - * Return the last error. - * - * @return The Last Error - * @access public - */ -function Swekey_GetLastError() -{ - global $gSwekeyLastError; - return $gSwekeyLastError; -} - -/** - * Return the last result. - * - * @return The Last Error - * @access public - */ -function Swekey_GetLastResult() -{ - global $gSwekeyLastResult; - return $gSwekeyLastResult; -} - -/** - * Send a synchronous request to the server. - * This function manages timeout then will not block if one of the server is down - * - * @param url The url to get - * @param response_code The response code - * - * @return The body of the response or "" in case of error - * @access private - */ -function Swekey_HttpGet($url, &$response_code) -{ - global $gSwekeyLastError; - $gSwekeyLastError = 0; - global $gSwekeyLastResult; - $gSwekeyLastResult = ""; - - // use curl if available - if (function_exists('curl_init')) { - $sess = curl_init($url); - if (substr($url, 0, 8) == "https://") { - global $gSwekeyCA; - - if (! empty($gSwekeyCA)) { - if (file_exists($gSwekeyCA)) { - if (! curl_setopt($sess, CURLOPT_CAINFO, $gSwekeyCA)) { - error_log("SWEKEY_ERROR:Could not set CA file : ".curl_error($sess)); - } else { - $caFileOk = true; - } - } else { - error_log("SWEKEY_ERROR:Could not find CA file $gSwekeyCA getting $url"); - } - } - - curl_setopt($sess, CURLOPT_SSL_VERIFYHOST, '2'); - curl_setopt($sess, CURLOPT_SSL_VERIFYPEER, '2'); - curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '20'); - curl_setopt($sess, CURLOPT_TIMEOUT, '20'); - } else { - curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '3'); - curl_setopt($sess, CURLOPT_TIMEOUT, '5'); - } - - curl_setopt($sess, CURLOPT_RETURNTRANSFER, '1'); - $res=curl_exec($sess); - $response_code = curl_getinfo($sess, CURLINFO_HTTP_CODE); - $curlerr = curl_error($sess); - curl_close($sess); - - if ($response_code == 200) { - $gSwekeyLastResult = $res; - return $res; - } - - if (! empty($response_code)) { - $gSwekeyLastError = $response_code; - error_log("SWEKEY_ERROR:Error $gSwekeyLastError ($curlerr) getting $url"); - return ""; - } - - $response_code = 408; // Request Timeout - $gSwekeyLastError = $response_code; - error_log("SWEKEY_ERROR:Error $curlerr getting $url"); - return ""; - } - - // use pecl_http if available - if (class_exists('HttpRequest')) { - // retry if one of the server is down - for ($num=1; $num <= 3; $num++ ) { - $r = new HttpRequest($url); - $options = array('timeout' => '3'); - - if (substr($url, 0, 6) == "https:") { - $sslOptions = array(); - $sslOptions['verifypeer'] = true; - $sslOptions['verifyhost'] = true; - - $capath = __FILE__; - $name = strrchr($capath, '/'); - // windows - if (empty($name)) { - $name = strrchr($capath, '\\'); - } - $capath = substr($capath, 0, strlen($capath) - strlen($name) + 1).'musbe-ca.crt'; - - if (! empty($gSwekeyCA)) { - $sslOptions['cainfo'] = $gSwekeyCA; - } - - $options['ssl'] = $sslOptions; - } - - $r->setOptions($options); - - // try - { - $reply = $r->send(); - $res = $reply->getBody(); - $info = $r->getResponseInfo(); - $response_code = $info['response_code']; - if ($response_code != 200) { - $gSwekeyLastError = $response_code; - error_log("SWEKEY_ERROR:Error ".$gSwekeyLastError." getting ".$url); - return ""; - } - - - $gSwekeyLastResult = $res; - return $res; - } - // catch (HttpException $e) - // { - // error_log("SWEKEY_WARNING:HttpException ".$e." getting ".$url); - // } - } - - $response_code = 408; // Request Timeout - $gSwekeyLastError = $response_code; - error_log("SWEKEY_ERROR:Error ".$gSwekeyLastError." getting ".$url); - return ""; - } - - global $http_response_header; - $res = @file_get_contents($url); - $response_code = substr($http_response_header[0], 9, 3); //HTTP/1.0 - if ($response_code == 200) { - $gSwekeyLastResult = $res; - return $res; - } - - $gSwekeyLastError = $response_code; - error_log("SWEKEY_ERROR:Error ".$response_code." getting ".$url); - return ""; -} - -/** - * Get a Random Token from a Token Server - * The RT is a 64 vhars hexadecimal value - * You should better use Swekey_GetFastRndToken() for performance - * @access public - */ -function Swekey_GetRndToken() -{ - global $gSwekeyRndTokenServer; - return Swekey_HttpGet($gSwekeyRndTokenServer.'/FULL-RND-TOKEN', $response_code); -} - -/** - * Get a Half Random Token from a Token Server - * The RT is a 64 vhars hexadecimal value - * Use this value if you want to make your own Swekey_GetFastRndToken() - * @access public - */ -function Swekey_GetHalfRndToken() -{ - global $gSwekeyRndTokenServer; - return Swekey_HttpGet($gSwekeyRndTokenServer.'/HALF-RND-TOKEN', $response_code); -} - -/** - * Get a Half Random Token - * The RT is a 64 vhars hexadecimal value - * This function get a new random token and reuse it. - * Token are refetched from the server only once every 30 seconds. - * You should always use this function to get half random token. - * @access public - */ -function Swekey_GetFastHalfRndToken() -{ - global $gSwekeyTokenCacheEnabled; - - $res = ""; - $cachefile = ""; - - // We check if we have a valid RT is the session - if (isset($_SESSION['rnd-token-date'])) { - if (time() - $_SESSION['rnd-token-date'] < 30) { - $res = $_SESSION['rnd-token']; - } - } - - // If not we try to get it from a temp file (PHP >= 5.2.1 only) - if (strlen($res) != 32 && $gSwekeyTokenCacheEnabled) { - if (function_exists('sys_get_temp_dir')) { - $tempdir = sys_get_temp_dir(); - $cachefile = $tempdir."/swekey-rnd-token-".get_current_user(); - $modif = filemtime($cachefile); - if ($modif != false) { - if (time() - $modif < 30) { - $res = @file_get_contents($cachefile); - if (strlen($res) != 32) { - $res = ""; - } else { - $_SESSION['rnd-token'] = $res; - $_SESSION['rnd-token-date'] = $modif; - } - } - } - } - } - - // If we don't have a valid RT here we have to get it from the server - if (strlen($res) != 32) { - $res = substr(Swekey_GetHalfRndToken(), 0, 32); - $_SESSION['rnd-token'] = $res; - $_SESSION['rnd-token-date'] = time(); - if (! empty($cachefile)) { - // we unlink the file so no possible tempfile race attack - unlink($cachefile); - $file = fopen($cachefile, "x"); - if ($file != false) { - @fwrite($file, $res); - @fclose($file); - } - } - } - - return $res."00000000000000000000000000000000"; -} - -/** - * Get a Random Token - * The RT is a 64 vhars hexadecimal value - * This function generates a unique random token for each call but call the - * server only once every 30 seconds. - * You should always use this function to get random token. - * @access public - */ -function Swekey_GetFastRndToken() -{ - $res = Swekey_GetFastHalfRndToken(); - if (strlen($res) == 64) { - return substr($res, 0, 32).strtoupper(md5("Musbe Authentication Key" + mt_rand() + date(DATE_ATOM))); - } - return ""; -} - - -/** - * Checks that an OTP generated by a Swekey is valid - * - * @param id The id of the swekey - * @param rt The random token used to generate the otp - * @param otp The otp generated by the swekey - * - * @return true or false - * @access public - */ -function Swekey_CheckOtp($id, $rt, $otp) -{ - global $gSwekeyCheckServer; - $res = Swekey_HttpGet($gSwekeyCheckServer.'/CHECK-OTP/'.$id.'/'.$rt.'/'.$otp, $response_code); - return $response_code == 200 && $res == "OK"; -} - -/** - * Values that are associated with a key. - * The following values can be returned by the Swekey_GetStatus() function - */ -define("SWEKEY_STATUS_OK", 0); -define("SWEKEY_STATUS_NOT_FOUND", 1); // The key does not exist in the db -define("SWEKEY_STATUS_INACTIVE", 2); // The key has never been activated -define("SWEKEY_STATUS_LOST", 3); // The user has lost his key -define("SWEKEY_STATUS_STOLEN", 4); // The key was stolen -define("SWEKEY_STATUS_FEE_DUE", 5); // The annual fee was not paid -define("SWEKEY_STATUS_OBSOLETE", 6); // The hardware is no longer supported -define("SWEKEY_STATUS_UNKOWN", 201); // We could not connect to the authentication server - -/** - * Values that are associated with a key. - * The Javascript Api can also return the following values - */ -define("SWEKEY_STATUS_REPLACED", 100); // This key has been replaced by a backup key -define("SWEKEY_STATUS_BACKUP_KEY", 101); // This key is a backup key that is not activated yet -define("SWEKEY_STATUS_NOTPLUGGED", 200); // This key is not plugged in the computer - - -/** - * Return the text corresponding to the integer status of a key - * - * @param status The status - * - * @return The text corresponding to the status - * @access public - */ -function Swekey_GetStatusStr($status) -{ - switch($status) - { - case SWEKEY_STATUS_OK : - return 'OK'; - case SWEKEY_STATUS_NOT_FOUND : - return 'Key does not exist in the db'; - case SWEKEY_STATUS_INACTIVE : - return 'Key not activated'; - case SWEKEY_STATUS_LOST : - return 'Key was lost'; - case SWEKEY_STATUS_STOLEN : - return 'Key was stolen'; - case SWEKEY_STATUS_FEE_DUE : - return 'The annual fee was not paid'; - case SWEKEY_STATUS_OBSOLETE : - return 'Key no longer supported'; - case SWEKEY_STATUS_REPLACED : - return 'This key has been replaced by a backup key'; - case SWEKEY_STATUS_BACKUP_KEY : - return 'This key is a backup key that is not activated yet'; - case SWEKEY_STATUS_NOTPLUGGED : - return 'This key is not plugged in the computer'; - case SWEKEY_STATUS_UNKOWN : - return 'Unknow Status, could not connect to the authentication server'; - } - return 'unknown status '.$status; -} - -/** - * If your web site requires a key to login you should check that the key - * is still valid (has not been lost or stolen) before requiring it. - * A key can be authenticated only if its status is SWEKEY_STATUS_OK - * - * @param id The id of the swekey - * - * @return The status of the swekey - * @access public - */ -function Swekey_GetStatus($id) -{ - global $gSwekeyStatusServer; - $res = Swekey_HttpGet($gSwekeyStatusServer.'/GET-STATUS/'.$id, $response_code); - if ($response_code == 200) { - return intval($res); - } - return SWEKEY_STATUS_UNKOWN; -} - -?> diff --git a/libraries/export/codegen.php b/libraries/export/codegen.php deleted file mode 100644 index f357622c24..0000000000 --- a/libraries/export/codegen.php +++ /dev/null @@ -1,456 +0,0 @@ - '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/csv.php b/libraries/export/csv.php deleted file mode 100644 index 9fdf8910ef..0000000000 --- a/libraries/export/csv.php +++ /dev/null @@ -1,298 +0,0 @@ - __('CSV'), - 'extension' => 'csv', - 'mime_type' => 'text/comma-separated-values', - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['csv']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'text', - 'name' => 'separator', - 'text' => __('Columns separated with:') - ), - array( - 'type' => 'text', - 'name' => 'enclosed', - 'text' => __('Columns enclosed with:') - ), - array( - 'type' => 'text', - 'name' => 'escaped', - 'text' => __('Columns escaped with:') - ), - array( - 'type' => 'text', - 'name' => 'terminated', - 'text' => __('Lines terminated with:') - ), - 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' => 'hidden', - 'name' => 'structure_or_data' - ), - array( - 'type' => 'end_group' - ) - ); -} else { - - /** - * 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() - { - global $what; - global $csv_terminated; - global $csv_separator; - global $csv_enclosed; - global $csv_escaped; - - // Here we just prepare some values for export - if ($what == 'excel') { - $csv_terminated = "\015\012"; - switch($GLOBALS['excel_edition']) { - case 'win': - // as tested on Windows with Excel 2002 and Excel 2007 - $csv_separator = ';'; - break; - case 'mac_excel2003': - $csv_separator = ';'; - break; - case 'mac_excel2008': - $csv_separator = ','; - break; - } - $csv_enclosed = '"'; - $csv_escaped = '"'; - if (isset($GLOBALS['excel_columns'])) { - $GLOBALS['csv_columns'] = 'yes'; - } - } else { - if (empty($csv_terminated) || strtolower($csv_terminated) == 'auto') { - $csv_terminated = $GLOBALS['crlf']; - } else { - $csv_terminated = str_replace('\\r', "\015", $csv_terminated); - $csv_terminated = str_replace('\\n', "\012", $csv_terminated); - $csv_terminated = str_replace('\\t', "\011", $csv_terminated); - } // end if - $csv_separator = str_replace('\\t', "\011", $csv_separator); - } - 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 CSV 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 $what; - global $csv_terminated; - global $csv_separator; - global $csv_enclosed; - global $csv_escaped; - - // Gets the data from the database - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - $fields_cnt = PMA_DBI_num_fields($result); - - // If required, get fields name at the first line - if (isset($GLOBALS['csv_columns'])) { - $schema_insert = ''; - for ($i = 0; $i < $fields_cnt; $i++) { - if ($csv_enclosed == '') { - $schema_insert .= stripslashes(PMA_DBI_field_name($result, $i)); - } else { - $schema_insert .= $csv_enclosed - . str_replace( - $csv_enclosed, - $csv_escaped . $csv_enclosed, - stripslashes(PMA_DBI_field_name($result, $i)) - ) - . $csv_enclosed; - } - $schema_insert .= $csv_separator; - } // end for - $schema_insert = trim(substr($schema_insert, 0, -1)); - if (! PMA_exportOutputHandler($schema_insert . $csv_terminated)) { - return false; - } - } // end if - - // Format the data - while ($row = PMA_DBI_fetch_row($result)) { - $schema_insert = ''; - for ($j = 0; $j < $fields_cnt; $j++) { - if (! isset($row[$j]) || is_null($row[$j])) { - $schema_insert .= $GLOBALS[$what . '_null']; - } elseif ($row[$j] == '0' || $row[$j] != '') { - // always enclose fields - if ($what == 'excel') { - $row[$j] = preg_replace("/\015(\012)?/", "\012", $row[$j]); - } - // remove CRLF characters within field - if (isset($GLOBALS[$what . '_removeCRLF']) - && $GLOBALS[$what . '_removeCRLF'] - ) { - $row[$j] = str_replace( - "\n", - "", - str_replace( - "\r", - "", - $row[$j] - ) - ); - } - if ($csv_enclosed == '') { - $schema_insert .= $row[$j]; - } else { - // also double the escape string if found in the data - if ($csv_escaped != $csv_enclosed) { - $schema_insert .= $csv_enclosed - . str_replace( - $csv_enclosed, - $csv_escaped . $csv_enclosed, - str_replace( - $csv_escaped, - $csv_escaped . $csv_escaped, - $row[$j] - ) - ) - . $csv_enclosed; - } else { - // avoid a problem when escape string equals enclose - $schema_insert .= $csv_enclosed - . str_replace( - $csv_enclosed, - $csv_escaped . $csv_enclosed, - $row[$j] - ) - . $csv_enclosed; - } - } - } else { - $schema_insert .= ''; - } - if ($j < $fields_cnt-1) { - $schema_insert .= $csv_separator; - } - } // end for - - if (! PMA_exportOutputHandler($schema_insert . $csv_terminated)) { - return false; - } - } // end while - PMA_DBI_free_result($result); - - return true; - } // end of the 'PMA_getTableCsv()' function - -} -?> 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/htmlword.php b/libraries/export/htmlword.php deleted file mode 100644 index ccb41d1a0f..0000000000 --- a/libraries/export/htmlword.php +++ /dev/null @@ -1,611 +0,0 @@ - __('Microsoft Word 2000'), - 'extension' => 'doc', - 'mime_type' => 'application/vnd.ms-word', - 'force_file' => true, - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['htmlword']['options'] = array( - /* what to dump (structure/data/both) */ - array( - 'type' => 'begin_group', - 'name' => 'dump_what', - 'text' => __('Dump table') - ), - array( - 'type' => 'radio', - 'name' => 'structure_or_data', - 'values' => array( - 'structure' => __('structure'), - 'data' => __('data'), - 'structure_and_data' => __('structure and data') - ) - ), - array( - 'type' => 'end_group' - ), - - /* data options */ - array( - 'type' => 'begin_group', - 'name' => 'data', - 'text' => __('Data dump options'), - 'force' => 'structure' - ), - array( - 'type' => 'text', - 'name' => 'null', - 'text' => __('Replace NULL with:') - ), - array( - 'type' => 'bool', - 'name' => 'columns', - 'text' => __('Put columns names in the first row') - ), - array( - 'type' => 'end_group' - ) - ); -} else { - - /** - * Outputs export footer - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportFooter() - { - return PMA_exportOutputHandler(''); - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - global $charset_of_file; - return PMA_exportOutputHandler( - ' - - - - - - - ' - ); - } - - /** - * Outputs database header - * - * @param string $db Database name - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportDBHeader($db) - { - return PMA_exportOutputHandler( - '

' . __('Database') . ' ' . htmlspecialchars($db) . '

' - ); - } - - /** - * 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 HTML (Microsoft Word) 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 $what; - - if (! PMA_exportOutputHandler( - '

' - . __('Dumping data for table') . ' ' . htmlspecialchars($table) - . '

' - )) { - return false; - } - if (! PMA_exportOutputHandler( - '' - )) { - return false; - } - - // Gets the data from the database - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - $fields_cnt = PMA_DBI_num_fields($result); - - // If required, get fields name at the first line - if (isset($GLOBALS['htmlword_columns'])) { - $schema_insert = ''; - for ($i = 0; $i < $fields_cnt; $i++) { - $schema_insert .= ''; - } // end for - $schema_insert .= ''; - if (! PMA_exportOutputHandler($schema_insert)) { - return false; - } - } // end if - - // Format the data - while ($row = PMA_DBI_fetch_row($result)) { - $schema_insert = ''; - for ($j = 0; $j < $fields_cnt; $j++) { - if (! isset($row[$j]) || is_null($row[$j])) { - $value = $GLOBALS[$what . '_null']; - } elseif ($row[$j] == '0' || $row[$j] != '') { - $value = $row[$j]; - } else { - $value = ''; - } - $schema_insert .= ''; - } // end for - $schema_insert .= ''; - if (! PMA_exportOutputHandler($schema_insert)) { - return false; - } - } // end while - PMA_DBI_free_result($result); - if (! PMA_exportOutputHandler('
')) { - return false; - } - - return true; - } - - /** - * Returns a stand-in CREATE definition to resolve view dependencies - * - * @param string $db the database name - * @param string $view the view name - * @param string $crlf the end of line sequence - * - * @return string resulting definition - * - * @access public - */ - function PMA_getTableDefStandIn($db, $view, $crlf) - { - $schema_insert = ''; - $schema_insert .= ''; - $schema_insert .= ''; - $schema_insert .= ''; - $schema_insert .= ''; - $schema_insert .= ''; - $schema_insert .= ''; - - /** - * Get the unique keys in the table - */ - $unique_keys = array(); - $keys = PMA_DBI_get_table_indexes($db, $table); - foreach ($keys as $key) { - if ($key['Non_unique'] == 0) { - $unique_keys[] = $key['Column_name']; - } - } - - $columns = PMA_DBI_get_columns($db, $view); - foreach ($columns as $column) { - $schema_insert .= PMA_formatOneColumnDefinition($column, $unique_keys); - $schema_insert .= ''; - } - - $schema_insert .= '
'; - return $schema_insert; - } - - /** - * Returns $table's CREATE definition - * - * @param string $db the database name - * @param string $table the table name - * @param string $crlf the end of line sequence - * @param string $error_url the url to go back in case of error - * @param bool $do_relation whether to include relation comments - * @param bool $do_comments whether to include the pmadb-style column - * comments as comments in the structure; - * this is deprecated but the parameter is - * left here because export.php calls - * PMA_exportStructure() also for other - * export types which use this parameter - * @param bool $do_mime whether to include mime comments - * @param bool $show_dates whether to include creation/update/check dates - * @param bool $add_semicolon whether to add semicolon and end-of-line - * at the end - * @param bool $view whether we're handling a view - * - * @return string resulting schema - * - * @access public - */ - function PMA_getTableDef( - $db, - $table, - $crlf, - $error_url, - $do_relation, - $do_comments, - $do_mime, - $show_dates = false, - $add_semicolon = true, - $view = false - ) { - global $cfgRelation; - - $schema_insert = ''; - - /** - * Gets fields properties - */ - PMA_DBI_select_db($db); - - // Check if we can use Relations - if ($do_relation && ! empty($cfgRelation['relation'])) { - // Find which tables are related with the current one and write it in - // an array - $res_rel = PMA_getForeigners($db, $table); - - if ($res_rel && count($res_rel) > 0) { - $have_rel = true; - } else { - $have_rel = false; - } - } else { - $have_rel = false; - } // end if - - /** - * Displays the table structure - */ - $schema_insert .= ''; - - $columns_cnt = 4; - if ($do_relation && $have_rel) { - $columns_cnt++; - } - if ($do_comments && $cfgRelation['commwork']) { - $columns_cnt++; - } - if ($do_mime && $cfgRelation['mimework']) { - $columns_cnt++; - } - - $schema_insert .= ''; - $schema_insert .= ''; - $schema_insert .= ''; - $schema_insert .= ''; - $schema_insert .= ''; - if ($do_relation && $have_rel) { - $schema_insert .= ''; - } - if ($do_comments) { - $schema_insert .= ''; - $comments = PMA_getComments($db, $table); - } - if ($do_mime && $cfgRelation['mimework']) { - $schema_insert .= ''; - $mime_map = PMA_getMIME($db, $table, true); - } - $schema_insert .= ''; - - $columns = PMA_DBI_get_columns($db, $table); - /** - * Get the unique keys in the table - */ - $unique_keys = array(); - $keys = PMA_DBI_get_table_indexes($db, $table); - foreach ($keys as $key) { - if ($key['Non_unique'] == 0) { - $unique_keys[] = $key['Column_name']; - } - } - foreach ($columns as $column) { - $schema_insert .= PMA_formatOneColumnDefinition($column, $unique_keys); - $field_name = $column['Field']; - - if ($do_relation && $have_rel) { - $schema_insert .= ''; - } - if ($do_comments && $cfgRelation['commwork']) { - $schema_insert .= ''; - } - if ($do_mime && $cfgRelation['mimework']) { - $schema_insert .= ''; - } - - $schema_insert .= ''; - } // end foreach - - $schema_insert .= '
' - . (isset($res_rel[$field_name]) - ? htmlspecialchars( - $res_rel[$field_name]['foreign_table'] - . ' (' . $res_rel[$field_name]['foreign_field'] - . ')' - ) - : '') . '' - . (isset($comments[$field_name]) - ? htmlspecialchars($comments[$field_name]) - : '') . '' - . (isset($mime_map[$field_name]) ? - htmlspecialchars( - str_replace('_', '/', $mime_map[$field_name]['mimetype']) - ) - : '') . '
'; - return $schema_insert; - } // end of the 'PMA_getTableDef()' function - - /** - * Outputs triggers - * - * @param string $db database name - * @param string $table table name - * - * @return string Formatted triggers list - * - * @access public - */ - function PMA_getTriggers($db, $table) - { - $dump = ''; - $dump .= ''; - $dump .= ''; - $dump .= ''; - $dump .= ''; - $dump .= ''; - $dump .= ''; - - $triggers = PMA_DBI_get_triggers($db, $table); - - foreach ($triggers as $trigger) { - $dump .= ''; - $dump .= '' - . '' - . '' - . '' - . ''; - } - - $dump .= '
'; - return $dump; - } - - /** - * 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 - ) { - $dump = ''; - - switch($export_mode) { - case 'create_table': - $dump .= '

' - . __('Table structure for table') . ' ' . htmlspecialchars($table) - . '

'; - $dump .= PMA_getTableDef( - $db, $table, $crlf, $error_url, $do_relation, $do_comments, $do_mime, - $dates - ); - break; - case 'triggers': - $dump = ''; - $triggers = PMA_DBI_get_triggers($db, $table); - if ($triggers) { - $dump .= '

' - . __('Triggers') . ' ' . htmlspecialchars($table) - . '

'; - $dump .= PMA_getTriggers($db, $table); - } - break; - case 'create_view': - $dump .= '

' - . __('Structure for view') . ' ' . htmlspecialchars($table) - . '

'; - $dump .= PMA_getTableDef( - $db, $table, $crlf, $error_url, $do_relation, $do_comments, $do_mime, - $dates, true, true - ); - break; - case 'stand_in': - $dump .= '

' - . __('Stand-in structure for view') . ' ' . htmlspecialchars($table) - . '

'; - // export a stand-in definition to resolve view dependencies - $dump .= PMA_getTableDefStandIn($db, $table, $crlf); - } // end switch - - return PMA_exportOutputHandler($dump); - } - - /** - * Formats the definition for one column - * - * @param array $column info about this column - * @param array $unique_keys unique keys of the table - * - * @return string Formatted column definition - * - * @access public - */ - function PMA_formatOneColumnDefinition( - $column, $unique_keys - ) { - $definition = '
' . $crlf; - for ($i = 0; $i < $columns_cnt; $i++) { - // If a cell is NULL, still export it to preserve - // the XML structure - if (! isset($record[$i]) || is_null($record[$i])) { - $record[$i] = 'NULL'; - } - $buffer .= ' ' - . htmlspecialchars((string)$record[$i]) - . '' . $crlf; - } - $buffer .= '
' . $crlf; - - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - } - PMA_DBI_free_result($result); - } - - return true; - } // end of the 'PMA_getTableXML()' function -} -?> diff --git a/libraries/export/yaml.php b/libraries/export/yaml.php deleted file mode 100644 index 2192f6bd1f..0000000000 --- a/libraries/export/yaml.php +++ /dev/null @@ -1,186 +0,0 @@ - 'YAML', - 'extension' => 'yml', - 'mime_type' => 'text/yaml', - 'force_file' => true, - 'options' => array(), - 'options_text' => __('Options') - ); - - $plugin_list['yaml']['options'] = array( - array( - 'type' => 'begin_group', - 'name' => 'general_opts' - ), - array( - 'type' => 'hidden', - 'name' => 'structure_or_data', - ), - 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() - { - PMA_exportOutputHandler('...' . $GLOBALS['crlf']); - return true; - } - - /** - * Outputs export header - * - * @return bool Whether it succeeded - * - * @access public - */ - function PMA_exportHeader() - { - PMA_exportOutputHandler( - '%YAML 1.1' . $GLOBALS['crlf'] . '---' . $GLOBALS['crlf'] - ); - 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 YAML 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) - { - $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED); - - $columns_cnt = PMA_DBI_num_fields($result); - for ($i = 0; $i < $columns_cnt; $i++) { - $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i)); - } - unset($i); - - $buffer = ''; - $record_cnt = 0; - while ($record = PMA_DBI_fetch_row($result)) { - $record_cnt++; - - // Output table name as comment if this is the first record of the table - if ($record_cnt == 1) { - $buffer = '# ' . $db . '.' . $table . $crlf; - $buffer .= '-' . $crlf; - } else { - $buffer = '-' . $crlf; - } - - for ($i = 0; $i < $columns_cnt; $i++) { - if (! isset($record[$i])) { - continue; - } - - $column = $columns[$i]; - - if (is_null($record[$i])) { - $buffer .= ' ' . $column . ': null' . $crlf; - continue; - } - - if (is_numeric($record[$i])) { - $buffer .= ' ' . $column . ': ' . $record[$i] . $crlf; - continue; - } - - $record[$i] = str_replace( - array('\\', '"', "\n", "\r"), - array('\\\\', '\"', '\n', '\r'), - $record[$i] - ); - $buffer .= ' ' . $column . ': "' . $record[$i] . '"' . $crlf; - } - - if (! PMA_exportOutputHandler($buffer)) { - return false; - } - } - PMA_DBI_free_result($result); - - return true; - } - -} -?> 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/import/README b/libraries/plugins/import/README similarity index 99% rename from libraries/import/README rename to libraries/plugins/import/README index 0f0d3d3547..7bf8e39ab7 100644 --- a/libraries/import/README +++ b/libraries/plugins/import/README @@ -1,3 +1,5 @@ +Todo: Rewrite! + This directory holds import plugins for phpMyAdmin. Plugin should basically look like following code. Official plugins need to have str* messages with their definition in language files, if you build some diff --git a/libraries/transformations/README b/libraries/plugins/transformations/todo_rewrite/README similarity index 100% rename from libraries/transformations/README rename to libraries/plugins/transformations/todo_rewrite/README diff --git a/libraries/transformations/TEMPLATE b/libraries/plugins/transformations/todo_rewrite/TEMPLATE similarity index 100% rename from libraries/transformations/TEMPLATE rename to libraries/plugins/transformations/todo_rewrite/TEMPLATE diff --git a/libraries/transformations/TEMPLATE_MIMETYPE b/libraries/plugins/transformations/todo_rewrite/TEMPLATE_MIMETYPE similarity index 100% rename from libraries/transformations/TEMPLATE_MIMETYPE rename to libraries/plugins/transformations/todo_rewrite/TEMPLATE_MIMETYPE diff --git a/libraries/transformations/generator.sh b/libraries/plugins/transformations/todo_rewrite/generator.sh similarity index 100% rename from libraries/transformations/generator.sh rename to libraries/plugins/transformations/todo_rewrite/generator.sh diff --git a/libraries/transformations/template_generator.sh b/libraries/plugins/transformations/todo_rewrite/template_generator.sh similarity index 100% rename from libraries/transformations/template_generator.sh rename to libraries/plugins/transformations/todo_rewrite/template_generator.sh diff --git a/libraries/transformations/template_generator_mimetype.sh b/libraries/plugins/transformations/todo_rewrite/template_generator_mimetype.sh similarity index 100% rename from libraries/transformations/template_generator_mimetype.sh rename to libraries/plugins/transformations/todo_rewrite/template_generator_mimetype.sh diff --git a/libraries/transformations/application_octetstream__download.inc.php b/libraries/transformations/application_octetstream__download.inc.php deleted file mode 100644 index 32f326e57c..0000000000 --- a/libraries/transformations/application_octetstream__download.inc.php +++ /dev/null @@ -1,52 +0,0 @@ - __('Displays a link to download the binary data of the column. You can use the first option to specify the filename, or use the second option as the name of a column which contains the filename. If you use the second option, you need to set the first option to the empty string.'), - ); -} - -/** - * - */ -function PMA_transformation_application_octetstream__download(&$buffer, $options = array(), $meta = '') -{ - global $row, $fields_meta; - - if (isset($options[0]) && !empty($options[0])) { - $cn = $options[0]; // filename - } else { - if (isset($options[1]) && !empty($options[1])) { - foreach ($fields_meta as $key => $val) { - if ($val->name == $options[1]) { - $pos = $key; - break; - } - } - if (isset($pos)) { - $cn = $row[$pos]; - } - } - if (empty($cn)) { - $cn = 'binary_file.dat'; - } - } - - return sprintf( - '%s', - $options['wrapper_link'], - urlencode($cn), - htmlspecialchars($cn), - htmlspecialchars($cn) - ); -} - -?> diff --git a/libraries/transformations/application_octetstream__hex.inc.php b/libraries/transformations/application_octetstream__hex.inc.php deleted file mode 100644 index 5b30343823..0000000000 --- a/libraries/transformations/application_octetstream__hex.inc.php +++ /dev/null @@ -1,37 +0,0 @@ - __('Displays hexadecimal representation of data. Optional first parameter specifies how often space will be added (defaults to 2 nibbles).'), - ); -} - -/** - * - */ -function PMA_transformation_application_octetstream__hex($buffer, $options = array(), $meta = '') -{ - // possibly use a global transform and feed it with special options - if (!isset($options[0])) { - $options[0] = 2; - } else { - $options[0] = (int)$options[0]; - } - - if ($options[0] < 1) { - return bin2hex($buffer); - } else { - return chunk_split(bin2hex($buffer), $options[0], ' '); - } - -} - -?> diff --git a/libraries/transformations/image_jpeg__inline.inc.php b/libraries/transformations/image_jpeg__inline.inc.php deleted file mode 100644 index 785a898700..0000000000 --- a/libraries/transformations/image_jpeg__inline.inc.php +++ /dev/null @@ -1,32 +0,0 @@ - __('Displays a clickable thumbnail. The options are the maximum width and height in pixels. The original aspect ratio is preserved.'), - ); -} - -/** - * - */ -function PMA_transformation_image_jpeg__inline($buffer, $options = array(), $meta = '') -{ - if (PMA_IS_GD2) { - $transform_options = array ('string' => '[__BUFFER__]'); - } else { - $transform_options = array ('string' => '[__BUFFER__]'); - } - $buffer = PMA_transformation_global_html_replace($buffer, $transform_options); - - return $buffer; -} - -?> diff --git a/libraries/transformations/image_jpeg__link.inc.php b/libraries/transformations/image_jpeg__link.inc.php deleted file mode 100644 index 5db2017390..0000000000 --- a/libraries/transformations/image_jpeg__link.inc.php +++ /dev/null @@ -1,28 +0,0 @@ - __('Displays a link to download this image.'), - ); -} - -/** - * - */ -function PMA_transformation_image_jpeg__link($buffer, $options = array(), $meta = '') -{ - $transform_options = array ('string' => '[BLOB]'); - $buffer = PMA_transformation_global_html_replace($buffer, $transform_options); - - return $buffer; -} - -?> diff --git a/libraries/transformations/image_png__inline.inc.php b/libraries/transformations/image_png__inline.inc.php deleted file mode 100644 index 5476f913cd..0000000000 --- a/libraries/transformations/image_png__inline.inc.php +++ /dev/null @@ -1,32 +0,0 @@ - __('Displays a clickable thumbnail. The options are the maximum width and height in pixels. The original aspect ratio is preserved.'), - ); -} - -/** - * - */ -function PMA_transformation_image_png__inline($buffer, $options = array(), $meta = '') -{ - if (PMA_IS_GD2) { - $transform_options = array ('string' => '[__BUFFER__]'); - } else { - $transform_options = array ('string' => '[__BUFFER__]'); - } - $buffer = PMA_transformation_global_html_replace($buffer, $transform_options); - - return $buffer; -} - -?> diff --git a/libraries/transformations/text_plain__append.inc.php b/libraries/transformations/text_plain__append.inc.php deleted file mode 100644 index 9afbec16fd..0000000000 --- a/libraries/transformations/text_plain__append.inc.php +++ /dev/null @@ -1,30 +0,0 @@ - __('Appends text to a string. The only option is the text to be appended (enclosed in single quotes, default empty string).'), - ); -} - -function PMA_transformation_text_plain__append($buffer, $options = array(), $meta = '') -{ - if (! isset($options[0]) || $options[0] == '') { - $options[0] = ''; - } - - $newtext = $buffer . htmlspecialchars($options[0]); //just append the option to the original text - - return $newtext; -} - -?> diff --git a/libraries/transformations/text_plain__dateformat.inc.php b/libraries/transformations/text_plain__dateformat.inc.php deleted file mode 100644 index 67aaa16e42..0000000000 --- a/libraries/transformations/text_plain__dateformat.inc.php +++ /dev/null @@ -1,105 +0,0 @@ - __('Displays a TIME, TIMESTAMP, DATETIME or numeric unix timestamp column as formatted date. The first option is the offset (in hours) which will be added to the timestamp (Default: 0). Use second option to specify a different date/time format string. Third option determines whether you want to see local date or UTC one (use "local" or "utc" strings) for that. According to that, date format has different value - for "local" see the documentation for PHP\'s strftime() function and for "utc" it is done using gmdate() function.'), - ); -} - -/** - * - */ -function PMA_transformation_text_plain__dateformat($buffer, $options = array(), $meta = '') -{ - // possibly use a global transform and feed it with special options - - // further operations on $buffer using the $options[] array. - if (empty($options[0])) { - $options[0] = 0; - } - - if (empty($options[2])) { - $options[2] = 'local'; - } else { - $options[2] = strtolower($options[2]); - } - - if (empty($options[1])) { - if ($options[2] == 'local') { - $options[1] = __('%B %d, %Y at %I:%M %p'); - } else { - $options[1] = 'Y-m-d H:i:s'; - } - } - - $timestamp = -1; - - // INT columns will be treated as UNIX timestamps - // and need to be detected before the verification for - // MySQL TIMESTAMP - if ($meta->type == 'int') { - $timestamp = $buffer; - - // Detect TIMESTAMP(6 | 8 | 10 | 12 | 14) - // TIMESTAMP (2 | 4) not supported here. - // (Note: prior to MySQL 4.1, TIMESTAMP has a display size, for example - // TIMESTAMP(8) means YYYYMMDD) - } else if (preg_match('/^(\d{2}){3,7}$/', $buffer)) { - - if (strlen($buffer) == 14 || strlen($buffer) == 8) { - $offset = 4; - } else { - $offset = 2; - } - - $d = array(); - $d['year'] = substr($buffer, 0, $offset); - $d['month'] = substr($buffer, $offset, 2); - $d['day'] = substr($buffer, $offset + 2, 2); - $d['hour'] = substr($buffer, $offset + 4, 2); - $d['minute'] = substr($buffer, $offset + 6, 2); - $d['second'] = substr($buffer, $offset + 8, 2); - - if (checkdate($d['month'], $d['day'], $d['year'])) { - $timestamp = mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'], $d['year']); - } - // If all fails, assume one of the dozens of valid strtime() syntaxes (http://www.gnu.org/manual/tar-1.12/html_chapter/tar_7.html) - } else { - if (preg_match('/^[0-9]\d{1,9}$/', $buffer)) { - $timestamp = (int)$buffer; - } else { - $timestamp = strtotime($buffer); - } - } - - // If all above failed, maybe it's a Unix timestamp already? - if ($timestamp < 0 && preg_match('/^[1-9]\d{1,9}$/', $buffer)) { - $timestamp = $buffer; - } - - // Reformat a valid timestamp - if ($timestamp >= 0) { - $timestamp -= $options[0] * 60 * 60; - $source = $buffer; - if ($options[2] == 'local') { - $text = PMA_localisedDate($timestamp, $options[1]); - } elseif ($options[2] == 'utc') { - $text = gmdate($options[1], $timestamp); - } else { - $text = 'INVALID DATE TYPE'; - } - $buffer = '' . $text . ''; - } - - return $buffer; -} - -?> diff --git a/libraries/transformations/text_plain__external.inc.php b/libraries/transformations/text_plain__external.inc.php deleted file mode 100644 index 0f013bc56f..0000000000 --- a/libraries/transformations/text_plain__external.inc.php +++ /dev/null @@ -1,107 +0,0 @@ - __('LINUX ONLY: Launches an external application and feeds it the column data via standard input. Returns the standard output of the application. The default is Tidy, to pretty-print HTML code. For security reasons, you have to manually edit the file libraries/transformations/text_plain__external.inc.php and list the tools you want to make available. The first option is then the number of the program you want to use and the second option is the parameters for the program. The third option, if set to 1, will convert the output using htmlspecialchars() (Default 1). The fourth option, if set to 1, will prevent wrapping and ensure that the output appears all on one line (Default 1).'), - ); -} - -/** - * - */ -function PMA_transformation_text_plain__external_nowrap($options = array()) -{ - if (!isset($options[3]) || $options[3] == '') { - $nowrap = true; - } elseif ($options[3] == '1' || $options[3] == 1) { - $nowrap = true; - } else { - $nowrap = false; - } - - return $nowrap; -} - -function PMA_transformation_text_plain__external($buffer, $options = array(), $meta = '') -{ - // possibly use a global transform and feed it with special options - - // further operations on $buffer using the $options[] array. - - $allowed_programs = array(); - - // - // WARNING: - // - // It's up to administrator to allow anything here. Note that users may - // specify any parameters, so when programs allow output redirection or - // any other possibly dangerous operations, you should write wrapper - // script that will publish only functions you really want. - // - // Add here program definitions like (note that these are NOT safe - // programs): - // - //$allowed_programs[0] = '/usr/local/bin/tidy'; - //$allowed_programs[1] = '/usr/local/bin/validate'; - - // no-op when no allowed programs - if (count($allowed_programs) == 0) { - return $buffer; - } - - if (!isset($options[0]) || $options[0] == '' || !isset($allowed_programs[$options[0]])) { - $program = $allowed_programs[0]; - } else { - $program = $allowed_programs[$options[0]]; - } - - if (!isset($options[1]) || $options[1] == '') { - $poptions = '-f /dev/null -i -wrap -q'; - } else { - $poptions = $options[1]; - } - - if (!isset($options[2]) || $options[2] == '') { - $options[2] = 1; - } - - if (!isset($options[3]) || $options[3] == '') { - $options[3] = 1; - } - - // needs PHP >= 4.3.0 - $newstring = ''; - $descriptorspec = array( - 0 => array("pipe", "r"), - 1 => array("pipe", "w") - ); - $process = proc_open($program . ' ' . $poptions, $descriptorspec, $pipes); - if (is_resource($process)) { - fwrite($pipes[0], $buffer); - fclose($pipes[0]); - - while (!feof($pipes[1])) { - $newstring .= fgets($pipes[1], 1024); - } - fclose($pipes[1]); - // we don't currently use the return value - proc_close($process); - } - - if ($options[2] == 1 || $options[2] == '2') { - $retstring = htmlspecialchars($newstring); - } else { - $retstring = $newstring; - } - - return $retstring; -} -?> diff --git a/libraries/transformations/text_plain__formatted.inc.php b/libraries/transformations/text_plain__formatted.inc.php deleted file mode 100644 index a02d657ac9..0000000000 --- a/libraries/transformations/text_plain__formatted.inc.php +++ /dev/null @@ -1,25 +0,0 @@ - __('Displays the contents of the column as-is, without running it through htmlspecialchars(). That is, the column is assumed to contain valid HTML.'), - ); -} - -/** - * - */ -function PMA_transformation_text_plain__formatted($buffer, $options = array(), $meta = '') -{ - return $buffer; -} - -?> diff --git a/libraries/transformations/text_plain__imagelink.inc.php b/libraries/transformations/text_plain__imagelink.inc.php deleted file mode 100644 index 9d41581369..0000000000 --- a/libraries/transformations/text_plain__imagelink.inc.php +++ /dev/null @@ -1,27 +0,0 @@ - __('Displays an image and a link; the column contains the filename. The first option is a URL prefix like "http://www.example.com/". The second and third options are the width and the height in pixels.'), - ); -} - -/** - * - */ -function PMA_transformation_text_plain__imagelink($buffer, $options = array(), $meta = '') -{ - $transform_options = array ('string' => '' . $buffer . ''); - $buffer = PMA_transformation_global_html_replace($buffer, $transform_options); - return $buffer; -} - -?> diff --git a/libraries/transformations/text_plain__link.inc.php b/libraries/transformations/text_plain__link.inc.php deleted file mode 100644 index e942286fca..0000000000 --- a/libraries/transformations/text_plain__link.inc.php +++ /dev/null @@ -1,32 +0,0 @@ - __('Displays a link; the column contains the filename. The first option is a URL prefix like "http://www.example.com/". The second option is a title for the link.'), - ); -} - -/** - * - */ -function PMA_transformation_text_plain__link($buffer, $options = array(), $meta = '') -{ - // $transform_options = array ('string' => '' . (isset($options[1]) ? $options[1] : '%1$s') . ''); - - $transform_options = array ('string' => '' . (isset($options[1]) ? $options[1] : $buffer) . ''); - - $buffer = PMA_transformation_global_html_replace($buffer, $transform_options); - - return $buffer; - -} - -?> diff --git a/libraries/transformations/text_plain__longToIpv4.inc.php b/libraries/transformations/text_plain__longToIpv4.inc.php deleted file mode 100644 index 14792b042d..0000000000 --- a/libraries/transformations/text_plain__longToIpv4.inc.php +++ /dev/null @@ -1,31 +0,0 @@ - __('Converts an (IPv4) Internet network address into a string in Internet standard dotted format.'), - ); -} - -/** - * returns IPv4 address - * - * @see http://php.net/long2ip - */ -function PMA_transformation_text_plain__longToIpv4($buffer, $options = array(), $meta = '') -{ - if ($buffer < 0 || $buffer > 4294967295) { - return $buffer; - } - - return long2ip($buffer); -} - -?> diff --git a/libraries/transformations/text_plain__sql.inc.php b/libraries/transformations/text_plain__sql.inc.php deleted file mode 100644 index 9be441c94d..0000000000 --- a/libraries/transformations/text_plain__sql.inc.php +++ /dev/null @@ -1,28 +0,0 @@ - __('Formats text as SQL query with syntax highlighting.'), - ); -} - -/** - * - */ -function PMA_transformation_text_plain__sql($buffer, $options = array(), $meta = '') -{ - $result = PMA_SQP_formatHtml(PMA_SQP_parse($buffer)); - // Need to clear error state not to break subsequent queries display. - PMA_SQP_resetError(); - return $result; -} - -?> diff --git a/libraries/transformations/text_plain__substr.inc.php b/libraries/transformations/text_plain__substr.inc.php deleted file mode 100644 index 5ab8c64dba..0000000000 --- a/libraries/transformations/text_plain__substr.inc.php +++ /dev/null @@ -1,59 +0,0 @@ - __('Displays a part of a string. The first option is the number of characters to skip from the beginning of the string (Default 0). The second option is the number of characters to return (Default: until end of string). The third option is the string to append and/or prepend when truncation occurs (Default: "...").'), - ); -} - -/** - * - */ -function PMA_transformation_text_plain__substr($buffer, $options = array(), $meta = '') -{ - // possibly use a global transform and feed it with special options - - // further operations on $buffer using the $options[] array. - if (!isset($options[0]) || $options[0] == '') { - $options[0] = 0; - } - - if (!isset($options[1]) || $options[1] == '') { - $options[1] = 'all'; - } - - if (!isset($options[2]) || $options[2] == '') { - $options[2] = '...'; - } - - $newtext = ''; - if ($options[1] != 'all') { - $newtext = PMA_substr($buffer, $options[0], $options[1]); - } else { - $newtext = PMA_substr($buffer, $options[0]); - } - - $length = strlen($newtext); - $baselength = strlen($buffer); - if ($length != $baselength) { - if ($options[0] != 0) { - $newtext = $options[2] . $newtext; - } - - if (($length + $options[0]) != $baselength) { - $newtext .= $options[2]; - } - } - - return $newtext; -} - -?> From beba0419ba410f4f5efb6d071d368816249a3a6c Mon Sep 17 00:00:00 2001 From: Alex Marin Date: Thu, 28 Jun 2012 07:14:13 +0300 Subject: [PATCH 55/55] oop: DisplayResults bug --- libraries/DisplayResults.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/DisplayResults.class.php b/libraries/DisplayResults.class.php index d096b39943..c4eb12fea0 100644 --- a/libraries/DisplayResults.class.php +++ b/libraries/DisplayResults.class.php @@ -3132,7 +3132,7 @@ class PMA_DisplayResults $function_nowrap = 'applyTransformationNoWrap'; $bool_nowrap = (($default_function != $transformation_plugin) - && function_exists($transformation_plugin->$function_nowrap)) + && function_exists($transformation_plugin->$function_nowrap())) ? $transformation_plugin->$function_nowrap($transform_options) : false;