PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/classes/Controllers/Table/SearchController.php

http://github.com/phpmyadmin/phpmyadmin
PHP | 417 lines | 265 code | 44 blank | 108 comment | 19 complexity | a6cdd86a76ea7f6f14672b6adf665bd3 MD5 | raw file
Possible License(s): GPL-2.0, MIT, LGPL-3.0
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin\Controllers\Table;
  4. use PhpMyAdmin\Core;
  5. use PhpMyAdmin\DatabaseInterface;
  6. use PhpMyAdmin\DbTableExists;
  7. use PhpMyAdmin\Operations;
  8. use PhpMyAdmin\Relation;
  9. use PhpMyAdmin\RelationCleanup;
  10. use PhpMyAdmin\ResponseRenderer;
  11. use PhpMyAdmin\Sql;
  12. use PhpMyAdmin\Table\Search;
  13. use PhpMyAdmin\Template;
  14. use PhpMyAdmin\Transformations;
  15. use PhpMyAdmin\Url;
  16. use PhpMyAdmin\Util;
  17. use PhpMyAdmin\Utils\Gis;
  18. use function in_array;
  19. use function intval;
  20. use function mb_strtolower;
  21. use function md5;
  22. use function preg_match;
  23. use function preg_replace;
  24. use function str_ireplace;
  25. use function str_replace;
  26. use function strncasecmp;
  27. use function strtoupper;
  28. /**
  29. * Handles table search tab.
  30. *
  31. * Display table search form, create SQL query from form data
  32. * and call Sql::executeQueryAndSendQueryResponse() to execute it.
  33. */
  34. class SearchController extends AbstractController
  35. {
  36. /**
  37. * Names of columns
  38. *
  39. * @access private
  40. * @var array
  41. */
  42. private $columnNames;
  43. /**
  44. * Types of columns
  45. *
  46. * @access private
  47. * @var array
  48. */
  49. private $columnTypes;
  50. /**
  51. * Types of columns without any replacement
  52. *
  53. * @access private
  54. * @var array
  55. */
  56. private $originalColumnTypes;
  57. /**
  58. * Collations of columns
  59. *
  60. * @access private
  61. * @var array
  62. */
  63. private $columnCollations;
  64. /**
  65. * Null Flags of columns
  66. *
  67. * @access private
  68. * @var array
  69. */
  70. private $columnNullFlags;
  71. /**
  72. * Whether a geometry column is present
  73. *
  74. * @access private
  75. * @var bool
  76. */
  77. private $geomColumnFlag;
  78. /**
  79. * Foreign Keys
  80. *
  81. * @access private
  82. * @var array
  83. */
  84. private $foreigners;
  85. /** @var Search */
  86. private $search;
  87. /** @var Relation */
  88. private $relation;
  89. /** @var DatabaseInterface */
  90. private $dbi;
  91. public function __construct(
  92. ResponseRenderer $response,
  93. Template $template,
  94. string $db,
  95. string $table,
  96. Search $search,
  97. Relation $relation,
  98. DatabaseInterface $dbi
  99. ) {
  100. parent::__construct($response, $template, $db, $table);
  101. $this->search = $search;
  102. $this->relation = $relation;
  103. $this->dbi = $dbi;
  104. $this->columnNames = [];
  105. $this->columnTypes = [];
  106. $this->originalColumnTypes = [];
  107. $this->columnCollations = [];
  108. $this->columnNullFlags = [];
  109. $this->geomColumnFlag = false;
  110. $this->foreigners = [];
  111. $this->loadTableInfo();
  112. }
  113. /**
  114. * Gets all the columns of a table along with their types, collations
  115. * and whether null or not.
  116. */
  117. private function loadTableInfo(): void
  118. {
  119. // Gets the list and number of columns
  120. $columns = $this->dbi->getColumns($this->db, $this->table, null, true);
  121. // Get details about the geometry functions
  122. $geom_types = Gis::getDataTypes();
  123. foreach ($columns as $row) {
  124. // set column name
  125. $this->columnNames[] = $row['Field'];
  126. $type = (string) $row['Type'];
  127. // before any replacement
  128. $this->originalColumnTypes[] = mb_strtolower($type);
  129. // check whether table contains geometric columns
  130. if (in_array($type, $geom_types)) {
  131. $this->geomColumnFlag = true;
  132. }
  133. // reformat mysql query output
  134. if (strncasecmp($type, 'set', 3) == 0 || strncasecmp($type, 'enum', 4) == 0) {
  135. $type = str_replace(',', ', ', $type);
  136. } else {
  137. // strip the "BINARY" attribute, except if we find "BINARY(" because
  138. // this would be a BINARY or VARBINARY column type
  139. if (! preg_match('@BINARY[\(]@i', $type)) {
  140. $type = str_ireplace('BINARY', '', $type);
  141. }
  142. $type = str_ireplace('ZEROFILL', '', $type);
  143. $type = str_ireplace('UNSIGNED', '', $type);
  144. $type = mb_strtolower($type);
  145. }
  146. if (empty($type)) {
  147. $type = '&nbsp;';
  148. }
  149. $this->columnTypes[] = $type;
  150. $this->columnNullFlags[] = $row['Null'];
  151. $this->columnCollations[] = ! empty($row['Collation']) && $row['Collation'] !== 'NULL'
  152. ? $row['Collation']
  153. : '';
  154. }
  155. // Retrieve foreign keys
  156. $this->foreigners = $this->relation->getForeigners($this->db, $this->table);
  157. }
  158. /**
  159. * Index action
  160. */
  161. public function __invoke(): void
  162. {
  163. global $db, $table, $urlParams, $cfg, $errorUrl;
  164. Util::checkParameters(['db', 'table']);
  165. $urlParams = ['db' => $db, 'table' => $table];
  166. $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
  167. $errorUrl .= Url::getCommon($urlParams, '&');
  168. DbTableExists::check();
  169. $this->addScriptFiles([
  170. 'makegrid.js',
  171. 'vendor/stickyfill.min.js',
  172. 'sql.js',
  173. 'table/select.js',
  174. 'table/change.js',
  175. 'vendor/jquery/jquery.uitablefilter.js',
  176. 'gis_data_editor.js',
  177. ]);
  178. if (isset($_POST['range_search'])) {
  179. $this->rangeSearchAction();
  180. return;
  181. }
  182. /**
  183. * No selection criteria received -> display the selection form
  184. */
  185. if (! isset($_POST['columnsToDisplay']) && ! isset($_POST['displayAllColumns'])) {
  186. $this->displaySelectionFormAction();
  187. } else {
  188. $this->doSelectionAction();
  189. }
  190. }
  191. /**
  192. * Get data row action
  193. */
  194. public function getDataRowAction(): void
  195. {
  196. if (! Core::checkSqlQuerySignature($_POST['where_clause'], $_POST['where_clause_sign'])) {
  197. return;
  198. }
  199. $extra_data = [];
  200. $row_info_query = 'SELECT * FROM ' . Util::backquote($_POST['db']) . '.'
  201. . Util::backquote($_POST['table']) . ' WHERE ' . $_POST['where_clause'];
  202. $result = $this->dbi->query(
  203. $row_info_query . ';',
  204. DatabaseInterface::CONNECT_USER,
  205. DatabaseInterface::QUERY_STORE
  206. );
  207. $fields_meta = $this->dbi->getFieldsMeta($result);
  208. while ($row = $this->dbi->fetchAssoc($result)) {
  209. // for bit fields we need to convert them to printable form
  210. $i = 0;
  211. foreach ($row as $col => $val) {
  212. if (isset($fields_meta[$i]) && $fields_meta[$i]->isMappedTypeBit) {
  213. $row[$col] = Util::printableBitValue((int) $val, (int) $fields_meta[$i]->length);
  214. }
  215. $i++;
  216. }
  217. $extra_data['row_info'] = $row;
  218. }
  219. $this->response->addJSON($extra_data);
  220. }
  221. /**
  222. * Do selection action
  223. */
  224. public function doSelectionAction(): void
  225. {
  226. /**
  227. * Selection criteria have been submitted -> do the work
  228. */
  229. $sql_query = $this->search->buildSqlQuery();
  230. /**
  231. * Add this to ensure following procedures included running correctly.
  232. */
  233. $sql = new Sql(
  234. $this->dbi,
  235. $this->relation,
  236. new RelationCleanup($this->dbi, $this->relation),
  237. new Operations($this->dbi, $this->relation),
  238. new Transformations(),
  239. $this->template
  240. );
  241. $this->response->addHTML($sql->executeQueryAndSendQueryResponse(
  242. null, // analyzed_sql_results
  243. false, // is_gotofile
  244. $this->db, // db
  245. $this->table, // table
  246. null, // find_real_end
  247. null, // sql_query_for_bookmark
  248. null, // extra_data
  249. null, // message_to_show
  250. null, // sql_data
  251. $GLOBALS['goto'], // goto
  252. null, // disp_query
  253. null, // disp_message
  254. $sql_query, // sql_query
  255. null // complete_query
  256. ));
  257. }
  258. /**
  259. * Display selection form action
  260. */
  261. public function displaySelectionFormAction(): void
  262. {
  263. global $goto, $cfg;
  264. if (! isset($goto)) {
  265. $goto = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
  266. }
  267. $this->render('table/search/index', [
  268. 'db' => $this->db,
  269. 'table' => $this->table,
  270. 'goto' => $goto,
  271. 'self' => $this,
  272. 'geom_column_flag' => $this->geomColumnFlag,
  273. 'column_names' => $this->columnNames,
  274. 'column_types' => $this->columnTypes,
  275. 'column_collations' => $this->columnCollations,
  276. 'default_sliders_state' => $cfg['InitialSlidersState'],
  277. 'max_rows' => intval($cfg['MaxRows']),
  278. ]);
  279. }
  280. /**
  281. * Range search action
  282. */
  283. public function rangeSearchAction(): void
  284. {
  285. $min_max = $this->getColumnMinMax($_POST['column']);
  286. $this->response->addJSON('column_data', $min_max);
  287. }
  288. /**
  289. * Finds minimum and maximum value of a given column.
  290. *
  291. * @param string $column Column name
  292. *
  293. * @return array|null
  294. */
  295. public function getColumnMinMax($column): ?array
  296. {
  297. $sql_query = 'SELECT MIN(' . Util::backquote($column) . ') AS `min`, '
  298. . 'MAX(' . Util::backquote($column) . ') AS `max` '
  299. . 'FROM ' . Util::backquote($this->db) . '.'
  300. . Util::backquote($this->table);
  301. return $this->dbi->fetchSingleRow($sql_query);
  302. }
  303. /**
  304. * Provides a column's type, collation, operators list, and criteria value
  305. * to display in table search form
  306. *
  307. * @param int $search_index Row number in table search form
  308. * @param int $column_index Column index in ColumnNames array
  309. *
  310. * @return array Array containing column's properties
  311. */
  312. public function getColumnProperties($search_index, $column_index)
  313. {
  314. $selected_operator = ($_POST['criteriaColumnOperators'][$search_index] ?? '');
  315. $entered_value = ($_POST['criteriaValues'] ?? '');
  316. //Gets column's type and collation
  317. $type = $this->columnTypes[$column_index];
  318. $collation = $this->columnCollations[$column_index];
  319. $cleanType = preg_replace('@\(.*@s', '', $type);
  320. //Gets column's comparison operators depending on column type
  321. $typeOperators = $this->dbi->types->getTypeOperatorsHtml(
  322. $cleanType,
  323. $this->columnNullFlags[$column_index],
  324. $selected_operator
  325. );
  326. $func = $this->template->render('table/search/column_comparison_operators', [
  327. 'search_index' => $search_index,
  328. 'type_operators' => $typeOperators,
  329. ]);
  330. //Gets link to browse foreign data(if any) and criteria inputbox
  331. $foreignData = $this->relation->getForeignData(
  332. $this->foreigners,
  333. $this->columnNames[$column_index],
  334. false,
  335. '',
  336. ''
  337. );
  338. $htmlAttributes = '';
  339. if (in_array($cleanType, $this->dbi->types->getIntegerTypes())) {
  340. $extractedColumnspec = Util::extractColumnSpec($this->originalColumnTypes[$column_index]);
  341. $is_unsigned = $extractedColumnspec['unsigned'];
  342. $minMaxValues = $this->dbi->types->getIntegerRange($cleanType, ! $is_unsigned);
  343. $htmlAttributes = 'data-min="' . $minMaxValues[0] . '" '
  344. . 'data-max="' . $minMaxValues[1] . '"';
  345. }
  346. $htmlAttributes .= ' onfocus="return '
  347. . 'verifyAfterSearchFieldChange(' . $search_index . ', \'#tbl_search_form\')"';
  348. $value = $this->template->render('table/search/input_box', [
  349. 'str' => '',
  350. 'column_type' => (string) $type,
  351. 'column_data_type' => strtoupper($cleanType),
  352. 'html_attributes' => $htmlAttributes,
  353. 'column_id' => 'fieldID_',
  354. 'in_zoom_search_edit' => false,
  355. 'foreigners' => $this->foreigners,
  356. 'column_name' => $this->columnNames[$column_index],
  357. 'column_name_hash' => md5($this->columnNames[$column_index]),
  358. 'foreign_data' => $foreignData,
  359. 'table' => $this->table,
  360. 'column_index' => $search_index,
  361. 'foreign_max_limit' => $GLOBALS['cfg']['ForeignKeyMaxLimit'],
  362. 'criteria_values' => $entered_value,
  363. 'db' => $this->db,
  364. 'in_fbs' => true,
  365. ]);
  366. return [
  367. 'type' => $type,
  368. 'collation' => $collation,
  369. 'func' => $func,
  370. 'value' => $value,
  371. ];
  372. }
  373. }