/**
 * Cleanup database related relation stuff
 *
 * @param string $db
 */
function PMA_relationsCleanupDatabase($db)
{
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['commwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['bookmarkwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['bookmark']) . ' WHERE dbase  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['displaywork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_info']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['pdfwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['pdf_pages']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_coords']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['designerwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['designer_coords']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['relwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' WHERE master_db  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' WHERE foreign_db  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
}
/**
 * Saves user preferences
 *
 * @param array $config_array configuration array
 *
 * @return true|PMA\libraries\Message
 */
function PMA_saveUserprefs(array $config_array)
{
    $cfgRelation = PMA_getRelationsParam();
    $server = isset($GLOBALS['server']) ? $GLOBALS['server'] : $GLOBALS['cfg']['ServerDefault'];
    $cache_key = 'server_' . $server;
    if (!$cfgRelation['userconfigwork']) {
        // no pmadb table, use session storage
        $_SESSION['userconfig'] = array('db' => $config_array, 'ts' => time());
        if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
            unset($_SESSION['cache'][$cache_key]['userprefs']);
        }
        return true;
    }
    // save configuration to pmadb
    $query_table = PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['userconfig']);
    $query = 'SELECT `username` FROM ' . $query_table . ' WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($cfgRelation['user']) . '\'';
    $has_config = $GLOBALS['dbi']->fetchValue($query, 0, 0, $GLOBALS['controllink']);
    $config_data = json_encode($config_array);
    if ($has_config) {
        $query = 'UPDATE ' . $query_table . ' SET `timevalue` = NOW(), `config_data` = \'' . $GLOBALS['dbi']->escapeString($config_data) . '\'' . ' WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($cfgRelation['user']) . '\'';
    } else {
        $query = 'INSERT INTO ' . $query_table . ' (`username`, `timevalue`,`config_data`) ' . 'VALUES (\'' . $GLOBALS['dbi']->escapeString($cfgRelation['user']) . '\', NOW(), ' . '\'' . $GLOBALS['dbi']->escapeString($config_data) . '\')';
    }
    if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
        unset($_SESSION['cache'][$cache_key]['userprefs']);
    }
    if (!$GLOBALS['dbi']->tryQuery($query, $GLOBALS['controllink'])) {
        $message = Message::error(__('Could not save configuration'));
        $message->addMessage('<br /><br />');
        $message->addMessage(Message::rawError($GLOBALS['dbi']->getError($GLOBALS['controllink'])));
        return $message;
    }
    return true;
}
Example #3
0
/**
 * Get SQL query for store new transformation details of a VIEW
 *
 * @param mysqli_result $pma_transformation_data Result set of SQL execution
 * @param array         $column_map              Details of VIEW columns
 * @param string        $view_name               Name of the VIEW
 * @param string        $db                      Database name of the VIEW
 *
 * @return string $new_transformations_sql SQL query for new transformations
 */
function PMA_getNewTransformationDataSql($pma_transformation_data, $column_map, $view_name, $db)
{
    $cfgRelation = PMA_getRelationsParam();
    // Need to store new transformation details for VIEW
    $new_transformations_sql = 'INSERT INTO ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['column_info']) . ' (`db_name`, `table_name`, `column_name`, `comment`, ' . '`mimetype`, `transformation`, `transformation_options`)' . ' VALUES ';
    $column_count = 0;
    $add_comma = false;
    while ($data_row = $GLOBALS['dbi']->fetchAssoc($pma_transformation_data)) {
        foreach ($column_map as $column) {
            if ($data_row['table_name'] == $column['table_name'] && $data_row['column_name'] == $column['refering_column']) {
                $new_transformations_sql .= $add_comma ? ', ' : '';
                $new_transformations_sql .= '(' . '\'' . $db . '\', ' . '\'' . $view_name . '\', ' . '\'';
                $new_transformations_sql .= isset($column['real_column']) ? $column['real_column'] : $column['refering_column'];
                $new_transformations_sql .= '\', ' . '\'' . $data_row['comment'] . '\', ' . '\'' . $data_row['mimetype'] . '\', ' . '\'' . $data_row['transformation'] . '\', ' . '\'' . PMA_Util::sqlAddSlashes($data_row['transformation_options']) . '\')';
                $add_comma = true;
                $column_count++;
                break;
            }
        }
        if ($column_count == count($column_map)) {
            break;
        }
    }
    return $column_count > 0 ? $new_transformations_sql : '';
}
 /**
  * Setup function for test cases
  *
  * @access protected
  * @return void
  */
 protected function setUp()
 {
     /**
      * SET these to avoid undefined index error
      */
     $_SESSION['PMA_Theme'] = new PMA_Theme();
     $_POST['zoom_submit'] = 'zoom';
     $GLOBALS['server'] = 1;
     $GLOBALS['PMA_PHP_SELF'] = 'index.php';
     $GLOBALS['pmaThemeImage'] = 'themes/dot.gif';
     $GLOBALS['is_ajax_request'] = false;
     $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
     $GLOBALS['PMA_Types'] = new PMA_Types_MySQL();
     $GLOBALS['cfg']['ServerDefault'] = 1;
     $GLOBALS['cfg']['maxRowPlotLimit'] = 500;
     $GLOBALS['cfg']['Server']['DisableIS'] = false;
     $GLOBALS['cfg']['ServerDefault'] = 1;
     $GLOBALS['cfg']['ActionLinksMode'] = 'both';
     $GLOBALS['cfg']['ForeignKeyMaxLimit'] = 100;
     $GLOBALS['cfg']['InitialSlidersState'] = 'closed';
     $GLOBALS['cfg']['MaxRows'] = 25;
     $GLOBALS['cfg']['TabsMode'] = 'text';
     $dbi = $this->getMockBuilder('PMA_DatabaseInterface')->disableOriginalConstructor()->getMock();
     $columns = array(array('Field' => 'Field1', 'Type' => 'Type1', 'Null' => 'Null1', 'Collation' => 'Collation1'), array('Field' => 'Field2', 'Type' => 'Type2', 'Null' => 'Null2', 'Collation' => 'Collation2'));
     $dbi->expects($this->any())->method('getColumns')->will($this->returnValue($columns));
     $show_create_table = "CREATE TABLE `pma_bookmark` (\n        `id` int(11) NOT NULL AUTO_INCREMENT,\n        `dbase` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n        `user` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n        `label` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',\n        `query` text COLLATE utf8_bin NOT NULL,\n        PRIMARY KEY (`id`),\n        KEY `foreign_field` (`foreign_db`,`foreign_table`)\n        ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin " . "COMMENT='Bookmarks'";
     $dbi->expects($this->any())->method('fetchValue')->will($this->returnValue($show_create_table));
     $GLOBALS['dbi'] = $dbi;
 }
 /**
  * Test for PMA_getRelationsParam & PMA_getRelationsParamDiagnostic
  *
  * @return void
  */
 public function testPMAGetRelationsParam()
 {
     $relationsPara = PMA_getRelationsParam();
     $this->assertEquals(false, $relationsPara['relwork']);
     $this->assertEquals(false, $relationsPara['bookmarkwork']);
     $this->assertEquals('root', $relationsPara['user']);
     $this->assertEquals('phpmyadmin', $relationsPara['db']);
     $retval = PMA_getRelationsParamDiagnostic($relationsPara);
     //check $cfg['Servers'][$i]['pmadb']
     $this->assertContains("\$cfg['Servers'][\$i]['pmadb']", $retval);
     $this->assertContains('<strong>OK</strong>', $retval);
     //$cfg['Servers'][$i]['relation']
     $result = "\$cfg['Servers'][\$i]['pmadb']  ... </th><td class=\"right\">" . "<font color=\"green\"><strong>OK</strong></font>";
     $this->assertContains($result, $retval);
     // $cfg['Servers'][$i]['relation']
     $result = "\$cfg['Servers'][\$i]['relation']  ... </th><td class=\"right\">" . "<font color=\"red\"><strong>not OK</strong></font>";
     $this->assertContains($result, $retval);
     // General relation features
     $result = 'General relation features: <font color="red">Disabled</font>';
     $this->assertContains($result, $retval);
     // $cfg['Servers'][$i]['table_info']
     $result = "\$cfg['Servers'][\$i]['table_info']  ... </th>" . "<td class=\"right\">" . "<font color=\"red\"><strong>not OK</strong></font>";
     $this->assertContains($result, $retval);
     // Display Features:
     $result = 'Display Features: <font color="red">Disabled</font>';
     $this->assertContains($result, $retval);
     $relationsPara['db'] = false;
     $retval = PMA_getRelationsParamDiagnostic($relationsPara);
     $result = __('General relation features');
     $this->assertContains($result, $retval);
     $result = 'Configuration of pmadbโ€ฆ ';
     $this->assertContains($result, $retval);
     $result = "<strong>not OK</strong>";
     $this->assertContains($result, $retval);
 }
 /**
  * Sets the import plugin properties.
  * Called in the constructor.
  *
  * @return void
  */
 protected function setProperties()
 {
     $this->_setCfgRelation(PMA_getRelationsParam());
     $cfgRelation = $this->_getCfgRelation();
     if ($GLOBALS['num_tables'] < 1 || !$cfgRelation['relwork'] || !$cfgRelation['commwork']) {
         return;
     }
     $props = 'libraries/properties/';
     include_once "{$props}/plugins/ImportPluginProperties.class.php";
     include_once "{$props}/options/groups/OptionsPropertyRootGroup.class.php";
     include_once "{$props}/options/groups/OptionsPropertyMainGroup.class.php";
     include_once "{$props}/options/items/TextPropertyItem.class.php";
     $importPluginProperties = new ImportPluginProperties();
     $importPluginProperties->setText('DocSQL');
     $importPluginProperties->setExtension('');
     $importPluginProperties->setOptionsText(__('Options'));
     // create the root group that will be the options field for
     // $importPluginProperties
     // this will be shown as "Format specific options"
     $importSpecificOptions = new OptionsPropertyRootGroup();
     $importSpecificOptions->setName("Format Specific Options");
     // general options main group
     $generalOptions = new OptionsPropertyMainGroup();
     $generalOptions->setName("general_opts");
     // create primary items and add them to the group
     $leaf = new TextPropertyItem();
     $leaf->setName("table");
     $leaf->setText(__('Table name'));
     $generalOptions->addProperty($leaf);
     // add the main group to the root group
     $importSpecificOptions->addProperty($generalOptions);
     // set the options for the import plugin property item
     $importPluginProperties->setOptions($importSpecificOptions);
     $this->properties = $importPluginProperties;
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  *
  * @access protected
  * @return void
  */
 protected function setUp()
 {
     $_REQUEST['page_number'] = 33;
     $_REQUEST['dia_show_color'] = true;
     $_REQUEST['dia_show_keys'] = true;
     $_REQUEST['dia_orientation'] = 'orientation';
     $_REQUEST['dia_paper'] = 'paper';
     $_REQUEST['t_h'] = array('information_schema.files' => 1);
     $_REQUEST['t_x'] = array('information_schema.files' => 0);
     $_REQUEST['t_y'] = array('information_schema.files' => 0);
     $GLOBALS['server'] = 1;
     $GLOBALS['controllink'] = null;
     $GLOBALS['db'] = 'information_schema';
     $GLOBALS['cfg']['ServerDefault'] = 1;
     $GLOBALS['cfg']['Server']['table_coords'] = "table_name";
     //_SESSION
     $_SESSION['relation'][$GLOBALS['server']] = array('PMA_VERSION' => PMA_VERSION, 'table_coords' => "table_name", 'displaywork' => 'displaywork', 'db' => "information_schema", 'table_info' => 'table_info', 'relwork' => 'relwork', 'relation' => 'relation');
     PMA_getRelationsParam();
     $dbi = $this->getMockBuilder('PMA_DatabaseInterface')->disableOriginalConstructor()->getMock();
     $dbi->expects($this->any())->method('numRows')->will($this->returnValue(1));
     $dbi->expects($this->any())->method('query')->will($this->returnValue("executed_1"));
     $dbi->expects($this->any())->method('tryQuery')->will($this->returnValue("executed_1"));
     $fetchArrayReturn = array('table_name' => 'CHARACTER_SETS');
     $fetchArrayReturn2 = array('table_name' => 'COLLATIONS');
     $dbi->expects($this->at(2))->method('fetchAssoc')->will($this->returnValue($fetchArrayReturn));
     $dbi->expects($this->at(3))->method('fetchAssoc')->will($this->returnValue($fetchArrayReturn2));
     $dbi->expects($this->at(4))->method('fetchAssoc')->will($this->returnValue(false));
     $getIndexesResult = array(array('Table' => 'pma_tbl', 'Field' => 'field1', 'Key' => 'PRIMARY', 'Key_name' => "Key_name", 'Column_name' => "Column_name"));
     $dbi->expects($this->any())->method('getTableIndexes')->will($this->returnValue($getIndexesResult));
     $fetchValue = "CREATE TABLE `pma_bookmark` (\n             `id` int(11) NOT NULL AUTO_INCREMENT,\n              `dbase` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n              `user` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n              `label` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',\n              `query` text COLLATE utf8_bin NOT NULL,\n              PRIMARY KEY (`id`)\n             ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 " . "COLLATE=utf8_bin COMMENT='Bookmarks'";
     $dbi->expects($this->any())->method('fetchValue')->will($this->returnValue($fetchValue));
     $GLOBALS['dbi'] = $dbi;
     $this->object = new PMA_Dia_Relation_Schema('information_schema');
 }
 /**
  * Setup function for test cases
  *
  * @access protected
  * @return void
  */
 protected function setUp()
 {
     /**
      * SET these to avoid undefined index error
      */
     $_SESSION['PMA_Theme'] = new Theme();
     $_POST['zoom_submit'] = 'zoom';
     $GLOBALS['server'] = 1;
     $GLOBALS['PMA_PHP_SELF'] = 'index.php';
     $GLOBALS['pmaThemeImage'] = 'themes/dot.gif';
     $GLOBALS['is_ajax_request'] = false;
     $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
     $GLOBALS['PMA_Types'] = new TypesMySQL();
     $GLOBALS['cfg']['Server']['DisableIS'] = false;
     $dbi = $this->getMockBuilder('PMA\\libraries\\DatabaseInterface')->disableOriginalConstructor()->getMock();
     $columns = array(array('Field' => 'Field1', 'Type' => 'Type1', 'Null' => 'Null1', 'Collation' => 'Collation1'), array('Field' => 'Field2', 'Type' => 'Type2', 'Null' => 'Null2', 'Collation' => 'Collation2'));
     $dbi->expects($this->any())->method('getColumns')->will($this->returnValue($columns));
     $show_create_table = "CREATE TABLE `pma_bookmark` (\n        `id` int(11) NOT NULL AUTO_INCREMENT,\n        `dbase` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n        `user` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n        `label` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',\n        `query` text COLLATE utf8_bin NOT NULL,\n        PRIMARY KEY (`id`),\n        KEY `foreign_field` (`foreign_db`,`foreign_table`)\n        ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin " . "COMMENT='Bookmarks'";
     $dbi->expects($this->any())->method('fetchValue')->will($this->returnValue($show_create_table));
     $GLOBALS['dbi'] = $dbi;
     $this->_response = new PMA\Test\Stubs\Response();
     $container = Container::getDefaultContainer();
     $container->set('db', 'PMA');
     $container->set('table', 'PMA_BookMark');
     $container->set('dbi', $GLOBALS['dbi']);
     $container->set('response', $this->_response);
     $container->set('searchType', 'replace');
 }
Example #9
0
 /**
  * Configures environment
  *
  * @return void
  */
 protected function setUp()
 {
     /**
      * SET these to avoid undefined index error
      */
     $GLOBALS['server'] = 0;
     $GLOBALS['cfg']['Server']['DisableIS'] = false;
     $GLOBALS['cfg']['ServerDefault'] = 1;
     $GLOBALS['cfg']['ActionLinksMode'] = 'both';
     $GLOBALS['cfg']['MaxExactCount'] = 100;
     $GLOBALS['cfg']['MaxExactCountViews'] = 100;
     $GLOBALS['cfg']['Server']['pmadb'] = "pmadb";
     $GLOBALS['sql_auto_increment'] = true;
     $GLOBALS['sql_if_not_exists'] = true;
     $GLOBALS['sql_drop_table'] = true;
     $GLOBALS['cfg']['Server']['table_uiprefs'] = "pma__table_uiprefs";
     $_SESSION['PMA_Theme'] = new PMA_Theme();
     $GLOBALS['pmaThemeImage'] = 'themes/dot.gif';
     $GLOBALS['is_ajax_request'] = false;
     $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
     $GLOBALS['pma'] = new DataBasePMAMock();
     $GLOBALS['pma']->databases = new DataBaseMock();
     $sql_isView_true = "SELECT TABLE_NAME\n            FROM information_schema.VIEWS\n            WHERE TABLE_SCHEMA = 'PMA'\n                AND TABLE_NAME = 'PMA_BookMark'";
     $sql_isView_false = "SELECT TABLE_NAME\n            FROM information_schema.VIEWS\n            WHERE TABLE_SCHEMA = 'PMA'\n                AND TABLE_NAME = 'PMA_BookMark_2'";
     $sql_isUpdatableView_true = "SELECT TABLE_NAME\n            FROM information_schema.VIEWS\n            WHERE TABLE_SCHEMA = 'PMA'\n                AND TABLE_NAME = 'PMA_BookMark'\n                AND IS_UPDATABLE = 'YES'";
     $sql_isUpdatableView_false = "SELECT TABLE_NAME\n            FROM information_schema.VIEWS\n            WHERE TABLE_SCHEMA = 'PMA'\n                AND TABLE_NAME = 'PMA_BookMark_2'\n                AND IS_UPDATABLE = 'YES'";
     $sql_analyzeStructure_true = "SELECT COLUMN_NAME, DATA_TYPE\n                FROM information_schema.COLUMNS\n                WHERE TABLE_SCHEMA = 'PMA'\n                AND TABLE_NAME = 'PMA_BookMark'";
     $sql_copy_data = "SELECT TABLE_NAME\n            FROM information_schema.VIEWS\n            WHERE TABLE_SCHEMA = 'db_data'\n                AND TABLE_NAME = 'table_data'";
     $getUniqueColumns_sql = "select unique column";
     $fetchResult = array(array($sql_isView_true, null, null, null, 0, true), array($sql_copy_data, null, null, null, 0, false), array($sql_isView_false, null, null, null, 0, false), array($sql_isUpdatableView_true, null, null, null, 0, true), array($sql_isUpdatableView_false, null, null, null, 0, false), array($sql_analyzeStructure_true, null, null, null, 0, array(array('COLUMN_NAME' => 'COLUMN_NAME', 'DATA_TYPE' => 'DATA_TYPE'))), array($getUniqueColumns_sql, array('Key_name', null), 'Column_name', null, 0, array(array('index1'), array('index3'), array('index5'))), array($getUniqueColumns_sql, 'Column_name', 'Column_name', null, 0, array('column1', 'column3', 'column5', 'ACCESSIBLE', 'ADD', 'ALL')), array('SHOW COLUMNS FROM `PMA`.`PMA_BookMark`', 'Field', 'Field', null, 0, array('column1', 'column3', 'column5', 'ACCESSIBLE', 'ADD', 'ALL')));
     $dbi = $this->getMockBuilder('PMA_DatabaseInterface')->disableOriginalConstructor()->getMock();
     $dbi->expects($this->any())->method('fetchResult')->will($this->returnValueMap($fetchResult));
     $dbi->expects($this->any())->method('fetchValue')->will($this->returnValue("CREATE TABLE `PMA`.`PMA_BookMark_2` (\n                    `id` int(11) NOT NULL AUTO_INCREMENT,\n                    `username` text NOT NULL\n                    )"));
     $dbi->_table_cache["PMA"]["PMA_BookMark"] = array('ENGINE' => true, 'Create_time' => true, 'TABLE_TYPE' => true, 'Comment' => true);
     $databases = array();
     $database_name = 'PMA';
     $databases[$database_name]['SCHEMA_TABLES'] = 1;
     $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 3;
     $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 5;
     $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 10;
     $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 10;
     $databases[$database_name]['SCHEMA_LENGTH'] = 10;
     $dbi->expects($this->any())->method('getTablesFull')->will($this->returnValue($databases));
     $dbi->expects($this->any())->method('isSystemSchema')->will($this->returnValue(false));
     $dbi->expects($this->any())->method('numRows')->will($this->returnValue(20));
     $dbi->expects($this->any())->method('tryQuery')->will($this->returnValue(10));
     $triggers = array(array("name" => "name1", "create" => "crate1"), array("name" => "name2", "create" => "crate2"), array("name" => "name3", "create" => "crate3"));
     $dbi->expects($this->any())->method('getTriggers')->will($this->returnValue($triggers));
     $create_sql = "CREATE TABLE `PMA`.`PMA_BookMark_2` (\n                    `id` int(11) NOT NULL AUTO_INCREMENT,\n                    `username` text NOT NULL";
     $dbi->expects($this->any())->method('query')->will($this->returnValue($create_sql));
     $dbi->expects($this->any())->method('getTableIndexesSql')->will($this->returnValue($getUniqueColumns_sql));
     $dbi->expects($this->any())->method('insertId')->will($this->returnValue(10));
     $dbi->expects($this->any())->method('fetchAssoc')->will($this->returnValue(false));
     $value = array("Auto_increment" => "Auto_increment");
     $dbi->expects($this->any())->method('fetchSingleRow')->will($this->returnValue($value));
     $dbi->expects($this->any())->method('fetchRow')->will($this->returnValue(false));
     $GLOBALS['dbi'] = $dbi;
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  *
  * @access protected
  * @return void
  */
 protected function setUp()
 {
     $_REQUEST['page_number'] = 33;
     $_REQUEST['pdf_show_grid'] = true;
     $_REQUEST['pdf_show_color'] = true;
     $_REQUEST['pdf_show_keys'] = true;
     $_REQUEST['pdf_orientation'] = 'orientation';
     $_REQUEST['pdf_show_table_dimension'] = true;
     $_REQUEST['pdf_all_tables_same_width'] = true;
     $_REQUEST['pdf_paper'] = 'paper';
     $_REQUEST['pdf_table_order'] = '';
     $_REQUEST['t_h'] = array('information_schema.files' => 1);
     $_REQUEST['t_x'] = array('information_schema.files' => 0);
     $_REQUEST['t_y'] = array('information_schema.files' => 0);
     $GLOBALS['server'] = 1;
     $GLOBALS['controllink'] = null;
     $GLOBALS['db'] = 'information_schema';
     $GLOBALS['cfg']['Server']['pmadb'] = "pmadb";
     $GLOBALS['cfg']['LimitChars'] = 100;
     $GLOBALS['cfg']['ServerDefault'] = 1;
     $GLOBALS['cfg']['Server']['user'] = "******";
     $GLOBALS['cfg']['Server']['table_coords'] = "table_name";
     $GLOBALS['cfg']['Server']['bookmarktable'] = "bookmarktable";
     $GLOBALS['cfg']['Server']['relation'] = "relation";
     $GLOBALS['cfg']['Server']['table_info'] = "table_info";
     //_SESSION
     $_SESSION['relation'][$GLOBALS['server']] = array('PMA_VERSION' => PMA_VERSION, 'table_coords' => "table_name", 'displaywork' => 'displaywork', 'db' => "information_schema", 'table_info' => 'table_info', 'relwork' => false, 'relation' => 'relation', 'mimework' => 'mimework', 'commwork' => 'commwork', 'column_info' => 'column_info', 'pdf_pages' => 'pdf_pages');
     PMA_getRelationsParam();
     $dbi = $this->getMockBuilder('PMA\\libraries\\DatabaseInterface')->disableOriginalConstructor()->getMock();
     $dbi->expects($this->any())->method('numRows')->will($this->returnValue(1));
     $dbi->expects($this->any())->method('query')->will($this->returnValue("executed_1"));
     $dbi->expects($this->any())->method('tryQuery')->will($this->returnValue("executed_1"));
     $fetchArrayReturn = array('table_name' => 'CHARACTER_SETS');
     $fetchArrayReturn2 = array('table_name' => 'COLLATIONS');
     $dbi->expects($this->at(2))->method('fetchAssoc')->will($this->returnValue($fetchArrayReturn));
     $dbi->expects($this->at(3))->method('fetchAssoc')->will($this->returnValue($fetchArrayReturn2));
     $dbi->expects($this->at(4))->method('fetchAssoc')->will($this->returnValue(false));
     $fetchRowReturn = array('table_name', 'table_name');
     //let fetchRow have more results
     for ($index = 0; $index < 4; ++$index) {
         $dbi->expects($this->at($index))->method('fetchRow')->will($this->returnValue($fetchRowReturn));
     }
     $fields_info = array("Host" => array("Field" => "host", "Type" => "char(60)", "Null" => "NO", 'Extra' => "Extra"));
     $dbi->expects($this->any())->method('getColumns')->will($this->returnValue($fields_info));
     $dbi->expects($this->any())->method('selectDb')->will($this->returnValue(true));
     $getIndexesResult = array(array('Table' => 'pma_tbl', 'Field' => 'field1', 'Key' => 'PRIMARY', 'Key_name' => "Key_name", 'Column_name' => "Column_name"));
     $dbi->expects($this->any())->method('getTableIndexes')->will($this->returnValue($getIndexesResult));
     $fetchValue = "CREATE TABLE `pma_bookmark` (\n             `id` int(11) NOT NULL AUTO_INCREMENT,\n              `dbase` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n              `user` varchar(255) COLLATE utf8_bin NOT NULL DEFAULT '',\n              `label` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',\n              `query` text COLLATE utf8_bin NOT NULL,\n              PRIMARY KEY (`id`)\n             ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 " . "COLLATE=utf8_bin COMMENT='Bookmarks'";
     $dbi->expects($this->any())->method('fetchValue')->will($this->returnValue($fetchValue));
     $fetchResult = array('column1' => array('mimetype' => 'value1', 'transformation' => 'pdf'), 'column2' => array('mimetype' => 'value2', 'transformation' => 'xml'));
     $dbi->expects($this->any())->method('fetchResult')->will($this->returnValue($fetchResult));
     $GLOBALS['dbi'] = $dbi;
     $this->object = new PdfRelationSchema('information_schema');
 }
 /**
  * Returns HTML for hide button displayed infront of the database child node
  *
  * @return String HTML for hide button
  */
 public function getHtmlForControlButtons()
 {
     $ret = '';
     $cfgRelation = PMA_getRelationsParam();
     if ($cfgRelation['navwork']) {
         $db = $this->realParent()->real_name;
         $item = $this->real_name;
         $ret = '<span class="navItemControls">' . '<a href="navigation.php' . PMA_URL_getCommon() . '&hideNavItem=true' . '&itemType=' . urlencode($this->getItemType()) . '&itemName=' . urlencode($item) . '&dbName=' . urlencode($db) . '"' . ' class="hideNavItem ajax">' . PMA_Util::getImage('lightbulb_off.png', __('Hide')) . '</a></span>';
     }
     return $ret;
 }
/**
 * Saves user preferences
 *
 * @param array $config_array configuration array
 *
 * @return true|PMA_Message
 */
function PMA_save_userprefs(array $config_array)
{
    
    $common_functions = PMA_CommonFunctions::getInstance();
    $cfgRelation = PMA_getRelationsParam();
    $server = isset($GLOBALS['server'])
        ? $GLOBALS['server']
        : $GLOBALS['cfg']['ServerDefault'];
    $cache_key = 'server_' . $server;
    if (! $cfgRelation['userconfigwork']) {
        // no pmadb table, use session storage
        $_SESSION['userconfig'] = array(
            'db' => $config_array,
            'ts' => time());
        if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
            unset($_SESSION['cache'][$cache_key]['userprefs']);
        }
        return true;
    }

    // save configuration to pmadb
    $query_table = $common_functions->backquote($cfgRelation['db']) . '.'
        . $common_functions->backquote($cfgRelation['userconfig']);
    $query = '
        SELECT `username`
        FROM ' . $query_table . '
          WHERE `username` = \'' . $common_functions->sqlAddSlashes($cfgRelation['user']) . '\'';

    $has_config = PMA_DBI_fetch_value($query, 0, 0, $GLOBALS['controllink']);
    $config_data = json_encode($config_array);
    if ($has_config) {
        $query = '
            UPDATE ' . $query_table . '
            SET `config_data` = \'' . $common_functions->sqlAddSlashes($config_data) . '\'
            WHERE `username` = \'' . $common_functions->sqlAddSlashes($cfgRelation['user']) . '\'';
    } else {
        $query = '
            INSERT INTO ' . $query_table . ' (`username`, `config_data`)
            VALUES (\'' . $common_functions->sqlAddSlashes($cfgRelation['user']) . '\',
                \'' . $common_functions->sqlAddSlashes($config_data) . '\')';
    }
    if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
        unset($_SESSION['cache'][$cache_key]['userprefs']);
    }
    if (!PMA_DBI_try_query($query, $GLOBALS['controllink'])) {
        $message = PMA_Message::error(__('Could not save configuration'));
        $message->addMessage('<br /><br />');
        $message->addMessage(
            PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink']))
        );
        return $message;
    }
    return true;
}
 /**
  * Returns HTML for control buttons displayed infront of a node
  *
  * @return String HTML for control buttons
  */
 public function getHtmlForControlButtons()
 {
     $ret = '';
     $cfgRelation = PMA_getRelationsParam();
     if ($cfgRelation['navwork']) {
         $db = $this->realParent()->real_name;
         $item = $this->real_name;
         $params = array('hideNavItem' => true, 'itemType' => $this->getItemType(), 'itemName' => $item, 'dbName' => $db);
         $ret = '<span class="navItemControls">' . '<a href="navigation.php' . URL::getCommon($params) . '"' . ' class="hideNavItem ajax">' . PMA\libraries\Util::getImage('hide.png', __('Hide')) . '</a></span>';
     }
     return $ret;
 }
/**
 * Defines the central_columns parameters for the current user
 *
 * @return array    the central_columns parameters for the current user
 * @access  public
 */
function PMA_centralColumnsGetParams()
{
    static $cfgCentralColumns = null;
    if (null !== $cfgCentralColumns) {
        return $cfgCentralColumns;
    }
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['centralcolumnswork']) {
        $cfgCentralColumns = array('user' => $GLOBALS['cfg']['Server']['user'], 'db' => $cfgRelation['db'], 'table' => $cfgRelation['central_columns']);
    } else {
        $cfgCentralColumns = false;
    }
    return $cfgCentralColumns;
}
/**
 * Defines the bookmark parameters for the current user
 *
 * @uses    $GLOBALS['server']
 * @uses    PMA_getRelationsParam()
 * @uses    $GLOBALS['cfg']['Server']['user']
 * @uses    $GLOBALS['cfg']['Server']['pmadb']
 * @uses    $GLOBALS['cfg']['Server']['bookmarktable']
 * @return  array    the bookmark parameters for the current user
 * @access  public
 */
function PMA_Bookmark_getParams()
{
    static $cfgBookmark = null;
    if (null !== $cfgBookmark) {
        return $cfgBookmark;
    }
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['bookmarkwork']) {
        $cfgBookmark = array('user' => $GLOBALS['cfg']['Server']['user'], 'db' => $GLOBALS['cfg']['Server']['pmadb'], 'table' => $GLOBALS['cfg']['Server']['bookmarktable']);
    } else {
        $cfgBookmark = false;
    }
    return $cfgBookmark;
}
/**
 * get the html of the form to add the new column to given table
 *
 * @param integer $num_fields number of columns to add
 * @param string  $db         current database
 * @param string  $table      current table
 * @param array   $columnMeta array containing default values for the fields
 *
 * @return string HTML
 */
function PMA_getHtmlForCreateNewColumn($num_fields, $db, $table, $columnMeta = array())
{
    $cfgRelation = PMA_getRelationsParam();
    $content_cells = array();
    $available_mime = array();
    $mime_map = array();
    if ($cfgRelation['mimework'] && $GLOBALS['cfg']['BrowseMIME']) {
        $mime_map = PMA_getMIME($db, $table);
        $available_mime = PMA_getAvailableMIMEtypes();
    }
    $comments_map = PMA_getComments($db, $table);
    for ($columnNumber = 0; $columnNumber < $num_fields; $columnNumber++) {
        $content_cells[$columnNumber] = array('columnNumber' => $columnNumber, 'columnMeta' => $columnMeta, 'type_upper' => '', 'length_values_input_size' => 8, 'length' => '', 'extracted_columnspec' => array(), 'submit_attribute' => null, 'comments_map' => $comments_map, 'fields_meta' => null, 'is_backup' => true, 'move_columns' => array(), 'cfgRelation' => $cfgRelation, 'available_mime' => isset($available_mime) ? $available_mime : array(), 'mime_map' => $mime_map);
    }
    return PMA\libraries\Template::get('columns_definitions/table_fields_definitions')->render(array('is_backup' => true, 'fields_meta' => null, 'mimework' => $cfgRelation['mimework'], 'content_cells' => $content_cells));
}
Example #17
0
/**
 * get the html of the form to add the new column to given table
 *
 * @param integer $num_fields number of columns to add
 * @param string  $db         current database
 * @param string  $table      current table
 * @param array   $columnMeta array containing default values for the fields
 *
 * @return HTML
 */
function PMA_getHtmlForCreateNewColumn($num_fields, $db, $table, $columnMeta = array())
{
    $cfgRelation = PMA_getRelationsParam();
    $content_cells = array();
    $available_mime = array();
    $mime_map = array();
    $header_cells = PMA_getHeaderCells(true, null, $cfgRelation['mimework'], $db, $table);
    if ($cfgRelation['mimework'] && $GLOBALS['cfg']['BrowseMIME']) {
        $mime_map = PMA_getMIME($db, $table);
        $available_mime = PMA_getAvailableMIMEtypes();
    }
    $comments_map = PMA_getComments($db, $table);
    for ($columnNumber = 0; $columnNumber < $num_fields; $columnNumber++) {
        $content_cells[$columnNumber] = PMA_getHtmlForColumnAttributes($columnNumber, $columnMeta, '', 8, '', null, array(), null, null, null, $comments_map, null, true, array(), $cfgRelation, isset($available_mime) ? $available_mime : array(), $mime_map);
    }
    return PMA_getHtmlForTableFieldDefinitions($header_cells, $content_cells);
}
Example #18
0
/**
 * returns the error report data collected from the current configuration or
 * from the request parameters sent by the error reporting js code.
 *
 * @param string $exception_type whether exception is 'js' or 'php'
 *
 * @return array error report if success, Empty Array otherwise
 */
function PMA_getReportData($exception_type = 'js')
{
    $relParams = PMA_getRelationsParam();
    // common params for both, php & js exceptions
    $report = array("pma_version" => PMA_VERSION, "browser_name" => PMA_USR_BROWSER_AGENT, "browser_version" => PMA_USR_BROWSER_VER, "user_os" => PMA_USR_OS, "server_software" => $_SERVER['SERVER_SOFTWARE'], "user_agent_string" => $_SERVER['HTTP_USER_AGENT'], "locale" => $_COOKIE['pma_lang'], "configuration_storage" => is_null($relParams['db']) ? "disabled" : "enabled", "php_version" => phpversion());
    if ($exception_type == 'js') {
        if (empty($_REQUEST['exception'])) {
            return array();
        }
        $exception = $_REQUEST['exception'];
        $exception["stack"] = PMA_translateStacktrace($exception["stack"]);
        list($uri, $script_name) = PMA_sanitizeUrl($exception["url"]);
        $exception["uri"] = $uri;
        unset($exception["url"]);
        $report["exception_type"] = 'js';
        $report["exception"] = $exception;
        $report["script_name"] = $script_name;
        $report["microhistory"] = $_REQUEST['microhistory'];
        if (!empty($_REQUEST['description'])) {
            $report['steps'] = $_REQUEST['description'];
        }
    } elseif ($exception_type == 'php') {
        $errors = array();
        // create php error report
        $i = 0;
        if (!isset($_SESSION['prev_errors']) || $_SESSION['prev_errors'] == '') {
            return array();
        }
        foreach ($_SESSION['prev_errors'] as $errorObj) {
            /* @var $errorObj PMA\libraries\Error */
            if ($errorObj->getLine() && $errorObj->getType() && $errorObj->getNumber() != E_USER_WARNING) {
                $errors[$i++] = array("lineNum" => $errorObj->getLine(), "file" => $errorObj->getFile(), "type" => $errorObj->getType(), "msg" => $errorObj->getOnlyMessage(), "stackTrace" => $errorObj->getBacktrace(5), "stackhash" => $errorObj->getHash());
            }
        }
        // if there were no 'actual' errors to be submitted.
        if ($i == 0) {
            return array();
            // then return empty array
        }
        $report["exception_type"] = 'php';
        $report["errors"] = $errors;
    } else {
        return array();
    }
    return $report;
}
/**
 * Cleanup database related relation stuff
 *
 * @param string $db database name
 *
 * @return void
 */
function PMA_relationsCleanupDatabase($db)
{
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['commwork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['column_info']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['bookmarkwork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['bookmark']) . ' WHERE dbase  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['displaywork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['table_info']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['pdfwork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['pdf_pages']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['table_coords']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['relwork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['relation']) . ' WHERE master_db  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['relation']) . ' WHERE foreign_db  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['uiprefswork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['table_uiprefs']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['navwork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['navigationhiding']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['savedsearcheswork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['savedsearches']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
    if (isset($cfgRelation['central_columnswork']) && $cfgRelation['central_columnswork']) {
        $remove_query = 'DELETE FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['central_columns']) . ' WHERE db_name  = \'' . PMA_Util::sqlAddSlashes($db) . '\'';
        PMA_queryAsControlUser($remove_query);
    }
}
 /**
  * Get SQL query for store new transformation details of a VIEW
  *
  * @param object $pma_transformation_data Result set of SQL execution
  * @param array  $column_map              Details of VIEW columns
  * @param string $view_name               Name of the VIEW
  * @param string $db                      Database name of the VIEW
  *
  * @return string $new_transformations_sql SQL query for new transformations
  */
 function getNewTransformationDataSql($pma_transformation_data, $column_map, $view_name, $db)
 {
     $cfgRelation = \PMA_getRelationsParam();
     // Need to store new transformation details for VIEW
     $new_transformations_sql = sprintf("INSERT INTO %s.%s (" . "`db_name`, `table_name`, `column_name`, " . "`comment`, `mimetype`, `transformation`, " . "`transformation_options`) VALUES", Util::backquote($cfgRelation['db']), Util::backquote($cfgRelation['column_info']));
     $column_count = 0;
     $add_comma = false;
     while ($data_row = $this->dbi->fetchAssoc($pma_transformation_data)) {
         foreach ($column_map as $column) {
             if ($data_row['table_name'] != $column['table_name'] || $data_row['column_name'] != $column['refering_column']) {
                 continue;
             }
             $new_transformations_sql .= sprintf("%s ('%s', '%s', '%s', '%s', '%s', '%s', '%s')", $add_comma ? ', ' : '', $db, $view_name, isset($column['real_column']) ? $column['real_column'] : $column['refering_column'], $data_row['comment'], $data_row['mimetype'], $data_row['transformation'], Util::sqlAddSlashes($data_row['transformation_options']));
             $add_comma = true;
             $column_count++;
             break;
         }
         if ($column_count == count($column_map)) {
             break;
         }
     }
     return $column_count > 0 ? $new_transformations_sql : '';
 }
}
// Get available character sets and storage engines
require_once './libraries/mysql_charsets.inc.php';
require_once './libraries/StorageEngine.class.php';
/**
 * Class for partition management
 */
require_once './libraries/Partition.class.php';
require_once './libraries/tbl_columns_definition_form.lib.php';
/** @var PMA_String $pmaString */
$pmaString = $GLOBALS['PMA_String'];
$length_values_input_size = 8;
$_form_params = PMA_getFormsParameters($server, $db, $table, $action, isset($num_fields) ? $num_fields : null, isset($selected) ? $selected : null);
$is_backup = $action != 'tbl_create.php' && $action != 'tbl_addfield.php';
require_once './libraries/transformations.lib.php';
$cfgRelation = PMA_getRelationsParam();
$comments_map = PMA_getComments($db, $table);
if (isset($fields_meta)) {
    $move_columns = PMA_getMoveColumns($db, $table);
}
if ($cfgRelation['mimework'] && $GLOBALS['cfg']['BrowseMIME']) {
    $mime_map = PMA_getMIME($db, $table);
    $available_mime = PMA_getAvailableMIMEtypes();
}
$header_cells = PMA_getHeaderCells($is_backup, isset($fields_meta) ? $fields_meta : null, $cfgRelation['mimework'], $db, $table);
//  workaround for field_fulltext, because its submitted indices contain
//  the index as a value, not a key. Inserted here for easier maintenance
//  and less code to change in existing files.
if (isset($field_fulltext) && is_array($field_fulltext)) {
    foreach ($field_fulltext as $fulltext_nr => $fulltext_indexkey) {
        $submit_fulltext[$fulltext_indexkey] = $fulltext_indexkey;
/**
 * Get table body for 'tableuserrights' table in userform
 *
 * @param array $db_rights user's database rights array
 *
 * @return string HTML snippet
 */
function PMA_getHtmlTableBodyForUserRights($db_rights)
{
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['menuswork']) {
        $users_table = PMA_Util::backquote($cfgRelation['db']) . "." . PMA_Util::backquote($cfgRelation['users']);
        $sql_query = 'SELECT * FROM ' . $users_table;
        $result = PMA_queryAsControlUser($sql_query, false);
        $group_assignment = array();
        if ($result) {
            while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
                $group_assignment[$row['username']] = $row['usergroup'];
            }
        }
        $GLOBALS['dbi']->freeResult($result);
        $user_group_count = PMA_getUserGroupCount();
    }
    $odd_row = true;
    $index_checkbox = 0;
    $html_output = '';
    foreach ($db_rights as $user) {
        ksort($user);
        foreach ($user as $host) {
            $index_checkbox++;
            $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">' . "\n";
            $html_output .= '<td>' . '<input type="checkbox" class="checkall" name="selected_usr[]" ' . 'id="checkbox_sel_users_' . $index_checkbox . '" value="' . htmlspecialchars($host['User'] . '&amp;#27;' . $host['Host']) . '"' . ' /></td>' . "\n";
            $html_output .= '<td><label ' . 'for="checkbox_sel_users_' . $index_checkbox . '">' . (empty($host['User']) ? '<span style="color: #FF0000">' . __('Any') . '</span>' : htmlspecialchars($host['User'])) . '</label></td>' . "\n" . '<td>' . htmlspecialchars($host['Host']) . '</td>' . "\n";
            $html_output .= '<td>';
            switch ($host['Password']) {
                case 'Y':
                    $html_output .= __('Yes');
                    break;
                case 'N':
                    $html_output .= '<span style="color: #FF0000">' . __('No') . '</span>';
                    break;
                    // this happens if this is a definition not coming from mysql.user
                // this happens if this is a definition not coming from mysql.user
                default:
                    $html_output .= '--';
                    // in future version, replace by "not present"
                    break;
            }
            // end switch
            $html_output .= '</td>' . "\n";
            $html_output .= '<td><code>' . "\n" . '' . implode(',' . "\n" . '            ', $host['privs']) . "\n" . '</code></td>' . "\n";
            if ($cfgRelation['menuswork']) {
                $html_output .= '<td class="usrGroup">' . "\n" . (isset($group_assignment[$host['User']]) ? $group_assignment[$host['User']] : '') . '</td>' . "\n";
            }
            $html_output .= '<td>' . ($host['Grant_priv'] == 'Y' ? __('Yes') : __('No')) . '</td>' . "\n";
            if ($GLOBALS['is_grantuser']) {
                $html_output .= '<td class="center">' . PMA_getUserLink('edit', $host['User'], $host['Host']) . '</td>';
            }
            if ($cfgRelation['menuswork'] && $user_group_count > 0) {
                if (empty($host['User'])) {
                    $html_output .= '<td class="center"></td>';
                } else {
                    $html_output .= '<td class="center">' . PMA_getUserGroupEditLink($host['User']) . '</td>';
                }
            }
            $html_output .= '<td class="center">' . PMA_getUserLink('export', $host['User'], $host['Host'], '', '', isset($_GET['initial']) ? $_GET['initial'] : '') . '</td>';
            $html_output .= '</tr>';
            $odd_row = !$odd_row;
        }
    }
    return $html_output;
}
Example #23
0
/**
 * Creates PMA tables in the given db, updates if already exists.
 *
 * @param string  $db     database
 * @param boolean $create whether to create tables if they don't exist.
 *
 * @return void
 */
function PMA_fixPMATables($db, $create = true)
{
    $tablesToFeatures = array('pma__bookmark' => 'bookmarktable', 'pma__relation' => 'relation', 'pma__table_info' => 'table_info', 'pma__table_coords' => 'table_coords', 'pma__pdf_pages' => 'pdf_pages', 'pma__column_info' => 'column_info', 'pma__history' => 'history', 'pma__recent' => 'recent', 'pma__favorite' => 'favorite', 'pma__table_uiprefs' => 'table_uiprefs', 'pma__tracking' => 'tracking', 'pma__userconfig' => 'userconfig', 'pma__users' => 'users', 'pma__usergroups' => 'usergroups', 'pma__navigationhiding' => 'navigationhiding', 'pma__savedsearches' => 'savedsearches', 'pma__central_columns' => 'central_columns');
    $existingTables = $GLOBALS['dbi']->getTables($db, $GLOBALS['controllink']);
    $createQueries = null;
    $foundOne = false;
    foreach ($tablesToFeatures as $table => $feature) {
        if (!in_array($table, $existingTables)) {
            if ($create) {
                if ($createQueries == null) {
                    // first create
                    $createQueries = PMA_getDefaultPMATableNames();
                    $GLOBALS['dbi']->selectDb($db);
                }
                $GLOBALS['dbi']->tryQuery($createQueries[$table]);
                if ($error = $GLOBALS['dbi']->getError()) {
                    $GLOBALS['message'] = $error;
                    return;
                }
                $GLOBALS['cfg']['Server'][$feature] = $table;
            }
        } else {
            $foundOne = true;
            $GLOBALS['cfg']['Server'][$feature] = $table;
        }
    }
    if (!$foundOne) {
        return;
    }
    $GLOBALS['cfg']['Server']['pmadb'] = $db;
    $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['recentwork'] || $cfgRelation['favoritework']) {
        // Since configuration storage is updated, we need to
        // re-initialize the favorite and recent tables stored in the
        // session from the current configuration storage.
        include_once 'libraries/RecentFavoriteTable.class.php';
        if ($cfgRelation['favoritework']) {
            $fav_tables = PMA_RecentFavoriteTable::getInstance('favorite');
            $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']] = $fav_tables->getFromDb();
        }
        if ($cfgRelation['recentwork']) {
            $recent_tables = PMA_RecentFavoriteTable::getInstance('recent');
            $_SESSION['tmpval']['recent_tables'][$GLOBALS['server']] = $recent_tables->getFromDb();
        }
        // Reload navi panel to update the recent/favorite lists.
        $GLOBALS['reload'] = true;
    }
}
 /**
  * Returns HTML for show hidden button displayed infront of database node
  *
  * @return String HTML for show hidden button
  */
 public function getHtmlForControlButtons()
 {
     $ret = '';
     $db = $this->real_name;
     $cfgRelation = PMA_getRelationsParam();
     if ($cfgRelation['navwork']) {
         $navTable = PMA_Util::backquote($cfgRelation['db']) . "." . PMA_Util::backquote($cfgRelation['navigationhiding']);
         $sqlQuery = "SELECT COUNT(*) FROM " . $navTable . " WHERE `username`='" . PMA_Util::sqlAddSlashes($GLOBALS['cfg']['Server']['user']) . "'" . " AND `db_name`='" . PMA_Util::sqlAddSlashes($db) . "'";
         $count = $GLOBALS['dbi']->fetchValue($sqlQuery, 0, 0, $GLOBALS['controllink']);
         if ($count > 0) {
             $ret = '<span class="dbItemControls">' . '<a href="navigation.php?' . PMA_URL_getCommon() . '&showUnhideDialog=true' . '&dbName=' . urldecode($db) . '"' . ' class="showUnhide ajax">' . PMA_Util::getImage('lightbulb.png', __('Show hidden items')) . '</a></span>';
         }
     }
     return $ret;
 }
Example #25
0
 /**
  * Sets default transformations for some columns
  *
  * @return void
  */
 private function _setDefaultTransformations()
 {
     $json_highlighting_data = array('libraries/plugins/transformations/output/Text_Plain_Json.class.php', 'Text_Plain_Json', 'Text_Plain');
     $sql_highlighting_data = array('libraries/plugins/transformations/output/Text_Plain_Sql.class.php', 'Text_Plain_Sql', 'Text_Plain');
     $blob_sql_highlighting_data = array('libraries/plugins/transformations/output/Text_Octetstream_Sql.class.php', 'Text_Octetstream_Sql', 'Text_Octetstream');
     $link_data = array('libraries/plugins/transformations/Text_Plain_Link.class.php', 'Text_Plain_Link', 'Text_Plain');
     $this->transformation_info = array('information_schema' => array('events' => array('event_definition' => $sql_highlighting_data), 'processlist' => array('info' => $sql_highlighting_data), 'routines' => array('routine_definition' => $sql_highlighting_data), 'triggers' => array('action_statement' => $sql_highlighting_data), 'views' => array('view_definition' => $sql_highlighting_data)), 'mysql' => array('event' => array('body' => $blob_sql_highlighting_data, 'body_utf8' => $blob_sql_highlighting_data), 'general_log' => array('argument' => $sql_highlighting_data), 'help_category' => array('url' => $link_data), 'help_topic' => array('example' => $sql_highlighting_data, 'url' => $link_data), 'proc' => array('param_list' => $blob_sql_highlighting_data, 'returns' => $blob_sql_highlighting_data, 'body' => $blob_sql_highlighting_data, 'body_utf8' => $blob_sql_highlighting_data), 'slow_log' => array('sql_text' => $sql_highlighting_data)));
     $cfgRelation = PMA_getRelationsParam();
     if ($cfgRelation['db']) {
         $this->transformation_info[$cfgRelation['db']] = array();
         $relDb =& $this->transformation_info[$cfgRelation['db']];
         if (!empty($cfgRelation['history'])) {
             $relDb[$cfgRelation['history']] = array('sqlquery' => $sql_highlighting_data);
         }
         if (!empty($cfgRelation['bookmark'])) {
             $relDb[$cfgRelation['bookmark']] = array('query' => $sql_highlighting_data);
         }
         if (!empty($cfgRelation['tracking'])) {
             $relDb[$cfgRelation['tracking']] = array('schema_sql' => $sql_highlighting_data, 'data_sql' => $sql_highlighting_data);
         }
         if (!empty($cfgRelation['favorite'])) {
             $relDb[$cfgRelation['favorite']] = array('tables' => $json_highlighting_data);
         }
         if (!empty($cfgRelation['recent'])) {
             $relDb[$cfgRelation['recent']] = array('tables' => $json_highlighting_data);
         }
         if (!empty($cfgRelation['savedsearches'])) {
             $relDb[$cfgRelation['savedsearches']] = array('search_data' => $json_highlighting_data);
         }
         if (!empty($cfgRelation['table_uiprefs'])) {
             $relDb[$cfgRelation['table_uiprefs']] = array('prefs' => $json_highlighting_data);
         }
         if (!empty($cfgRelation['userconfig'])) {
             $relDb[$cfgRelation['userconfig']] = array('config_data' => $json_highlighting_data);
         }
     }
 }
Example #26
0
 /**
  * renames table
  *
  * @param   string  new table name
  * @param   string  new database name
  * @return  boolean success
  */
 function rename($new_name, $new_db = null)
 {
     if (null !== $new_db && $new_db !== $this->getDbName()) {
         // Ensure the target is valid
         if (!$GLOBALS['PMA_List_Database']->exists($new_db)) {
             $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
             return false;
         }
     } else {
         $new_db = $this->getDbName();
     }
     $new_table = new PMA_Table($new_name, $new_db);
     if ($this->getFullName() === $new_table->getFullName()) {
         return true;
     }
     if (!PMA_Table::isValidName($new_name)) {
         $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
         return false;
     }
     $GLOBALS['sql_query'] = '
         RENAME TABLE ' . $this->getFullName(true) . '
                   TO ' . $new_table->getFullName(true) . ';';
     if (!PMA_DBI_query($GLOBALS['sql_query'])) {
         $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
         return false;
     }
     $old_name = $this->getName();
     $old_db = $this->getDbName();
     $this->setName($new_name);
     $this->setDbName($new_db);
     /**
      * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
      */
     // garvin: Move old entries from comments to new table
     require_once './libraries/relation.lib.php';
     $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
     if ($GLOBALS['cfgRelation']['commwork']) {
         $remove_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
                SET `db_name`    = \'' . PMA_sqlAddslashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddslashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
         PMA_query_as_cu($remove_query);
         unset($remove_query);
     }
     if ($GLOBALS['cfgRelation']['displaywork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
                SET `db_name`    = \'' . PMA_sqlAddslashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddslashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
         PMA_query_as_cu($table_query);
         unset($table_query);
     }
     if ($GLOBALS['cfgRelation']['relwork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
                SET `foreign_db`    = \'' . PMA_sqlAddslashes($new_db) . '\',
                    `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
              WHERE `foreign_db`    = \'' . PMA_sqlAddslashes($old_db) . '\'
                AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
         PMA_query_as_cu($table_query);
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
                SET `master_db`    = \'' . PMA_sqlAddslashes($new_db) . '\',
                    `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
              WHERE `master_db`    = \'' . PMA_sqlAddslashes($old_db) . '\'
                AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
         PMA_query_as_cu($table_query);
         unset($table_query);
     }
     if ($GLOBALS['cfgRelation']['pdfwork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
                SET `db_name`    = \'' . PMA_sqlAddslashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddslashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
         PMA_query_as_cu($table_query);
         unset($table_query);
     }
     if ($GLOBALS['cfgRelation']['designerwork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
                SET `db_name`    = \'' . PMA_sqlAddslashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddslashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
         PMA_query_as_cu($table_query);
         unset($table_query);
     }
     $this->messages[] = sprintf($GLOBALS['strRenameTableOK'], htmlspecialchars($old_name), htmlspecialchars($new_name));
     return true;
 }
Example #27
0
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Displays the 'User groups' sub page under 'Users' page.
 *
 * @package PhpMyAdmin
 */
use PMA\libraries\Response;

require_once 'libraries/common.inc.php';
require_once 'libraries/server_users.lib.php';
require_once 'libraries/server_user_groups.lib.php';

PMA_getRelationsParam();
if (! $GLOBALS['cfgRelation']['menuswork']) {
    exit;
}

$response = Response::getInstance();
$header   = $response->getHeader();
$scripts  = $header->getScripts();
$scripts->addFile('server_user_groups.js');

/**
 * Only allowed to superuser
 */
if (! $GLOBALS['is_superuser']) {
    $response->addHTML(
        PMA\libraries\Message::error(__('No Privileges'))
            ->getDisplay()
    );
Example #28
0
 /**
  * renames table
  *
  * @param string $new_name new table name
  * @param string $new_db   new database name
  * @param bool   $is_view  is this for a VIEW rename?
  * @todo    remove the $is_view parameter (also in callers)
  *
  * @return bool success
  */
 function rename($new_name, $new_db = null, $is_view = false)
 {
     if (null !== $new_db && $new_db !== $this->getDbName()) {
         // Ensure the target is valid
         if (!$GLOBALS['pma']->databases->exists($new_db)) {
             $this->errors[] = __('Invalid database') . ': ' . $new_db;
             return false;
         }
     } else {
         $new_db = $this->getDbName();
     }
     $new_table = new PMA_Table($new_name, $new_db);
     if ($this->getFullName() === $new_table->getFullName()) {
         return true;
     }
     if (!PMA_Table::isValidName($new_name)) {
         $this->errors[] = __('Invalid table name') . ': ' . $new_table->getFullName();
         return false;
     }
     // If the table is moved to a different database drop its triggers first
     $triggers = PMA_DBI_get_triggers($this->getDbName(), $this->getName(), '');
     $handle_triggers = $this->getDbName() != $new_db && $triggers;
     if ($handle_triggers) {
         foreach ($triggers as $trigger) {
             $sql = 'DROP TRIGGER IF EXISTS ' . PMA_backquote($this->getDbName()) . '.' . PMA_backquote($trigger['name']) . ';';
             PMA_DBI_query($sql);
         }
     }
     /*
      * tested also for a view, in MySQL 5.0.92, 5.1.55 and 5.5.13
      */
     $GLOBALS['sql_query'] = '
         RENAME TABLE ' . $this->getFullName(true) . '
               TO ' . $new_table->getFullName(true) . ';';
     // I don't think a specific error message for views is necessary
     if (!PMA_DBI_query($GLOBALS['sql_query'])) {
         // Restore triggers in the old database
         if ($handle_triggers) {
             PMA_DBI_select_db($this->getDbName());
             foreach ($triggers as $trigger) {
                 PMA_DBI_query($trigger['create']);
             }
         }
         $this->errors[] = sprintf(__('Error renaming table %1$s to %2$s'), $this->getFullName(), $new_table->getFullName());
         return false;
     }
     $old_name = $this->getName();
     $old_db = $this->getDbName();
     $this->setName($new_name);
     $this->setDbName($new_db);
     /**
      * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
      */
     // Move old entries from comments to new table
     $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
     if ($GLOBALS['cfgRelation']['commwork']) {
         $remove_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
                SET `db_name`    = \'' . PMA_sqlAddSlashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddSlashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
         PMA_query_as_controluser($remove_query);
         unset($remove_query);
     }
     if ($GLOBALS['cfgRelation']['displaywork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
                SET `db_name`    = \'' . PMA_sqlAddSlashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddSlashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
         PMA_query_as_controluser($table_query);
         unset($table_query);
     }
     if ($GLOBALS['cfgRelation']['relwork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
                SET `foreign_db`    = \'' . PMA_sqlAddSlashes($new_db) . '\',
                    `foreign_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
              WHERE `foreign_db`    = \'' . PMA_sqlAddSlashes($old_db) . '\'
                AND `foreign_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
         PMA_query_as_controluser($table_query);
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
                SET `master_db`    = \'' . PMA_sqlAddSlashes($new_db) . '\',
                    `master_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
              WHERE `master_db`    = \'' . PMA_sqlAddSlashes($old_db) . '\'
                AND `master_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
         PMA_query_as_controluser($table_query);
         unset($table_query);
     }
     if ($GLOBALS['cfgRelation']['pdfwork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
                SET `db_name`    = \'' . PMA_sqlAddSlashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddSlashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
         PMA_query_as_controluser($table_query);
         unset($table_query);
     }
     if ($GLOBALS['cfgRelation']['designerwork']) {
         $table_query = '
             UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
                SET `db_name`    = \'' . PMA_sqlAddSlashes($new_db) . '\',
                    `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
              WHERE `db_name`    = \'' . PMA_sqlAddSlashes($old_db) . '\'
                AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
         PMA_query_as_controluser($table_query);
         unset($table_query);
     }
     $this->messages[] = sprintf(__('Table %1$s has been renamed to %2$s.'), htmlspecialchars($old_name), htmlspecialchars($new_name));
     return true;
 }
Example #29
0
function PMA_RT_DOC($alltables)
{
    global $db, $pdf, $orientation;
    //TOC
    $pdf->addpage("P");
    $pdf->Cell(0, 9, $GLOBALS['strTableOfContents'], 1, 0, 'C');
    $pdf->Ln(15);
    $i = 1;
    foreach ($alltables as $table) {
        $pdf->PMA_links['doc'][$table]['-'] = $pdf->AddLink();
        $pdf->SetX(10);
        //$pdf->Ln(1);
        $pdf->Cell(0, 6, $GLOBALS['strPageNumber'] . ' {' . sprintf("%02d", $i) . '}', 0, 0, 'R', 0, $pdf->PMA_links['doc'][$table]['-']);
        $pdf->SetX(10);
        $pdf->Cell(0, 6, $i . ' ' . $table, 0, 1, 'L', 0, $pdf->PMA_links['doc'][$table]['-']);
        //$pdf->Ln(1);
        $local_query = 'SHOW FIELDS FROM ' . PMA_backquote($table);
        $result = PMA_mysql_query($local_query) or PMA_mysqlDie('', $local_query, '', $err_url);
        while ($row = PMA_mysql_fetch_array($result)) {
            $pdf->SetX(20);
            $field_name = $row['Field'];
            $pdf->PMA_links['doc'][$table][$field_name] = $pdf->AddLink();
            //$pdf->Cell(0,6,$field_name,0,1,'L',0,$pdf->PMA_links['doc'][$table][$field_name]);
        }
        $lasttable = $table;
        $i++;
    }
    $pdf->PMA_links['RT']['-'] = $pdf->AddLink();
    $pdf->SetX(10);
    $pdf->Cell(0, 6, $GLOBALS['strPageNumber'] . ' {00}', 0, 0, 'R', 0, $pdf->PMA_links['doc'][$lasttable]['-']);
    $pdf->SetX(10);
    $pdf->Cell(0, 6, $i . ' ' . $GLOBALS['strRelationalSchema'], 0, 1, 'L', 0, $pdf->PMA_links['RT']['-']);
    $z = 0;
    foreach ($alltables as $table) {
        $z++;
        $pdf->addpage($GLOBALS['orientation']);
        $pdf->Bookmark($table);
        $pdf->SetAlias('{' . sprintf("%02d", $z) . '}', $pdf->PageNo());
        $pdf->PMA_links['RT'][$table]['-'] = $pdf->AddLink();
        $pdf->SetLink($pdf->PMA_links['doc'][$table]['-'], -1);
        $pdf->SetFont('', 'B', 18);
        $pdf->Cell(0, 8, $z . ' ' . $table, 1, 1, 'C', 0, $pdf->PMA_links['RT'][$table]['-']);
        $pdf->SetFont('', '', 8);
        $pdf->ln();
        $cfgRelation = PMA_getRelationsParam();
        if ($cfgRelation['commwork']) {
            $comments = PMA_getComments($db, $table);
        }
        if ($cfgRelation['mimework']) {
            $mime_map = PMA_getMIME($db, $table, true);
        }
        /**
         * Gets table informations
         */
        $local_query = "SHOW TABLE STATUS LIKE '" . PMA_sqlAddslashes($table, TRUE) . "'";
        $result = PMA_mysql_query($local_query) or PMA_mysqlDie('', $local_query, '', $err_url);
        $showtable = PMA_mysql_fetch_array($result);
        $num_rows = isset($showtable['Rows']) ? $showtable['Rows'] : 0;
        $show_comment = isset($showtable['Comment']) ? $showtable['Comment'] : '';
        $create_time = isset($showtable['Create_time']) ? PMA_localisedDate(strtotime($showtable['Create_time'])) : '';
        $update_time = isset($showtable['Update_time']) ? PMA_localisedDate(strtotime($showtable['Update_time'])) : '';
        $check_time = isset($showtable['Check_time']) ? PMA_localisedDate(strtotime($showtable['Check_time'])) : '';
        if ($result) {
            mysql_free_result($result);
        }
        /**
         * Gets table keys and retains them
         */
        $local_query = 'SHOW KEYS FROM ' . PMA_backquote($table);
        $result = PMA_mysql_query($local_query) or PMA_mysqlDie('', $local_query, '', $err_url);
        $primary = '';
        $indexes = array();
        $lastIndex = '';
        $indexes_info = array();
        $indexes_data = array();
        $pk_array = array();
        // will be use to emphasis prim. keys in the table
        // view
        while ($row = PMA_mysql_fetch_array($result)) {
            // Backups the list of primary keys
            if ($row['Key_name'] == 'PRIMARY') {
                $primary .= $row['Column_name'] . ', ';
                $pk_array[$row['Column_name']] = 1;
            }
            // Retains keys informations
            if ($row['Key_name'] != $lastIndex) {
                $indexes[] = $row['Key_name'];
                $lastIndex = $row['Key_name'];
            }
            $indexes_info[$row['Key_name']]['Sequences'][] = $row['Seq_in_index'];
            $indexes_info[$row['Key_name']]['Non_unique'] = $row['Non_unique'];
            if (isset($row['Cardinality'])) {
                $indexes_info[$row['Key_name']]['Cardinality'] = $row['Cardinality'];
            }
            // I don't know what does following column mean....
            // $indexes_info[$row['Key_name']]['Packed']          = $row['Packed'];
            $indexes_info[$row['Key_name']]['Comment'] = $row['Comment'];
            $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Column_name'] = $row['Column_name'];
            if (isset($row['Sub_part'])) {
                $indexes_data[$row['Key_name']][$row['Seq_in_index']]['Sub_part'] = $row['Sub_part'];
            }
        }
        // end while
        if ($result) {
            mysql_free_result($result);
        }
        /**
         * Gets fields properties
         */
        $local_query = 'SHOW FIELDS FROM ' . PMA_backquote($table);
        $result = PMA_mysql_query($local_query) or PMA_mysqlDie('', $local_query, '', $err_url);
        $fields_cnt = mysql_num_rows($result);
        // Check if we can use Relations (Mike Beck)
        if (!empty($cfgRelation['relation'])) {
            // Find which tables are related with the current one and write it in
            // an array
            $res_rel = PMA_getForeigners($db, $table);
            if (count($res_rel) > 0) {
                $have_rel = TRUE;
            } else {
                $have_rel = FALSE;
            }
        } else {
            $have_rel = FALSE;
        }
        // end if
        /**
         * Displays the comments of the table if MySQL >= 3.23
         */
        $break = false;
        if (!empty($show_comment)) {
            $pdf->Cell(0, 3, $GLOBALS['strTableComments'] . ' : ' . $show_comment, 0, 1);
            $break = true;
        }
        if (!empty($create_time)) {
            $pdf->Cell(0, 3, $GLOBALS['strStatCreateTime'] . ': ' . $create_time, 0, 1);
            $break = true;
        }
        if (!empty($update_time)) {
            $pdf->Cell(0, 3, $GLOBALS['strStatUpdateTime'] . ': ' . $update_time, 0, 1);
            $break = true;
        }
        if (!empty($check_time)) {
            $pdf->Cell(0, 3, $GLOBALS['strStatCheckTime'] . ': ' . $check_time, 0, 1);
            $break = true;
        }
        if ($break == true) {
            $pdf->Cell(0, 3, '', 0, 1);
            $pdf->Ln();
        }
        $i = 0;
        $pdf->SetFont('', 'B');
        if (isset($orientation) && $orientation == 'L') {
            $pdf->Cell(25, 8, ucfirst($GLOBALS['strField']), 1, 0, 'C');
            $pdf->Cell(20, 8, ucfirst($GLOBALS['strType']), 1, 0, 'C');
            $pdf->Cell(20, 8, ucfirst($GLOBALS['strAttr']), 1, 0, 'C');
            $pdf->Cell(10, 8, ucfirst($GLOBALS['strNull']), 1, 0, 'C');
            $pdf->Cell(20, 8, ucfirst($GLOBALS['strDefault']), 1, 0, 'C');
            $pdf->Cell(25, 8, ucfirst($GLOBALS['strExtra']), 1, 0, 'C');
            $pdf->Cell(45, 8, ucfirst($GLOBALS['strLinksTo']), 1, 0, 'C');
            $pdf->Cell(67, 8, ucfirst($GLOBALS['strComments']), 1, 0, 'C');
            $pdf->Cell(45, 8, 'MIME', 1, 1, 'C');
            $pdf->SetWidths(array(25, 20, 20, 10, 20, 25, 45, 67, 45));
        } else {
            $pdf->Cell(20, 8, ucfirst($GLOBALS['strField']), 1, 0, 'C');
            $pdf->Cell(20, 8, ucfirst($GLOBALS['strType']), 1, 0, 'C');
            $pdf->Cell(20, 8, ucfirst($GLOBALS['strAttr']), 1, 0, 'C');
            $pdf->Cell(10, 8, ucfirst($GLOBALS['strNull']), 1, 0, 'C');
            $pdf->Cell(15, 8, ucfirst($GLOBALS['strDefault']), 1, 0, 'C');
            $pdf->Cell(15, 8, ucfirst($GLOBALS['strExtra']), 1, 0, 'C');
            $pdf->Cell(30, 8, ucfirst($GLOBALS['strLinksTo']), 1, 0, 'C');
            $pdf->Cell(30, 8, ucfirst($GLOBALS['strComments']), 1, 0, 'C');
            $pdf->Cell(30, 8, 'MIME', 1, 1, 'C');
            $pdf->SetWidths(array(20, 20, 20, 10, 15, 15, 30, 30, 30));
        }
        $pdf->SetFont('', '');
        while ($row = PMA_mysql_fetch_array($result)) {
            $bgcolor = $i % 2 ? $GLOBALS['cfg']['BgcolorOne'] : $GLOBALS['cfg']['BgcolorTwo'];
            $i++;
            $type = $row['Type'];
            // reformat mysql query output - staybyte - 9. June 2001
            // loic1: set or enum types: slashes single quotes inside options
            if (preg_match('@^(set|enum)\\((.+)\\)$@i', $type, $tmp)) {
                $tmp[2] = substr(preg_replace("@([^,])''@", "\\1\\'", ',' . $tmp[2]), 1);
                $type = $tmp[1] . '(' . str_replace(',', ', ', $tmp[2]) . ')';
                $type_nowrap = '';
                $binary = 0;
                $unsigned = 0;
                $zerofill = 0;
            } else {
                $type_nowrap = ' nowrap="nowrap"';
                $type = preg_replace('@BINARY@i', '', $type);
                $type = preg_replace('@ZEROFILL@i', '', $type);
                $type = preg_replace('@UNSIGNED@i', '', $type);
                if (empty($type)) {
                    $type = '&nbsp;';
                }
                $binary = stristr($row['Type'], 'BINARY');
                $unsigned = stristr($row['Type'], 'UNSIGNED');
                $zerofill = stristr($row['Type'], 'ZEROFILL');
            }
            $strAttribute = ' ';
            if ($binary) {
                $strAttribute = 'BINARY';
            }
            if ($unsigned) {
                $strAttribute = 'UNSIGNED';
            }
            if ($zerofill) {
                $strAttribute = 'UNSIGNED ZEROFILL';
            }
            if (!isset($row['Default'])) {
                if ($row['Null'] != '') {
                    $row['Default'] = 'NULL';
                }
            }
            $field_name = $row['Field'];
            //$pdf->Ln();
            $pdf->PMA_links['RT'][$table][$field_name] = $pdf->AddLink();
            $pdf->Bookmark($field_name, 1, -1);
            $pdf->SetLink($pdf->PMA_links['doc'][$table][$field_name], -1);
            $pdf_row = array($field_name, $type, $strAttribute, $row['Null'] == '' ? $GLOBALS['strNo'] : $GLOBALS['strYes'], isset($row['Default']) ? $row['Default'] : '', $row['Extra'], isset($res_rel[$field_name]) ? $res_rel[$field_name]['foreign_table'] . ' -> ' . $res_rel[$field_name]['foreign_field'] : '', isset($comments[$field_name]) ? $comments[$field_name] : '', isset($mime_map) && isset($mime_map[$field_name]) ? str_replace('_', '/', $mime_map[$field_name]['mimetype']) : '');
            $links[0] = $pdf->PMA_links['RT'][$table][$field_name];
            if (isset($res_rel[$field_name]['foreign_table']) and isset($res_rel[$field_name]['foreign_field']) and isset($pdf->PMA_links['doc'][$res_rel[$field_name]['foreign_table']][$res_rel[$field_name]['foreign_field']])) {
                $links[6] = $pdf->PMA_links['doc'][$res_rel[$field_name]['foreign_table']][$res_rel[$field_name]['foreign_field']];
            } else {
                unset($links[6]);
            }
            $pdf->Row($pdf_row, $links);
            /*$pdf->Cell(20,8,$field_name,1,0,'L',0,$pdf->PMA_links['RT'][$table][$field_name]);
                      //echo '    ' . $field_name . '&nbsp;' . "\n";
                  }
              $pdf->Cell(20,8,$type,1,0,'L');
              $pdf->Cell(20,8,$strAttribute,1,0,'L');
              $pdf->Cell(15,8,,1,0,'L');
              $pdf->Cell(15,8,((isset($row['Default'])) ?  $row['Default'] : ''),1,0,'L');
              $pdf->Cell(15,8,$row['Extra'],1,0,'L');
                 if ($have_rel) {
                      if (isset($res_rel[$field_name])) {
                          $pdf->Cell(30,8,$res_rel[$field_name]['foreign_table'] . ' -> ' . $res_rel[$field_name]['foreign_field'],1,0,'L');
                      }
                  }
                  if ($cfgRelation['commwork']) {
                      if (isset($comments[$field_name])) {
                          $pdf->Cell(0,8,$comments[$field_name],1,0,'L');
                      }
                  } */
        }
        // end while
        $pdf->SetFont('', '', 14);
        mysql_free_result($result);
    }
    //end each
}
/**
 * Cleanup user related relation stuff
 *
 * @param string $username username
 *
 * @return void
 */
function PMA_relationsCleanupUser($username)
{
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['bookmarkwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['bookmark']) . " WHERE `user`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['historywork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['history']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['recentwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['recent']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['favoritework']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['favorite']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['uiprefswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['table_uiprefs']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['userconfigwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['userconfig']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['menuswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['users']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['navwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['navigationhiding']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['savedsearcheswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['savedsearches']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['designersettingswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['designer_settings']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
}