Export.php 26.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * functions for displaying server, database and table export
 *
 * @package PhpMyAdmin
 */
namespace PhpMyAdmin\Display;

use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Encoding;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins;
use PhpMyAdmin\Plugins\ExportPlugin;
use PhpMyAdmin\Relation;
use PhpMyAdmin\Response;
use PhpMyAdmin\Table;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;

/**
 * PhpMyAdmin\Display\Export class
 *
 * @package PhpMyAdmin
 */
class Export
{
    /**
     * @var Relation $relation
     */
    private $relation;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->relation = new Relation();
    }

    /**
     * Outputs appropriate checked statement for checkbox.
     *
     * @param string $str option name
     *
     * @return boolean
     */
    private function checkboxCheck($str)
    {
        return isset($GLOBALS['cfg']['Export'][$str])
            && $GLOBALS['cfg']['Export'][$str];
    }

    /**
     * Prints Html For Export Selection Options
     *
     * @param string $tmpSelect Tmp selected method of export
     *
     * @return string
     */
    public function getHtmlForSelectOptions($tmpSelect = '')
    {
        // Check if the selected databases are defined in $_POST
        // (from clicking Back button on export.php)
        if (isset($_POST['db_select'])) {
            $_POST['db_select'] = urldecode($_POST['db_select']);
            $_POST['db_select'] = explode(",", $_POST['db_select']);
        }

        $databases = [];
        foreach ($GLOBALS['dblist']->databases as $currentDb) {
            if ($GLOBALS['dbi']->isSystemSchema($currentDb, true)) {
                continue;
            }
            $isSelected = false;
            if (isset($_POST['db_select'])) {
                if (in_array($currentDb, $_POST['db_select'])) {
                    $isSelected = true;
                }
            } elseif (!empty($tmpSelect)) {
                if (mb_strpos(
                    ' ' . $tmpSelect,
                    '|' . $currentDb . '|'
                )) {
                    $isSelected = true;
                }
            } else {
                $isSelected = true;
            }
            $databases[] = [
                'name' => $currentDb,
                'is_selected' => $isSelected,
            ];
        }

        return Template::get('display/export/select_options')->render([
            'databases' => $databases,
        ]);
    }

    /**
     * Prints Html For Export Hidden Input
     *
     * @param string $exportType  Selected Export Type
     * @param string $db          Selected DB
     * @param string $table       Selected Table
     * @param string $singleTable Single Table
     * @param string $sqlQuery    SQL Query
     *
     * @return string
     */
    public function getHtmlForHiddenInputs(
        $exportType,
        $db,
        $table,
        $singleTable,
        $sqlQuery
    ) {
        global $cfg;

        // If the export method was not set, the default is quick
        if (isset($_POST['export_method'])) {
            $cfg['Export']['method'] = $_POST['export_method'];
        } elseif (! isset($cfg['Export']['method'])) {
            $cfg['Export']['method'] = 'quick';
        }

        if (empty($sqlQuery) && isset($_POST['sql_query'])) {
            $sqlQuery = $_POST['sql_query'];
        }

        return Template::get('display/export/hidden_inputs')->render([
            'db' => $db,
            'table' => $table,
            'export_type' => $exportType,
            'export_method' => $cfg['Export']['method'],
            'single_table' => $singleTable,
            'sql_query' => $sqlQuery,
            'template_id' => isset($_POST['template_id']) ? $_POST['template_id'] : '',
        ]);
    }

    /**
     * Returns HTML for the options in template dropdown
     *
     * @param string $exportType export type - server, database, or table
     *
     * @return string HTML for the options in teplate dropdown
     */
    private function getOptionsForTemplates($exportType)
    {
        // Get the relation settings
        $cfgRelation = $this->relation->getRelationsParam();

        $query = "SELECT `id`, `template_name` FROM "
           . Util::backquote($cfgRelation['db']) . '.'
           . Util::backquote($cfgRelation['export_templates'])
           . " WHERE `username` = "
           . "'" . $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['user'])
            . "' AND `export_type` = '" . $GLOBALS['dbi']->escapeString($exportType) . "'"
           . " ORDER BY `template_name`;";

        $result = $this->relation->queryAsControlUser($query);

        $templates = [];
        if ($result !== false) {
            while ($row = $GLOBALS['dbi']->fetchAssoc($result, DatabaseInterface::CONNECT_CONTROL)) {
                $templates[] = [
                    'name' => $row['template_name'],
                    'id' => $row['id'],
                ];
            }
        }

        return Template::get('display/export/template_options')->render([
            'templates' => $templates,
            'selected_template' => !empty($_POST['template_id']) ? $_POST['template_id'] : null,
        ]);
    }

    /**
     * Prints Html For Export Options Method
     *
     * @return string
     */
    private function getHtmlForOptionsMethod()
    {
        global $cfg;
        if (isset($_POST['quick_or_custom'])) {
            $exportMethod = $_POST['quick_or_custom'];
        } else {
            $exportMethod = $cfg['Export']['method'];
        }

        return Template::get('display/export/method')->render([
            'export_method' => $exportMethod,
        ]);
    }

    /**
     * Prints Html For Export Options Selection
     *
     * @param string $exportType  Selected Export Type
     * @param string $multiValues Export Options
     *
     * @return string
     */
    private function getHtmlForOptionsSelection($exportType, $multiValues)
    {
        return Template::get('display/export/selection')->render([
            'export_type' => $exportType,
            'multi_values' => $multiValues,
        ]);
    }

    /**
     * Prints Html For Export Options Format dropdown
     *
     * @param ExportPlugin[] $exportList Export List
     *
     * @return string
     */
    private function getHtmlForOptionsFormatDropdown($exportList)
    {
        $dropdown = Plugins::getChoice('Export', 'what', $exportList, 'format');
        return Template::get('display/export/format_dropdown')->render([
            'dropdown' => $dropdown,
        ]);
    }

    /**
     * Prints Html For Export Options Format-specific options
     *
     * @param ExportPlugin[] $exportList Export List
     *
     * @return string
     */
    private function getHtmlForOptionsFormat($exportList)
    {
        global $cfg;
        $options = Plugins::getOptions('Export', $exportList);

        return Template::get('display/export/options_format')->render([
            'options' => $options,
            'can_convert_kanji' => Encoding::canConvertKanji(),
            'exec_time_limit' => $cfg['ExecTimeLimit'],
        ]);
    }

    /**
     * Prints Html For Export Options Rows
     *
     * @param string $db           Selected DB
     * @param string $table        Selected Table
     * @param string $unlimNumRows Num of Rows
     *
     * @return string
     */
    private function getHtmlForOptionsRows($db, $table, $unlimNumRows)
    {
        $tableObject = new Table($table, $db);
        $numberOfRows = $tableObject->countRecords();

        return Template::get('display/export/options_rows')->render([
            'allrows' => isset($_POST['allrows']) ? $_POST['allrows'] : null,
            'limit_to' => isset($_POST['limit_to']) ? $_POST['limit_to'] : null,
            'limit_from' => isset($_POST['limit_from']) ? $_POST['limit_from'] : null,
            'unlim_num_rows' => $unlimNumRows,
            'number_of_rows' => $numberOfRows,
        ]);
    }

    /**
     * Prints Html For Export Options Quick Export
     *
     * @return string
     */
    private function getHtmlForOptionsQuickExport()
    {
        global $cfg;
        $saveDir = Util::userDir($cfg['SaveDir']);
        $exportIsChecked = $this->checkboxCheck(
            'quick_export_onserver'
        );
        $exportOverwriteIsChecked = $this->checkboxCheck(
            'quick_export_onserver_overwrite'
        );

        return Template::get('display/export/options_quick_export')->render([
            'save_dir' => $saveDir,
            'export_is_checked' => $exportIsChecked,
            'export_overwrite_is_checked' => $exportOverwriteIsChecked,
        ]);
    }

    /**
     * Prints Html For Export Options Save Dir
     *
     * @return string
     */
    private function getHtmlForOptionsOutputSaveDir()
    {
        global $cfg;
        $saveDir = Util::userDir($cfg['SaveDir']);
        $exportIsChecked = $this->checkboxCheck(
            'onserver'
        );
        $exportOverwriteIsChecked = $this->checkboxCheck(
            'onserver_overwrite'
        );

        return Template::get('display/export/options_output_save_dir')->render([
            'save_dir' => $saveDir,
            'export_is_checked' => $exportIsChecked,
            'export_overwrite_is_checked' => $exportOverwriteIsChecked,
        ]);
    }


    /**
     * Prints Html For Export Options
     *
     * @param string $exportType Selected Export Type
     *
     * @return string
     */
    private function getHtmlForOptionsOutputFormat($exportType)
    {
        $trans = new Message;
        $trans->addText(__('@SERVER@ will become the server name'));
        if ($exportType == 'database' || $exportType == 'table') {
            $trans->addText(__(', @DATABASE@ will become the database name'));
            if ($exportType == 'table') {
                $trans->addText(__(', @TABLE@ will become the table name'));
            }
        }

        $msg = new Message(
            __(
                'This value is interpreted using %1$sstrftime%2$s, '
                . 'so you can use time formatting strings. '
                . 'Additionally the following transformations will happen: %3$s. '
                . 'Other text will be kept as is. See the %4$sFAQ%5$s for details.'
            )
        );
        $msg->addParamHtml(
            '<a href="' . Core::linkURL(Core::getPHPDocLink('function.strftime.php'))
            . '" target="documentation" title="' . __('Documentation') . '">'
        );
        $msg->addParamHtml('</a>');
        $msg->addParam($trans);
        $docUrl = Util::getDocuLink('faq', 'faq6-27');
        $msg->addParamHtml(
            '<a href="' . $docUrl . '" target="documentation">'
        );
        $msg->addParamHtml('</a>');

        if (isset($_POST['filename_template'])) {
            $filenameTemplate = $_POST['filename_template'];
        } else {
            if ($exportType == 'database') {
                $filenameTemplate = $GLOBALS['PMA_Config']->getUserValue(
                    'pma_db_filename_template',
                    $GLOBALS['cfg']['Export']['file_template_database']
                );
            } elseif ($exportType == 'table') {
                $filenameTemplate = $GLOBALS['PMA_Config']->getUserValue(
                    'pma_table_filename_template',
                    $GLOBALS['cfg']['Export']['file_template_table']
                );
            } else {
                $filenameTemplate = $GLOBALS['PMA_Config']->getUserValue(
                    'pma_server_filename_template',
                    $GLOBALS['cfg']['Export']['file_template_server']
                );
            }
        }

        return Template::get('display/export/options_output_format')->render([
            'message' => $msg->getMessage(),
            'filename_template' => $filenameTemplate,
            'is_checked' => $this->checkboxCheck('remember_file_template'),
        ]);
    }

    /**
     * Prints Html For Export Options Charset
     *
     * @return string
     */
    private function getHtmlForOptionsOutputCharset()
    {
        global $cfg;

        return Template::get('display/export/options_output_charset')->render([
            'encodings' => Encoding::listEncodings(),
            'export_charset' => $cfg['Export']['charset'],
        ]);
    }

    /**
     * Prints Html For Export Options Compression
     *
     * @return string
     */
    private function getHtmlForOptionsOutputCompression()
    {
        global $cfg;
        if (isset($_POST['compression'])) {
            $selectedCompression = $_POST['compression'];
        } elseif (isset($cfg['Export']['compression'])) {
            $selectedCompression = $cfg['Export']['compression'];
        } else {
            $selectedCompression = 'none';
        }

        // Since separate files export works with ZIP only
        if (isset($cfg['Export']['as_separate_files'])
            && $cfg['Export']['as_separate_files']
        ) {
            $selectedCompression = 'zip';
        }

        // zip and gzip encode features
        $isZip = ($cfg['ZipDump'] && function_exists('gzcompress'));
        $isGzip = ($cfg['GZipDump'] && function_exists('gzencode'));

        return Template::get('display/export/options_output_compression')->render([
            'is_zip' => $isZip,
            'is_gzip' => $isGzip,
            'selected_compression' => $selectedCompression,
        ]);
    }

    /**
     * Prints Html For Export Options Radio
     *
     * @return string
     */
    private function getHtmlForOptionsOutputRadio()
    {
        return Template::get('display/export/options_output_radio')->render([
            'has_repopulate' => isset($_POST['repopulate']),
            'export_asfile' => $GLOBALS['cfg']['Export']['asfile'],
        ]);
    }

    /**
     * Prints Html For Export Options Checkbox - Separate files
     *
     * @param string $exportType Selected Export Type
     *
     * @return string
     */
    private function getHtmlForOptionsOutputSeparateFiles($exportType)
    {
        $isChecked = $this->checkboxCheck('as_separate_files');

        return Template::get('display/export/options_output_separate_files')->render([
            'is_checked' => $isChecked,
            'export_type' => $exportType,
        ]);
    }

    /**
     * Prints Html For Export Options
     *
     * @param string $exportType Selected Export Type
     *
     * @return string
     */
    private function getHtmlForOptionsOutput($exportType)
    {
        global $cfg;

        $hasAliases = isset($_SESSION['tmpval']['aliases'])
            && !Core::emptyRecursive($_SESSION['tmpval']['aliases']);
        unset($_SESSION['tmpval']['aliases']);

        $isCheckedLockTables = $this->checkboxCheck('lock_tables');
        $isCheckedAsfile = $this->checkboxCheck('asfile');

        $optionsOutputSaveDir = '';
        if (isset($cfg['SaveDir']) && !empty($cfg['SaveDir'])) {
            $optionsOutputSaveDir = $this->getHtmlForOptionsOutputSaveDir();
        }
        $optionsOutputFormat = $this->getHtmlForOptionsOutputFormat($exportType);
        $optionsOutputCharset = '';
        if (Encoding::isSupported()) {
            $optionsOutputCharset = $this->getHtmlForOptionsOutputCharset();
        }
        $optionsOutputCompression = $this->getHtmlForOptionsOutputCompression();
        $optionsOutputSeparateFiles = '';
        if ($exportType == 'server' || $exportType == 'database') {
            $optionsOutputSeparateFiles = $this->getHtmlForOptionsOutputSeparateFiles(
                $exportType
            );
        }
        $optionsOutputRadio = $this->getHtmlForOptionsOutputRadio();

        return Template::get('display/export/options_output')->render([
            'has_aliases' => $hasAliases,
            'export_type' => $exportType,
            'is_checked_lock_tables' => $isCheckedLockTables,
            'is_checked_asfile' => $isCheckedAsfile,
            'repopulate' => isset($_POST['repopulate']),
            'lock_tables' => isset($_POST['lock_tables']),
            'save_dir' => isset($cfg['SaveDir']) ? $cfg['SaveDir'] : null,
            'is_encoding_supported' => Encoding::isSupported(),
            'options_output_save_dir' => $optionsOutputSaveDir,
            'options_output_format' => $optionsOutputFormat,
            'options_output_charset' => $optionsOutputCharset,
            'options_output_compression' => $optionsOutputCompression,
            'options_output_separate_files' => $optionsOutputSeparateFiles,
            'options_output_radio' => $optionsOutputRadio,
        ]);
    }

    /**
     * Prints Html For Export Options
     *
     * @param string         $exportType   Selected Export Type
     * @param string         $db           Selected DB
     * @param string         $table        Selected Table
     * @param string         $multiValues  Export selection
     * @param string         $numTables    number of tables
     * @param ExportPlugin[] $exportList   Export List
     * @param string         $unlimNumRows Number of Rows
     *
     * @return string
     */
    public function getHtmlForOptions(
        $exportType,
        $db,
        $table,
        $multiValues,
        $numTables,
        $exportList,
        $unlimNumRows
    ) {
        global $cfg;
        $html = $this->getHtmlForOptionsMethod();
        $html .= $this->getHtmlForOptionsFormatDropdown($exportList);
        $html .= $this->getHtmlForOptionsSelection($exportType, $multiValues);

        $tableObject = new Table($table, $db);
        if (strlen($table) > 0 && empty($numTables) && ! $tableObject->isMerge()) {
            $html .= $this->getHtmlForOptionsRows($db, $table, $unlimNumRows);
        }

        if (isset($cfg['SaveDir']) && !empty($cfg['SaveDir'])) {
            $html .= $this->getHtmlForOptionsQuickExport();
        }

        $html .= $this->getHtmlForAliasModalDialog();
        $html .= $this->getHtmlForOptionsOutput($exportType);
        $html .= $this->getHtmlForOptionsFormat($exportList);
        return $html;
    }

    /**
     * Generate Html For currently defined aliases
     *
     * @return string
     */
    private function getHtmlForCurrentAlias()
    {
        $result = '<table id="alias_data"><thead><tr><th colspan="4">'
            . __('Defined aliases')
            . '</th></tr></thead><tbody>';

        $template = Template::get('export/alias_item');
        if (isset($_SESSION['tmpval']['aliases'])) {
            foreach ($_SESSION['tmpval']['aliases'] as $db => $dbData) {
                if (isset($dbData['alias'])) {
                    $result .= $template->render(array(
                        'type' => _pgettext('Alias', 'Database'),
                        'name' => $db,
                        'field' => 'aliases[' . $db . '][alias]',
                        'value' => $dbData['alias'],
                    ));
                }
                if (! isset($dbData['tables'])) {
                    continue;
                }
                foreach ($dbData['tables'] as $table => $tableData) {
                    if (isset($tableData['alias'])) {
                        $result .= $template->render(array(
                            'type' => _pgettext('Alias', 'Table'),
                            'name' => $db . '.' . $table,
                            'field' => 'aliases[' . $db . '][tables][' . $table . '][alias]',
                            'value' => $tableData['alias'],
                        ));
                    }
                    if (! isset($tableData['columns'])) {
                        continue;
                    }
                    foreach ($tableData['columns'] as $column => $columnName) {
                        $result .= $template->render(array(
                            'type' => _pgettext('Alias', 'Column'),
                            'name' => $db . '.' . $table . '.'. $column,
                            'field' => 'aliases[' . $db . '][tables][' . $table . '][colums][' . $column . ']',
                            'value' => $columnName,
                        ));
                    }
                }
            }
        }

        // Empty row for javascript manipulations
        $result .= '</tbody><tfoot class="hide">' . $template->render(array(
            'type' => '', 'name' => '', 'field' => 'aliases_new', 'value' => ''
        )) . '</tfoot>';

        return $result . '</table>';
    }

    /**
     * Generate Html For Alias Modal Dialog
     *
     * @return string
     */
    public function getHtmlForAliasModalDialog()
    {
        $title = __('Rename exported databases/tables/columns');

        $html = '<div id="alias_modal" class="hide" title="' . $title . '">';
        $html .= $this->getHtmlForCurrentAlias();
        $html .= Template::get('export/alias_add')->render();

        $html .= '</div>';
        return $html;
    }

    /**
     * Gets HTML to display export dialogs
     *
     * @param string $exportType   export type: server|database|table
     * @param string $db           selected DB
     * @param string $table        selected table
     * @param string $sqlQuery     SQL query
     * @param int    $numTables    number of tables
     * @param int    $unlimNumRows unlimited number of rows
     * @param string $multiValues  selector options
     *
     * @return string $html
     */
    public function getDisplay(
        $exportType,
        $db,
        $table,
        $sqlQuery,
        $numTables,
        $unlimNumRows,
        $multiValues
    ) {
        $cfgRelation = $this->relation->getRelationsParam();

        if (isset($_POST['single_table'])) {
            $GLOBALS['single_table'] = $_POST['single_table'];
        }

        // Export a single table
        if (isset($_GET['single_table'])) {
            $GLOBALS['single_table'] = $_GET['single_table'];
        }

        /* Scan for plugins */
        /* @var $exportList ExportPlugin[] */
        $exportList = Plugins::getPlugins(
            "export",
            'libraries/classes/Plugins/Export/',
            array(
                'export_type' => $exportType,
                'single_table' => isset($GLOBALS['single_table'])
            )
        );

        /* Fail if we didn't find any plugin */
        if (empty($exportList)) {
            Message::error(
                __('Could not load export plugins, please check your installation!')
            )->display();
            exit;
        }

        $html = Template::get('display/export/option_header')->render([
            'export_type' => $exportType,
            'db' => $db,
            'table' => $table,
        ]);

        if ($cfgRelation['exporttemplateswork']) {
            $html .= Template::get('display/export/template_loading')->render([
                'options' => $this->getOptionsForTemplates($exportType),
            ]);
        }

        $html .= '<form method="post" action="export.php" '
            . ' name="dump" class="disableAjax">';

        //output Hidden Inputs
        $singleTableStr = isset($GLOBALS['single_table']) ? $GLOBALS['single_table']
            : '';
        $html .= $this->getHtmlForHiddenInputs(
            $exportType,
            $db,
            $table,
            $singleTableStr,
            $sqlQuery
        );

        //output Export Options
        $html .= $this->getHtmlForOptions(
            $exportType,
            $db,
            $table,
            $multiValues,
            $numTables,
            $exportList,
            $unlimNumRows
        );

        $html .= '</form>';
        return $html;
    }

    /**
     * Handles export template actions
     *
     * @param array $cfgRelation Relation configuration
     *
     * @return void
     */
    public function handleTemplateActions(array $cfgRelation)
    {
        if (isset($_POST['templateId'])) {
            $id = $GLOBALS['dbi']->escapeString($_POST['templateId']);
        } else {
            $id = '';
        }

        $templateTable = Util::backquote($cfgRelation['db']) . '.'
           . Util::backquote($cfgRelation['export_templates']);
        $user = $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['user']);

        switch ($_POST['templateAction']) {
        case 'create':
            $query = "INSERT INTO " . $templateTable . "("
                . " `username`, `export_type`,"
                . " `template_name`, `template_data`"
                . ") VALUES ("
                . "'" . $user . "', "
                . "'" . $GLOBALS['dbi']->escapeString($_POST['exportType'])
                . "', '" . $GLOBALS['dbi']->escapeString($_POST['templateName'])
                . "', '" . $GLOBALS['dbi']->escapeString($_POST['templateData'])
                . "');";
            break;
        case 'load':
            $query = "SELECT `template_data` FROM " . $templateTable
                 . " WHERE `id` = " . $id  . " AND `username` = '" . $user . "'";
            break;
        case 'update':
            $query = "UPDATE " . $templateTable . " SET `template_data` = "
              . "'" . $GLOBALS['dbi']->escapeString($_POST['templateData']) . "'"
              . " WHERE `id` = " . $id  . " AND `username` = '" . $user . "'";
            break;
        case 'delete':
            $query = "DELETE FROM " . $templateTable
               . " WHERE `id` = " . $id  . " AND `username` = '" . $user . "'";
            break;
        default:
            $query = '';
            break;
        }

        $result = $this->relation->queryAsControlUser($query, false);

        $response = Response::getInstance();
        if (! $result) {
            $error = $GLOBALS['dbi']->getError(DatabaseInterface::CONNECT_CONTROL);
            $response->setRequestStatus(false);
            $response->addJSON('message', $error);
            exit;
        }

        $response->setRequestStatus(true);
        if ('create' == $_POST['templateAction']) {
            $response->addJSON(
                'data',
                $this->getOptionsForTemplates($_POST['exportType'])
            );
        } elseif ('load' == $_POST['templateAction']) {
            $data = null;
            while ($row = $GLOBALS['dbi']->fetchAssoc(
                $result, DatabaseInterface::CONNECT_CONTROL
            )) {
                $data = $row['template_data'];
            }
            $response->addJSON('data', $data);
        }
        $GLOBALS['dbi']->freeResult($result);
    }
}