';
} 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
$buttonHtml .= '
';
}
$this->properties['display_params'] = $displayParams;
return [
$colspan,
$buttonHtml,
];
}
/**
* Get table comments as array
*
* @see getTableHeaders()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return array table comments
*
* @access private
*/
private function getTableCommentsArray(array $analyzedSqlResults)
{
if (
! $GLOBALS['cfg']['ShowBrowseComments']
|| empty($analyzedSqlResults['statement']->from)
) {
return [];
}
$ret = [];
foreach ($analyzedSqlResults['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 $analyzedSqlResults analyzed sql results
*
* @return void
*
* @access private
*/
private function setHighlightedColumnGlobalField(array $analyzedSqlResults)
{
$highlightColumns = [];
if (! empty($analyzedSqlResults['statement']->where)) {
foreach ($analyzedSqlResults['statement']->where as $expr) {
foreach ($expr->identifiers as $identifier) {
$highlightColumns[$identifier] = 'true';
}
}
}
$this->properties['highlight_columns'] = $highlightColumns;
}
/**
* 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()
{
global $theme;
$urlParamsFullText = [
'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
$tmpImageFile = 's_partialtext.png';
$tmpTxt = __('Partial texts');
$urlParamsFullText['pftext'] = self::DISPLAY_PARTIAL_TEXT;
} else {
$tmpImageFile = 's_fulltext.png';
$tmpTxt = __('Full texts');
$urlParamsFullText['pftext'] = self::DISPLAY_FULL_TEXT;
}
$tmpImage = '';
$tmpUrl = Url::getFromRoute('/sql', $urlParamsFullText);
return Generator::linkOrButton($tmpUrl, $tmpImage);
}
/**
* Get comment for row
*
* @see getTableHeaders()
*
* @param array $commentsMap comments array
* @param FieldMetadata $fieldsMeta set of field properties
*
* @return string html content
*
* @access private
*/
private function getCommentForRow(array $commentsMap, FieldMetadata $fieldsMeta)
{
return $this->template->render('display/results/comment_for_row', [
'comments_map' => $commentsMap,
'column_name' => $fieldsMeta->name,
'table_name' => $fieldsMeta->table,
'limit_chars' => $GLOBALS['cfg']['LimitChars'],
]);
}
/**
* Prepare parameters and html for sorted table header fields
*
* @see getTableHeaders()
*
* @param FieldMetadata $fieldsMeta set of field properties
* @param array $sortExpression sort expression
* @param array $sortExpressionNoDirection sort expression without direction
* @param int $columnIndex the index of the column
* @param string $unsortedSqlQuery the unsorted sql query
* @param int $sessionMaxRows maximum rows resulted by sql
* @param string $comments comment for row
* @param array $sortDirection sort direction
* @param bool $colVisib column is visible(false) or column isn't visible(string array)
* @param string $colVisibElement element of $col_visib array
*
* @return array 2 element array - $orderLink, $sortedHeaderHtml
*
* @access private
*/
private function getOrderLinkAndSortedHeaderHtml(
FieldMetadata $fieldsMeta,
array $sortExpression,
array $sortExpressionNoDirection,
$columnIndex,
$unsortedSqlQuery,
$sessionMaxRows,
$comments,
array $sortDirection,
$colVisib,
$colVisibElement
) {
$sortedHeaderHtml = '';
// 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`
$sortTable = isset($fieldsMeta->table)
&& strlen($fieldsMeta->table) > 0
&& $fieldsMeta->orgname == $fieldsMeta->name
? Util::backquote(
$fieldsMeta->table
) . '.'
: '';
$nameToUseInSort = $fieldsMeta->name;
// Generates the orderby clause part of the query which is part
// of URL
[$singleSortOrder, $multiSortOrder, $orderImg] = $this->getSingleAndMultiSortUrls(
$sortExpression,
$sortExpressionNoDirection,
$sortTable,
$nameToUseInSort,
$sortDirection,
$fieldsMeta
);
if (
preg_match(
'@(.*)([[:space:]](LIMIT (.*)|PROCEDURE (.*)|FOR UPDATE|'
. 'LOCK IN SHARE MODE))@is',
$unsortedSqlQuery,
$regs3
)
) {
$singleSortedSqlQuery = $regs3[1] . $singleSortOrder . $regs3[2];
$multiSortedSqlQuery = $regs3[1] . $multiSortOrder . $regs3[2];
} else {
$singleSortedSqlQuery = $unsortedSqlQuery . $singleSortOrder;
$multiSortedSqlQuery = $unsortedSqlQuery . $multiSortOrder;
}
$singleUrlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $singleSortedSqlQuery,
'sql_signature' => Core::signSqlQuery($singleSortedSqlQuery),
'session_max_rows' => $sessionMaxRows,
'is_browse_distinct' => $this->properties['is_browse_distinct'],
];
$multiUrlParams = [
'db' => $this->properties['db'],
'table' => $this->properties['table'],
'sql_query' => $multiSortedSqlQuery,
'sql_signature' => Core::signSqlQuery($multiSortedSqlQuery),
'session_max_rows' => $sessionMaxRows,
'is_browse_distinct' => $this->properties['is_browse_distinct'],
];
$singleOrderUrl = Url::getFromRoute('/sql', $singleUrlParams);
$multiOrderUrl = Url::getFromRoute('/sql', $multiUrlParams);
// Displays the sorting URL
// enable sort order swapping for image
$orderLink = $this->getSortOrderLink(
$orderImg,
$fieldsMeta,
$singleOrderUrl,
$multiOrderUrl
);
$orderLink .= $this->getSortOrderHiddenInputs(
$multiUrlParams,
$nameToUseInSort
);
$sortedHeaderHtml .= $this->getDraggableClassForSortableColumns(
$colVisib,
$colVisibElement,
$fieldsMeta,
$orderLink,
$comments
);
return [
$orderLink,
$sortedHeaderHtml,
];
}
/**
* Prepare parameters and html for sorted table header fields
*
* @see getOrderLinkAndSortedHeaderHtml()
*
* @param array $sortExpression sort expression
* @param array $sortExpressionNoDirection sort expression without direction
* @param string $sortTable The name of the table to which
* the current column belongs to
* @param string $nameToUseInSort The current column under
* consideration
* @param array $sortDirection sort direction
* @param FieldMetadata $fieldsMeta set of field properties
*
* @return array 3 element array - $single_sort_order, $sort_order, $order_img
*
* @access private
*/
private function getSingleAndMultiSortUrls(
array $sortExpression,
array $sortExpressionNoDirection,
$sortTable,
$nameToUseInSort,
array $sortDirection,
FieldMetadata $fieldsMeta
) {
$sortOrder = '';
// Check if the current column is in the order by clause
$isInSort = $this->isInSorted(
$sortExpression,
$sortExpressionNoDirection,
$sortTable,
$nameToUseInSort
);
$currentName = $nameToUseInSort;
if ($sortExpressionNoDirection[0] == '' || ! $isInSort) {
$specialIndex = $sortExpressionNoDirection[0] == ''
? 0
: count($sortExpressionNoDirection);
$sortExpressionNoDirection[$specialIndex] = Util::backquote(
$currentName
);
$isTimeOrDate = $fieldsMeta->isType(FieldMetadata::TYPE_TIME)
|| $fieldsMeta->isType(FieldMetadata::TYPE_DATE)
|| $fieldsMeta->isType(FieldMetadata::TYPE_DATETIME)
|| $fieldsMeta->isType(FieldMetadata::TYPE_TIMESTAMP);
$sortDirection[$specialIndex] = $isTimeOrDate ? self::DESCENDING_SORT_DIR : self::ASCENDING_SORT_DIR;
}
$sortExpressionNoDirection = array_filter($sortExpressionNoDirection);
$singleSortOrder = null;
foreach ($sortExpressionNoDirection as $index => $expression) {
// check if this is the first clause,
// if it is then we have to add "order by"
$isFirstClause = ($index == 0);
$nameToUseInSort = $expression;
$sortTableNew = $sortTable;
// 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($nameToUseInSort, '.') !== false) {
$matches = explode('.', $nameToUseInSort);
// Matches[0] has the table name
// Matches[1] has the column name
$nameToUseInSort = $matches[1];
$sortTableNew = $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
$nameToUseInSort = str_replace([' )', '``'], [')', '`'], $nameToUseInSort);
$nameToUseInSort = trim($nameToUseInSort, '`');
// If this the first column name in the order by clause add
// order by clause to the column name
$queryHead = $isFirstClause ? "\nORDER BY " : '';
// Again a check to see if the given column is a aggregate column
if (mb_strpos($nameToUseInSort, '(') !== false) {
$sortOrder .= $queryHead . $nameToUseInSort . ' ';
} else {
if (strlen($sortTableNew) > 0) {
$sortTableNew .= '.';
}
$sortOrder .= $queryHead . $sortTableNew
. Util::backquote(
$nameToUseInSort
) . ' ';
}
// For a special case where the code generates two dots between
// column name and table name.
$sortOrder = preg_replace('/\.\./', '.', $sortOrder);
// Incase this is the current column save $single_sort_order
if ($currentName == $nameToUseInSort) {
if (mb_strpos($currentName, '(') !== false) {
$singleSortOrder = "\n" . 'ORDER BY ' . Util::backquote($currentName) . ' ';
} else {
$singleSortOrder = "\n" . 'ORDER BY ' . $sortTable
. Util::backquote(
$currentName
) . ' ';
}
if ($isInSort) {
[$singleSortOrder, $orderImg] = $this->getSortingUrlParams(
$sortDirection,
$singleSortOrder,
$index
);
} else {
$singleSortOrder .= strtoupper($sortDirection[$index]);
}
}
if ($currentName == $nameToUseInSort && $isInSort) {
// We need to generate the arrow button and related html
[$sortOrder, $orderImg] = $this->getSortingUrlParams(
$sortDirection,
$sortOrder,
$index
);
$orderImg .= ' ' . ($index + 1) . '';
} else {
$sortOrder .= strtoupper($sortDirection[$index]);
}
// Separate columns by a comma
$sortOrder .= ', ';
}
// remove the comma from the last column name in the newly
// constructed clause
$sortOrder = mb_substr(
$sortOrder,
0,
mb_strlen($sortOrder) - 2
);
if (empty($orderImg)) {
$orderImg = '';
}
return [
$singleSortOrder,
$sortOrder,
$orderImg,
];
}
/**
* Check whether the column is sorted
*
* @see getTableHeaders()
*
* @param array $sortExpression sort expression
* @param array $sortExpressionNoDirection sort expression without direction
* @param string $sortTable the table name
* @param string $nameToUseInSort the sorting column name
*
* @return bool the column sorted or not
*
* @access private
*/
private function isInSorted(
array $sortExpression,
array $sortExpressionNoDirection,
$sortTable,
$nameToUseInSort
) {
$indexInExpression = 0;
foreach ($sortExpressionNoDirection as $index => $clause) {
if (mb_strpos($clause, '.') !== false) {
$fragments = explode('.', $clause);
$clause2 = $fragments[0] . '.' . str_replace('`', '', $fragments[1]);
} else {
$clause2 = $sortTable . str_replace('`', '', $clause);
}
if ($clause2 === $sortTable . $nameToUseInSort) {
$indexInExpression = $index;
break;
}
}
if (empty($sortExpression[$indexInExpression])) {
$isInSort = 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($sortTable) || mb_strpos(
$sortExpressionNoDirection[$indexInExpression],
$sortTable
) === false;
$noOpenParenthesis = mb_strpos(
$sortExpressionNoDirection[$indexInExpression],
'('
) === false;
if (! empty($sortTable) && $noSortTable && $noOpenParenthesis) {
$newSortExpressionNoDirection = $sortTable
. $sortExpressionNoDirection[$indexInExpression];
} else {
$newSortExpressionNoDirection = $sortExpressionNoDirection[$indexInExpression];
}
//Back quotes are removed in next comparison, so remove them from value
//to compare.
$nameToUseInSort = str_replace('`', '', $nameToUseInSort);
$isInSort = false;
$sortName = str_replace('`', '', $sortTable) . $nameToUseInSort;
if (
$sortName == str_replace('`', '', $newSortExpressionNoDirection)
|| $sortName == str_replace('`', '', $sortExpressionNoDirection[$indexInExpression])
) {
$isInSort = true;
}
}
return $isInSort;
}
/**
* Get sort url parameters - sort order and order image
*
* @see getSingleAndMultiSortUrls()
*
* @param array $sortDirection the sort direction
* @param string $sortOrder 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 $sortDirection, $sortOrder, $index)
{
if (strtoupper(trim($sortDirection[$index])) === self::DESCENDING_SORT_DIR) {
$sortOrder .= ' ASC';
$orderImg = ' ' . Generator::getImage(
's_desc',
__('Descending'),
[
'class' => 'soimg',
'title' => '',
]
);
$orderImg .= ' ' . Generator::getImage(
's_asc',
__('Ascending'),
[
'class' => 'soimg hide',
'title' => '',
]
);
} else {
$sortOrder .= ' DESC';
$orderImg = ' ' . Generator::getImage(
's_asc',
__('Ascending'),
[
'class' => 'soimg',
'title' => '',
]
);
$orderImg .= ' ' . Generator::getImage(
's_desc',
__('Descending'),
[
'class' => 'soimg hide',
'title' => '',
]
);
}
return [
$sortOrder,
$orderImg,
];
}
/**
* Get sort order link
*
* @see getTableHeaders()
*
* @param string $orderImg the sort order image
* @param FieldMetadata $fieldsMeta set of field properties
* @param string $orderUrl the url for sort
* @param string $multiOrderUrl the url for sort
*
* @return string the sort order link
*
* @access private
*/
private function getSortOrderLink(
$orderImg,
FieldMetadata $fieldsMeta,
$orderUrl,
$multiOrderUrl
) {
$orderLinkParams = ['class' => 'sortlink'];
$orderLinkContent = htmlspecialchars($fieldsMeta->name);
$innerLinkContent = $orderLinkContent . $orderImg
. '';
return Generator::linkOrButton(
$orderUrl,
$innerLinkContent,
$orderLinkParams
);
}
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 FieldMetadata $fieldsMeta set of field properties
* @param array $thClass array containing classes
*
* @return void
*/
private function getClassForNumericColumnType(FieldMetadata $fieldsMeta, array &$thClass)
{
// This was defined in commit b661cd7c9b31f8bc564d2f9a1b8527e0eb966de8
// For issue https://github.com/phpmyadmin/phpmyadmin/issues/4746
if (
! $fieldsMeta->isType(FieldMetadata::TYPE_REAL)
&& ! $fieldsMeta->isMappedTypeBit
&& ! $fieldsMeta->isType(FieldMetadata::TYPE_INT)
) {
return;
}
$thClass[] = 'text-end';
}
/**
* Prepare columns to draggable effect for sortable columns
*
* @see getTableHeaders()
*
* @param bool $colVisib the column is visible (false)
* array the column is not visible (string array)
* @param string $colVisibElement element of $col_visib array
* @param FieldMetadata $fieldsMeta set of field properties
* @param string $orderLink the order link
* @param string $comments the comment for the column
*
* @return string html content
*
* @access private
*/
private function getDraggableClassForSortableColumns(
$colVisib,
$colVisibElement,
FieldMetadata $fieldsMeta,
$orderLink,
$comments
) {
$draggableHtml = '
';
return $draggableHtml;
}
/**
* Prepare columns to draggable effect for non sortable columns
*
* @see getTableHeaders()
*
* @param bool $colVisib the column is visible (false)
* array the column is not visible (string array)
* @param string $colVisibElement element of $col_visib array
* @param bool $conditionField whether to add CSS class condition
* @param FieldMetadata $fieldsMeta set of field properties
* @param string $comments the comment for the column
*
* @return string html content
*
* @access private
*/
private function getDraggableClassForNonSortableColumns(
$colVisib,
$colVisibElement,
$conditionField,
FieldMetadata $fieldsMeta,
$comments
) {
$draggableHtml = '
';
}
$this->properties['display_params'] = $displayParams;
return $rightColumnHtml;
}
/**
* 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 FieldMetadata $meta the meta-information about this field
* @param string $align cell alignment
*
* @return string the td
*
* @access private
*/
private function buildNullDisplay($class, $conditionField, FieldMetadata $meta, $align = '')
{
$classes = $this->addClass($class, $conditionField, $meta, '');
return $this->template->render('display/results/null_display', [
'align' => $align,
'data_decimals' => $meta->decimals ?? -1,
'data_type' => $meta->getMappedType(),
'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 FieldMetadata $meta the meta-information about this field
* @param string $align cell alignment
*
* @return string the td
*
* @access private
*/
private function buildEmptyDisplay($class, $conditionField, FieldMetadata $meta, $align = '')
{
$classes = $this->addClass($class, $conditionField, $meta, 'text-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 $conditionField whether to add CSS class
* condition
* @param FieldMetadata $meta the meta-information about the
* field
* @param string $nowrap avoid wrapping
* @param bool $isFieldTruncated is field truncated (display ...)
* @param TransformationsPlugin|string $transformationPlugin transformation plugin.
* Can also be the default function:
* Core::mimeDefaultFunction
* @param string $defaultFunction default transformation function
*
* @return string the list of classes
*
* @access private
*/
private function addClass(
$class,
$conditionField,
FieldMetadata $meta,
$nowrap,
$isFieldTruncated = false,
$transformationPlugin = '',
$defaultFunction = ''
) {
$classes = [
$class,
$nowrap,
];
if (isset($meta->internalMediaType)) {
$classes[] = preg_replace('/\//', '_', $meta->internalMediaType);
}
if ($conditionField) {
$classes[] = 'condition';
}
if ($isFieldTruncated) {
$classes[] = 'truncated';
}
$mediaTypeMap = $this->properties['mime_map'];
$orgFullColName = $this->properties['db'] . '.' . $meta->orgtable
. '.' . $meta->orgname;
if (
$transformationPlugin != $defaultFunction
|| ! empty($mediaTypeMap[$orgFullColName]['input_transformation'])
) {
$classes[] = 'transformed';
}
// Define classes to be added to this data field based on the type of data
if ($meta->isEnum()) {
$classes[] = 'enum';
}
if ($meta->isSet()) {
$classes[] = 'set';
}
if ($meta->isMappedTypeBit) {
$classes[] = 'bit';
}
if ($meta->isBinary()) {
$classes[] = 'hex';
}
return implode(' ', $classes);
}
/**
* Prepare the body of the results table
*
* @see getTable()
*
* @param int $dtResult 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 $analyzedSqlResults analyzed sql results
* @param bool $isLimitedDisplay with limited operations or not
*
* @return string html content
*
* @global array $row current row data
* @access private
*/
private function getTableBody(
&$dtResult,
array &$displayParts,
array $map,
array $analyzedSqlResults,
$isLimitedDisplay = false
) {
global $dbi;
// Mostly because of browser transformations, to make the row-data accessible in a plugin.
global $row;
$tableBodyHtml = '';
// query without conditions to shorten URLs when needed, 200 is just
// guess, it should depend on remaining URL length
$urlSqlQuery = $this->getUrlSqlQuery($analyzedSqlResults);
$displayParams = $this->properties['display_params'];
if (! is_array($map)) {
$map = [];
}
$rowNumber = 0;
$displayParams['edit'] = [];
$displayParams['copy'] = [];
$displayParams['delete'] = [];
$displayParams['data'] = [];
$displayParams['row_delete'] = [];
$this->properties['display_params'] = $displayParams;
// 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 ($isLimitedDisplay || ! $this->properties['editable']) {
$gridEditClass = '';
} else {
switch ($GLOBALS['cfg']['GridEditing']) {
case 'double-click':
// trying to reduce generated HTML by using shorter
// classes like click1 and click2
$gridEditClass = 'grid_edit click2';
break;
case 'click':
$gridEditClass = 'grid_edit click1';
break;
default: // 'disabled'
$gridEditClass = '';
break;
}
}
// prepare to get the column order, if available
[$colOrder, $colVisib] = $this->getColumnParams(
$analyzedSqlResults
);
// 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($dtResult)) {
// add repeating headers
if (
($rowNumber != 0) && ($_SESSION['tmpval']['repeat_cells'] != 0)
&& ! $rowNumber % $_SESSION['tmpval']['repeat_cells']
) {
$tableBodyHtml .= $this->getRepeatingHeaders(
$displayParams
);
}
$trClass = [];
if ($GLOBALS['cfg']['BrowsePointerEnable'] != true) {
$trClass[] = 'nopointer';
}
if ($GLOBALS['cfg']['BrowseMarkerEnable'] != true) {
$trClass[] = 'nomarker';
}
// pointer code part
$classes = (empty($trClass) ? ' ' : 'class="' . implode(' ', $trClass) . '"');
$tableBodyHtml .= '
';
// 1. Prepares the row
// In print view these variable needs to be initialized
$deleteUrl = null;
$deleteString = null;
$editString = null;
$jsConf = null;
$copyUrl = null;
$copyString = null;
$editUrl = 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($analyzedSqlResults['statement'])
&& $analyzedSqlResults['statement'] instanceof SelectStatement
) {
$expressions = $analyzedSqlResults['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
*/
[$whereClause, $clauseIsUnique, $conditionArray] = Util::getUniqueCondition(
$dtResult,
$this->properties['fields_cnt'],
$this->properties['fields_meta'],
$row,
false,
$this->properties['table'],
$expressions
);
$whereClauseMap[$rowNumber][$this->properties['table']] = $whereClause;
$this->properties['whereClauseMap'] = $whereClauseMap;
// 1.2.1 Modify link(s) - update row case
if ($displayParts['edit_lnk'] === self::UPDATE_ROW) {
[
$editUrl,
$copyUrl,
$editString,
$copyString,
] = $this->getModifiedLinks(
$whereClause,
$clauseIsUnique,
$urlSqlQuery
);
}
// 1.2.2 Delete/Kill link(s)
[$deleteUrl, $deleteString, $jsConf] = $this->getDeleteAndKillLinks(
$whereClause,
$clauseIsUnique,
$urlSqlQuery,
$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)
) {
$tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_LEFT,
'has_checkbox' => ! empty($deleteUrl) && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => ['url' => $editUrl, 'string' => $editString, 'clause_is_unique' => $clauseIsUnique],
'copy' => ['url' => $copyUrl, 'string' => $copyString],
'delete' => ['url' => $deleteUrl, 'string' => $deleteString],
'row_number' => $rowNumber,
'where_clause' => $whereClause,
'condition' => json_encode($conditionArray),
'is_ajax' => Response::getInstance()->isAjax(),
'js_conf' => $jsConf ?? '',
]);
} elseif ($GLOBALS['cfg']['RowActionLinks'] === self::POSITION_NONE) {
$tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_NONE,
'has_checkbox' => ! empty($deleteUrl) && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => ['url' => $editUrl, 'string' => $editString, 'clause_is_unique' => $clauseIsUnique],
'copy' => ['url' => $copyUrl, 'string' => $copyString],
'delete' => ['url' => $deleteUrl, 'string' => $deleteString],
'row_number' => $rowNumber,
'where_clause' => $whereClause,
'condition' => json_encode($conditionArray),
'is_ajax' => Response::getInstance()->isAjax(),
'js_conf' => $jsConf ?? '',
]);
}
}
// 2. Displays the rows' values
if ($this->properties['mime_map'] === null) {
$this->setMimeMap();
}
$tableBodyHtml .= $this->getRowValues(
$dtResult,
$row,
$rowNumber,
$colOrder,
$map,
$gridEditClass,
$colVisib,
$urlSqlQuery,
$analyzedSqlResults
);
// 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)
) {
$tableBodyHtml .= $this->template->render('display/results/checkbox_and_links', [
'position' => self::POSITION_RIGHT,
'has_checkbox' => ! empty($deleteUrl) && $displayParts['del_lnk'] !== self::KILL_PROCESS,
'edit' => [
'url' => $editUrl,
'string' => $editString,
'clause_is_unique' => $clauseIsUnique ?? true,
],
'copy' => ['url' => $copyUrl, 'string' => $copyString],
'delete' => ['url' => $deleteUrl, 'string' => $deleteString],
'row_number' => $rowNumber,
'where_clause' => $whereClause ?? '',
'condition' => json_encode($conditionArray ?? []),
'is_ajax' => Response::getInstance()->isAjax(),
'js_conf' => $jsConf ?? '',
]);
}
}
$tableBodyHtml .= '
';
$tableBodyHtml .= "\n";
$rowNumber++;
}
return $tableBodyHtml;
}
/**
* Sets the MIME details of the columns in the results set
*
* @return void
*/
private function setMimeMap()
{
/** @var FieldMetadata[] $fieldsMeta */
$fieldsMeta = $this->properties['fields_meta'];
$mediaTypeMap = [];
$added = [];
for ($currentColumn = 0; $currentColumn < $this->properties['fields_cnt']; ++$currentColumn) {
$meta = $fieldsMeta[$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;
}
$mediaTypeMap = array_merge(
$mediaTypeMap,
$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) {
$mediaTypeMap['..Info'] = [
'mimetype' => 'Text_Plain',
'transformation' => 'output/Text_Plain_Sql.php',
];
}
$isShowCreateTable = preg_match(
'@CREATE[[:space:]]+TABLE@i',
$this->properties['sql_query']
);
if ($isShowCreateTable) {
$mediaTypeMap['..Create Table'] = [
'mimetype' => 'Text_Plain',
'transformation' => 'output/Text_Plain_Sql.php',
];
}
}
}
$this->properties['mime_map'] = $mediaTypeMap;
}
/**
* Get the values for one data row
*
* @see getTableBody()
*
* @param int $dtResult the link id associated to the query
* which results have to be displayed
* @param array $row current row data
* @param int $rowNumber the index of current row
* @param array|false $colOrder the column order false when
* a property not found false
* when a property not found
* @param array $map the list of relations
* @param string $gridEditClass the class for all editable
* columns
* @param bool|array|string $colVisib column is visible(false);
* column isn't visible(string
* array)
* @param string $urlSqlQuery the analyzed sql query
* @param array $analyzedSqlResults analyzed sql results
*
* @return string html content
*
* @access private
*/
private function getRowValues(
&$dtResult,
array $row,
$rowNumber,
$colOrder,
array $map,
$gridEditClass,
$colVisib,
$urlSqlQuery,
array $analyzedSqlResults
) {
$rowValuesHtml = '';
// Following variable are needed for use in isset/empty or
// use with array indexes/safe use in foreach
$sqlQuery = $this->properties['sql_query'];
/** @var FieldMetadata[] $fieldsMeta */
$fieldsMeta = $this->properties['fields_meta'];
$highlightColumns = $this->properties['highlight_columns'];
$mediaTypeMap = $this->properties['mime_map'];
$rowInfo = $this->getRowInfoForSpecialLinks($row, $colOrder);
$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($colOrder) ? $colOrder[$currentColumn] : $currentColumn;
$meta = $fieldsMeta[$i];
$orgFullColName = $this->properties['db'] . '.' . $meta->orgtable . '.' . $meta->orgname;
$notNullClass = $meta->isNotNull() ? 'not_null' : '';
$relationClass = isset($map[$meta->name]) ? 'relation' : '';
$hideClass = is_array($colVisib) && isset($colVisib[$currentColumn]) && ! $colVisib[$currentColumn]
? 'hide'
: '';
$gridEdit = $meta->orgtable != '' ? $gridEditClass : '';
// handle datetime-related class, for grid editing
$fieldTypeClass = $this->getClassForDateTimeRelatedFields($meta);
$isFieldTruncated = false;
// combine all the classes applicable to this column's value
$class = $this->getClassesForColumn(
$gridEdit,
$notNullClass,
$relationClass,
$hideClass,
$fieldTypeClass
);
// See if this column should get highlight because it's used in the
// where-query.
$conditionField = isset($highlightColumns)
&& (isset($highlightColumns[$meta->name])
|| isset($highlightColumns[Util::backquote($meta->name)]));
// Wrap MIME-transformations. [MIME]
$defaultFunction = [
Core::class,
'mimeDefaultFunction',
]; // default_function
$transformationPlugin = $defaultFunction;
$transformOptions = [];
if (
$GLOBALS['cfgRelation']['mimework']
&& $GLOBALS['cfg']['BrowseMIME']
) {
if (
isset($mediaTypeMap[$orgFullColName]['mimetype'])
&& ! empty($mediaTypeMap[$orgFullColName]['transformation'])
) {
$file = $mediaTypeMap[$orgFullColName]['transformation'];
$includeFile = 'libraries/classes/Plugins/Transformations/' . $file;
if (@file_exists($includeFile)) {
$className = $this->transformations->getClassName($includeFile);
if (class_exists($className)) {
// todo add $plugin_manager
$pluginManager = null;
$transformationPlugin = new $className(
$pluginManager
);
$transformOptions = $this->transformations->getOptions(
$mediaTypeMap[$orgFullColName]['transformation_options'] ?? ''
);
$meta->internalMediaType = str_replace(
'_',
'/',
$mediaTypeMap[$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];
$transformationPlugin = new $this->transformationInfo[$dbLower][$tblLower][$nameLower][1](null);
$transformOptions = $this->transformations->getOptions(
$mediaTypeMap[$orgFullColName]['transformation_options'] ?? ''
);
$orgTable = mb_strtolower($meta->orgtable);
$orgName = mb_strtolower($meta->orgname);
$meta->internalMediaType = 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])) {
$linkingUrl = $this->getSpecialLinkUrl(
$specialSchemaLinks[$dbLower][$tblLower][$nameLower],
$row[$i],
$rowInfo
);
$transformationPlugin = new Text_Plain_Link();
$transformOptions = [
0 => $linkingUrl,
2 => true,
];
$meta->internalMediaType = str_replace(
'_',
'/',
'Text/Plain'
);
}
$expressions = [];
if (
isset($analyzedSqlResults['statement'])
&& $analyzedSqlResults['statement'] instanceof SelectStatement
) {
$expressions = $analyzedSqlResults['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[$rowNumber][$meta->orgtable])) {
$uniqueConditions = Util::getUniqueCondition(
$dtResult,
$this->properties['fields_cnt'],
$this->properties['fields_meta'],
$row,
false,
$meta->orgtable,
$expressions
);
$whereClauseMap[$rowNumber][$meta->orgtable] = $uniqueConditions[0];
}
$urlParams = [
'db' => $this->properties['db'],
'table' => $meta->orgtable,
'where_clause_sign' => Core::signSqlQuery($whereClauseMap[$rowNumber][$meta->orgtable]),
'where_clause' => $whereClauseMap[$rowNumber][$meta->orgtable],
'transform_key' => $meta->orgname,
];
if (! empty($sqlQuery)) {
$urlParams['sql_query'] = $urlSqlQuery;
}
$transformOptions['wrapper_link'] = Url::getCommon($urlParams);
$transformOptions['wrapper_params'] = $urlParams;
$displayParams = $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->isNumeric && $meta->isNotType(FieldMetadata::TYPE_STRING))
|| $meta->isType(FieldMetadata::TYPE_REAL)
) {
// n u m e r i c
$displayParams['data'][$rowNumber][$i] = $this->getDataCellForNumericColumns(
$row[$i] === null ? null : (string) $row[$i],
$class,
$conditionField,
$meta,
$map,
$isFieldTruncated,
$analyzedSqlResults,
$transformationPlugin,
$defaultFunction,
$transformOptions
);
} elseif ($meta->isMappedTypeGeometry) {
// 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);
$displayParams['data'][$rowNumber][$i] = $this->getDataCellForGeometryColumns(
$row[$i],
$class,
$meta,
$map,
$urlParams,
$conditionField,
$transformationPlugin,
$defaultFunction,
$transformOptions,
$analyzedSqlResults
);
} else {
// n o t n u m e r i c
$displayParams['data'][$rowNumber][$i] = $this->getDataCellForNonNumericColumns(
$row[$i],
$class,
$meta,
$map,
$urlParams,
$conditionField,
$transformationPlugin,
$defaultFunction,
$transformOptions,
$isFieldTruncated,
$analyzedSqlResults,
$dtResult,
$i
);
}
// output stored cell
$rowValuesHtml .= $displayParams['data'][$rowNumber][$i];
if (isset($displayParams['rowdata'][$i][$rowNumber])) {
$displayParams['rowdata'][$i][$rowNumber] .= $displayParams['data'][$rowNumber][$i];
} else {
$displayParams['rowdata'][$i][$rowNumber] = $displayParams['data'][$rowNumber][$i];
}
$this->properties['display_params'] = $displayParams;
}
return $rowValuesHtml;
}
/**
* Get link for display special schema links
*
* @param array>|string> $linkRelations
* @param string $columnValue column value
* @param array $rowInfo information about row
* @phpstan-param array{
* 'link_param': string,
* 'link_dependancy_params'?: array<
* int,
* array{'param_info': string, 'column_name': string}
* >,
* 'default_page': string
* } $linkRelations
*
* @return string generated link
*/
private function getSpecialLinkUrl(
array $linkRelations,
$columnValue,
array $rowInfo
) {
$linkingUrlParams = [];
$linkingUrlParams[$linkRelations['link_param']] = $columnValue;
$divider = strpos($linkRelations['default_page'], '?') ? '&' : '?';
if (empty($linkRelations['link_dependancy_params'])) {
return $linkRelations['default_page']
. Url::getCommonRaw($linkingUrlParams, $divider);
}
foreach ($linkRelations['link_dependancy_params'] as $new_param) {
$columnName = mb_strtolower($new_param['column_name']);
// If there is a value for this column name in the rowInfo provided
if (isset($rowInfo[$columnName])) {
$urlParameterName = $new_param['param_info'];
$linkingUrlParams[$urlParameterName] = $rowInfo[$columnName];
}
// Special case 1 - when executing routines, according
// to the type of the routine, url param changes
if (empty($rowInfo['routine_type'])) {
continue;
}
}
return $linkRelations['default_page']
. Url::getCommonRaw($linkingUrlParams, $divider);
}
/**
* Prepare row information for display special links
*
* @param array $row current row data
* @param array|bool $colOrder the column order
*
* @return array associative array with column nama -> value
*/
private function getRowInfoForSpecialLinks(array $row, $colOrder)
{
$rowInfo = [];
/** @var FieldMetadata[] $fieldsMeta */
$fieldsMeta = $this->properties['fields_meta'];
for ($n = 0; $n < $this->properties['fields_cnt']; ++$n) {
$m = is_array($colOrder) ? $colOrder[$n] : $n;
$rowInfo[mb_strtolower($fieldsMeta[$m]->orgname)] = $row[$m];
}
return $rowInfo;
}
/**
* Get url sql query without conditions to shorten URLs
*
* @see getTableBody()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return string analyzed sql query
*
* @access private
*/
private function getUrlSqlQuery(array $analyzedSqlResults)
{
if (
($analyzedSqlResults['querytype'] !== 'SELECT')
|| (mb_strlen($this->properties['sql_query']) < 200)
) {
return $this->properties['sql_query'];
}
$query = 'SELECT ' . Query::getClause(
$analyzedSqlResults['statement'],
$analyzedSqlResults['parser']->list,
'SELECT'
);
$fromClause = Query::getClause(
$analyzedSqlResults['statement'],
$analyzedSqlResults['parser']->list,
'FROM'
);
if (! empty($fromClause)) {
$query .= ' FROM ' . $fromClause;
}
return $query;
}
/**
* Get column order and column visibility
*
* @see getTableBody()
*
* @param array $analyzedSqlResults analyzed sql results
*
* @return array 2 element array - $col_order, $col_visib
*
* @access private
*/
private function getColumnParams(array $analyzedSqlResults)
{
if ($this->isSelect($analyzedSqlResults)) {
$pmatable = new Table($this->properties['table'], $this->properties['db']);
$colOrder = $pmatable->getUiProp(Table::PROP_COLUMN_ORDER);
/* Validate the value */
if ($colOrder !== false) {
$fieldsCount = $this->properties['fields_cnt'];
foreach ($colOrder as $value) {
if ($value < $fieldsCount) {
continue;
}
$pmatable->removeUiProp(Table::PROP_COLUMN_ORDER);
$fieldsCount = false;
}
}
$colVisib = $pmatable->getUiProp(Table::PROP_COLUMN_VISIB);
} else {
$colOrder = false;
$colVisib = false;
}
return [
$colOrder,
$colVisib,
];
}
/**
* Get HTML for repeating headers
*
* @see getTableBody()
*
* @param array $displayParams holds various display info
*
* @return string html content
*
* @access private
*/
private function getRepeatingHeaders(
array $displayParams
) {
$headerHtml = '