Update website

This commit is contained in:
Guilhem Lavaux 2025-02-11 21:30:02 +01:00
parent 0a686aeb9a
commit c4ffa0f6ee
4360 changed files with 1727 additions and 718385 deletions

View file

@ -1,21 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Controllers\AbstractController as Controller;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
abstract class AbstractController extends Controller
{
/** @var string */
protected $db;
public function __construct(ResponseRenderer $response, Template $template, string $db)
{
parent::__construct($response, $template);
$this->db = $db;
}
}

View file

@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\CentralColumns;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Database\CentralColumns;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
final class PopulateColumnsController extends AbstractController
{
/** @var CentralColumns */
private $centralColumns;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
CentralColumns $centralColumns
) {
parent::__construct($response, $template, $db);
$this->centralColumns = $centralColumns;
}
public function __invoke(): void
{
$columns = $this->centralColumns->getColumnsNotInCentralList($this->db, $_POST['selectedTable']);
$this->render('database/central_columns/populate_columns', ['columns' => $columns]);
}
}

View file

@ -1,280 +0,0 @@
<?php
/**
* Central Columns view/edit
*/
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Database\CentralColumns;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use function __;
use function is_bool;
use function is_numeric;
use function parse_str;
use function sprintf;
class CentralColumnsController extends AbstractController
{
/** @var CentralColumns */
private $centralColumns;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
CentralColumns $centralColumns
) {
parent::__construct($response, $template, $db);
$this->centralColumns = $centralColumns;
}
public function __invoke(): void
{
global $cfg, $db, $message, $pos, $num_cols;
if (isset($_POST['edit_save'])) {
echo $this->editSave([
'col_name' => $_POST['col_name'] ?? null,
'orig_col_name' => $_POST['orig_col_name'] ?? null,
'col_default' => $_POST['col_default'] ?? null,
'col_default_sel' => $_POST['col_default_sel'] ?? null,
'col_extra' => $_POST['col_extra'] ?? null,
'col_isNull' => $_POST['col_isNull'] ?? null,
'col_length' => $_POST['col_length'] ?? null,
'col_attribute' => $_POST['col_attribute'] ?? null,
'col_type' => $_POST['col_type'] ?? null,
'collation' => $_POST['collation'] ?? null,
]);
return;
}
if (isset($_POST['add_new_column'])) {
$tmp_msg = $this->addNewColumn([
'col_name' => $_POST['col_name'] ?? null,
'col_default' => $_POST['col_default'] ?? null,
'col_default_sel' => $_POST['col_default_sel'] ?? null,
'col_extra' => $_POST['col_extra'] ?? null,
'col_isNull' => $_POST['col_isNull'] ?? null,
'col_length' => $_POST['col_length'] ?? null,
'col_attribute' => $_POST['col_attribute'] ?? null,
'col_type' => $_POST['col_type'] ?? null,
'collation' => $_POST['collation'] ?? null,
]);
}
if (isset($_POST['getColumnList'])) {
$this->response->addJSON('message', $this->getColumnList([
'cur_table' => $_POST['cur_table'] ?? null,
]));
return;
}
if (isset($_POST['add_column'])) {
$tmp_msg = $this->addColumn([
'table-select' => $_POST['table-select'] ?? null,
'column-select' => $_POST['column-select'] ?? null,
]);
}
$this->addScriptFiles([
'vendor/jquery/jquery.uitablefilter.js',
'vendor/jquery/jquery.tablesorter.js',
'database/central_columns.js',
]);
if (isset($_POST['edit_central_columns_page'])) {
$this->editPage([
'selected_fld' => $_POST['selected_fld'] ?? null,
'db' => $_POST['db'] ?? null,
]);
return;
}
if (isset($_POST['multi_edit_central_column_save'])) {
$message = $this->updateMultipleColumn([
'db' => $_POST['db'] ?? null,
'orig_col_name' => $_POST['orig_col_name'] ?? null,
'field_name' => $_POST['field_name'] ?? null,
'field_default_type' => $_POST['field_default_type'] ?? null,
'field_default_value' => $_POST['field_default_value'] ?? null,
'field_length' => $_POST['field_length'] ?? null,
'field_attribute' => $_POST['field_attribute'] ?? null,
'field_type' => $_POST['field_type'] ?? null,
'field_collation' => $_POST['field_collation'] ?? null,
'field_null' => $_POST['field_null'] ?? null,
'col_extra' => $_POST['col_extra'] ?? null,
]);
if (! is_bool($message)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', $message);
}
}
if (isset($_POST['delete_save'])) {
$tmp_msg = $this->deleteSave([
'db' => $_POST['db'] ?? null,
'col_name' => $_POST['col_name'] ?? null,
]);
}
$this->main([
'pos' => $_POST['pos'] ?? null,
'total_rows' => $_POST['total_rows'] ?? null,
]);
$pos = 0;
if (isset($_POST['pos']) && is_numeric($_POST['pos'])) {
$pos = (int) $_POST['pos'];
}
$num_cols = $this->centralColumns->getColumnsCount($db, $pos, (int) $cfg['MaxRows']);
$message = Message::success(
sprintf(__('Showing rows %1$s - %2$s.'), $pos + 1, $pos + $num_cols)
);
if (! isset($tmp_msg) || $tmp_msg === true) {
return;
}
$message = $tmp_msg;
}
/**
* @param array $params Request parameters
*/
public function main(array $params): void
{
global $text_dir;
if (! empty($params['total_rows']) && is_numeric($params['total_rows'])) {
$totalRows = (int) $params['total_rows'];
} else {
$totalRows = $this->centralColumns->getCount($this->db);
}
$pos = 0;
if (isset($params['pos']) && is_numeric($params['pos'])) {
$pos = (int) $params['pos'];
}
$variables = $this->centralColumns->getTemplateVariablesForMain($this->db, $totalRows, $pos, $text_dir);
$this->render('database/central_columns/main', $variables);
}
/**
* @param array $params Request parameters
*
* @return array JSON
*/
public function getColumnList(array $params): array
{
return $this->centralColumns->getListRaw($this->db, $params['cur_table'] ?? '');
}
/**
* @param array $params Request parameters
*
* @return true|Message
*/
public function editSave(array $params)
{
$columnDefault = $params['col_default'];
if ($columnDefault === 'NONE' && $params['col_default_sel'] !== 'USER_DEFINED') {
$columnDefault = '';
}
return $this->centralColumns->updateOneColumn(
$this->db,
$params['orig_col_name'],
$params['col_name'],
$params['col_type'],
$params['col_attribute'],
$params['col_length'],
isset($params['col_isNull']) ? 1 : 0,
$params['collation'],
$params['col_extra'] ?? '',
$columnDefault
);
}
/**
* @param array $params Request parameters
*
* @return true|Message
*/
public function addNewColumn(array $params)
{
$columnDefault = $params['col_default'];
if ($columnDefault === 'NONE' && $params['col_default_sel'] !== 'USER_DEFINED') {
$columnDefault = '';
}
return $this->centralColumns->updateOneColumn(
$this->db,
'',
$params['col_name'],
$params['col_type'],
$params['col_attribute'],
$params['col_length'],
isset($params['col_isNull']) ? 1 : 0,
$params['collation'],
$params['col_extra'] ?? '',
$columnDefault
);
}
/**
* @param array $params Request parameters
*
* @return true|Message
*/
public function addColumn(array $params)
{
return $this->centralColumns->syncUniqueColumns(
[$params['column-select']],
false,
$params['table-select']
);
}
/**
* @param array $params Request parameters
*/
public function editPage(array $params): void
{
$rows = $this->centralColumns->getHtmlForEditingPage($params['selected_fld'], $params['db']);
$this->render('database/central_columns/edit', ['rows' => $rows]);
}
/**
* @param array $params Request parameters
*
* @return true|Message
*/
public function updateMultipleColumn(array $params)
{
return $this->centralColumns->updateMultipleColumn($params);
}
/**
* @param array $params Request parameters
*
* @return true|Message
*/
public function deleteSave(array $params)
{
$name = [];
parse_str($params['col_name'], $name);
return $this->centralColumns->deleteColumnsFromList($params['db'], $name['selected_fld'], false);
}
}

View file

@ -1,122 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Index;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Transformations;
use PhpMyAdmin\Util;
use function is_array;
use function str_replace;
class DataDictionaryController extends AbstractController
{
/** @var Relation */
private $relation;
/** @var Transformations */
private $transformations;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Relation $relation,
Transformations $transformations,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->relation = $relation;
$this->transformations = $transformations;
$this->dbi = $dbi;
}
public function __invoke(): void
{
Util::checkParameters(['db'], true);
$relationParameters = $this->relation->getRelationParameters();
$comment = $this->relation->getDbComment($this->db);
$this->dbi->selectDb($this->db);
$tablesNames = $this->dbi->getTables($this->db);
$tables = [];
foreach ($tablesNames as $tableName) {
$showComment = (string) $this->dbi->getTable($this->db, $tableName)->getStatusInfo('TABLE_COMMENT');
[, $primaryKeys] = Util::processIndexData(
$this->dbi->getTableIndexes($this->db, $tableName)
);
[$foreigners, $hasRelation] = $this->relation->getRelationsAndStatus(
$relationParameters->relationFeature !== null,
$this->db,
$tableName
);
$columnsComments = $this->relation->getComments($this->db, $tableName);
$columns = $this->dbi->getColumns($this->db, $tableName);
$rows = [];
foreach ($columns as $row) {
$extractedColumnSpec = Util::extractColumnSpec($row['Type']);
$relation = '';
if ($hasRelation) {
$foreigner = $this->relation->searchColumnInForeigners($foreigners, $row['Field']);
if (is_array($foreigner) && isset($foreigner['foreign_table'], $foreigner['foreign_field'])) {
$relation = $foreigner['foreign_table'];
$relation .= ' -> ';
$relation .= $foreigner['foreign_field'];
}
}
$mime = '';
if ($relationParameters->browserTransformationFeature !== null) {
$mimeMap = $this->transformations->getMime($this->db, $tableName, true);
if (is_array($mimeMap) && isset($mimeMap[$row['Field']]['mimetype'])) {
$mime = str_replace('_', '/', $mimeMap[$row['Field']]['mimetype']);
}
}
$rows[$row['Field']] = [
'name' => $row['Field'],
'has_primary_key' => isset($primaryKeys[$row['Field']]),
'type' => $extractedColumnSpec['type'],
'print_type' => $extractedColumnSpec['print_type'],
'is_nullable' => $row['Null'] !== '' && $row['Null'] !== 'NO',
'default' => $row['Default'] ?? null,
'comment' => $columnsComments[$row['Field']] ?? '',
'mime' => $mime,
'relation' => $relation,
];
}
$tables[$tableName] = [
'name' => $tableName,
'comment' => $showComment,
'has_relation' => $hasRelation,
'has_mime' => $relationParameters->browserTransformationFeature !== null,
'columns' => $rows,
'indexes' => Index::getFromTable($tableName, $this->db),
];
}
$this->render('database/data_dictionary/index', [
'database' => $this->db,
'comment' => $comment,
'tables' => $tables,
]);
}
}

View file

@ -1,250 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Database\Designer;
use PhpMyAdmin\Database\Designer\Common as DesignerCommon;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function htmlspecialchars;
use function in_array;
use function sprintf;
class DesignerController extends AbstractController
{
/** @var Designer */
private $databaseDesigner;
/** @var DesignerCommon */
private $designerCommon;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Designer $databaseDesigner,
DesignerCommon $designerCommon
) {
parent::__construct($response, $template, $db);
$this->databaseDesigner = $databaseDesigner;
$this->designerCommon = $designerCommon;
}
public function __invoke(): void
{
global $db, $script_display_field, $tab_column, $tables_all_keys, $tables_pk_or_unique_keys;
global $success, $page, $message, $display_page, $selected_page, $tab_pos, $fullTableNames, $script_tables;
global $script_contr, $params, $tables, $num_tables, $total_num_tables, $sub_part;
global $tooltip_truename, $tooltip_aliasname, $pos, $classes_side_menu, $cfg, $errorUrl;
if (isset($_POST['dialog'])) {
if ($_POST['dialog'] === 'edit') {
$html = $this->databaseDesigner->getHtmlForEditOrDeletePages($_POST['db'], 'editPage');
} elseif ($_POST['dialog'] === 'delete') {
$html = $this->databaseDesigner->getHtmlForEditOrDeletePages($_POST['db'], 'deletePage');
} elseif ($_POST['dialog'] === 'save_as') {
$html = $this->databaseDesigner->getHtmlForPageSaveAs($_POST['db']);
} elseif ($_POST['dialog'] === 'export') {
$html = $this->databaseDesigner->getHtmlForSchemaExport($_POST['db'], $_POST['selected_page']);
} elseif ($_POST['dialog'] === 'add_table') {
// Pass the db and table to the getTablesInfo so we only have the table we asked for
$script_display_field = $this->designerCommon->getTablesInfo($_POST['db'], $_POST['table']);
$tab_column = $this->designerCommon->getColumnsInfo($script_display_field);
$tables_all_keys = $this->designerCommon->getAllKeys($script_display_field);
$tables_pk_or_unique_keys = $this->designerCommon->getPkOrUniqueKeys($script_display_field);
$html = $this->databaseDesigner->getDatabaseTables(
$_POST['db'],
$script_display_field,
[],
-1,
$tab_column,
$tables_all_keys,
$tables_pk_or_unique_keys
);
}
if (! empty($html)) {
$this->response->addHTML($html);
}
return;
}
if (isset($_POST['operation'])) {
if ($_POST['operation'] === 'deletePage') {
$success = $this->designerCommon->deletePage($_POST['selected_page']);
$this->response->setRequestStatus($success);
} elseif ($_POST['operation'] === 'savePage') {
if ($_POST['save_page'] === 'same') {
$page = $_POST['selected_page'];
} elseif ($this->designerCommon->getPageExists($_POST['selected_value'])) {
$this->response->addJSON(
'message',
sprintf(
/* l10n: The user tries to save a page with an existing name in Designer */
__('There already exists a page named "%s" please rename it to something else.'),
htmlspecialchars($_POST['selected_value'])
)
);
$this->response->setRequestStatus(false);
return;
} else {
$page = $this->designerCommon->createNewPage($_POST['selected_value'], $_POST['db']);
$this->response->addJSON('id', $page);
}
$success = $this->designerCommon->saveTablePositions($page);
$this->response->setRequestStatus($success);
} elseif ($_POST['operation'] === 'setDisplayField') {
[
$success,
$message,
] = $this->designerCommon->saveDisplayField($_POST['db'], $_POST['table'], $_POST['field']);
$this->response->setRequestStatus($success);
$this->response->addJSON('message', $message);
} elseif ($_POST['operation'] === 'addNewRelation') {
[$success, $message] = $this->designerCommon->addNewRelation(
$_POST['db'],
$_POST['T1'],
$_POST['F1'],
$_POST['T2'],
$_POST['F2'],
$_POST['on_delete'],
$_POST['on_update'],
$_POST['DB1'],
$_POST['DB2']
);
$this->response->setRequestStatus($success);
$this->response->addJSON('message', $message);
} elseif ($_POST['operation'] === 'removeRelation') {
[$success, $message] = $this->designerCommon->removeRelation(
$_POST['T1'],
$_POST['F1'],
$_POST['T2'],
$_POST['F2']
);
$this->response->setRequestStatus($success);
$this->response->addJSON('message', $message);
} elseif ($_POST['operation'] === 'save_setting_value') {
$success = $this->designerCommon->saveSetting($_POST['index'], $_POST['value']);
$this->response->setRequestStatus($success);
}
return;
}
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
$script_display_field = $this->designerCommon->getTablesInfo();
$display_page = -1;
$selected_page = null;
$visualBuilderMode = isset($_GET['query']);
if ($visualBuilderMode) {
$display_page = $this->designerCommon->getDefaultPage($_GET['db']);
} elseif (! empty($_GET['page'])) {
$display_page = $_GET['page'];
} else {
$display_page = $this->designerCommon->getLoadingPage($_GET['db']);
}
if ($display_page != -1) {
$selected_page = $this->designerCommon->getPageName($display_page);
}
$tab_pos = $this->designerCommon->getTablePositions($display_page);
$fullTableNames = [];
foreach ($script_display_field as $designerTable) {
$fullTableNames[] = $designerTable->getDbTableString();
}
foreach ($tab_pos as $position) {
if (in_array($position['dbName'] . '.' . $position['tableName'], $fullTableNames)) {
continue;
}
$designerTables = $this->designerCommon->getTablesInfo($position['dbName'], $position['tableName']);
foreach ($designerTables as $designerTable) {
$script_display_field[] = $designerTable;
}
}
$tab_column = $this->designerCommon->getColumnsInfo($script_display_field);
$script_tables = $this->designerCommon->getScriptTabs($script_display_field);
$tables_pk_or_unique_keys = $this->designerCommon->getPkOrUniqueKeys($script_display_field);
$tables_all_keys = $this->designerCommon->getAllKeys($script_display_field);
$classes_side_menu = $this->databaseDesigner->returnClassNamesFromMenuButtons();
$script_contr = $this->designerCommon->getScriptContr($script_display_field);
$params = ['lang' => $GLOBALS['lang']];
if (isset($_GET['db'])) {
$params['db'] = $_GET['db'];
}
$this->response->getFooter()->setMinimal();
$header = $this->response->getHeader();
$header->setBodyId('designer_body');
$this->addScriptFiles([
'designer/database.js',
'designer/objects.js',
'designer/page.js',
'designer/history.js',
'designer/move.js',
'designer/init.js',
]);
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part ?? '');
// Embed some data into HTML, later it will be read
// by designer/init.js and converted to JS variables.
$this->response->addHTML(
$this->databaseDesigner->getHtmlForMain(
$db,
$_GET['db'],
$script_display_field,
$script_tables,
$script_contr,
$script_display_field,
$display_page,
$visualBuilderMode,
$selected_page,
$classes_side_menu,
$tab_pos,
$tab_column,
$tables_all_keys,
$tables_pk_or_unique_keys
)
);
$this->response->addHTML('<div id="PMA_disable_floating_menubar"></div>');
}
}

View file

@ -1,86 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Database\Events;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function strlen;
final class EventsController extends AbstractController
{
/** @var Events */
private $events;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Events $events,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->events = $events;
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db, $tables, $num_tables, $total_num_tables, $sub_part, $errors, $text_dir;
global $tooltip_truename, $tooltip_aliasname, $pos, $cfg, $errorUrl;
$this->addScriptFiles(['database/events.js']);
if (! $this->response->isAjax()) {
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part ?? '');
} elseif (strlen($db) > 0) {
$this->dbi->selectDb($db);
}
/**
* Keep a list of errors that occurred while
* processing an 'Add' or 'Edit' operation.
*/
$errors = [];
$this->events->handleEditor();
$this->events->export();
$items = $this->dbi->getEvents($db);
$this->render('database/events/index', [
'db' => $db,
'items' => $items,
'has_privilege' => Util::currentUserHasPrivilege('EVENT', $db),
'scheduler_state' => $this->events->getEventSchedulerStatus(),
'text_dir' => $text_dir,
'is_ajax' => $this->response->isAjax() && empty($_REQUEST['ajax_page_request']),
]);
}
}

View file

@ -1,166 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\Export;
use PhpMyAdmin\Export\Options;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function array_merge;
use function is_array;
final class ExportController extends AbstractController
{
/** @var Export */
private $export;
/** @var Options */
private $exportOptions;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Export $export,
Options $exportOptions
) {
parent::__construct($response, $template, $db);
$this->export = $export;
$this->exportOptions = $exportOptions;
}
public function __invoke(): void
{
global $db, $table, $sub_part, $urlParams, $sql_query;
global $tables, $num_tables, $total_num_tables, $tooltip_truename;
global $tooltip_aliasname, $pos, $table_select, $unlim_num_rows, $cfg, $errorUrl;
$pageSettings = new PageSettings('Export');
$pageSettingsErrorHtml = $pageSettings->getErrorHTML();
$pageSettingsHtml = $pageSettings->getHTML();
$this->addScriptFiles(['export.js']);
// $sub_part is used in Util::getDbInfo() to see if we are coming from
// /database/export, in which case we don't obey $cfg['MaxTableList']
$sub_part = '_export';
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
$urlParams['goto'] = Url::getFromRoute('/database/export');
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part);
// exit if no tables in db found
if ($num_tables < 1) {
$this->response->addHTML(
Message::error(__('No tables found in database.'))->getDisplay()
);
return;
}
if (! empty($_POST['selected_tbl']) && empty($table_select)) {
$table_select = $_POST['selected_tbl'];
}
$tablesForMultiValues = [];
foreach ($tables as $each_table) {
if (isset($_POST['table_select']) && is_array($_POST['table_select'])) {
$is_checked = $this->export->getCheckedClause($each_table['Name'], $_POST['table_select']);
} elseif (isset($table_select)) {
$is_checked = $this->export->getCheckedClause($each_table['Name'], $table_select);
} else {
$is_checked = true;
}
if (isset($_POST['table_structure']) && is_array($_POST['table_structure'])) {
$structure_checked = $this->export->getCheckedClause($each_table['Name'], $_POST['table_structure']);
} else {
$structure_checked = $is_checked;
}
if (isset($_POST['table_data']) && is_array($_POST['table_data'])) {
$data_checked = $this->export->getCheckedClause($each_table['Name'], $_POST['table_data']);
} else {
$data_checked = $is_checked;
}
$tablesForMultiValues[] = [
'name' => $each_table['Name'],
'is_checked_select' => $is_checked,
'is_checked_structure' => $structure_checked,
'is_checked_data' => $data_checked,
];
}
if (! isset($sql_query)) {
$sql_query = '';
}
if (! isset($unlim_num_rows)) {
$unlim_num_rows = 0;
}
$isReturnBackFromRawExport = isset($_POST['export_type']) && $_POST['export_type'] === 'raw';
if (isset($_POST['raw_query']) || $isReturnBackFromRawExport) {
$export_type = 'raw';
} else {
$export_type = 'database';
}
$GLOBALS['single_table'] = $_POST['single_table'] ?? $_GET['single_table'] ?? $GLOBALS['single_table'] ?? null;
$exportList = Plugins::getExport($export_type, isset($GLOBALS['single_table']));
if (empty($exportList)) {
$this->response->addHTML(Message::error(
__('Could not load export plugins, please check your installation!')
)->getDisplay());
return;
}
$options = $this->exportOptions->getOptions(
$export_type,
$db,
$table,
$sql_query,
$num_tables,
$unlim_num_rows,
$exportList
);
$this->render('database/export/index', array_merge($options, [
'page_settings_error_html' => $pageSettingsErrorHtml,
'page_settings_html' => $pageSettingsHtml,
'structure_or_data_forced' => $_POST['structure_or_data_forced'] ?? 0,
'tables' => $tablesForMultiValues,
]));
}
}

View file

@ -1,134 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Charsets;
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Encoding;
use PhpMyAdmin\Import;
use PhpMyAdmin\Import\Ajax;
use PhpMyAdmin\Message;
use PhpMyAdmin\Plugins;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use PhpMyAdmin\Utils\ForeignKey;
use function __;
use function intval;
use function is_numeric;
final class ImportController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db, $table, $tables, $num_tables, $total_num_tables, $cfg;
global $tooltip_truename, $tooltip_aliasname, $pos, $sub_part, $SESSION_KEY, $errorUrl;
$pageSettings = new PageSettings('Import');
$pageSettingsErrorHtml = $pageSettings->getErrorHTML();
$pageSettingsHtml = $pageSettings->getHTML();
$this->addScriptFiles(['import.js']);
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part ?? '');
[$SESSION_KEY, $uploadId] = Ajax::uploadProgressSetup();
$importList = Plugins::getImport('database');
if (empty($importList)) {
$this->response->addHTML(Message::error(__(
'Could not load import plugins, please check your installation!'
))->getDisplay());
return;
}
$offset = null;
if (isset($_REQUEST['offset']) && is_numeric($_REQUEST['offset'])) {
$offset = intval($_REQUEST['offset']);
}
$timeoutPassed = $_REQUEST['timeout_passed'] ?? null;
$localImportFile = $_REQUEST['local_import_file'] ?? null;
$compressions = Import::getCompressions();
$charsets = Charsets::getCharsets($this->dbi, $cfg['Server']['DisableIS']);
$idKey = $_SESSION[$SESSION_KEY]['handler']::getIdKey();
$hiddenInputs = [
$idKey => $uploadId,
'import_type' => 'database',
'db' => $db,
];
$default = isset($_GET['format']) ? (string) $_GET['format'] : Plugins::getDefault('Import', 'format');
$choice = Plugins::getChoice($importList, $default);
$options = Plugins::getOptions('Import', $importList);
$skipQueriesDefault = Plugins::getDefault('Import', 'skip_queries');
$isAllowInterruptChecked = Plugins::checkboxCheck('Import', 'allow_interrupt');
$maxUploadSize = (int) $GLOBALS['config']->get('max_upload_size');
$this->render('database/import/index', [
'page_settings_error_html' => $pageSettingsErrorHtml,
'page_settings_html' => $pageSettingsHtml,
'upload_id' => $uploadId,
'handler' => $_SESSION[$SESSION_KEY]['handler'],
'hidden_inputs' => $hiddenInputs,
'db' => $db,
'table' => $table,
'max_upload_size' => $maxUploadSize,
'formatted_maximum_upload_size' => Util::getFormattedMaximumUploadSize($maxUploadSize),
'plugins_choice' => $choice,
'options' => $options,
'skip_queries_default' => $skipQueriesDefault,
'is_allow_interrupt_checked' => $isAllowInterruptChecked,
'local_import_file' => $localImportFile,
'is_upload' => $GLOBALS['config']->get('enable_upload'),
'upload_dir' => $cfg['UploadDir'] ?? null,
'timeout_passed_global' => $GLOBALS['timeout_passed'] ?? null,
'compressions' => $compressions,
'is_encoding_supported' => Encoding::isSupported(),
'encodings' => Encoding::listEncodings(),
'import_charset' => $cfg['Import']['charset'] ?? null,
'timeout_passed' => $timeoutPassed,
'offset' => $offset,
'can_convert_kanji' => Encoding::canConvertKanji(),
'charsets' => $charsets,
'is_foreign_key_check' => ForeignKey::isCheckEnabled(),
'user_upload_dir' => Util::userDir((string) ($cfg['UploadDir'] ?? '')),
'local_files' => Import::getLocalFiles($importList),
]);
}
}

View file

@ -1,21 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\MultiTableQuery;
use PhpMyAdmin\Controllers\AbstractController;
use PhpMyAdmin\Database\MultiTableQuery;
final class QueryController extends AbstractController
{
public function __invoke(): void
{
$params = [
'sql_query' => $_POST['sql_query'],
'db' => $_POST['db'] ?? $_GET['db'] ?? null,
];
$this->response->addHTML(MultiTableQuery::displayResults($params['sql_query'], $params['db']));
}
}

View file

@ -1,48 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\MultiTableQuery;
use PhpMyAdmin\Controllers\AbstractController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Query\Generator as QueryGenerator;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use function rtrim;
final class TablesController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, DatabaseInterface $dbi)
{
parent::__construct($response, $template);
$this->dbi = $dbi;
}
public function __invoke(): void
{
$params = [
'tables' => $_GET['tables'] ?? [],
'db' => $_GET['db'] ?? '',
];
$tablesListForQuery = '';
foreach ($params['tables'] as $table) {
$tablesListForQuery .= "'" . $this->dbi->escapeString($table) . "',";
}
$tablesListForQuery = rtrim($tablesListForQuery, ',');
$constrains = $this->dbi->fetchResult(
QueryGenerator::getInformationSchemaForeignKeyConstraintsRequest(
$this->dbi->escapeString($params['db']),
$tablesListForQuery
)
);
$this->response->addJSON(['foreignKeyConstrains' => $constrains]);
}
}

View file

@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Database\MultiTableQuery;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
/**
* Handles database multi-table querying
*/
class MultiTableQueryController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
$this->addScriptFiles([
'database/multi_table_query.js',
'database/query_generator.js',
]);
$queryInstance = new MultiTableQuery($this->dbi, $this->template, $this->db);
$this->response->addHTML($queryInstance->getFormHtml());
}
}

View file

@ -1,104 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Operations;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\Operations;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
final class CollationController extends AbstractController
{
/** @var Operations */
private $operations;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Operations $operations,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->operations = $operations;
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db, $cfg, $errorUrl;
if (! $this->response->isAjax()) {
return;
}
if (empty($_POST['db_collation'])) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', Message::error(__('No collation provided.')));
return;
}
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
$sql_query = 'ALTER DATABASE ' . Util::backquote($db)
. ' DEFAULT' . Util::getCharsetQueryPart($_POST['db_collation'] ?? '');
$this->dbi->query($sql_query);
$message = Message::success();
/**
* Changes tables charset if requested by the user
*/
if (isset($_POST['change_all_tables_collations']) && $_POST['change_all_tables_collations'] === 'on') {
[$tables] = Util::getDbInfo($db, '');
foreach ($tables as $tableName => $data) {
if ($this->dbi->getTable($db, $tableName)->isView()) {
// Skip views, we can not change the collation of a view.
// issue #15283
continue;
}
$sql_query = 'ALTER TABLE '
. Util::backquote($db)
. '.'
. Util::backquote($tableName)
. ' DEFAULT '
. Util::getCharsetQueryPart($_POST['db_collation'] ?? '');
$this->dbi->query($sql_query);
/**
* Changes columns charset if requested by the user
*/
if (
! isset($_POST['change_all_tables_columns_collations']) ||
$_POST['change_all_tables_columns_collations'] !== 'on'
) {
continue;
}
$this->operations->changeAllColumnsCollation($db, $tableName, $_POST['db_collation']);
}
}
$this->response->setRequestStatus($message->isSuccess());
$this->response->addJSON('message', $message);
}
}

View file

@ -1,323 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Charsets;
use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\ConfigStorage\RelationCleanup;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Message;
use PhpMyAdmin\Operations;
use PhpMyAdmin\Plugins;
use PhpMyAdmin\Plugins\Export\ExportSql;
use PhpMyAdmin\Query\Utilities;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function count;
use function mb_strtolower;
use function strlen;
/**
* Handles miscellaneous database operations.
*/
class OperationsController extends AbstractController
{
/** @var Operations */
private $operations;
/** @var CheckUserPrivileges */
private $checkUserPrivileges;
/** @var Relation */
private $relation;
/** @var RelationCleanup */
private $relationCleanup;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Operations $operations,
CheckUserPrivileges $checkUserPrivileges,
Relation $relation,
RelationCleanup $relationCleanup,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->operations = $operations;
$this->checkUserPrivileges = $checkUserPrivileges;
$this->relation = $relation;
$this->relationCleanup = $relationCleanup;
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $cfg, $db, $server, $sql_query, $move, $message, $tables_full, $errorUrl;
global $export_sql_plugin, $views, $sqlConstratints, $local_query, $reload, $urlParams, $tables;
global $total_num_tables, $sub_part, $tooltip_truename;
global $db_collation, $tooltip_aliasname, $pos, $is_information_schema, $single_table, $num_tables;
$this->checkUserPrivileges->getPrivileges();
$this->addScriptFiles(['database/operations.js']);
$sql_query = '';
/**
* Rename/move or copy database
*/
if (strlen($db) > 0 && (! empty($_POST['db_rename']) || ! empty($_POST['db_copy']))) {
if (! empty($_POST['db_rename'])) {
$move = true;
} else {
$move = false;
}
if (! isset($_POST['newname']) || strlen($_POST['newname']) === 0) {
$message = Message::error(__('The database name is empty!'));
} else {
// lower_case_table_names=1 `DB` becomes `db`
if ($this->dbi->getLowerCaseNames() === '1') {
$_POST['newname'] = mb_strtolower($_POST['newname']);
}
if ($_POST['newname'] === $_REQUEST['db']) {
$message = Message::error(
__('Cannot copy database to the same name. Change the name and try again.')
);
} else {
$_error = false;
if ($move || ! empty($_POST['create_database_before_copying'])) {
$this->operations->createDbBeforeCopy();
}
// here I don't use DELIMITER because it's not part of the
// language; I have to send each statement one by one
// to avoid selecting alternatively the current and new db
// we would need to modify the CREATE definitions to qualify
// the db name
$this->operations->runProcedureAndFunctionDefinitions($db);
// go back to current db, just in case
$this->dbi->selectDb($db);
$tables_full = $this->dbi->getTablesFull($db);
// remove all foreign key constraints, otherwise we can get errors
/** @var ExportSql $export_sql_plugin */
$export_sql_plugin = Plugins::getPlugin('export', 'sql', [
'export_type' => 'database',
'single_table' => isset($single_table),
]);
// create stand-in tables for views
$views = $this->operations->getViewsAndCreateSqlViewStandIn($tables_full, $export_sql_plugin, $db);
// copy tables
$sqlConstratints = $this->operations->copyTables($tables_full, $move, $db);
// handle the views
if (! $_error) {
$this->operations->handleTheViews($views, $move, $db);
}
unset($views);
// now that all tables exist, create all the accumulated constraints
if (! $_error && count($sqlConstratints) > 0) {
$this->operations->createAllAccumulatedConstraints($sqlConstratints);
}
unset($sqlConstratints);
if ($this->dbi->getVersion() >= 50100) {
// here DELIMITER is not used because it's not part of the
// language; each statement is sent one by one
$this->operations->runEventDefinitionsForDb($db);
}
// go back to current db, just in case
$this->dbi->selectDb($db);
// Duplicate the bookmarks for this db (done once for each db)
$this->operations->duplicateBookmarks($_error, $db);
if (! $_error && $move) {
if (isset($_POST['adjust_privileges']) && ! empty($_POST['adjust_privileges'])) {
$this->operations->adjustPrivilegesMoveDb($db, $_POST['newname']);
}
/**
* cleanup pmadb stuff for this db
*/
$this->relationCleanup->database($db);
// if someday the RENAME DATABASE reappears, do not DROP
$local_query = 'DROP DATABASE '
. Util::backquote($db) . ';';
$sql_query .= "\n" . $local_query;
$this->dbi->query($local_query);
$message = Message::success(
__('Database %1$s has been renamed to %2$s.')
);
$message->addParam($db);
$message->addParam($_POST['newname']);
} elseif (! $_error) {
if (isset($_POST['adjust_privileges']) && ! empty($_POST['adjust_privileges'])) {
$this->operations->adjustPrivilegesCopyDb($db, $_POST['newname']);
}
$message = Message::success(
__('Database %1$s has been copied to %2$s.')
);
$message->addParam($db);
$message->addParam($_POST['newname']);
} else {
$message = Message::error();
}
$reload = true;
/* Change database to be used */
if (! $_error && $move) {
$db = $_POST['newname'];
} elseif (! $_error) {
if (isset($_POST['switch_to_new']) && $_POST['switch_to_new'] === 'true') {
$_SESSION['pma_switch_to_new'] = true;
$db = $_POST['newname'];
} else {
$_SESSION['pma_switch_to_new'] = false;
}
}
}
}
/**
* Database has been successfully renamed/moved. If in an Ajax request,
* generate the output with {@link ResponseRenderer} and exit
*/
if ($this->response->isAjax()) {
$this->response->setRequestStatus($message->isSuccess());
$this->response->addJSON('message', $message);
$this->response->addJSON('newname', $_POST['newname']);
$this->response->addJSON(
'sql_query',
Generator::getMessage('', $sql_query)
);
$this->response->addJSON('db', $db);
return;
}
}
$relationParameters = $this->relation->getRelationParameters();
/**
* Check if comments were updated
* (must be done before displaying the menu tabs)
*/
if (isset($_POST['comment'])) {
$this->relation->setDbComment($db, $_POST['comment']);
}
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
$urlParams['goto'] = Url::getFromRoute('/database/operations');
// Gets the database structure
$sub_part = '_structure';
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,
$isSystemSchema,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part);
$oldMessage = '';
if (isset($message)) {
$oldMessage = Generator::getMessage($message, $sql_query);
unset($message);
}
$db_collation = $this->dbi->getDbCollation($db);
$is_information_schema = Utilities::isSystemSchema($db);
if ($is_information_schema) {
return;
}
$databaseComment = '';
if ($relationParameters->columnCommentsFeature !== null) {
$databaseComment = $this->relation->getDbComment($db);
}
$hasAdjustPrivileges = $GLOBALS['db_priv'] && $GLOBALS['table_priv']
&& $GLOBALS['col_priv'] && $GLOBALS['proc_priv'] && $GLOBALS['is_reload_priv'];
$isDropDatabaseAllowed = ($this->dbi->isSuperUser() || $cfg['AllowUserDropDatabase'])
&& ! $isSystemSchema && $db !== 'mysql';
$switchToNew = isset($_SESSION['pma_switch_to_new']) && $_SESSION['pma_switch_to_new'];
$charsets = Charsets::getCharsets($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']);
$collations = Charsets::getCollations($this->dbi, $GLOBALS['cfg']['Server']['DisableIS']);
if (! $relationParameters->hasAllFeatures() && $cfg['PmaNoRelation_DisableWarning'] == false) {
$message = Message::notice(
__(
'The phpMyAdmin configuration storage has been deactivated. %sFind out why%s.'
)
);
$message->addParamHtml(
'<a href="' . Url::getFromRoute('/check-relations')
. '" data-post="' . Url::getCommon(['db' => $db]) . '">'
);
$message->addParamHtml('</a>');
/* Show error if user has configured something, notice elsewhere */
if (! empty($cfg['Servers'][$server]['pmadb'])) {
$message->isError(true);
}
}
$this->render('database/operations/index', [
'message' => $oldMessage,
'db' => $db,
'has_comment' => $relationParameters->columnCommentsFeature !== null,
'db_comment' => $databaseComment,
'db_collation' => $db_collation,
'has_adjust_privileges' => $hasAdjustPrivileges,
'is_drop_database_allowed' => $isDropDatabaseAllowed,
'switch_to_new' => $switchToNew,
'charsets' => $charsets,
'collations' => $collations,
]);
}
}

View file

@ -1,71 +0,0 @@
<?php
/**
* Controller for database privileges
*/
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Server\Privileges;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;
use function mb_strtolower;
/**
* Controller for database privileges
*/
class PrivilegesController extends AbstractController
{
/** @var Privileges */
private $privileges;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Privileges $privileges,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->privileges = $privileges;
$this->dbi = $dbi;
}
/**
* @param string[] $params Request parameters
* @psalm-param array{checkprivsdb: string} $params
*/
public function __invoke(array $params): string
{
global $cfg, $text_dir;
$scriptName = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$db = $params['checkprivsdb'];
if ($this->dbi->getLowerCaseNames() === '1') {
$db = mb_strtolower($params['checkprivsdb']);
}
$privileges = [];
if ($this->dbi->isSuperUser()) {
$privileges = $this->privileges->getAllPrivileges($db);
}
return $this->template->render('database/privileges/index', [
'is_superuser' => $this->dbi->isSuperUser(),
'db' => $db,
'database_url' => $scriptName,
'text_dir' => $text_dir,
'is_createuser' => $this->dbi->isCreateUser(),
'is_grantuser' => $this->dbi->isGrantUser(),
'privileges' => $privileges,
]);
}
}

View file

@ -1,168 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\ConfigStorage\RelationCleanup;
use PhpMyAdmin\Database\Qbe;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Operations;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\SavedSearches;
use PhpMyAdmin\Sql;
use PhpMyAdmin\Template;
use PhpMyAdmin\Transformations;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function stripos;
class QueryByExampleController extends AbstractController
{
/** @var Relation */
private $relation;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Relation $relation,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->relation = $relation;
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db, $savedSearchList, $savedSearch, $currentSearchId;
global $sql_query, $goto, $sub_part, $tables, $num_tables, $total_num_tables;
global $tooltip_truename, $tooltip_aliasname, $pos, $urlParams, $cfg, $errorUrl;
$savedQbeSearchesFeature = $this->relation->getRelationParameters()->savedQueryByExampleSearchesFeature;
$savedSearchList = [];
$savedSearch = null;
$currentSearchId = null;
$this->addScriptFiles(['database/qbe.js']);
if ($savedQbeSearchesFeature !== null) {
//Get saved search list.
$savedSearch = new SavedSearches();
$savedSearch->setUsername($GLOBALS['cfg']['Server']['user'])
->setDbname($db);
if (! empty($_POST['searchId'])) {
$savedSearch->setId($_POST['searchId']);
}
//Action field is sent.
if (isset($_POST['action'])) {
$savedSearch->setSearchName($_POST['searchName']);
if ($_POST['action'] === 'create') {
$savedSearch->setId(null)
->setCriterias($_POST)
->save($savedQbeSearchesFeature);
} elseif ($_POST['action'] === 'update') {
$savedSearch->setCriterias($_POST)
->save($savedQbeSearchesFeature);
} elseif ($_POST['action'] === 'delete') {
$savedSearch->delete($savedQbeSearchesFeature);
//After deletion, reset search.
$savedSearch = new SavedSearches();
$savedSearch->setUsername($GLOBALS['cfg']['Server']['user'])
->setDbname($db);
$_POST = [];
} elseif ($_POST['action'] === 'load') {
if (empty($_POST['searchId'])) {
//when not loading a search, reset the object.
$savedSearch = new SavedSearches();
$savedSearch->setUsername($GLOBALS['cfg']['Server']['user'])
->setDbname($db);
$_POST = [];
} else {
$savedSearch->load($savedQbeSearchesFeature);
}
}
//Else, it's an "update query"
}
$savedSearchList = $savedSearch->getList($savedQbeSearchesFeature);
$currentSearchId = $savedSearch->getId();
}
/**
* A query has been submitted -> (maybe) execute it
*/
$hasMessageToDisplay = false;
if (isset($_POST['submit_sql']) && ! empty($sql_query)) {
if (stripos($sql_query, 'SELECT') !== 0) {
$hasMessageToDisplay = true;
} else {
$goto = Url::getFromRoute('/database/sql');
$sql = new Sql(
$this->dbi,
$this->relation,
new RelationCleanup($this->dbi, $this->relation),
new Operations($this->dbi, $this->relation),
new Transformations(),
$this->template
);
$this->response->addHTML($sql->executeQueryAndSendQueryResponse(
null, // analyzed_sql_results
false, // is_gotofile
$_POST['db'], // db
null, // table
false, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // sql_data
$goto, // goto
null, // disp_query
null, // disp_message
$sql_query, // sql_query
null // complete_query
));
}
}
$sub_part = '_qbe';
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
$urlParams['goto'] = Url::getFromRoute('/database/qbe');
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part);
$databaseQbe = new Qbe($this->relation, $this->template, $this->dbi, $db, $savedSearchList, $savedSearch);
$this->render('database/qbe/index', [
'url_params' => $urlParams,
'has_message_to_display' => $hasMessageToDisplay,
'selection_form_html' => $databaseQbe->getSelectionForm(),
]);
}
}

View file

@ -1,124 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\Database\Routines;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\DbTableExists;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function in_array;
use function strlen;
/**
* Routines management.
*/
class RoutinesController extends AbstractController
{
/** @var CheckUserPrivileges */
private $checkUserPrivileges;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
CheckUserPrivileges $checkUserPrivileges,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->checkUserPrivileges = $checkUserPrivileges;
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db, $table, $tables, $num_tables, $total_num_tables, $sub_part;
global $tooltip_truename, $tooltip_aliasname, $pos;
global $errors, $errorUrl, $urlParams, $cfg;
$this->addScriptFiles(['database/routines.js']);
$type = $_REQUEST['type'] ?? null;
$this->checkUserPrivileges->getPrivileges();
if (! $this->response->isAjax()) {
/**
* Displays the header and tabs
*/
if (! empty($table) && in_array($table, $this->dbi->getTables($db))) {
Util::checkParameters(['db', 'table']);
$urlParams = ['db' => $db, 'table' => $table];
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
$errorUrl .= Url::getCommon($urlParams, '&');
DbTableExists::check();
} else {
$table = '';
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part ?? '');
}
} elseif (strlen($db) > 0) {
$this->dbi->selectDb($db);
}
/**
* Keep a list of errors that occurred while
* processing an 'Add' or 'Edit' operation.
*/
$errors = [];
$routines = new Routines($this->dbi, $this->template, $this->response);
$routines->handleEditor();
$routines->handleExecute();
$routines->export();
if (! isset($type) || ! in_array($type, ['FUNCTION', 'PROCEDURE'])) {
$type = null;
}
$items = $this->dbi->getRoutines($db, $type);
$isAjax = $this->response->isAjax() && empty($_REQUEST['ajax_page_request']);
$rows = '';
foreach ($items as $item) {
$rows .= $routines->getRow($item, $isAjax ? 'ajaxInsert hide' : '');
}
$this->render('database/routines/index', [
'db' => $db,
'table' => $table,
'items' => $items,
'rows' => $rows,
'has_privilege' => Util::currentUserHasPrivilege('CREATE ROUTINE', $db, $table),
]);
}
}

View file

@ -1,85 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Database\Search;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
class SearchController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $cfg, $db, $errorUrl, $urlParams, $tables, $num_tables, $total_num_tables, $sub_part;
global $tooltip_truename, $tooltip_aliasname, $pos;
$this->addScriptFiles(['database/search.js', 'sql.js', 'makegrid.js']);
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
// If config variable $cfg['UseDbSearch'] is on false : exit.
if (! $cfg['UseDbSearch']) {
Generator::mysqlDie(
__('Access denied!'),
'',
false,
$errorUrl
);
}
$urlParams['goto'] = Url::getFromRoute('/database/search');
// Create a database search instance
$databaseSearch = new Search($this->dbi, $db, $this->template);
// Display top links if we are not in an Ajax request
if (! $this->response->isAjax()) {
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part ?? '');
}
// Main search form has been submitted, get results
if (isset($_POST['submit_search'])) {
$this->response->addHTML($databaseSearch->getSearchResults());
}
// If we are in an Ajax request, we need to exit after displaying all the HTML
if ($this->response->isAjax() && empty($_REQUEST['ajax_page_request'])) {
return;
}
// Display the search form
$this->response->addHTML($databaseSearch->getMainHtml());
}
}

View file

@ -1,45 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use function json_encode;
/**
* Table/Column autocomplete in SQL editors.
*/
class SqlAutoCompleteController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $cfg, $db, $sql_autocomplete;
$sql_autocomplete = true;
if ($cfg['EnableAutocompleteForTablesAndColumns']) {
$db = $_POST['db'] ?? $db;
$sql_autocomplete = [];
if ($db) {
$tableNames = $this->dbi->getTables($db);
foreach ($tableNames as $tableName) {
$sql_autocomplete[$tableName] = $this->dbi->getColumns($db, $tableName);
}
}
}
$this->response->addJSON(['tables' => json_encode($sql_autocomplete)]);
}
}

View file

@ -1,66 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\SqlQueryForm;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function htmlspecialchars;
/**
* Database SQL executor
*/
class SqlController extends AbstractController
{
/** @var SqlQueryForm */
private $sqlQueryForm;
public function __construct(ResponseRenderer $response, Template $template, string $db, SqlQueryForm $sqlQueryForm)
{
parent::__construct($response, $template, $db);
$this->sqlQueryForm = $sqlQueryForm;
}
public function __invoke(): void
{
global $goto, $back, $db, $cfg, $errorUrl;
$this->addScriptFiles(['makegrid.js', 'vendor/jquery/jquery.uitablefilter.js', 'sql.js']);
$pageSettings = new PageSettings('Sql');
$this->response->addHTML($pageSettings->getErrorHTML());
$this->response->addHTML($pageSettings->getHTML());
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
/**
* After a syntax error, we return to this script
* with the typed query in the textarea.
*/
$goto = Url::getFromRoute('/database/sql');
$back = $goto;
$this->response->addHTML($this->sqlQueryForm->getHtml(
$db,
'',
true,
false,
isset($_POST['delimiter'])
? htmlspecialchars($_POST['delimiter'])
: ';'
));
}
}

View file

@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\SqlParser\Utils\Formatter;
use function strlen;
/**
* Format SQL for SQL editors.
*/
class SqlFormatController extends AbstractController
{
public function __invoke(): void
{
$params = ['sql' => $_POST['sql'] ?? null];
$query = strlen((string) $params['sql']) > 0 ? $params['sql'] : '';
$this->response->addJSON(['sql' => Formatter::format($query)]);
}
}

View file

@ -1,34 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use function __;
final class AddPrefixController extends AbstractController
{
public function __invoke(): void
{
global $db;
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$params = ['db' => $db];
foreach ($selected as $selectedValue) {
$params['selected'][] = $selectedValue;
}
$this->response->disable();
$this->render('database/structure/add_prefix', ['url_params' => $params]);
}
}

View file

@ -1,64 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;
use function count;
final class AddPrefixTableController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
DatabaseInterface $dbi,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $db, $message, $sql_query;
$selected = $_POST['selected'] ?? [];
$sql_query = '';
$selectedCount = count($selected);
for ($i = 0; $i < $selectedCount; $i++) {
$newTableName = $_POST['add_prefix'] . $selected[$i];
$aQuery = 'ALTER TABLE ' . Util::backquote($selected[$i])
. ' RENAME ' . Util::backquote($newTableName);
$sql_query .= $aQuery . ';' . "\n";
$this->dbi->selectDb($db);
$this->dbi->query($aQuery);
}
$message = Message::success();
if (empty($_POST['message'])) {
$_POST['message'] = $message;
}
($this->structureController)();
}
}

View file

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure\CentralColumns;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\Database\CentralColumns;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use function __;
final class AddController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
DatabaseInterface $dbi,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $message;
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$centralColumns = new CentralColumns($this->dbi);
$error = $centralColumns->syncUniqueColumns($selected);
$message = $error instanceof Message ? $error : Message::success(__('Success!'));
unset($_POST['submit_mult']);
($this->structureController)();
}
}

View file

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure\CentralColumns;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\Database\CentralColumns;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use function __;
final class MakeConsistentController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
DatabaseInterface $dbi,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $db, $message;
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$centralColumns = new CentralColumns($this->dbi);
$error = $centralColumns->makeConsistentWithList($db, $selected);
$message = $error instanceof Message ? $error : Message::success(__('Success!'));
unset($_POST['submit_mult']);
($this->structureController)();
}
}

View file

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure\CentralColumns;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\Database\CentralColumns;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use function __;
final class RemoveController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
DatabaseInterface $dbi,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $message;
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$centralColumns = new CentralColumns($this->dbi);
$error = $centralColumns->deleteColumnsFromList($_POST['db'], $selected);
$message = $error instanceof Message ? $error : Message::success(__('Success!'));
unset($_POST['submit_mult']);
($this->structureController)();
}
}

View file

@ -1,43 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use function __;
final class ChangePrefixFormController extends AbstractController
{
public function __invoke(): void
{
global $db;
$selected = $_POST['selected_tbl'] ?? [];
$submitMult = $_POST['submit_mult'] ?? '';
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$route = '/database/structure/replace-prefix';
if ($submitMult === 'copy_tbl_change_prefix') {
$route = '/database/structure/copy-table-with-prefix';
}
$urlParams = ['db' => $db];
foreach ($selected as $selectedValue) {
$urlParams['selected'][] = $selectedValue;
}
$this->response->disable();
$this->render('database/structure/change_prefix_form', [
'route' => $route,
'url_params' => $urlParams,
]);
}
}

View file

@ -1,45 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use function __;
final class CopyFormController extends AbstractController
{
public function __invoke(): void
{
global $db, $dblist;
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$urlParams = ['db' => $db];
foreach ($selected as $selectedValue) {
$urlParams['selected'][] = $selectedValue;
}
$databasesList = $dblist->databases;
foreach ($databasesList as $key => $databaseName) {
if ($databaseName == $db) {
$databasesList->offsetUnset($key);
break;
}
}
$this->response->disable();
$this->render('database/structure/copy_form', [
'url_params' => $urlParams,
'options' => $databasesList->getList(),
]);
}
}

View file

@ -1,72 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\Message;
use PhpMyAdmin\Operations;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Table;
use PhpMyAdmin\Template;
use function count;
final class CopyTableController extends AbstractController
{
/** @var Operations */
private $operations;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Operations $operations,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->operations = $operations;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $db, $message;
$selected = $_POST['selected'] ?? [];
$targetDb = $_POST['target_db'] ?? null;
$selectedCount = count($selected);
for ($i = 0; $i < $selectedCount; $i++) {
Table::moveCopy(
$db,
$selected[$i],
$targetDb,
$selected[$i],
$_POST['what'],
false,
'one_table',
isset($_POST['drop_if_exists']) && $_POST['drop_if_exists'] === 'true'
);
if (empty($_POST['adjust_privileges'])) {
continue;
}
$this->operations->adjustPrivilegesCopyTable($db, $selected[$i], $targetDb, $selected[$i]);
}
$message = Message::success();
if (empty($_POST['message'])) {
$_POST['message'] = $message;
}
($this->structureController)();
}
}

View file

@ -1,67 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Table;
use PhpMyAdmin\Template;
use function count;
use function mb_strlen;
use function mb_substr;
final class CopyTableWithPrefixController extends AbstractController
{
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $db, $message;
$selected = $_POST['selected'] ?? [];
$fromPrefix = $_POST['from_prefix'] ?? null;
$toPrefix = $_POST['to_prefix'] ?? null;
$selectedCount = count($selected);
for ($i = 0; $i < $selectedCount; $i++) {
$current = $selected[$i];
$newTableName = $toPrefix . mb_substr($current, mb_strlen((string) $fromPrefix));
Table::moveCopy(
$db,
$current,
$db,
$newTableName,
'data',
false,
'one_table',
isset($_POST['drop_if_exists']) && $_POST['drop_if_exists'] === 'true'
);
}
$message = Message::success();
if (empty($_POST['message'])) {
$_POST['message'] = $message;
}
($this->structureController)();
}
}

View file

@ -1,81 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;
use PhpMyAdmin\Utils\ForeignKey;
use function __;
use function htmlspecialchars;
use function in_array;
final class DropFormController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db;
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$views = $this->dbi->getVirtualTables($db);
$fullQueryViews = '';
$fullQuery = '';
foreach ($selected as $selectedValue) {
$current = $selectedValue;
if (! empty($views) && in_array($current, $views)) {
$fullQueryViews .= (empty($fullQueryViews) ? 'DROP VIEW ' : ', ')
. Util::backquote(htmlspecialchars($current));
} else {
$fullQuery .= (empty($fullQuery) ? 'DROP TABLE ' : ', ')
. Util::backquote(htmlspecialchars($current));
}
}
if (! empty($fullQuery)) {
$fullQuery .= ';<br>' . "\n";
}
if (! empty($fullQueryViews)) {
$fullQuery .= $fullQueryViews . ';<br>' . "\n";
}
$urlParams = ['db' => $db];
foreach ($selected as $selectedValue) {
$urlParams['selected'][] = $selectedValue;
}
foreach ($views as $current) {
$urlParams['views'][] = $current;
}
$this->render('database/structure/drop_form', [
'url_params' => $urlParams,
'full_query' => $fullQuery,
'is_foreign_key_check' => ForeignKey::isCheckEnabled(),
]);
}
}

View file

@ -1,135 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\ConfigStorage\RelationCleanup;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;
use PhpMyAdmin\Utils\ForeignKey;
use function __;
use function count;
use function in_array;
final class DropTableController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
/** @var RelationCleanup */
private $relationCleanup;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
DatabaseInterface $dbi,
RelationCleanup $relationCleanup,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
$this->relationCleanup = $relationCleanup;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $db, $message, $reload, $sql_query;
$reload = $_POST['reload'] ?? $reload ?? null;
$multBtn = $_POST['mult_btn'] ?? '';
$selected = $_POST['selected'] ?? [];
$views = $this->dbi->getVirtualTables($db);
if ($multBtn !== __('Yes')) {
$message = Message::success(__('No change'));
if (empty($_POST['message'])) {
$_POST['message'] = Message::success();
}
unset($_POST['mult_btn']);
($this->structureController)();
return;
}
$defaultFkCheckValue = ForeignKey::handleDisableCheckInit();
$sql_query = '';
$sqlQueryViews = '';
$selectedCount = count($selected);
for ($i = 0; $i < $selectedCount; $i++) {
$this->relationCleanup->table($db, $selected[$i]);
$current = $selected[$i];
if (! empty($views) && in_array($current, $views)) {
$sqlQueryViews .= (empty($sqlQueryViews) ? 'DROP VIEW ' : ', ') . Util::backquote($current);
} else {
$sql_query .= (empty($sql_query) ? 'DROP TABLE ' : ', ') . Util::backquote($current);
}
$reload = 1;
}
if (! empty($sql_query)) {
$sql_query .= ';';
} elseif (! empty($sqlQueryViews)) {
$sql_query = $sqlQueryViews . ';';
unset($sqlQueryViews);
}
// Unset cache values for tables count, issue #14205
if (isset($_SESSION['tmpval'])) {
if (isset($_SESSION['tmpval']['table_limit_offset'])) {
unset($_SESSION['tmpval']['table_limit_offset']);
}
if (isset($_SESSION['tmpval']['table_limit_offset_db'])) {
unset($_SESSION['tmpval']['table_limit_offset_db']);
}
}
$message = Message::success();
$this->dbi->selectDb($db);
$result = $this->dbi->tryQuery($sql_query);
if (! $result) {
$message = Message::error($this->dbi->getError());
}
if ($result && ! empty($sqlQueryViews)) {
$sql_query .= ' ' . $sqlQueryViews . ';';
$result = $this->dbi->tryQuery($sqlQueryViews);
unset($sqlQueryViews);
}
if (! $result) {
$message = Message::error($this->dbi->getError());
}
ForeignKey::handleDisableCheckCleanup($defaultFkCheckValue);
if (empty($_POST['message'])) {
$_POST['message'] = $message;
}
unset($_POST['mult_btn']);
($this->structureController)();
}
}

View file

@ -1,44 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Util;
use PhpMyAdmin\Utils\ForeignKey;
use function __;
use function htmlspecialchars;
final class EmptyFormController extends AbstractController
{
public function __invoke(): void
{
global $db;
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$fullQuery = '';
$urlParams = ['db' => $db];
foreach ($selected as $selectedValue) {
$fullQuery .= 'TRUNCATE ';
$fullQuery .= Util::backquote(htmlspecialchars($selectedValue)) . ';<br>';
$urlParams['selected'][] = $selectedValue;
}
$this->render('database/structure/empty_form', [
'url_params' => $urlParams,
'full_query' => $fullQuery,
'is_foreign_key_check' => ForeignKey::isCheckEnabled(),
]);
}
}

View file

@ -1,118 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\ConfigStorage\RelationCleanup;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\FlashMessages;
use PhpMyAdmin\Message;
use PhpMyAdmin\Operations;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Sql;
use PhpMyAdmin\Template;
use PhpMyAdmin\Transformations;
use PhpMyAdmin\Util;
use PhpMyAdmin\Utils\ForeignKey;
use function __;
use function count;
final class EmptyTableController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
/** @var Relation */
private $relation;
/** @var RelationCleanup */
private $relationCleanup;
/** @var Operations */
private $operations;
/** @var FlashMessages */
private $flash;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
DatabaseInterface $dbi,
Relation $relation,
RelationCleanup $relationCleanup,
Operations $operations,
FlashMessages $flash,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
$this->relation = $relation;
$this->relationCleanup = $relationCleanup;
$this->operations = $operations;
$this->flash = $flash;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $db, $table, $message, $sql_query;
$multBtn = $_POST['mult_btn'] ?? '';
$selected = $_POST['selected'] ?? [];
if ($multBtn !== __('Yes')) {
$this->flash->addMessage('success', __('No change'));
$this->redirect('/database/structure', ['db' => $db]);
return;
}
$defaultFkCheckValue = ForeignKey::handleDisableCheckInit();
$sql_query = '';
$selectedCount = count($selected);
for ($i = 0; $i < $selectedCount; $i++) {
$aQuery = 'TRUNCATE ';
$aQuery .= Util::backquote($selected[$i]);
$sql_query .= $aQuery . ';' . "\n";
$this->dbi->selectDb($db);
$this->dbi->query($aQuery);
}
if (! empty($_REQUEST['pos'])) {
$sql = new Sql(
$this->dbi,
$this->relation,
$this->relationCleanup,
$this->operations,
new Transformations(),
$this->template
);
$_REQUEST['pos'] = $sql->calculatePosForLastPage($db, $table, $_REQUEST['pos']);
}
ForeignKey::handleDisableCheckCleanup($defaultFkCheckValue);
$message = Message::success();
if (empty($_POST['message'])) {
$_POST['message'] = $message;
}
unset($_POST['mult_btn']);
($this->structureController)();
}
}

View file

@ -1,184 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\RecentFavoriteTable;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function count;
use function json_decode;
use function json_encode;
use function md5;
use function sha1;
final class FavoriteTableController extends AbstractController
{
/** @var Relation */
private $relation;
public function __construct(ResponseRenderer $response, Template $template, string $db, Relation $relation)
{
parent::__construct($response, $template, $db);
$this->relation = $relation;
}
public function __invoke(): void
{
global $cfg, $db, $errorUrl;
$parameters = [
'favorite_table' => $_REQUEST['favorite_table'] ?? null,
'favoriteTables' => $_REQUEST['favoriteTables'] ?? null,
'sync_favorite_tables' => $_REQUEST['sync_favorite_tables'] ?? null,
];
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase() || ! $this->response->isAjax()) {
return;
}
$favoriteInstance = RecentFavoriteTable::getInstance('favorite');
if (isset($parameters['favoriteTables'])) {
$favoriteTables = json_decode($parameters['favoriteTables'], true);
} else {
$favoriteTables = [];
}
// Required to keep each user's preferences separate.
$user = sha1($cfg['Server']['user']);
// Request for Synchronization of favorite tables.
if (isset($parameters['sync_favorite_tables'])) {
$relationParameters = $this->relation->getRelationParameters();
if ($relationParameters->favoriteTablesFeature !== null) {
$this->response->addJSON($this->synchronizeFavoriteTables(
$favoriteInstance,
$user,
$favoriteTables
));
}
return;
}
$changes = true;
$favoriteTable = $parameters['favorite_table'] ?? '';
$alreadyFavorite = $this->checkFavoriteTable($favoriteTable);
if (isset($_REQUEST['remove_favorite'])) {
if ($alreadyFavorite) {
// If already in favorite list, remove it.
$favoriteInstance->remove($this->db, $favoriteTable);
$alreadyFavorite = false; // for favorite_anchor template
}
} elseif (isset($_REQUEST['add_favorite'])) {
if (! $alreadyFavorite) {
$numTables = count($favoriteInstance->getTables());
if ($numTables == $cfg['NumFavoriteTables']) {
$changes = false;
} else {
// Otherwise add to favorite list.
$favoriteInstance->add($this->db, $favoriteTable);
$alreadyFavorite = true; // for favorite_anchor template
}
}
}
$favoriteTables[$user] = $favoriteInstance->getTables();
$json = [];
$json['changes'] = $changes;
if (! $changes) {
$json['message'] = $this->template->render('components/error_message', [
'msg' => __('Favorite List is full!'),
]);
$this->response->addJSON($json);
return;
}
// Check if current table is already in favorite list.
$favoriteParams = [
'db' => $this->db,
'ajax_request' => true,
'favorite_table' => $favoriteTable,
($alreadyFavorite ? 'remove' : 'add') . '_favorite' => true,
];
$json['user'] = $user;
$json['favoriteTables'] = json_encode($favoriteTables);
$json['list'] = $favoriteInstance->getHtmlList();
$json['anchor'] = $this->template->render('database/structure/favorite_anchor', [
'table_name_hash' => md5($favoriteTable),
'db_table_name_hash' => md5($this->db . '.' . $favoriteTable),
'fav_params' => $favoriteParams,
'already_favorite' => $alreadyFavorite,
]);
$this->response->addJSON($json);
}
/**
* Synchronize favorite tables
*
* @param RecentFavoriteTable $favoriteInstance Instance of this class
* @param string $user The user hash
* @param array $favoriteTables Existing favorites
*
* @return array
*/
private function synchronizeFavoriteTables(
RecentFavoriteTable $favoriteInstance,
string $user,
array $favoriteTables
): array {
$favoriteInstanceTables = $favoriteInstance->getTables();
if (empty($favoriteInstanceTables) && isset($favoriteTables[$user])) {
foreach ($favoriteTables[$user] as $value) {
$favoriteInstance->add($value['db'], $value['table']);
}
}
$favoriteTables[$user] = $favoriteInstance->getTables();
// Set flag when localStorage and pmadb(if present) are in sync.
$_SESSION['tmpval']['favorites_synced'][$GLOBALS['server']] = true;
return [
'favoriteTables' => json_encode($favoriteTables),
'list' => $favoriteInstance->getHtmlList(),
];
}
/**
* Function to check if a table is already in favorite list.
*
* @param string $currentTable current table
*/
private function checkFavoriteTable(string $currentTable): bool
{
// ensure $_SESSION['tmpval']['favoriteTables'] is initialized
RecentFavoriteTable::getInstance('favorite');
$favoriteTables = $_SESSION['tmpval']['favoriteTables'][$GLOBALS['server']] ?? [];
foreach ($favoriteTables as $value) {
if ($value['db'] == $this->db && $value['table'] == $currentTable) {
return true;
}
}
return false;
}
}

View file

@ -1,79 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function json_encode;
/**
* Handles request for real row count on database level view page.
*/
final class RealRowCountController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $cfg, $db, $errorUrl;
$parameters = [
'real_row_count_all' => $_REQUEST['real_row_count_all'] ?? null,
'table' => $_REQUEST['table'] ?? null,
];
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase() || ! $this->response->isAjax()) {
return;
}
[$tables] = Util::getDbInfo($this->db, '_structure');
// If there is a request to update all table's row count.
if (! isset($parameters['real_row_count_all'])) {
// Get the real row count for the table.
$realRowCount = (int) $this->dbi
->getTable($this->db, (string) $parameters['table'])
->getRealRowCountTable();
// Format the number.
$realRowCount = Util::formatNumber($realRowCount, 0);
$this->response->addJSON(['real_row_count' => $realRowCount]);
return;
}
// Array to store the results.
$realRowCountAll = [];
// Iterate over each table and fetch real row count.
foreach ($tables as $table) {
$rowCount = $this->dbi
->getTable($this->db, $table['TABLE_NAME'])
->getRealRowCountTable();
$realRowCountAll[] = [
'table' => $table['TABLE_NAME'],
'row_count' => $rowCount,
];
}
$this->response->addJSON(['real_row_count_all' => json_encode($realRowCountAll)]);
}
}

View file

@ -1,76 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Controllers\Database\StructureController;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;
use function count;
use function mb_strlen;
use function mb_substr;
final class ReplacePrefixController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
/** @var StructureController */
private $structureController;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
DatabaseInterface $dbi,
StructureController $structureController
) {
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
$this->structureController = $structureController;
}
public function __invoke(): void
{
global $db, $message, $sql_query;
$selected = $_POST['selected'] ?? [];
$fromPrefix = $_POST['from_prefix'] ?? '';
$toPrefix = $_POST['to_prefix'] ?? '';
$sql_query = '';
$selectedCount = count($selected);
for ($i = 0; $i < $selectedCount; $i++) {
$current = $selected[$i];
$subFromPrefix = mb_substr($current, 0, mb_strlen((string) $fromPrefix));
if ($subFromPrefix === $fromPrefix) {
$newTableName = $toPrefix . mb_substr($current, mb_strlen((string) $fromPrefix));
} else {
$newTableName = $current;
}
$aQuery = 'ALTER TABLE ' . Util::backquote($selected[$i])
. ' RENAME ' . Util::backquote($newTableName);
$sql_query .= $aQuery . ';' . "\n";
$this->dbi->selectDb($db);
$this->dbi->query($aQuery);
}
$message = Message::success();
if (empty($_POST['message'])) {
$_POST['message'] = $message;
}
($this->structureController)();
}
}

View file

@ -1,64 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\AbstractController;
use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use function __;
final class ShowCreateController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
$selected = $_POST['selected_tbl'] ?? [];
if (empty($selected)) {
$this->response->setRequestStatus(false);
$this->response->addJSON('message', __('No table selected.'));
return;
}
$tables = $this->getShowCreateTables($selected);
$showCreate = $this->template->render('database/structure/show_create', ['tables' => $tables]);
$this->response->addJSON('message', $showCreate);
}
/**
* @param string[] $selected Selected tables.
*
* @return array<string, array<int, array<string, string>>>
*/
private function getShowCreateTables(array $selected): array
{
$tables = ['tables' => [], 'views' => []];
foreach ($selected as $table) {
$object = $this->dbi->getTable($this->db, $table);
$tables[$object->isView() ? 'views' : 'tables'][] = [
'name' => Core::mimeDefaultFunction($table),
'show_create' => Core::mimeDefaultFunction($object->showCreate()),
];
}
return $tables;
}
}

View file

@ -1,918 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Charsets;
use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\Config\PageSettings;
use PhpMyAdmin\ConfigStorage\Relation;
use PhpMyAdmin\ConfigStorage\RelationCleanup;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\FlashMessages;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Operations;
use PhpMyAdmin\RecentFavoriteTable;
use PhpMyAdmin\Replication;
use PhpMyAdmin\ReplicationInfo;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Sanitize;
use PhpMyAdmin\StorageEngine;
use PhpMyAdmin\Template;
use PhpMyAdmin\Tracker;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function array_search;
use function ceil;
use function count;
use function htmlspecialchars;
use function implode;
use function in_array;
use function is_string;
use function max;
use function mb_substr;
use function md5;
use function preg_match;
use function preg_quote;
use function sprintf;
use function str_replace;
use function strlen;
use function strtotime;
use function urlencode;
/**
* Handles database structure logic
*/
class StructureController extends AbstractController
{
/** @var int Number of tables */
protected $numTables;
/** @var int Current position in the list */
protected $position;
/** @var bool DB is information_schema */
protected $dbIsSystemSchema;
/** @var int Number of tables */
protected $totalNumTables;
/** @var array Tables in the database */
protected $tables;
/** @var bool whether stats show or not */
protected $isShowStats;
/** @var Relation */
private $relation;
/** @var Replication */
private $replication;
/** @var RelationCleanup */
private $relationCleanup;
/** @var Operations */
private $operations;
/** @var ReplicationInfo */
private $replicationInfo;
/** @var DatabaseInterface */
private $dbi;
/** @var FlashMessages */
private $flash;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Relation $relation,
Replication $replication,
RelationCleanup $relationCleanup,
Operations $operations,
DatabaseInterface $dbi,
FlashMessages $flash
) {
parent::__construct($response, $template, $db);
$this->relation = $relation;
$this->replication = $replication;
$this->relationCleanup = $relationCleanup;
$this->operations = $operations;
$this->dbi = $dbi;
$this->flash = $flash;
$this->replicationInfo = new ReplicationInfo($this->dbi);
}
/**
* Retrieves database information for further use
*
* @param string $subPart Page part name
*/
private function getDatabaseInfo(string $subPart): void
{
[
$tables,
$numTables,
$totalNumTables,,
$isShowStats,
$dbIsSystemSchema,,,
$position,
] = Util::getDbInfo($this->db, $subPart);
$this->tables = $tables;
$this->numTables = $numTables;
$this->position = $position;
$this->dbIsSystemSchema = $dbIsSystemSchema;
$this->totalNumTables = $totalNumTables;
$this->isShowStats = $isShowStats;
}
public function __invoke(): void
{
global $cfg, $db, $errorUrl;
$parameters = [
'sort' => $_REQUEST['sort'] ?? null,
'sort_order' => $_REQUEST['sort_order'] ?? null,
];
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
$this->addScriptFiles(['database/structure.js', 'table/change.js']);
// Gets the database structure
$this->getDatabaseInfo('_structure');
// Checks if there are any tables to be shown on current page.
// If there are no tables, the user is redirected to the last page
// having any.
if ($this->totalNumTables > 0 && $this->position > $this->totalNumTables) {
$this->redirect('/database/structure', [
'db' => $this->db,
'pos' => max(0, $this->totalNumTables - $cfg['MaxTableList']),
'reload' => 1,
]);
}
$this->replicationInfo->load($_POST['primary_connection'] ?? null);
$replicaInfo = $this->replicationInfo->getReplicaInfo();
$pageSettings = new PageSettings('DbStructure');
$this->response->addHTML($pageSettings->getErrorHTML());
$this->response->addHTML($pageSettings->getHTML());
if ($this->numTables > 0) {
$urlParams = [
'pos' => $this->position,
'db' => $this->db,
];
if (isset($parameters['sort'])) {
$urlParams['sort'] = $parameters['sort'];
}
if (isset($parameters['sort_order'])) {
$urlParams['sort_order'] = $parameters['sort_order'];
}
$listNavigator = Generator::getListNavigator(
$this->totalNumTables,
$this->position,
$urlParams,
Url::getFromRoute('/database/structure'),
'frame_content',
$cfg['MaxTableList']
);
$tableList = $this->displayTableList($replicaInfo);
}
$createTable = '';
if (empty($this->dbIsSystemSchema)) {
$checkUserPrivileges = new CheckUserPrivileges($this->dbi);
$checkUserPrivileges->getPrivileges();
$createTable = $this->template->render('database/create_table', ['db' => $this->db]);
}
$this->render('database/structure/index', [
'database' => $this->db,
'has_tables' => $this->numTables > 0,
'list_navigator_html' => $listNavigator ?? '',
'table_list_html' => $tableList ?? '',
'is_system_schema' => ! empty($this->dbIsSystemSchema),
'create_table_html' => $createTable,
]);
}
/**
* @param array $replicaInfo
*/
protected function displayTableList($replicaInfo): string
{
$html = '';
// filtering
$html .= $this->template->render('filter', ['filter_value' => '']);
$i = $sumEntries = 0;
$overheadCheck = false;
$createTimeAll = '';
$updateTimeAll = '';
$checkTimeAll = '';
$numColumns = $GLOBALS['cfg']['PropertiesNumColumns'] > 1
? ceil($this->numTables / $GLOBALS['cfg']['PropertiesNumColumns']) + 1
: 0;
$rowCount = 0;
$sumSize = 0;
$overheadSize = 0;
$hiddenFields = [];
$overallApproxRows = false;
$structureTableRows = [];
foreach ($this->tables as $currentTable) {
// Get valid statistics whatever is the table type
$dropQuery = '';
$dropMessage = '';
$overhead = '';
$inputClass = ['checkall'];
// Sets parameters for links
$tableUrlParams = [
'db' => $this->db,
'table' => $currentTable['TABLE_NAME'],
];
// do not list the previous table's size info for a view
[
$currentTable,
$formattedSize,
$unit,
$formattedOverhead,
$overheadUnit,
$overheadSize,
$tableIsView,
$sumSize,
] = $this->getStuffForEngineTypeTable($currentTable, $sumSize, $overheadSize);
$curTable = $this->dbi
->getTable($this->db, $currentTable['TABLE_NAME']);
if (! $curTable->isMerge()) {
$sumEntries += $currentTable['TABLE_ROWS'];
}
$collationDefinition = '---';
if (isset($currentTable['Collation'])) {
$tableCollation = Charsets::findCollationByName(
$this->dbi,
$GLOBALS['cfg']['Server']['DisableIS'],
$currentTable['Collation']
);
if ($tableCollation !== null) {
$collationDefinition = $this->template->render('database/structure/collation_definition', [
'valueTitle' => $tableCollation->getDescription(),
'value' => $tableCollation->getName(),
]);
}
}
if ($this->isShowStats) {
$overhead = '-';
if ($formattedOverhead != '') {
$overhead = $this->template->render('database/structure/overhead', [
'table_url_params' => $tableUrlParams,
'formatted_overhead' => $formattedOverhead,
'overhead_unit' => $overheadUnit,
]);
$overheadCheck = true;
$inputClass[] = 'tbl-overhead';
}
}
if ($GLOBALS['cfg']['ShowDbStructureCharset']) {
$charset = '';
if (isset($tableCollation)) {
$charset = $tableCollation->getCharset();
}
}
if ($GLOBALS['cfg']['ShowDbStructureCreation']) {
$createTime = $currentTable['Create_time'] ?? '';
if ($createTime && (! $createTimeAll || $createTime < $createTimeAll)) {
$createTimeAll = $createTime;
}
}
if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) {
$updateTime = $currentTable['Update_time'] ?? '';
if ($updateTime && (! $updateTimeAll || $updateTime < $updateTimeAll)) {
$updateTimeAll = $updateTime;
}
}
if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) {
$checkTime = $currentTable['Check_time'] ?? '';
if ($checkTime && (! $checkTimeAll || $checkTime < $checkTimeAll)) {
$checkTimeAll = $checkTime;
}
}
$truename = $currentTable['TABLE_NAME'];
$i++;
$rowCount++;
if ($tableIsView) {
$hiddenFields[] = '<input type="hidden" name="views[]" value="'
. htmlspecialchars($currentTable['TABLE_NAME']) . '">';
}
/*
* Always activate links for Browse, Search and Empty, even if
* the icons are greyed, because
* 1. for views, we don't know the number of rows at this point
* 2. for tables, another source could have populated them since the
* page was generated
*
* I could have used the PHP ternary conditional operator but I find
* the code easier to read without this operator.
*/
$mayHaveRows = $currentTable['TABLE_ROWS'] > 0 || $tableIsView;
if (! $this->dbIsSystemSchema) {
$dropQuery = sprintf(
'DROP %s %s',
$tableIsView || $currentTable['ENGINE'] == null ? 'VIEW'
: 'TABLE',
Util::backquote(
$currentTable['TABLE_NAME']
)
);
$dropMessage = sprintf(
($tableIsView || $currentTable['ENGINE'] == null
? __('View %s has been dropped.')
: __('Table %s has been dropped.')),
str_replace(
' ',
'&nbsp;',
htmlspecialchars($currentTable['TABLE_NAME'])
)
);
}
if ($numColumns > 0 && $this->numTables > $numColumns && ($rowCount % $numColumns) == 0) {
$rowCount = 1;
$html .= $this->template->render('database/structure/table_header', [
'db' => $this->db,
'db_is_system_schema' => $this->dbIsSystemSchema,
'replication' => $replicaInfo['status'],
'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
'is_show_stats' => $this->isShowStats,
'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
'structure_table_rows' => $structureTableRows,
]);
$structureTableRows = [];
}
[$approxRows, $showSuperscript] = $this->isRowCountApproximated($currentTable, $tableIsView);
[$do, $ignored] = $this->getReplicationStatus($replicaInfo, $truename);
$structureTableRows[] = [
'table_name_hash' => md5($currentTable['TABLE_NAME']),
'db_table_name_hash' => md5($this->db . '.' . $currentTable['TABLE_NAME']),
'db' => $this->db,
'curr' => $i,
'input_class' => implode(' ', $inputClass),
'table_is_view' => $tableIsView,
'current_table' => $currentTable,
'may_have_rows' => $mayHaveRows,
'browse_table_label_title' => htmlspecialchars($currentTable['TABLE_COMMENT']),
'browse_table_label_truename' => $truename,
'empty_table_sql_query' => 'TRUNCATE ' . Util::backquote($currentTable['TABLE_NAME']),
'empty_table_message_to_show' => urlencode(
sprintf(
__('Table %s has been emptied.'),
htmlspecialchars(
$currentTable['TABLE_NAME']
)
)
),
'tracking_icon' => $this->getTrackingIcon($truename),
'server_replica_status' => $replicaInfo['status'],
'table_url_params' => $tableUrlParams,
'db_is_system_schema' => $this->dbIsSystemSchema,
'drop_query' => $dropQuery,
'drop_message' => $dropMessage,
'collation' => $collationDefinition,
'formatted_size' => $formattedSize,
'unit' => $unit,
'overhead' => $overhead,
'create_time' => isset($createTime) && $createTime
? Util::localisedDate(strtotime($createTime)) : '-',
'update_time' => isset($updateTime) && $updateTime
? Util::localisedDate(strtotime($updateTime)) : '-',
'check_time' => isset($checkTime) && $checkTime
? Util::localisedDate(strtotime($checkTime)) : '-',
'charset' => $charset ?? '',
'is_show_stats' => $this->isShowStats,
'ignored' => $ignored,
'do' => $do,
'approx_rows' => $approxRows,
'show_superscript' => $showSuperscript,
'already_favorite' => $this->checkFavoriteTable($currentTable['TABLE_NAME']),
'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
'limit_chars' => $GLOBALS['cfg']['LimitChars'],
'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
];
$overallApproxRows = $overallApproxRows || $approxRows;
}
$databaseCollation = [];
$databaseCharset = '';
$collation = Charsets::findCollationByName(
$this->dbi,
$GLOBALS['cfg']['Server']['DisableIS'],
$this->dbi->getDbCollation($this->db)
);
if ($collation !== null) {
$databaseCollation = [
'name' => $collation->getName(),
'description' => $collation->getDescription(),
];
$databaseCharset = $collation->getCharset();
}
$relationParameters = $this->relation->getRelationParameters();
return $html . $this->template->render('database/structure/table_header', [
'db' => $this->db,
'db_is_system_schema' => $this->dbIsSystemSchema,
'replication' => $replicaInfo['status'],
'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
'is_show_stats' => $this->isShowStats,
'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
'structure_table_rows' => $structureTableRows,
'body_for_table_summary' => [
'num_tables' => $this->numTables,
'server_replica_status' => $replicaInfo['status'],
'db_is_system_schema' => $this->dbIsSystemSchema,
'sum_entries' => $sumEntries,
'database_collation' => $databaseCollation,
'is_show_stats' => $this->isShowStats,
'database_charset' => $databaseCharset,
'sum_size' => $sumSize,
'overhead_size' => $overheadSize,
'create_time_all' => $createTimeAll ? Util::localisedDate(strtotime($createTimeAll)) : '-',
'update_time_all' => $updateTimeAll ? Util::localisedDate(strtotime($updateTimeAll)) : '-',
'check_time_all' => $checkTimeAll ? Util::localisedDate(strtotime($checkTimeAll)) : '-',
'approx_rows' => $overallApproxRows,
'num_favorite_tables' => $GLOBALS['cfg']['NumFavoriteTables'],
'db' => $GLOBALS['db'],
'properties_num_columns' => $GLOBALS['cfg']['PropertiesNumColumns'],
'dbi' => $this->dbi,
'show_charset' => $GLOBALS['cfg']['ShowDbStructureCharset'],
'show_comment' => $GLOBALS['cfg']['ShowDbStructureComment'],
'show_creation' => $GLOBALS['cfg']['ShowDbStructureCreation'],
'show_last_update' => $GLOBALS['cfg']['ShowDbStructureLastUpdate'],
'show_last_check' => $GLOBALS['cfg']['ShowDbStructureLastCheck'],
],
'check_all_tables' => [
'text_dir' => $GLOBALS['text_dir'],
'overhead_check' => $overheadCheck,
'db_is_system_schema' => $this->dbIsSystemSchema,
'hidden_fields' => $hiddenFields,
'disable_multi_table' => $GLOBALS['cfg']['DisableMultiTableMaintenance'],
'central_columns_work' => $relationParameters->centralColumnsFeature !== null,
],
]);
}
/**
* Returns the tracking icon if the table is tracked
*
* @param string $table table name
*
* @return string HTML for tracking icon
*/
protected function getTrackingIcon(string $table): string
{
$trackingIcon = '';
if (Tracker::isActive()) {
$isTracked = Tracker::isTracked($this->db, $table);
if ($isTracked || Tracker::getVersion($this->db, $table) > 0) {
$trackingIcon = $this->template->render('database/structure/tracking_icon', [
'db' => $this->db,
'table' => $table,
'is_tracked' => $isTracked,
]);
}
}
return $trackingIcon;
}
/**
* Returns whether the row count is approximated
*
* @param array $currentTable array containing details about the table
* @param bool $tableIsView whether the table is a view
*
* @return array
*/
protected function isRowCountApproximated(
array $currentTable,
bool $tableIsView
): array {
$approxRows = false;
$showSuperscript = '';
// there is a null value in the ENGINE
// - when the table needs to be repaired, or
// - when it's a view
// so ensure that we'll display "in use" below for a table
// that needs to be repaired
if (isset($currentTable['TABLE_ROWS']) && ($currentTable['ENGINE'] != null || $tableIsView)) {
// InnoDB/TokuDB table: we did not get an accurate row count
$approxRows = ! $tableIsView
&& in_array($currentTable['ENGINE'], ['InnoDB', 'TokuDB'])
&& ! $currentTable['COUNTED'];
if ($tableIsView && $currentTable['TABLE_ROWS'] >= $GLOBALS['cfg']['MaxExactCountViews']) {
$approxRows = true;
$showSuperscript = Generator::showHint(
Sanitize::sanitizeMessage(
sprintf(
__(
'This view has at least this number of rows. Please refer to %sdocumentation%s.'
),
'[doc@cfg_MaxExactCountViews]',
'[/doc]'
)
)
);
}
}
return [
$approxRows,
$showSuperscript,
];
}
/**
* Returns the replication status of the table.
*
* @param array $replicaInfo
* @param string $table table name
*
* @return array
*/
protected function getReplicationStatus($replicaInfo, string $table): array
{
$do = $ignored = false;
if ($replicaInfo['status']) {
$nbServReplicaDoDb = count($replicaInfo['Do_DB']);
$nbServReplicaIgnoreDb = count($replicaInfo['Ignore_DB']);
$searchDoDBInTruename = array_search($table, $replicaInfo['Do_DB']);
$searchDoDBInDB = array_search($this->db, $replicaInfo['Do_DB']);
$do = (is_string($searchDoDBInTruename) && strlen($searchDoDBInTruename) > 0)
|| (is_string($searchDoDBInDB) && strlen($searchDoDBInDB) > 0)
|| ($nbServReplicaDoDb == 0 && $nbServReplicaIgnoreDb == 0)
|| $this->hasTable($replicaInfo['Wild_Do_Table'], $table);
$searchDb = array_search($this->db, $replicaInfo['Ignore_DB']);
$searchTable = array_search($table, $replicaInfo['Ignore_Table']);
$ignored = (is_string($searchTable) && strlen($searchTable) > 0)
|| (is_string($searchDb) && strlen($searchDb) > 0)
|| $this->hasTable($replicaInfo['Wild_Ignore_Table'], $table);
}
return [
$do,
$ignored,
];
}
/**
* Function to check if a table is already in favorite list.
*
* @param string $currentTable current table
*/
protected function checkFavoriteTable(string $currentTable): bool
{
// ensure $_SESSION['tmpval']['favoriteTables'] is initialized
RecentFavoriteTable::getInstance('favorite');
$favoriteTables = $_SESSION['tmpval']['favoriteTables'][$GLOBALS['server']] ?? [];
foreach ($favoriteTables as $value) {
if ($value['db'] == $this->db && $value['table'] == $currentTable) {
return true;
}
}
return false;
}
/**
* Find table with truename
*
* @param array $db DB to look into
* @param string $truename Table name
*/
protected function hasTable(array $db, $truename): bool
{
foreach ($db as $dbTable) {
if (
$this->db == $this->replication->extractDbOrTable($dbTable)
&& preg_match(
'@^' .
preg_quote(mb_substr($this->replication->extractDbOrTable($dbTable, 'table'), 0, -1), '@') . '@',
$truename
)
) {
return true;
}
}
return false;
}
/**
* Get the value set for ENGINE table,
*
* @internal param bool $table_is_view whether table is view or not
*
* @param array $currentTable current table
* @param int $sumSize total table size
* @param int $overheadSize overhead size
*
* @return array
*/
protected function getStuffForEngineTypeTable(
array $currentTable,
$sumSize,
$overheadSize
) {
$formattedSize = '-';
$unit = '';
$formattedOverhead = '';
$overheadUnit = '';
$tableIsView = false;
switch ($currentTable['ENGINE']) {
// MyISAM, ISAM or Heap table: Row count, data size and index size
// are accurate; data size is accurate for ARCHIVE
case 'MyISAM':
case 'ISAM':
case 'HEAP':
case 'MEMORY':
case 'ARCHIVE':
case 'Aria':
case 'Maria':
[
$currentTable,
$formattedSize,
$unit,
$formattedOverhead,
$overheadUnit,
$overheadSize,
$sumSize,
] = $this->getValuesForAriaTable(
$currentTable,
$sumSize,
$overheadSize,
$formattedSize,
$unit,
$formattedOverhead,
$overheadUnit
);
break;
case 'InnoDB':
case 'PBMS':
case 'TokuDB':
// InnoDB table: Row count is not accurate but data and index sizes are.
// PBMS table in Drizzle: TABLE_ROWS is taken from table cache,
// so it may be unavailable
[$currentTable, $formattedSize, $unit, $sumSize] = $this->getValuesForInnodbTable(
$currentTable,
$sumSize
);
break;
// Mysql 5.0.x (and lower) uses MRG_MyISAM
// and MySQL 5.1.x (and higher) uses MRG_MYISAM
// Both are aliases for MERGE
case 'MRG_MyISAM':
case 'MRG_MYISAM':
case 'MERGE':
case 'BerkeleyDB':
// Merge or BerkleyDB table: Only row count is accurate.
if ($this->isShowStats) {
$formattedSize = ' - ';
$unit = '';
}
break;
// for a view, the ENGINE is sometimes reported as null,
// or on some servers it's reported as "SYSTEM VIEW"
case null:
case 'SYSTEM VIEW':
// possibly a view, do nothing
break;
case 'Mroonga':
// The idea is to show the size only if Mroonga is available,
// in other case the old unknown message will appear
if (StorageEngine::hasMroongaEngine()) {
[$currentTable, $formattedSize, $unit, $sumSize] = $this->getValuesForMroongaTable(
$currentTable,
$sumSize
);
break;
}
// no break, go to default case
default:
// Unknown table type.
if ($this->isShowStats) {
$formattedSize = __('unknown');
$unit = '';
}
}
if ($currentTable['TABLE_TYPE'] === 'VIEW' || $currentTable['TABLE_TYPE'] === 'SYSTEM VIEW') {
// countRecords() takes care of $cfg['MaxExactCountViews']
$currentTable['TABLE_ROWS'] = $this->dbi
->getTable($this->db, $currentTable['TABLE_NAME'])
->countRecords(true);
$tableIsView = true;
}
return [
$currentTable,
$formattedSize,
$unit,
$formattedOverhead,
$overheadUnit,
$overheadSize,
$tableIsView,
$sumSize,
];
}
/**
* Get values for ARIA/MARIA tables
*
* @param array $currentTable current table
* @param int $sumSize sum size
* @param int $overheadSize overhead size
* @param int $formattedSize formatted size
* @param string $unit unit
* @param int $formattedOverhead overhead formatted
* @param string $overheadUnit overhead unit
*
* @return array
*/
protected function getValuesForAriaTable(
array $currentTable,
$sumSize,
$overheadSize,
$formattedSize,
$unit,
$formattedOverhead,
$overheadUnit
) {
if ($this->dbIsSystemSchema) {
$currentTable['Rows'] = $this->dbi
->getTable($this->db, $currentTable['Name'])
->countRecords();
}
if ($this->isShowStats) {
/** @var int $tblsize */
$tblsize = $currentTable['Data_length']
+ $currentTable['Index_length'];
$sumSize += $tblsize;
[$formattedSize, $unit] = Util::formatByteDown($tblsize, 3, $tblsize > 0 ? 1 : 0);
if (isset($currentTable['Data_free']) && $currentTable['Data_free'] > 0) {
[$formattedOverhead, $overheadUnit] = Util::formatByteDown(
$currentTable['Data_free'],
3,
($currentTable['Data_free'] > 0 ? 1 : 0)
);
$overheadSize += $currentTable['Data_free'];
}
}
return [
$currentTable,
$formattedSize,
$unit,
$formattedOverhead,
$overheadUnit,
$overheadSize,
$sumSize,
];
}
/**
* Get values for InnoDB table
*
* @param array $currentTable current table
* @param int $sumSize sum size
*
* @return array
*/
protected function getValuesForInnodbTable(
array $currentTable,
$sumSize
) {
$formattedSize = $unit = '';
if (
(in_array($currentTable['ENGINE'], ['InnoDB', 'TokuDB'])
&& $currentTable['TABLE_ROWS'] < $GLOBALS['cfg']['MaxExactCount'])
|| ! isset($currentTable['TABLE_ROWS'])
) {
$currentTable['COUNTED'] = true;
$currentTable['TABLE_ROWS'] = $this->dbi
->getTable($this->db, $currentTable['TABLE_NAME'])
->countRecords(true);
} else {
$currentTable['COUNTED'] = false;
}
if ($this->isShowStats) {
/** @var int $tblsize */
$tblsize = $currentTable['Data_length']
+ $currentTable['Index_length'];
$sumSize += $tblsize;
[$formattedSize, $unit] = Util::formatByteDown($tblsize, 3, ($tblsize > 0 ? 1 : 0));
}
return [
$currentTable,
$formattedSize,
$unit,
$sumSize,
];
}
/**
* Get values for Mroonga table
*
* @param array $currentTable current table
* @param int $sumSize sum size
*
* @return array
*/
protected function getValuesForMroongaTable(
array $currentTable,
int $sumSize
): array {
$formattedSize = '';
$unit = '';
if ($this->isShowStats) {
/** @var int $tblsize */
$tblsize = $currentTable['Data_length'] + $currentTable['Index_length'];
$sumSize += $tblsize;
[$formattedSize, $unit] = Util::formatByteDown($tblsize, 3, ($tblsize > 0 ? 1 : 0));
}
return [
$currentTable,
$formattedSize,
$unit,
$sumSize,
];
}
}

View file

@ -1,157 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\CheckUserPrivileges;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Tracker;
use PhpMyAdmin\Tracking;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function __;
use function count;
use function htmlspecialchars;
use function sprintf;
/**
* Tracking configuration for database.
*/
class TrackingController extends AbstractController
{
/** @var Tracking */
private $tracking;
/** @var DatabaseInterface */
private $dbi;
public function __construct(
ResponseRenderer $response,
Template $template,
string $db,
Tracking $tracking,
DatabaseInterface $dbi
) {
parent::__construct($response, $template, $db);
$this->tracking = $tracking;
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db, $text_dir, $urlParams, $tables, $num_tables;
global $total_num_tables, $sub_part, $pos, $data, $cfg;
global $tooltip_truename, $tooltip_aliasname, $errorUrl;
$this->addScriptFiles(['vendor/jquery/jquery.tablesorter.js', 'database/tracking.js']);
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
$urlParams['goto'] = Url::getFromRoute('/table/tracking');
$urlParams['back'] = Url::getFromRoute('/database/tracking');
// Get the database structure
$sub_part = '_structure';
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,
$isSystemSchema,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part);
if (isset($_POST['delete_tracking'], $_POST['table'])) {
Tracker::deleteTracking($db, $_POST['table']);
echo Message::success(
__('Tracking data deleted successfully.')
)->getDisplay();
} elseif (isset($_POST['submit_create_version'])) {
$this->tracking->createTrackingForMultipleTables($db, $_POST['selected']);
echo Message::success(
sprintf(
__(
'Version %1$s was created for selected tables, tracking is active for them.'
),
htmlspecialchars($_POST['version'])
)
)->getDisplay();
} elseif (isset($_POST['submit_mult'])) {
if (! empty($_POST['selected_tbl'])) {
if ($_POST['submit_mult'] === 'delete_tracking') {
foreach ($_POST['selected_tbl'] as $table) {
Tracker::deleteTracking($db, $table);
}
echo Message::success(
__('Tracking data deleted successfully.')
)->getDisplay();
} elseif ($_POST['submit_mult'] === 'track') {
echo $this->template->render('create_tracking_version', [
'route' => '/database/tracking',
'url_params' => $urlParams,
'last_version' => 0,
'db' => $db,
'selected' => $_POST['selected_tbl'],
'type' => 'both',
'default_statements' => $cfg['Server']['tracking_default_statements'],
]);
return;
}
} else {
echo Message::notice(
__('No tables selected.')
)->getDisplay();
}
}
// Get tracked data about the database
$data = Tracker::getTrackedData($db, '', '1');
// No tables present and no log exist
if ($num_tables == 0 && count($data['ddlog']) === 0) {
echo '<p>' , __('No tables found in database.') , '</p>' , "\n";
if (empty($isSystemSchema)) {
$checkUserPrivileges = new CheckUserPrivileges($this->dbi);
$checkUserPrivileges->getPrivileges();
echo $this->template->render('database/create_table', ['db' => $db]);
}
return;
}
echo $this->tracking->getHtmlForDbTrackingTables($db, $urlParams, $text_dir);
// If available print out database log
if (count($data['ddlog']) <= 0) {
return;
}
$log = '';
foreach ($data['ddlog'] as $entry) {
$log .= '# ' . $entry['date'] . ' ' . $entry['username'] . "\n"
. $entry['statement'] . "\n";
}
echo Generator::getMessage(__('Database Log'), $log);
}
}

View file

@ -1,87 +0,0 @@
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Database;
use PhpMyAdmin\Database\Triggers;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\DbTableExists;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function in_array;
use function strlen;
/**
* Triggers management.
*/
class TriggersController extends AbstractController
{
/** @var DatabaseInterface */
private $dbi;
public function __construct(ResponseRenderer $response, Template $template, string $db, DatabaseInterface $dbi)
{
parent::__construct($response, $template, $db);
$this->dbi = $dbi;
}
public function __invoke(): void
{
global $db, $table, $tables, $num_tables, $total_num_tables, $sub_part;
global $tooltip_truename, $tooltip_aliasname, $pos;
global $errors, $urlParams, $errorUrl, $cfg;
$this->addScriptFiles(['database/triggers.js']);
if (! $this->response->isAjax()) {
/**
* Displays the header and tabs
*/
if (! empty($table) && in_array($table, $this->dbi->getTables($db))) {
Util::checkParameters(['db', 'table']);
$urlParams = ['db' => $db, 'table' => $table];
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
$errorUrl .= Url::getCommon($urlParams, '&');
DbTableExists::check();
} else {
$table = '';
Util::checkParameters(['db']);
$errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
$errorUrl .= Url::getCommon(['db' => $db], '&');
if (! $this->hasDatabase()) {
return;
}
[
$tables,
$num_tables,
$total_num_tables,
$sub_part,,,
$tooltip_truename,
$tooltip_aliasname,
$pos,
] = Util::getDbInfo($db, $sub_part ?? '');
}
} elseif (strlen($db) > 0) {
$this->dbi->selectDb($db);
}
/**
* Keep a list of errors that occurred while
* processing an 'Add' or 'Edit' operation.
*/
$errors = [];
$triggers = new Triggers($this->dbi, $this->template, $this->response);
$triggers->main();
}
}