';
} elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
// ... elseif display an empty column if the actions links are
// disabled to match the rest of the table
$button_html .= '
';
}
$this->properties['display_params'] = $display_params;
return [
$colspan,
$button_html,
];
}
/**
* Get table comments as array
*
* @see getTableHeaders()
*
* @param array $analyzed_sql_results analyzed sql results
*
* @return array table comments
*
* @access private
*/
private function getTableCommentsArray(array $analyzed_sql_results)
{
if (! $GLOBALS['cfg']['ShowBrowseComments']
|| empty($analyzed_sql_results['statement']->from)
) {
return [];
}
$ret = [];
foreach ($analyzed_sql_results['statement']->from as $field) {
if (empty($field->table)) {
continue;
}
$ret[$field->table] = $this->relation->getComments(
empty($field->database) ? $this->properties['db'] : $field->database,
$field->table
);
}
return $ret;
}
/**
* Set global array for store highlighted header fields
*
* @see getTableHeaders()
*
* @param array $analyzed_sql_results analyzed sql results
*
* @return void
*
* @access private
*/
private function setHighlightedColumnGlobalField(array $analyzed_sql_results)
{
$highlight_columns = [];
if (! empty($analyzed_sql_results['statement']->where)) {
foreach ($analyzed_sql_results['statement']->where as $expr) {
foreach ($expr->identifiers as $identifier) {
$highlight_columns[$identifier] = 'true';
}
}
}
$this->properties['highlight_columns'] = $highlight_columns;
}
/**
* Prepare data for column restoring and show/hide
*
* @see getTableHeaders()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return array
*/
private function getDataForResettingColumnOrder(array $analyzedSqlResults): array
{
global $dbi;
if (! $this->isSelect($analyzedSqlResults)) {
return [];
}
[$columnOrder, $columnVisibility] = $this->getColumnParams(
$analyzedSqlResults
);
$tableCreateTime = '';
$table = new Table($this->properties['table'], $this->properties['db']);
if (! $table->isView()) {
$tableCreateTime = $dbi->getTable(
$this->properties['db'],
$this->properties['table']
)->getStatusInfo('Create_time');
}
return [
'order' => $columnOrder,
'visibility' => $columnVisibility,
'is_view' => $table->isView(),
'table_create_time' => $tableCreateTime,
];
}
/**
* Prepare option fields block
*
* @see getTableHeaders()
*
* @return array
*/
private function getOptionsBlock(): array
{
if (isset($_SESSION['tmpval']['possible_as_geometry'])
&& $_SESSION['tmpval']['possible_as_geometry'] == false
) {
if ($_SESSION['tmpval']['geoOption'] === self::GEOMETRY_DISP_GEOM) {
$_SESSION['tmpval']['geoOption'] = self::GEOMETRY_DISP_WKT;
}
}
return [
'geo_option' => $_SESSION['tmpval']['geoOption'],
'hide_transformation' => $_SESSION['tmpval']['hide_transformation'],
'display_blob' => $_SESSION['tmpval']['display_blob'],
'display_binary' => $_SESSION['tmpval']['display_binary'],
'relational_display' => $_SESSION['tmpval']['relational_display'],
'possible_as_geometry' => $_SESSION['tmpval']['possible_as_geometry'],
'pftext' => $_SESSION['tmpval']['pftext'],
];
}
/**
* Get full/partial text button or link
*
* @see getTableHeaders()
*
* @return string html content
*
* @access private
*/
private function getFullOrPartialTextButtonOrLink()
{
$url_params_full_text = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $this->properties['sql_query'],
'goto' => $this->properties['goto'],
'full_text_button' => 1,
];
if ($_SESSION['tmpval']['pftext'] === self::DISPLAY_FULL_TEXT) {
// currently in fulltext mode so show the opposite link
$tmp_image_file = $this->properties['theme_image_path'] . 's_partialtext.png';
$tmp_txt = __('Partial texts');
$url_params_full_text['pftext'] = self::DISPLAY_PARTIAL_TEXT;
} else {
$tmp_image_file = $this->properties['theme_image_path'] . 's_fulltext.png';
$tmp_txt = __('Full texts');
$url_params_full_text['pftext'] = self::DISPLAY_FULL_TEXT;
}
$tmp_image = '';
$tmp_url = Url::getFromRoute('/sql', $url_params_full_text);
return Generator::linkOrButton($tmp_url, $tmp_image);
}
/**
* Get comment for row
*
* @see getTableHeaders()
*
* @param array $commentsMap comments array
* @param array $fieldsMeta set of field properties
*
* @return string html content
*
* @access private
*/
private function getCommentForRow(array $commentsMap, $fieldsMeta)
{
return $this->template->render('display/results/comment_for_row', [
'comments_map' => $commentsMap,
'fields_meta' => $fieldsMeta,
'limit_chars' => $GLOBALS['cfg']['LimitChars'],
]);
}
/**
* Prepare parameters and html for sorted table header fields
*
* @see getTableHeaders()
*
* @param stdClass $fields_meta set of field properties
* @param array $sort_expression sort expression
* @param array $sort_expression_nodirection sort expression without direction
* @param int $column_index the index of the column
* @param string $unsorted_sql_query the unsorted sql query
* @param int $session_max_rows maximum rows resulted by sql
* @param string $comments comment for row
* @param array $sort_direction sort direction
* @param bool $col_visib column is visible(false) or column isn't visible(string array)
* @param string $col_visib_j element of $col_visib array
*
* @return array 2 element array - $order_link, $sorted_header_html
*
* @access private
*/
private function getOrderLinkAndSortedHeaderHtml(
$fields_meta,
array $sort_expression,
array $sort_expression_nodirection,
$column_index,
$unsorted_sql_query,
$session_max_rows,
$comments,
array $sort_direction,
$col_visib,
$col_visib_j
) {
$sorted_header_html = '';
// Checks if the table name is required; it's the case
// for a query with a "JOIN" statement and if the column
// isn't aliased, or in queries like
// SELECT `1`.`master_field` , `2`.`master_field`
// FROM `PMA_relation` AS `1` , `PMA_relation` AS `2`
$sort_tbl = isset($fields_meta->table)
&& strlen($fields_meta->table) > 0
&& $fields_meta->orgname == $fields_meta->name
? Util::backquote(
$fields_meta->table
) . '.'
: '';
$name_to_use_in_sort = $fields_meta->name;
// Generates the orderby clause part of the query which is part
// of URL
[$single_sort_order, $multi_sort_order, $order_img]
= $this->getSingleAndMultiSortUrls(
$sort_expression,
$sort_expression_nodirection,
$sort_tbl,
$name_to_use_in_sort,
$sort_direction,
$fields_meta
);
if (preg_match(
'@(.*)([[:space:]](LIMIT (.*)|PROCEDURE (.*)|FOR UPDATE|'
. 'LOCK IN SHARE MODE))@is',
$unsorted_sql_query,
$regs3
)) {
$single_sorted_sql_query = $regs3[1] . $single_sort_order . $regs3[2];
$multi_sorted_sql_query = $regs3[1] . $multi_sort_order . $regs3[2];
} else {
$single_sorted_sql_query = $unsorted_sql_query . $single_sort_order;
$multi_sorted_sql_query = $unsorted_sql_query . $multi_sort_order;
}
$_single_url_params = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $single_sorted_sql_query,
'sql_signature' => Core::signSqlQuery($single_sorted_sql_query),
'session_max_rows' => $session_max_rows,
'is_browse_distinct' => $this->properties['is_browse_distinct'],
];
$_multi_url_params = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $multi_sorted_sql_query,
'sql_signature' => Core::signSqlQuery($multi_sorted_sql_query),
'session_max_rows' => $session_max_rows,
'is_browse_distinct' => $this->properties['is_browse_distinct'],
];
$single_order_url = Url::getFromRoute('/sql', $_single_url_params);
$multi_order_url = Url::getFromRoute('/sql', $_multi_url_params);
// Displays the sorting URL
// enable sort order swapping for image
$order_link = $this->getSortOrderLink(
$order_img,
$fields_meta,
$single_order_url,
$multi_order_url
);
$order_link .= $this->getSortOrderHiddenInputs(
$_multi_url_params,
$name_to_use_in_sort
);
$sorted_header_html .= $this->getDraggableClassForSortableColumns(
$col_visib,
$col_visib_j,
$fields_meta,
$order_link,
$comments
);
return [
$order_link,
$sorted_header_html,
];
}
/**
* Prepare parameters and html for sorted table header fields
*
* @see getOrderLinkAndSortedHeaderHtml()
*
* @param array $sort_expression sort expression
* @param array $sort_expression_nodirection sort expression without direction
* @param string $sort_tbl The name of the table to which
* the current column belongs to
* @param string $name_to_use_in_sort The current column under
* consideration
* @param array $sort_direction sort direction
* @param stdClass $fields_meta set of field properties
*
* @return array 3 element array - $single_sort_order, $sort_order, $order_img
*
* @access private
*/
private function getSingleAndMultiSortUrls(
array $sort_expression,
array $sort_expression_nodirection,
$sort_tbl,
$name_to_use_in_sort,
array $sort_direction,
$fields_meta
) {
$sort_order = '';
// Check if the current column is in the order by clause
$is_in_sort = $this->isInSorted(
$sort_expression,
$sort_expression_nodirection,
$sort_tbl,
$name_to_use_in_sort
);
$current_name = $name_to_use_in_sort;
if ($sort_expression_nodirection[0] == '' || ! $is_in_sort) {
$special_index = $sort_expression_nodirection[0] == ''
? 0
: count($sort_expression_nodirection);
$sort_expression_nodirection[$special_index]
= Util::backquote(
$current_name
);
$sort_direction[$special_index] = preg_match(
'@time|date@i',
$fields_meta->type ?? ''
) ? self::DESCENDING_SORT_DIR : self::ASCENDING_SORT_DIR;
}
$sort_expression_nodirection = array_filter($sort_expression_nodirection);
$single_sort_order = null;
foreach ($sort_expression_nodirection as $index => $expression) {
// check if this is the first clause,
// if it is then we have to add "order by"
$is_first_clause = ($index == 0);
$name_to_use_in_sort = $expression;
$sort_tbl_new = $sort_tbl;
// Test to detect if the column name is a standard name
// Standard name has the table name prefixed to the column name
if (mb_strpos($name_to_use_in_sort, '.') !== false) {
$matches = explode('.', $name_to_use_in_sort);
// Matches[0] has the table name
// Matches[1] has the column name
$name_to_use_in_sort = $matches[1];
$sort_tbl_new = $matches[0];
}
// $name_to_use_in_sort might contain a space due to
// formatting of function expressions like "COUNT(name )"
// so we remove the space in this situation
$name_to_use_in_sort = str_replace([' )', '``'], [')', '`'], $name_to_use_in_sort);
$name_to_use_in_sort = trim($name_to_use_in_sort, '`');
// If this the first column name in the order by clause add
// order by clause to the column name
$query_head = $is_first_clause ? "\nORDER BY " : '';
// Again a check to see if the given column is a aggregate column
if (mb_strpos($name_to_use_in_sort, '(') !== false) {
$sort_order .= $query_head . $name_to_use_in_sort . ' ';
} else {
if (strlen($sort_tbl_new) > 0) {
$sort_tbl_new .= '.';
}
$sort_order .= $query_head . $sort_tbl_new
. Util::backquote(
$name_to_use_in_sort
) . ' ';
}
// For a special case where the code generates two dots between
// column name and table name.
$sort_order = preg_replace('/\.\./', '.', $sort_order);
// Incase this is the current column save $single_sort_order
if ($current_name == $name_to_use_in_sort) {
if (mb_strpos($current_name, '(') !== false) {
$single_sort_order = "\n" . 'ORDER BY ' . Util::backquote($current_name) . ' ';
} else {
$single_sort_order = "\n" . 'ORDER BY ' . $sort_tbl
. Util::backquote(
$current_name
) . ' ';
}
if ($is_in_sort) {
[$single_sort_order, $order_img]
= $this->getSortingUrlParams(
$sort_direction,
$single_sort_order,
$index
);
} else {
$single_sort_order .= strtoupper($sort_direction[$index]);
}
}
if ($current_name == $name_to_use_in_sort && $is_in_sort) {
// We need to generate the arrow button and related html
[$sort_order, $order_img] = $this->getSortingUrlParams(
$sort_direction,
$sort_order,
$index
);
$order_img .= ' ' . ($index + 1) . '';
} else {
$sort_order .= strtoupper($sort_direction[$index]);
}
// Separate columns by a comma
$sort_order .= ', ';
}
// remove the comma from the last column name in the newly
// constructed clause
$sort_order = mb_substr(
$sort_order,
0,
mb_strlen($sort_order) - 2
);
if (empty($order_img)) {
$order_img = '';
}
return [
$single_sort_order,
$sort_order,
$order_img,
];
}
/**
* Check whether the column is sorted
*
* @see getTableHeaders()
*
* @param array $sort_expression sort expression
* @param array $sort_expression_nodirection sort expression without direction
* @param string $sort_tbl the table name
* @param string $name_to_use_in_sort the sorting column name
*
* @return bool the column sorted or not
*
* @access private
*/
private function isInSorted(
array $sort_expression,
array $sort_expression_nodirection,
$sort_tbl,
$name_to_use_in_sort
) {
$index_in_expression = 0;
foreach ($sort_expression_nodirection as $index => $clause) {
if (mb_strpos($clause, '.') !== false) {
$fragments = explode('.', $clause);
$clause2 = $fragments[0] . '.' . str_replace('`', '', $fragments[1]);
} else {
$clause2 = $sort_tbl . str_replace('`', '', $clause);
}
if ($clause2 === $sort_tbl . $name_to_use_in_sort) {
$index_in_expression = $index;
break;
}
}
if (empty($sort_expression[$index_in_expression])) {
$is_in_sort = false;
} else {
// Field name may be preceded by a space, or any number
// of characters followed by a dot (tablename.fieldname)
// so do a direct comparison for the sort expression;
// this avoids problems with queries like
// "SELECT id, count(id)..." and clicking to sort
// on id or on count(id).
// Another query to test this:
// SELECT p.*, FROM_UNIXTIME(p.temps) FROM mytable AS p
// (and try clicking on each column's header twice)
$noSortTable = empty($sort_tbl) || mb_strpos(
$sort_expression_nodirection[$index_in_expression],
$sort_tbl
) === false;
$noOpenParenthesis = mb_strpos(
$sort_expression_nodirection[$index_in_expression],
'('
) === false;
if (! empty($sort_tbl) && $noSortTable && $noOpenParenthesis) {
$new_sort_expression_nodirection = $sort_tbl
. $sort_expression_nodirection[$index_in_expression];
} else {
$new_sort_expression_nodirection
= $sort_expression_nodirection[$index_in_expression];
}
//Back quotes are removed in next comparison, so remove them from value
//to compare.
$name_to_use_in_sort = str_replace('`', '', $name_to_use_in_sort);
$is_in_sort = false;
$sort_name = str_replace('`', '', $sort_tbl) . $name_to_use_in_sort;
if ($sort_name == str_replace('`', '', $new_sort_expression_nodirection)
|| $sort_name == str_replace('`', '', $sort_expression_nodirection[$index_in_expression])
) {
$is_in_sort = true;
}
}
return $is_in_sort;
}
/**
* Get sort url parameters - sort order and order image
*
* @see getSingleAndMultiSortUrls()
*
* @param array $sort_direction the sort direction
* @param string $sort_order the sorting order
* @param int $index the index of sort direction array.
*
* @return array 2 element array - $sort_order, $order_img
*
* @access private
*/
private function getSortingUrlParams(array $sort_direction, $sort_order, $index)
{
if (strtoupper(trim($sort_direction[$index])) === self::DESCENDING_SORT_DIR) {
$sort_order .= ' ASC';
$order_img = ' ' . Generator::getImage(
's_desc',
__('Descending'),
[
'class' => 'soimg',
'title' => '',
]
);
$order_img .= ' ' . Generator::getImage(
's_asc',
__('Ascending'),
[
'class' => 'soimg hide',
'title' => '',
]
);
} else {
$sort_order .= ' DESC';
$order_img = ' ' . Generator::getImage(
's_asc',
__('Ascending'),
[
'class' => 'soimg',
'title' => '',
]
);
$order_img .= ' ' . Generator::getImage(
's_desc',
__('Descending'),
[
'class' => 'soimg hide',
'title' => '',
]
);
}
return [
$sort_order,
$order_img,
];
}
/**
* Get sort order link
*
* @see getTableHeaders()
*
* @param string $order_img the sort order image
* @param stdClass $fields_meta set of field properties
* @param string $order_url the url for sort
* @param string $multi_order_url the url for sort
*
* @return string the sort order link
*
* @access private
*/
private function getSortOrderLink(
$order_img,
$fields_meta,
$order_url,
$multi_order_url
) {
$order_link_params = ['class' => 'sortlink'];
$order_link_content = htmlspecialchars($fields_meta->name);
$inner_link_content = $order_link_content . $order_img
. '';
return Generator::linkOrButton(
$order_url,
$inner_link_content,
$order_link_params
);
}
private function getSortOrderHiddenInputs(
array $multipleUrlParams,
string $nameToUseInSort
): string {
$sqlQuery = $multipleUrlParams['sql_query'];
$sqlQueryAdd = $sqlQuery;
$sqlQueryRemove = null;
$parser = new Parser($sqlQuery);
$firstStatement = $parser->statements[0] ?? null;
$numberOfClausesFound = null;
if ($firstStatement instanceof SelectStatement) {
$orderClauses = $firstStatement->order ?? [];
foreach ($orderClauses as $key => $order) {
// If this is the column name, then remove it from the order clause
if ($order->expr->column !== $nameToUseInSort) {
continue;
}
// remove the order clause for this column and from the counted array
unset($firstStatement->order[$key], $orderClauses[$key]);
}
$numberOfClausesFound = count($orderClauses);
$sqlQueryRemove = $firstStatement->build();
}
$multipleUrlParams['sql_query'] = $sqlQueryRemove ?? $sqlQuery;
$multipleUrlParams['sql_signature'] = Core::signSqlQuery($multipleUrlParams['sql_query']);
$urlRemoveOrder = Url::getFromRoute('/sql', $multipleUrlParams);
if ($numberOfClausesFound !== null && $numberOfClausesFound === 0) {
$urlRemoveOrder .= '&discard_remembered_sort=1';
}
$multipleUrlParams['sql_query'] = $sqlQueryAdd;
$multipleUrlParams['sql_signature'] = Core::signSqlQuery($multipleUrlParams['sql_query']);
$urlAddOrder = Url::getFromRoute('/sql', $multipleUrlParams);
return '' . "\n"
. '';
}
/**
* Check if the column contains numeric data. If yes, then set the
* column header's alignment right
*
* @see getDraggableClassForSortableColumns()
*
* @param stdClass $fields_meta set of field properties
* @param array $th_class array containing classes
*
* @return void
*/
private function getClassForNumericColumnType($fields_meta, array &$th_class)
{
if (! preg_match(
'@int|decimal|float|double|real|bit|boolean|serial@i',
(string) $fields_meta->type
)) {
return;
}
$th_class[] = 'right';
}
/**
* Prepare columns to draggable effect for sortable columns
*
* @see getTableHeaders()
*
* @param bool $col_visib the column is visible (false)
* array the column is not visible (string array)
* @param string $col_visib_j element of $col_visib array
* @param stdClass $fields_meta set of field properties
* @param string $order_link the order link
* @param string $comments the comment for the column
*
* @return string html content
*
* @access private
*/
private function getDraggableClassForSortableColumns(
$col_visib,
$col_visib_j,
$fields_meta,
$order_link,
$comments
) {
$draggable_html = '
';
return $draggable_html;
}
/**
* Prepare columns to draggable effect for non sortable columns
*
* @see getTableHeaders()
*
* @param bool $col_visib the column is visible (false)
* array the column is not visible (string array)
* @param string $col_visib_j element of $col_visib array
* @param bool $condition_field whether to add CSS class condition
* @param stdClass $fields_meta set of field properties
* @param string $comments the comment for the column
*
* @return string html content
*
* @access private
*/
private function getDraggableClassForNonSortableColumns(
$col_visib,
$col_visib_j,
$condition_field,
$fields_meta,
$comments
) {
$draggable_html = '
';
}
$this->properties['display_params'] = $display_params;
return $right_column_html;
}
/**
* Prepares the display for a value
*
* @see getDataCellForGeometryColumns(),
* getDataCellForNonNumericColumns()
*
* @param string $class class of table cell
* @param bool $conditionField whether to add CSS class condition
* @param string $value value to display
*
* @return string the td
*
* @access private
*/
private function buildValueDisplay($class, $conditionField, $value)
{
return $this->template->render('display/results/value_display', [
'class' => $class,
'condition_field' => $conditionField,
'value' => $value,
]);
}
/**
* Prepares the display for a null value
*
* @see getDataCellForNumericColumns(),
* getDataCellForGeometryColumns(),
* getDataCellForNonNumericColumns()
*
* @param string $class class of table cell
* @param bool $conditionField whether to add CSS class condition
* @param stdClass $meta the meta-information about this field
* @param string $align cell alignment
*
* @return string the td
*
* @access private
*/
private function buildNullDisplay($class, $conditionField, $meta, $align = '')
{
$classes = $this->addClass($class, $conditionField, $meta, '');
return $this->template->render('display/results/null_display', [
'align' => $align,
'meta' => $meta,
'classes' => $classes,
]);
}
/**
* Prepares the display for an empty value
*
* @see getDataCellForNumericColumns(),
* getDataCellForGeometryColumns(),
* getDataCellForNonNumericColumns()
*
* @param string $class class of table cell
* @param bool $conditionField whether to add CSS class condition
* @param stdClass $meta the meta-information about this field
* @param string $align cell alignment
*
* @return string the td
*
* @access private
*/
private function buildEmptyDisplay($class, $conditionField, $meta, $align = '')
{
$classes = $this->addClass($class, $conditionField, $meta, 'nowrap');
return $this->template->render('display/results/empty_display', [
'align' => $align,
'classes' => $classes,
]);
}
/**
* Adds the relevant classes.
*
* @see buildNullDisplay(), getRowData()
*
* @param string $class class of table cell
* @param bool $condition_field whether to add CSS class
* condition
* @param stdClass $meta the meta-information about the
* field
* @param string $nowrap avoid wrapping
* @param bool $is_field_truncated is field truncated (display ...)
* @param TransformationsPlugin|string $transformation_plugin transformation plugin.
* Can also be the default function:
* Core::mimeDefaultFunction
* @param string $default_function default transformation function
*
* @return string the list of classes
*
* @access private
*/
private function addClass(
$class,
$condition_field,
$meta,
$nowrap,
$is_field_truncated = false,
$transformation_plugin = '',
$default_function = ''
) {
$classes = [
$class,
$nowrap,
];
if (isset($meta->mimetype)) {
$classes[] = preg_replace('/\//', '_', $meta->mimetype);
}
if ($condition_field) {
$classes[] = 'condition';
}
if ($is_field_truncated) {
$classes[] = 'truncated';
}
$mime_map = $this->properties['mime_map'];
$orgFullColName = $this->properties['db'] . '.' . $meta->orgtable
. '.' . $meta->orgname;
if ($transformation_plugin != $default_function
|| ! empty($mime_map[$orgFullColName]['input_transformation'])
) {
$classes[] = 'transformed';
}
// Define classes to be added to this data field based on the type of data
$matches = [
'enum' => 'enum',
'set' => 'set',
'binary' => 'hex',
];
foreach ($matches as $key => $value) {
if (mb_strpos($meta->flags, $key) === false) {
continue;
}
$classes[] = $value;
}
if (mb_strpos($meta->type, 'bit') !== false) {
$classes[] = 'bit';
}
return implode(' ', $classes);
}
/**
* Prepare the body of the results table
*
* @see getTable()
*
* @param int $dt_result the link id associated to the query
* which results have to be displayed
* @param array $displayParts which elements to display
* @param array $map the list of relations
* @param array $analyzed_sql_results analyzed sql results
* @param bool $is_limited_display with limited operations or not
*
* @return string html content
*
* @global array $row current row data
* @access private
*/
private function getTableBody(
&$dt_result,
array &$displayParts,
array $map,
array $analyzed_sql_results,
$is_limited_display = false
) {
global $dbi;
// Mostly because of browser transformations, to make the row-data accessible in a plugin.
global $row;
$table_body_html = '';
// query without conditions to shorten URLs when needed, 200 is just
// guess, it should depend on remaining URL length
$url_sql_query = $this->getUrlSqlQuery($analyzed_sql_results);
$display_params = $this->properties['display_params'];
if (! is_array($map)) {
$map = [];
}
$row_no = 0;
$display_params['edit'] = [];
$display_params['copy'] = [];
$display_params['delete'] = [];
$display_params['data'] = [];
$display_params['row_delete'] = [];
$this->properties['display_params'] = $display_params;
// name of the class added to all grid editable elements;
// if we don't have all the columns of a unique key in the result set,
// do not permit grid editing
if ($is_limited_display || ! $this->properties['editable']) {
$grid_edit_class = '';
} else {
switch ($GLOBALS['cfg']['GridEditing']) {
case 'double-click':
// trying to reduce generated HTML by using shorter
// classes like click1 and click2
$grid_edit_class = 'grid_edit click2';
break;
case 'click':
$grid_edit_class = 'grid_edit click1';
break;
default: // 'disabled'
$grid_edit_class = '';
break;
}
}
// prepare to get the column order, if available
[$col_order, $col_visib] = $this->getColumnParams(
$analyzed_sql_results
);
// Correction University of Virginia 19991216 in the while below
// Previous code assumed that all tables have keys, specifically that
// the phpMyAdmin GUI should support row delete/edit only for such
// tables.
// Although always using keys is arguably the prescribed way of
// defining a relational table, it is not required. This will in
// particular be violated by the novice.
// We want to encourage phpMyAdmin usage by such novices. So the code
// below has been changed to conditionally work as before when the
// table being displayed has one or more keys; but to display
// delete/edit options correctly for tables without keys.
$whereClauseMap = $this->properties['whereClauseMap'];
while ($row = $dbi->fetchRow($dt_result)) {
// add repeating headers
if (($row_no != 0) && ($_SESSION['tmpval']['repeat_cells'] != 0)
&& ! $row_no % $_SESSION['tmpval']['repeat_cells']
) {
$table_body_html .= $this->getRepeatingHeaders(
$display_params
);
}
$tr_class = [];
if ($GLOBALS['cfg']['BrowsePointerEnable'] != true) {
$tr_class[] = 'nopointer';
}
if ($GLOBALS['cfg']['BrowseMarkerEnable'] != true) {
$tr_class[] = 'nomarker';
}
// pointer code part
$classes = (empty($tr_class) ? ' ' : 'class="' . implode(' ', $tr_class) . '"');
$table_body_html .= '
';
// 1. Prepares the row
// In print view these variable needs to be initialized
$del_url = null;
$del_str = null;
$edit_str = null;
$js_conf = null;
$copy_url = null;
$copy_str = null;
$edit_url = null;
// 1.2 Defines the URLs for the modify/delete link(s)
if (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
|| ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
) {
$expressions = [];
if (isset($analyzed_sql_results['statement'])
&& $analyzed_sql_results['statement'] instanceof SelectStatement
) {
$expressions = $analyzed_sql_results['statement']->expr;
}
// Results from a "SELECT" statement -> builds the
// WHERE clause to use in links (a unique key if possible)
/**
* @todo $where_clause could be empty, for example a table
* with only one field and it's a BLOB; in this case,
* avoid to display the delete and edit links
*/
[$where_clause, $clause_is_unique, $condition_array] = Util::getUniqueCondition(
$dt_result,
$this->properties['fields_cnt'],
$this->properties['fields_meta'],
$row,
false,
$this->properties['table'],
$expressions
);
$whereClauseMap[$row_no][$this->properties['table']] = $where_clause;
$this->properties['whereClauseMap'] = $whereClauseMap;
// 1.2.1 Modify link(s) - update row case
if ($displayParts['edit_lnk'] === self::UPDATE_ROW) {
[
$edit_url,
$copy_url,
$edit_str,
$copy_str,
]
= $this->getModifiedLinks(
$where_clause,
$clause_is_unique,
$url_sql_query
);
}
// 1.2.2 Delete/Kill link(s)
[$del_url, $del_str, $js_conf]
= $this->getDeleteAndKillLinks(
$where_clause,
$clause_is_unique,
$url_sql_query,
$displayParts['del_lnk'],
$row
);
// 1.3 Displays the links at left if required
if (($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_LEFT)
|| ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
) {
$table_body_html .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_LEFT,
'has_checkbox' => ! empty($del_url) && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => ['url' => $edit_url, 'string' => $edit_str, 'clause_is_unique' => $clause_is_unique],
'copy' => ['url' => $copy_url, 'string' => $copy_str],
'delete' => ['url' => $del_url, 'string' => $del_str],
'row_number' => $row_no,
'where_clause' => $where_clause,
'condition' => json_encode($condition_array),
'is_ajax' => Response::getInstance()->isAjax(),
'js_conf' => $js_conf ?? '',
]);
} elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
$table_body_html .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_NONE,
'has_checkbox' => ! empty($del_url) && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => ['url' => $edit_url, 'string' => $edit_str, 'clause_is_unique' => $clause_is_unique],
'copy' => ['url' => $copy_url, 'string' => $copy_str],
'delete' => ['url' => $del_url, 'string' => $del_str],
'row_number' => $row_no,
'where_clause' => $where_clause,
'condition' => json_encode($condition_array),
'is_ajax' => Response::getInstance()->isAjax(),
'js_conf' => $js_conf ?? '',
]);
}
}
// 2. Displays the rows' values
if ($this->properties['mime_map'] === null) {
$this->setMimeMap();
}
$table_body_html .= $this->getRowValues(
$dt_result,
$row,
$row_no,
$col_order,
$map,
$grid_edit_class,
$col_visib,
$url_sql_query,
$analyzed_sql_results
);
// 3. Displays the modify/delete links on the right if required
if (($displayParts['edit_lnk'] != self::NO_EDIT_OR_DELETE)
|| ($displayParts['del_lnk'] != self::NO_EDIT_OR_DELETE)
) {
if (($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_RIGHT)
|| ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_BOTH)
) {
$table_body_html .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_RIGHT,
'has_checkbox' => ! empty($del_url) && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => [
'url' => $edit_url,
'string' => $edit_str,
'clause_is_unique' => $clause_is_unique ?? true,
],
'copy' => ['url' => $copy_url, 'string' => $copy_str],
'delete' => ['url' => $del_url, 'string' => $del_str],
'row_number' => $row_no,
'where_clause' => $where_clause ?? '',
'condition' => json_encode($condition_array ?? []),
'is_ajax' => Response::getInstance()->isAjax(),
'js_conf' => $js_conf ?? '',
]);
}
}
$table_body_html .= '
';
$table_body_html .= "\n";
$row_no++;
}
return $table_body_html;
}
/**
* Sets the MIME details of the columns in the results set
*
* @return void
*/
private function setMimeMap()
{
$fields_meta = $this->properties['fields_meta'];
$mimeMap = [];
$added = [];
for ($currentColumn = 0; $currentColumn < $this->properties['fields_cnt']; ++$currentColumn) {
$meta = $fields_meta[$currentColumn];
$orgFullTableName = $this->properties['db'] . '.' . $meta->orgtable;
if (! $GLOBALS['cfgRelation']['commwork']
|| ! $GLOBALS['cfgRelation']['mimework']
|| ! $GLOBALS['cfg']['BrowseMIME']
|| $_SESSION['tmpval']['hide_transformation']
|| ! empty($added[$orgFullTableName])
) {
continue;
}
$mimeMap = array_merge(
$mimeMap,
$this->transformations->getMime($this->properties['db'], $meta->orgtable, false, true) ?? []
);
$added[$orgFullTableName] = true;
}
// special browser transformation for some SHOW statements
if ($this->properties['is_show']
&& ! $_SESSION['tmpval']['hide_transformation']
) {
preg_match(
'@^SHOW[[:space:]]+(VARIABLES|(FULL[[:space:]]+)?'
. 'PROCESSLIST|STATUS|TABLE|GRANTS|CREATE|LOGS|DATABASES|FIELDS'
. ')@i',
$this->properties['sql_query'],
$which
);
if (isset($which[1])) {
$str = ' ' . strtoupper($which[1]);
$isShowProcessList = strpos($str, 'PROCESSLIST') > 0;
if ($isShowProcessList) {
$mimeMap['..Info'] = [
'mimetype' => 'Text_Plain',
'transformation' => 'output/Text_Plain_Sql.php',
];
}
$isShowCreateTable = preg_match(
'@CREATE[[:space:]]+TABLE@i',
$this->properties['sql_query']
);
if ($isShowCreateTable) {
$mimeMap['..Create Table'] = [
'mimetype' => 'Text_Plain',
'transformation' => 'output/Text_Plain_Sql.php',
];
}
}
}
$this->properties['mime_map'] = $mimeMap;
}
/**
* Get the values for one data row
*
* @see getTableBody()
*
* @param int $dt_result the link id associated to the query
* which results have to be displayed
* @param array $row current row data
* @param int $row_no the index of current row
* @param array|false $col_order the column order false when
* a property not found false
* when a property not found
* @param array $map the list of relations
* @param string $grid_edit_class the class for all editable
* columns
* @param bool|array|string $col_visib column is visible(false);
* column isn't visible(string
* array)
* @param string $url_sql_query the analyzed sql query
* @param array $analyzed_sql_results analyzed sql results
*
* @return string html content
*
* @access private
*/
private function getRowValues(
&$dt_result,
array $row,
$row_no,
$col_order,
array $map,
$grid_edit_class,
$col_visib,
$url_sql_query,
array $analyzed_sql_results
) {
$row_values_html = '';
// Following variable are needed for use in isset/empty or
// use with array indexes/safe use in foreach
$sql_query = $this->properties['sql_query'];
$fields_meta = $this->properties['fields_meta'];
$highlight_columns = $this->properties['highlight_columns'];
$mime_map = $this->properties['mime_map'];
$row_info = $this->getRowInfoForSpecialLinks($row, $col_order);
$whereClauseMap = $this->properties['whereClauseMap'];
$columnCount = $this->properties['fields_cnt'];
// Load SpecialSchemaLinks for all rows
$specialSchemaLinks = SpecialSchemaLinks::get();
for ($currentColumn = 0; $currentColumn < $columnCount; ++$currentColumn) {
// assign $i with appropriate column order
$i = is_array($col_order) ? $col_order[$currentColumn] : $currentColumn;
$meta = $fields_meta[$i];
$orgFullColName
= $this->properties['db'] . '.' . $meta->orgtable . '.' . $meta->orgname;
$not_null_class = $meta->not_null ? 'not_null' : '';
$relation_class = isset($map[$meta->name]) ? 'relation' : '';
$hide_class = is_array($col_visib) && isset($col_visib[$currentColumn]) && ! $col_visib[$currentColumn]
? 'hide'
: '';
$grid_edit = $meta->orgtable != '' ? $grid_edit_class : '';
// handle datetime-related class, for grid editing
$field_type_class
= $this->getClassForDateTimeRelatedFields($meta->type);
$is_field_truncated = false;
// combine all the classes applicable to this column's value
$class = $this->getClassesForColumn(
$grid_edit,
$not_null_class,
$relation_class,
$hide_class,
$field_type_class
);
// See if this column should get highlight because it's used in the
// where-query.
$condition_field = isset($highlight_columns)
&& (isset($highlight_columns[$meta->name])
|| isset($highlight_columns[Util::backquote($meta->name)]));
// Wrap MIME-transformations. [MIME]
$default_function = [
Core::class,
'mimeDefaultFunction',
]; // default_function
$transformation_plugin = $default_function;
$transform_options = [];
if ($GLOBALS['cfgRelation']['mimework']
&& $GLOBALS['cfg']['BrowseMIME']
) {
if (isset($mime_map[$orgFullColName]['mimetype'])
&& ! empty($mime_map[$orgFullColName]['transformation'])
) {
$file = $mime_map[$orgFullColName]['transformation'];
$include_file = 'libraries/classes/Plugins/Transformations/' . $file;
if (@file_exists($include_file)) {
$class_name = $this->transformations->getClassName($include_file);
if (class_exists($class_name)) {
// todo add $plugin_manager
$plugin_manager = null;
$transformation_plugin = new $class_name(
$plugin_manager
);
$transform_options = $this->transformations->getOptions(
$mime_map[$orgFullColName]['transformation_options'] ?? ''
);
$meta->mimetype = str_replace(
'_',
'/',
$mime_map[$orgFullColName]['mimetype']
);
}
}
}
}
// Check whether the field needs to display with syntax highlighting
$dbLower = mb_strtolower($this->properties['db']);
$tblLower = mb_strtolower($meta->orgtable);
$nameLower = mb_strtolower($meta->orgname);
if (! empty($this->transformationInfo[$dbLower][$tblLower][$nameLower])
&& isset($row[$i])
&& (trim($row[$i]) != '')
&& ! $_SESSION['tmpval']['hide_transformation']
) {
include_once $this->transformationInfo[$dbLower][$tblLower][$nameLower][0];
$transformation_plugin = new $this->transformationInfo[$dbLower][$tblLower][$nameLower][1](null);
$transform_options = $this->transformations->getOptions(
$mime_map[$orgFullColName]['transformation_options'] ?? ''
);
$orgTable = mb_strtolower($meta->orgtable);
$orgName = mb_strtolower($meta->orgname);
$meta->mimetype = str_replace(
'_',
'/',
$this->transformationInfo[$dbLower][$orgTable][$orgName][2]
);
}
// Check for the predefined fields need to show as link in schemas
if (! empty($specialSchemaLinks[$dbLower][$tblLower][$nameLower])) {
$linking_url = $this->getSpecialLinkUrl(
$specialSchemaLinks[$dbLower][$tblLower][$nameLower],
$row[$i],
$row_info
);
$transformation_plugin = new Text_Plain_Link();
$transform_options = [
0 => $linking_url,
2 => true,
];
$meta->mimetype = str_replace(
'_',
'/',
'Text/Plain'
);
}
$expressions = [];
if (isset($analyzed_sql_results['statement'])
&& $analyzed_sql_results['statement'] instanceof SelectStatement
) {
$expressions = $analyzed_sql_results['statement']->expr;
}
/**
* The result set can have columns from more than one table,
* this is why we have to check for the unique conditions
* related to this table; however getUniqueCondition() is
* costly and does not need to be called if we already know
* the conditions for the current table.
*/
if (! isset($whereClauseMap[$row_no][$meta->orgtable])) {
$unique_conditions = Util::getUniqueCondition(
$dt_result,
$this->properties['fields_cnt'],
$this->properties['fields_meta'],
$row,
false,
$meta->orgtable,
$expressions
);
$whereClauseMap[$row_no][$meta->orgtable] = $unique_conditions[0];
}
$_url_params = [
'db' => $this->properties['db'],
'table' => $meta->orgtable,
'where_clause_sign' => Core::signSqlQuery($whereClauseMap[$row_no][$meta->orgtable]),
'where_clause' => $whereClauseMap[$row_no][$meta->orgtable],
'transform_key' => $meta->orgname,
];
if (! empty($sql_query)) {
$_url_params['sql_query'] = $url_sql_query;
}
$transform_options['wrapper_link'] = Url::getCommon($_url_params);
$transform_options['wrapper_params'] = $_url_params;
$display_params = $this->properties['display_params'];
// in some situations (issue 11406), numeric returns 1
// even for a string type
// for decimal numeric is returning 1
// have to improve logic
if (($meta->numeric == 1 && $meta->type !== 'string') || $meta->type === 'real') {
// n u m e r i c
$display_params['data'][$row_no][$i]
= $this->getDataCellForNumericColumns(
$row[$i] === null ? null : (string) $row[$i],
$class,
$condition_field,
$meta,
$map,
$is_field_truncated,
$analyzed_sql_results,
$transformation_plugin,
$default_function,
$transform_options
);
} elseif ($meta->type === self::GEOMETRY_FIELD) {
// g e o m e t r y
// Remove 'grid_edit' from $class as we do not allow to
// inline-edit geometry data.
$class = str_replace('grid_edit', '', $class);
$display_params['data'][$row_no][$i]
= $this->getDataCellForGeometryColumns(
$row[$i],
$class,
$meta,
$map,
$_url_params,
$condition_field,
$transformation_plugin,
$default_function,
$transform_options,
$analyzed_sql_results
);
} else {
// n o t n u m e r i c
$display_params['data'][$row_no][$i]
= $this->getDataCellForNonNumericColumns(
$row[$i],
$class,
$meta,
$map,
$_url_params,
$condition_field,
$transformation_plugin,
$default_function,
$transform_options,
$is_field_truncated,
$analyzed_sql_results,
$dt_result,
$i
);
}
// output stored cell
$row_values_html .= $display_params['data'][$row_no][$i];
if (isset($display_params['rowdata'][$i][$row_no])) {
$display_params['rowdata'][$i][$row_no]
.= $display_params['data'][$row_no][$i];
} else {
$display_params['rowdata'][$i][$row_no]
= $display_params['data'][$row_no][$i];
}
$this->properties['display_params'] = $display_params;
}
return $row_values_html;
}
/**
* Get link for display special schema links
*
* @param array>|string> $link_relations
* @param string $column_value column value
* @param array $row_info information about row
*
* @return string generated link
*
* @phpstan-param array{
* 'link_param': string,
* 'link_dependancy_params'?: array<
* int,
* array{'param_info': string, 'column_name': string}
* >,
* 'default_page': string
* } $link_relations
*/
private function getSpecialLinkUrl(
array $link_relations,
$column_value,
array $row_info
) {
$linking_url_params = [];
$linking_url_params[$link_relations['link_param']] = $column_value;
$divider = strpos($link_relations['default_page'], '?') ? '&' : '?';
if (empty($link_relations['link_dependancy_params'])) {
return $link_relations['default_page']
. Url::getCommonRaw($linking_url_params, $divider);
}
foreach ($link_relations['link_dependancy_params'] as $new_param) {
$columnName = mb_strtolower($new_param['column_name']);
// If there is a value for this column name in the row_info provided
if (isset($row_info[$columnName])) {
$urlParameterName = $new_param['param_info'];
$linking_url_params[$urlParameterName] = $row_info[$columnName];
}
// Special case 1 - when executing routines, according
// to the type of the routine, url param changes
if (empty($row_info['routine_type'])) {
continue;
}
}
return $link_relations['default_page']
. Url::getCommonRaw($linking_url_params, $divider);
}
/**
* Prepare row information for display special links
*
* @param array $row current row data
* @param array|bool $col_order the column order
*
* @return array associative array with column nama -> value
*/
private function getRowInfoForSpecialLinks(array $row, $col_order)
{
$row_info = [];
$fields_meta = $this->properties['fields_meta'];
for ($n = 0; $n < $this->properties['fields_cnt']; ++$n) {
$m = is_array($col_order) ? $col_order[$n] : $n;
$row_info[mb_strtolower($fields_meta[$m]->orgname)]
= $row[$m];
}
return $row_info;
}
/**
* Get url sql query without conditions to shorten URLs
*
* @see getTableBody()
*
* @param array $analyzed_sql_results analyzed sql results
*
* @return string analyzed sql query
*
* @access private
*/
private function getUrlSqlQuery(array $analyzed_sql_results)
{
if (($analyzed_sql_results['querytype'] !== 'SELECT')
|| (mb_strlen($this->properties['sql_query']) < 200)
) {
return $this->properties['sql_query'];
}
$query = 'SELECT ' . Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'SELECT'
);
$from_clause = Query::getClause(
$analyzed_sql_results['statement'],
$analyzed_sql_results['parser']->list,
'FROM'
);
if (! empty($from_clause)) {
$query .= ' FROM ' . $from_clause;
}
return $query;
}
/**
* Get column order and column visibility
*
* @see getTableBody()
*
* @param array $analyzed_sql_results analyzed sql results
*
* @return array 2 element array - $col_order, $col_visib
*
* @access private
*/
private function getColumnParams(array $analyzed_sql_results)
{
if ($this->isSelect($analyzed_sql_results)) {
$pmatable = new Table($this->properties['table'], $this->properties['db']);
$col_order = $pmatable->getUiProp(Table::PROP_COLUMN_ORDER);
/* Validate the value */
if ($col_order !== false) {
$fields_cnt = $this->properties['fields_cnt'];
foreach ($col_order as $value) {
if ($value < $fields_cnt) {
continue;
}
$pmatable->removeUiProp(Table::PROP_COLUMN_ORDER);
$fields_cnt = false;
}
}
$col_visib = $pmatable->getUiProp(Table::PROP_COLUMN_VISIB);
} else {
$col_order = false;
$col_visib = false;
}
return [
$col_order,
$col_visib,
];
}
/**
* Get HTML for repeating headers
*
* @see getTableBody()
*
* @param array $display_params holds various display info
*
* @return string html content
*
* @access private
*/
private function getRepeatingHeaders(
array $display_params
) {
$header_html = '