SearchController.php 13 KB

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