Tracking.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Functions used for database and table tracking
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin;
  9. use PhpMyAdmin\Core;
  10. use PhpMyAdmin\Message;
  11. use PhpMyAdmin\Relation;
  12. use PhpMyAdmin\Response;
  13. use PhpMyAdmin\Sanitize;
  14. use PhpMyAdmin\SqlQueryForm;
  15. use PhpMyAdmin\Template;
  16. use PhpMyAdmin\Tracker;
  17. use PhpMyAdmin\Url;
  18. use PhpMyAdmin\Util;
  19. /**
  20. * PhpMyAdmin\Tracking class
  21. *
  22. * @package PhpMyAdmin
  23. */
  24. class Tracking
  25. {
  26. /**
  27. * Filters tracking entries
  28. *
  29. * @param array $data the entries to filter
  30. * @param string $filter_ts_from "from" date
  31. * @param string $filter_ts_to "to" date
  32. * @param array $filter_users users
  33. *
  34. * @return array filtered entries
  35. */
  36. public static function filterTracking(
  37. array $data, $filter_ts_from, $filter_ts_to, array $filter_users
  38. ) {
  39. $tmp_entries = array();
  40. $id = 0;
  41. foreach ($data as $entry) {
  42. $timestamp = strtotime($entry['date']);
  43. $filtered_user = in_array($entry['username'], $filter_users);
  44. if ($timestamp >= $filter_ts_from
  45. && $timestamp <= $filter_ts_to
  46. && (in_array('*', $filter_users) || $filtered_user)
  47. ) {
  48. $tmp_entries[] = array(
  49. 'id' => $id,
  50. 'timestamp' => $timestamp,
  51. 'username' => $entry['username'],
  52. 'statement' => $entry['statement']
  53. );
  54. }
  55. $id++;
  56. }
  57. return($tmp_entries);
  58. }
  59. /**
  60. * Function to get html for data definition and data manipulation statements
  61. *
  62. * @param string $urlQuery url query
  63. * @param int $lastVersion last version
  64. * @param string $db database
  65. * @param array $selected selected tables
  66. * @param string $type type of the table; table, view or both
  67. *
  68. * @return string HTML
  69. */
  70. public static function getHtmlForDataDefinitionAndManipulationStatements(
  71. $urlQuery,
  72. $lastVersion,
  73. $db,
  74. array $selected,
  75. $type = 'both'
  76. ) {
  77. return Template::get('table/tracking/create_version')->render([
  78. 'url_query' => $urlQuery,
  79. 'last_version' => $lastVersion,
  80. 'db' => $db,
  81. 'selected' => $selected,
  82. 'type' => $type,
  83. 'default_statements' => $GLOBALS['cfg']['Server']['tracking_default_statements'],
  84. ]);
  85. }
  86. /**
  87. * Function to get html for activate/deactivate tracking
  88. *
  89. * @param string $action activate|deactivate
  90. * @param string $urlQuery url query
  91. * @param int $lastVersion last version
  92. *
  93. * @return string HTML
  94. */
  95. public static function getHtmlForActivateDeactivateTracking(
  96. $action,
  97. $urlQuery,
  98. $lastVersion
  99. ) {
  100. return Template::get('table/tracking/activate_deactivate')->render([
  101. 'action' => $action,
  102. 'url_query' => $urlQuery,
  103. 'last_version' => $lastVersion,
  104. 'db' => $GLOBALS['db'],
  105. 'table' => $GLOBALS['table'],
  106. ]);
  107. }
  108. /**
  109. * Function to get the list versions of the table
  110. *
  111. * @return array
  112. */
  113. public static function getListOfVersionsOfTable()
  114. {
  115. $relation = new Relation();
  116. $cfgRelation = $relation->getRelationsParam();
  117. $sql_query = " SELECT * FROM " .
  118. Util::backquote($cfgRelation['db']) . "." .
  119. Util::backquote($cfgRelation['tracking']) .
  120. " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($GLOBALS['db']) .
  121. "' " .
  122. " AND table_name = '" .
  123. $GLOBALS['dbi']->escapeString($GLOBALS['table']) . "' " .
  124. " ORDER BY version DESC ";
  125. return $relation->queryAsControlUser($sql_query);
  126. }
  127. /**
  128. * Function to get html for displaying last version number
  129. *
  130. * @param array $sql_result sql result
  131. * @param int $last_version last version
  132. * @param array $url_params url parameters
  133. * @param string $url_query url query
  134. * @param string $pmaThemeImage path to theme's image folder
  135. * @param string $text_dir text direction
  136. *
  137. * @return string
  138. */
  139. public static function getHtmlForTableVersionDetails(
  140. $sql_result, $last_version, array $url_params,
  141. $url_query, $pmaThemeImage, $text_dir
  142. ) {
  143. $tracking_active = false;
  144. $html = '<form method="post" action="tbl_tracking.php" name="versionsForm"'
  145. . ' id="versionsForm" class="ajax">';
  146. $html .= Url::getHiddenInputs($GLOBALS['db'], $GLOBALS['table']);
  147. $html .= '<table id="versions" class="data">';
  148. $html .= '<thead>';
  149. $html .= '<tr>';
  150. $html .= '<th></th>';
  151. $html .= '<th>' . __('Version') . '</th>';
  152. $html .= '<th>' . __('Created') . '</th>';
  153. $html .= '<th>' . __('Updated') . '</th>';
  154. $html .= '<th>' . __('Status') . '</th>';
  155. $html .= '<th>' . __('Action') . '</th>';
  156. $html .= '<th>' . __('Show') . '</th>';
  157. $html .= '</tr>';
  158. $html .= '</thead>';
  159. $html .= '<tbody>';
  160. $GLOBALS['dbi']->dataSeek($sql_result, 0);
  161. $delete = Util::getIcon('b_drop', __('Delete version'));
  162. $report = Util::getIcon('b_report', __('Tracking report'));
  163. $structure = Util::getIcon('b_props', __('Structure snapshot'));
  164. while ($version = $GLOBALS['dbi']->fetchArray($sql_result)) {
  165. if ($version['version'] == $last_version) {
  166. if ($version['tracking_active'] == 1) {
  167. $tracking_active = true;
  168. } else {
  169. $tracking_active = false;
  170. }
  171. }
  172. $checkbox_id = 'selected_versions_' . htmlspecialchars($version['version']);
  173. $html .= '<tr>';
  174. $html .= '<td class="center">';
  175. $html .= '<input type="checkbox" name="selected_versions[]"'
  176. . ' class="checkall" id="' . $checkbox_id . '"'
  177. . ' value="' . htmlspecialchars($version['version']) . '"/>';
  178. $html .= '</td>';
  179. $html .= '<th class="floatright">';
  180. $html .= '<label for="' . $checkbox_id . '">'
  181. . htmlspecialchars($version['version']) . '</label>';
  182. $html .= '</th>';
  183. $html .= '<td>' . htmlspecialchars($version['date_created']) . '</td>';
  184. $html .= '<td>' . htmlspecialchars($version['date_updated']) . '</td>';
  185. $html .= '<td>' . self::getVersionStatus($version) . '</td>';
  186. $html .= '<td><a class="delete_version_anchor ajax"'
  187. . ' href="tbl_tracking.php" data-post="';
  188. $html .= Url::getCommon($url_params + [
  189. 'version' => $version['version'],
  190. 'submit_delete_version' => true,
  191. ], '', false);
  192. $html .= '">' . $delete . '</a></td>';
  193. $html .= '<td><a href="tbl_tracking.php" data-post="';
  194. $html .= Url::getCommon($url_params + [
  195. 'report' => 'true',
  196. 'version' => $version['version'],
  197. ], '', false);
  198. $html .= '">' . $report . '</a>';
  199. $html .= '&nbsp;&nbsp;';
  200. $html .= '<a href="tbl_tracking.php" data-post="';
  201. $html .= Url::getCommon($url_params + [
  202. 'snapshot' => 'true',
  203. 'version' => $version['version'],
  204. ], '', false);
  205. $html .= '">' . $structure . '</a>';
  206. $html .= '</td>';
  207. $html .= '</tr>';
  208. }
  209. $html .= '</tbody>';
  210. $html .= '</table>';
  211. $html .= Template::get('select_all')
  212. ->render(
  213. array(
  214. 'pma_theme_image' => $pmaThemeImage,
  215. 'text_dir' => $text_dir,
  216. 'form_name' => 'versionsForm',
  217. )
  218. );
  219. $html .= Util::getButtonOrImage(
  220. 'submit_mult', 'mult_submit',
  221. __('Delete version'), 'b_drop', 'delete_version'
  222. );
  223. $html .= '</form>';
  224. if ($tracking_active) {
  225. $html .= self::getHtmlForActivateDeactivateTracking(
  226. 'deactivate', $url_query, $last_version
  227. );
  228. } else {
  229. $html .= self::getHtmlForActivateDeactivateTracking(
  230. 'activate', $url_query, $last_version
  231. );
  232. }
  233. return $html;
  234. }
  235. /**
  236. * Function to get the last version number of a table
  237. *
  238. * @param array $sql_result sql result
  239. *
  240. * @return int
  241. */
  242. public static function getTableLastVersionNumber($sql_result)
  243. {
  244. $maxversion = $GLOBALS['dbi']->fetchArray($sql_result);
  245. return intval(is_array($maxversion) ? $maxversion['version'] : null);
  246. }
  247. /**
  248. * Function to get sql results for selectable tables
  249. *
  250. * @return array
  251. */
  252. public static function getSqlResultForSelectableTables()
  253. {
  254. $relation = new Relation();
  255. $cfgRelation = $relation->getRelationsParam();
  256. $sql_query = " SELECT DISTINCT db_name, table_name FROM " .
  257. Util::backquote($cfgRelation['db']) . "." .
  258. Util::backquote($cfgRelation['tracking']) .
  259. " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($GLOBALS['db']) .
  260. "' " .
  261. " ORDER BY db_name, table_name";
  262. return $relation->queryAsControlUser($sql_query);
  263. }
  264. /**
  265. * Function to get html for selectable table rows
  266. *
  267. * @param array $selectableTablesSqlResult sql results for selectable rows
  268. * @param string $urlQuery url query
  269. *
  270. * @return string
  271. */
  272. public static function getHtmlForSelectableTables(
  273. $selectableTablesSqlResult,
  274. $urlQuery
  275. ) {
  276. $entries = [];
  277. while ($entry = $GLOBALS['dbi']->fetchArray($selectableTablesSqlResult)) {
  278. $entry['is_tracked'] = Tracker::isTracked(
  279. $entry['db_name'],
  280. $entry['table_name']
  281. );
  282. $entries[] = $entry;
  283. }
  284. return Template::get('table/tracking/selectable_tables')->render([
  285. 'url_query' => $urlQuery,
  286. 'db' => $GLOBALS['db'],
  287. 'table' => $GLOBALS['table'],
  288. 'entries' => $entries,
  289. 'selected_table' => isset($_POST['table']) ? $_POST['table'] : null,
  290. ]);
  291. }
  292. /**
  293. * Function to get html for tracking report and tracking report export
  294. *
  295. * @param string $url_query url query
  296. * @param array $data data
  297. * @param array $url_params url params
  298. * @param boolean $selection_schema selection schema
  299. * @param boolean $selection_data selection data
  300. * @param boolean $selection_both selection both
  301. * @param int $filter_ts_to filter time stamp from
  302. * @param int $filter_ts_from filter time stamp tp
  303. * @param array $filter_users filter users
  304. *
  305. * @return string
  306. */
  307. public static function getHtmlForTrackingReport($url_query, array $data, array $url_params,
  308. $selection_schema, $selection_data, $selection_both, $filter_ts_to,
  309. $filter_ts_from, array $filter_users
  310. ) {
  311. $html = '<h3>' . __('Tracking report')
  312. . ' [<a href="tbl_tracking.php' . $url_query . '">' . __('Close')
  313. . '</a>]</h3>';
  314. $html .= '<small>' . __('Tracking statements') . ' '
  315. . htmlspecialchars($data['tracking']) . '</small><br/>';
  316. $html .= '<br/>';
  317. list($str1, $str2, $str3, $str4, $str5) = self::getHtmlForElementsOfTrackingReport(
  318. $selection_schema, $selection_data, $selection_both
  319. );
  320. // Prepare delete link content here
  321. $drop_image_or_text = '';
  322. if (Util::showIcons('ActionLinksMode')) {
  323. $drop_image_or_text .= Util::getImage(
  324. 'b_drop', __('Delete tracking data row from report')
  325. );
  326. }
  327. if (Util::showText('ActionLinksMode')) {
  328. $drop_image_or_text .= __('Delete');
  329. }
  330. /*
  331. * First, list tracked data definition statements
  332. */
  333. if (count($data['ddlog']) == 0 && count($data['dmlog']) == 0) {
  334. $msg = Message::notice(__('No data'));
  335. $msg->display();
  336. }
  337. $html .= self::getHtmlForTrackingReportExportForm1(
  338. $data, $url_params, $selection_schema, $selection_data, $selection_both,
  339. $filter_ts_to, $filter_ts_from, $filter_users, $str1, $str2, $str3,
  340. $str4, $str5, $drop_image_or_text
  341. );
  342. $html .= self::getHtmlForTrackingReportExportForm2(
  343. $url_params, $str1, $str2, $str3, $str4, $str5
  344. );
  345. $html .= "<br/><br/><hr/><br/>\n";
  346. return $html;
  347. }
  348. /**
  349. * Generate HTML element for report form
  350. *
  351. * @param boolean $selection_schema selection schema
  352. * @param boolean $selection_data selection data
  353. * @param boolean $selection_both selection both
  354. *
  355. * @return array
  356. */
  357. public static function getHtmlForElementsOfTrackingReport(
  358. $selection_schema, $selection_data, $selection_both
  359. ) {
  360. $str1 = '<select name="logtype">'
  361. . '<option value="schema"'
  362. . ($selection_schema ? ' selected="selected"' : '') . '>'
  363. . __('Structure only') . '</option>'
  364. . '<option value="data"'
  365. . ($selection_data ? ' selected="selected"' : '') . '>'
  366. . __('Data only') . '</option>'
  367. . '<option value="schema_and_data"'
  368. . ($selection_both ? ' selected="selected"' : '') . '>'
  369. . __('Structure and data') . '</option>'
  370. . '</select>';
  371. $str2 = '<input type="text" name="date_from" value="'
  372. . htmlspecialchars($_POST['date_from']) . '" size="19" />';
  373. $str3 = '<input type="text" name="date_to" value="'
  374. . htmlspecialchars($_POST['date_to']) . '" size="19" />';
  375. $str4 = '<input type="text" name="users" value="'
  376. . htmlspecialchars($_POST['users']) . '" />';
  377. $str5 = '<input type="hidden" name="list_report" value="1" />'
  378. . '<input type="submit" value="' . __('Go') . '" />';
  379. return array($str1, $str2, $str3, $str4, $str5);
  380. }
  381. /**
  382. * Generate HTML for export form
  383. *
  384. * @param array $data data
  385. * @param array $url_params url params
  386. * @param boolean $selection_schema selection schema
  387. * @param boolean $selection_data selection data
  388. * @param boolean $selection_both selection both
  389. * @param int $filter_ts_to filter time stamp from
  390. * @param int $filter_ts_from filter time stamp tp
  391. * @param array $filter_users filter users
  392. * @param string $str1 HTML for logtype select
  393. * @param string $str2 HTML for "from date"
  394. * @param string $str3 HTML for "to date"
  395. * @param string $str4 HTML for user
  396. * @param string $str5 HTML for "list report"
  397. * @param string $drop_image_or_text HTML for image or text
  398. *
  399. * @return string HTML for form
  400. */
  401. public static function getHtmlForTrackingReportExportForm1(
  402. array $data, array $url_params, $selection_schema, $selection_data, $selection_both,
  403. $filter_ts_to, $filter_ts_from, array $filter_users, $str1, $str2, $str3,
  404. $str4, $str5, $drop_image_or_text
  405. ) {
  406. $ddlog_count = 0;
  407. $html = '<form method="post" action="tbl_tracking.php">';
  408. $html .= Url::getHiddenInputs($url_params + [
  409. 'report' => 'true',
  410. 'version' => $_POST['version'],
  411. ]);
  412. $html .= sprintf(
  413. __('Show %1$s with dates from %2$s to %3$s by user %4$s %5$s'),
  414. $str1, $str2, $str3, $str4, $str5
  415. );
  416. if ($selection_schema || $selection_both && count($data['ddlog']) > 0) {
  417. list($temp, $ddlog_count) = self::getHtmlForDataDefinitionStatements(
  418. $data, $filter_users, $filter_ts_from, $filter_ts_to, $url_params,
  419. $drop_image_or_text
  420. );
  421. $html .= $temp;
  422. unset($temp);
  423. } //endif
  424. /*
  425. * Secondly, list tracked data manipulation statements
  426. */
  427. if (($selection_data || $selection_both) && count($data['dmlog']) > 0) {
  428. $html .= self::getHtmlForDataManipulationStatements(
  429. $data, $filter_users, $filter_ts_from, $filter_ts_to, $url_params,
  430. $ddlog_count, $drop_image_or_text
  431. );
  432. }
  433. $html .= '</form>';
  434. return $html;
  435. }
  436. /**
  437. * Generate HTML for export form
  438. *
  439. * @param array $url_params Parameters
  440. * @param string $str1 HTML for logtype select
  441. * @param string $str2 HTML for "from date"
  442. * @param string $str3 HTML for "to date"
  443. * @param string $str4 HTML for user
  444. * @param string $str5 HTML for "list report"
  445. *
  446. * @return string HTML for form
  447. */
  448. public static function getHtmlForTrackingReportExportForm2(
  449. array $url_params, $str1, $str2, $str3, $str4, $str5
  450. ) {
  451. $html = '<form method="post" action="tbl_tracking.php">';
  452. $html .= Url::getHiddenInputs($url_params + [
  453. 'report' => 'true',
  454. 'version' => $_POST['version'],
  455. ]);
  456. $html .= sprintf(
  457. __('Show %1$s with dates from %2$s to %3$s by user %4$s %5$s'),
  458. $str1, $str2, $str3, $str4, $str5
  459. );
  460. $html .= '</form>';
  461. $html .= '<form class="disableAjax" method="post" action="tbl_tracking.php">';
  462. $html .= Url::getHiddenInputs($url_params + [
  463. 'report' => 'true',
  464. 'version' => $_POST['version'],
  465. 'logtype' => $_POST['logtype'],
  466. 'date_from' => $_POST['date_from'],
  467. 'date_to' => $_POST['date_to'],
  468. 'users' => $_POST['users'],
  469. 'report_export' => 'true',
  470. ]);
  471. $str_export1 = '<select name="export_type">'
  472. . '<option value="sqldumpfile">' . __('SQL dump (file download)')
  473. . '</option>'
  474. . '<option value="sqldump">' . __('SQL dump') . '</option>'
  475. . '<option value="execution" onclick="alert(\''
  476. . Sanitize::escapeJsString(
  477. __('This option will replace your table and contained data.')
  478. )
  479. . '\')">' . __('SQL execution') . '</option>' . '</select>';
  480. $str_export2 = '<input type="submit" value="' . __('Go') . '" />';
  481. $html .= "<br/>" . sprintf(__('Export as %s'), $str_export1)
  482. . $str_export2 . "<br/>";
  483. $html .= '</form>';
  484. return $html;
  485. }
  486. /**
  487. * Function to get html for data manipulation statements
  488. *
  489. * @param array $data data
  490. * @param array $filter_users filter users
  491. * @param int $filter_ts_from filter time staml from
  492. * @param int $filter_ts_to filter time stamp to
  493. * @param array $url_params url parameters
  494. * @param int $ddlog_count data definition log count
  495. * @param string $drop_image_or_text drop image or text
  496. *
  497. * @return string
  498. */
  499. public static function getHtmlForDataManipulationStatements(array $data, array $filter_users,
  500. $filter_ts_from, $filter_ts_to, array $url_params, $ddlog_count,
  501. $drop_image_or_text
  502. ) {
  503. // no need for the secondth returned parameter
  504. list($html,) = self::getHtmlForDataStatements(
  505. $data, $filter_users, $filter_ts_from, $filter_ts_to, $url_params,
  506. $drop_image_or_text, 'dmlog', __('Data manipulation statement'),
  507. $ddlog_count, 'dml_versions'
  508. );
  509. return $html;
  510. }
  511. /**
  512. * Function to get html for data definition statements in schema snapshot
  513. *
  514. * @param array $data data
  515. * @param array $filter_users filter users
  516. * @param int $filter_ts_from filter time stamp from
  517. * @param int $filter_ts_to filter time stamp to
  518. * @param array $url_params url parameters
  519. * @param string $drop_image_or_text drop image or text
  520. *
  521. * @return array
  522. */
  523. public static function getHtmlForDataDefinitionStatements(array $data, array $filter_users,
  524. $filter_ts_from, $filter_ts_to, array $url_params, $drop_image_or_text
  525. ) {
  526. list($html, $line_number) = self::getHtmlForDataStatements(
  527. $data, $filter_users, $filter_ts_from, $filter_ts_to, $url_params,
  528. $drop_image_or_text, 'ddlog', __('Data definition statement'),
  529. 1, 'ddl_versions'
  530. );
  531. return array($html, $line_number);
  532. }
  533. /**
  534. * Function to get html for data statements in schema snapshot
  535. *
  536. * @param array $data data
  537. * @param array $filterUsers filter users
  538. * @param int $filterTsFrom filter time stamp from
  539. * @param int $filterTsTo filter time stamp to
  540. * @param array $urlParams url parameters
  541. * @param string $dropImageOrText drop image or text
  542. * @param string $whichLog dmlog|ddlog
  543. * @param string $headerMessage message for this section
  544. * @param int $lineNumber line number
  545. * @param string $tableId id for the table element
  546. *
  547. * @return array [$html, $lineNumber]
  548. */
  549. private static function getHtmlForDataStatements(
  550. array $data,
  551. array $filterUsers,
  552. $filterTsFrom,
  553. $filterTsTo,
  554. array $urlParams,
  555. $dropImageOrText,
  556. $whichLog,
  557. $headerMessage,
  558. $lineNumber,
  559. $tableId
  560. ) {
  561. $offset = $lineNumber;
  562. $entries = [];
  563. foreach ($data[$whichLog] as $entry) {
  564. $timestamp = strtotime($entry['date']);
  565. if ($timestamp >= $filterTsFrom
  566. && $timestamp <= $filterTsTo
  567. && (in_array('*', $filterUsers)
  568. || in_array($entry['username'], $filterUsers))
  569. ) {
  570. $entry['formated_statement'] = Util::formatSql($entry['statement'], true);
  571. $deleteParam = 'delete_' . $whichLog;
  572. $entry['url_params'] = Url::getCommon($urlParams + [
  573. 'report' => 'true',
  574. 'version' => $_POST['version'],
  575. $deleteParam => ($lineNumber - $offset),
  576. ], '');
  577. $entry['line_number'] = $lineNumber;
  578. $entries[] = $entry;
  579. }
  580. $lineNumber++;
  581. }
  582. $html = Template::get('table/tracking/report_table')->render([
  583. 'table_id' => $tableId,
  584. 'header_message' => $headerMessage,
  585. 'entries' => $entries,
  586. 'drop_image_or_text' => $dropImageOrText,
  587. ]);
  588. return [$html, $lineNumber];
  589. }
  590. /**
  591. * Function to get html for schema snapshot
  592. *
  593. * @param string $url_query url query
  594. *
  595. * @return string
  596. */
  597. public static function getHtmlForSchemaSnapshot($url_query)
  598. {
  599. $html = '<h3>' . __('Structure snapshot')
  600. . ' [<a href="tbl_tracking.php' . $url_query . '">' . __('Close')
  601. . '</a>]</h3>';
  602. $data = Tracker::getTrackedData(
  603. $_POST['db'], $_POST['table'], $_POST['version']
  604. );
  605. // Get first DROP TABLE/VIEW and CREATE TABLE/VIEW statements
  606. $drop_create_statements = $data['ddlog'][0]['statement'];
  607. if (mb_strstr($data['ddlog'][0]['statement'], 'DROP TABLE')
  608. || mb_strstr($data['ddlog'][0]['statement'], 'DROP VIEW')
  609. ) {
  610. $drop_create_statements .= $data['ddlog'][1]['statement'];
  611. }
  612. // Print SQL code
  613. $html .= Util::getMessage(
  614. sprintf(
  615. __('Version %s snapshot (SQL code)'),
  616. htmlspecialchars($_POST['version'])
  617. ),
  618. $drop_create_statements
  619. );
  620. // Unserialize snapshot
  621. $temp = Core::safeUnserialize($data['schema_snapshot']);
  622. if ($temp === null) {
  623. $temp = array('COLUMNS' => array(), 'INDEXES' => array());
  624. }
  625. $columns = $temp['COLUMNS'];
  626. $indexes = $temp['INDEXES'];
  627. $html .= self::getHtmlForColumns($columns);
  628. if (count($indexes) > 0) {
  629. $html .= self::getHtmlForIndexes($indexes);
  630. } // endif
  631. $html .= '<br /><hr /><br />';
  632. return $html;
  633. }
  634. /**
  635. * Function to get html for displaying columns in the schema snapshot
  636. *
  637. * @param array $columns columns
  638. *
  639. * @return string
  640. */
  641. public static function getHtmlForColumns(array $columns)
  642. {
  643. return Template::get('table/tracking/structure_snapshot_columns')->render([
  644. 'columns' => $columns,
  645. ]);
  646. }
  647. /**
  648. * Function to get html for the indexes in schema snapshot
  649. *
  650. * @param array $indexes indexes
  651. *
  652. * @return string
  653. */
  654. public static function getHtmlForIndexes(array $indexes)
  655. {
  656. return Template::get('table/tracking/structure_snapshot_indexes')->render([
  657. 'indexes' => $indexes,
  658. ]);;
  659. }
  660. /**
  661. * Function to handle the tracking report
  662. *
  663. * @param array &$data tracked data
  664. *
  665. * @return string HTML for the message
  666. */
  667. public static function deleteTrackingReportRows(array &$data)
  668. {
  669. $html = '';
  670. if (isset($_POST['delete_ddlog'])) {
  671. // Delete ddlog row data
  672. $html .= self::deleteFromTrackingReportLog(
  673. $data,
  674. 'ddlog',
  675. 'DDL',
  676. __('Tracking data definition successfully deleted')
  677. );
  678. }
  679. if (isset($_POST['delete_dmlog'])) {
  680. // Delete dmlog row data
  681. $html .= self::deleteFromTrackingReportLog(
  682. $data,
  683. 'dmlog',
  684. 'DML',
  685. __('Tracking data manipulation successfully deleted')
  686. );
  687. }
  688. return $html;
  689. }
  690. /**
  691. * Function to delete from a tracking report log
  692. *
  693. * @param array &$data tracked data
  694. * @param string $which_log ddlog|dmlog
  695. * @param string $type DDL|DML
  696. * @param string $message success message
  697. *
  698. * @return string HTML for the message
  699. */
  700. public static function deleteFromTrackingReportLog(array &$data, $which_log, $type, $message)
  701. {
  702. $html = '';
  703. $delete_id = $_POST['delete_' . $which_log];
  704. // Only in case of valid id
  705. if ($delete_id == (int)$delete_id) {
  706. unset($data[$which_log][$delete_id]);
  707. $successfullyDeleted = Tracker::changeTrackingData(
  708. $GLOBALS['db'],
  709. $GLOBALS['table'],
  710. $_POST['version'],
  711. $type,
  712. $data[$which_log]
  713. );
  714. if ($successfullyDeleted) {
  715. $msg = Message::success($message);
  716. } else {
  717. $msg = Message::rawError(__('Query error'));
  718. }
  719. $html .= $msg->getDisplay();
  720. }
  721. return $html;
  722. }
  723. /**
  724. * Function to export as sql dump
  725. *
  726. * @param array $entries entries
  727. *
  728. * @return string HTML SQL query form
  729. */
  730. public static function exportAsSqlDump(array $entries)
  731. {
  732. $html = '';
  733. $new_query = "# "
  734. . __(
  735. 'You can execute the dump by creating and using a temporary database. '
  736. . 'Please ensure that you have the privileges to do so.'
  737. )
  738. . "\n"
  739. . "# " . __('Comment out these two lines if you do not need them.') . "\n"
  740. . "\n"
  741. . "CREATE database IF NOT EXISTS pma_temp_db; \n"
  742. . "USE pma_temp_db; \n"
  743. . "\n";
  744. foreach ($entries as $entry) {
  745. $new_query .= $entry['statement'];
  746. }
  747. $msg = Message::success(
  748. __('SQL statements exported. Please copy the dump or execute it.')
  749. );
  750. $html .= $msg->getDisplay();
  751. $db_temp = $GLOBALS['db'];
  752. $table_temp = $GLOBALS['table'];
  753. $GLOBALS['db'] = $GLOBALS['table'] = '';
  754. $html .= SqlQueryForm::getHtml($new_query, 'sql');
  755. $GLOBALS['db'] = $db_temp;
  756. $GLOBALS['table'] = $table_temp;
  757. return $html;
  758. }
  759. /**
  760. * Function to export as sql execution
  761. *
  762. * @param array $entries entries
  763. *
  764. * @return array
  765. */
  766. public static function exportAsSqlExecution(array $entries)
  767. {
  768. $sql_result = array();
  769. foreach ($entries as $entry) {
  770. $sql_result = $GLOBALS['dbi']->query("/*NOTRACK*/\n" . $entry['statement']);
  771. }
  772. return $sql_result;
  773. }
  774. /**
  775. * Function to export as entries
  776. *
  777. * @param array $entries entries
  778. *
  779. * @return void
  780. */
  781. public static function exportAsFileDownload(array $entries)
  782. {
  783. ini_set('url_rewriter.tags', '');
  784. // Replace all multiple whitespaces by a single space
  785. $table = htmlspecialchars(preg_replace('/\s+/', ' ', $_POST['table']));
  786. $dump = "# " . sprintf(
  787. __('Tracking report for table `%s`'), $table
  788. )
  789. . "\n" . "# " . date('Y-m-d H:i:s') . "\n";
  790. foreach ($entries as $entry) {
  791. $dump .= $entry['statement'];
  792. }
  793. $filename = 'log_' . $table . '.sql';
  794. Response::getInstance()->disable();
  795. Core::downloadHeader(
  796. $filename,
  797. 'text/x-sql',
  798. strlen($dump)
  799. );
  800. echo $dump;
  801. exit();
  802. }
  803. /**
  804. * Function to activate or deactivate tracking
  805. *
  806. * @param string $action activate|deactivate
  807. *
  808. * @return string HTML for the success message
  809. */
  810. public static function changeTracking($action)
  811. {
  812. $html = '';
  813. if ($action == 'activate') {
  814. $method = 'activateTracking';
  815. $message = __('Tracking for %1$s was activated at version %2$s.');
  816. } else {
  817. $method = 'deactivateTracking';
  818. $message = __('Tracking for %1$s was deactivated at version %2$s.');
  819. }
  820. $status = Tracker::$method(
  821. $GLOBALS['db'], $GLOBALS['table'], $_POST['version']
  822. );
  823. if ($status) {
  824. $msg = Message::success(
  825. sprintf(
  826. $message,
  827. htmlspecialchars($GLOBALS['db'] . '.' . $GLOBALS['table']),
  828. htmlspecialchars($_POST['version'])
  829. )
  830. );
  831. $html .= $msg->getDisplay();
  832. }
  833. return $html;
  834. }
  835. /**
  836. * Function to get tracking set
  837. *
  838. * @return string
  839. */
  840. public static function getTrackingSet()
  841. {
  842. $tracking_set = '';
  843. // a key is absent from the request if it has been removed from
  844. // tracking_default_statements in the config
  845. if (isset($_POST['alter_table']) && $_POST['alter_table'] == true) {
  846. $tracking_set .= 'ALTER TABLE,';
  847. }
  848. if (isset($_POST['rename_table']) && $_POST['rename_table'] == true) {
  849. $tracking_set .= 'RENAME TABLE,';
  850. }
  851. if (isset($_POST['create_table']) && $_POST['create_table'] == true) {
  852. $tracking_set .= 'CREATE TABLE,';
  853. }
  854. if (isset($_POST['drop_table']) && $_POST['drop_table'] == true) {
  855. $tracking_set .= 'DROP TABLE,';
  856. }
  857. if (isset($_POST['alter_view']) && $_POST['alter_view'] == true) {
  858. $tracking_set .= 'ALTER VIEW,';
  859. }
  860. if (isset($_POST['create_view']) && $_POST['create_view'] == true) {
  861. $tracking_set .= 'CREATE VIEW,';
  862. }
  863. if (isset($_POST['drop_view']) && $_POST['drop_view'] == true) {
  864. $tracking_set .= 'DROP VIEW,';
  865. }
  866. if (isset($_POST['create_index']) && $_POST['create_index'] == true) {
  867. $tracking_set .= 'CREATE INDEX,';
  868. }
  869. if (isset($_POST['drop_index']) && $_POST['drop_index'] == true) {
  870. $tracking_set .= 'DROP INDEX,';
  871. }
  872. if (isset($_POST['insert']) && $_POST['insert'] == true) {
  873. $tracking_set .= 'INSERT,';
  874. }
  875. if (isset($_POST['update']) && $_POST['update'] == true) {
  876. $tracking_set .= 'UPDATE,';
  877. }
  878. if (isset($_POST['delete']) && $_POST['delete'] == true) {
  879. $tracking_set .= 'DELETE,';
  880. }
  881. if (isset($_POST['truncate']) && $_POST['truncate'] == true) {
  882. $tracking_set .= 'TRUNCATE,';
  883. }
  884. $tracking_set = rtrim($tracking_set, ',');
  885. return $tracking_set;
  886. }
  887. /**
  888. * Deletes a tracking version
  889. *
  890. * @param string $version tracking version
  891. *
  892. * @return string HTML of the success message
  893. */
  894. public static function deleteTrackingVersion($version)
  895. {
  896. $html = '';
  897. $versionDeleted = Tracker::deleteTracking(
  898. $GLOBALS['db'],
  899. $GLOBALS['table'],
  900. $version
  901. );
  902. if ($versionDeleted) {
  903. $msg = Message::success(
  904. sprintf(
  905. __('Version %1$s of %2$s was deleted.'),
  906. htmlspecialchars($version),
  907. htmlspecialchars($GLOBALS['db'] . '.' . $GLOBALS['table'])
  908. )
  909. );
  910. $html .= $msg->getDisplay();
  911. }
  912. return $html;
  913. }
  914. /**
  915. * Function to create the tracking version
  916. *
  917. * @return string HTML of the success message
  918. */
  919. public static function createTrackingVersion()
  920. {
  921. $html = '';
  922. $tracking_set = self::getTrackingSet();
  923. $versionCreated = Tracker::createVersion(
  924. $GLOBALS['db'],
  925. $GLOBALS['table'],
  926. $_POST['version'],
  927. $tracking_set,
  928. $GLOBALS['dbi']->getTable($GLOBALS['db'], $GLOBALS['table'])->isView()
  929. );
  930. if ($versionCreated) {
  931. $msg = Message::success(
  932. sprintf(
  933. __('Version %1$s was created, tracking for %2$s is active.'),
  934. htmlspecialchars($_POST['version']),
  935. htmlspecialchars($GLOBALS['db'] . '.' . $GLOBALS['table'])
  936. )
  937. );
  938. $html .= $msg->getDisplay();
  939. }
  940. return $html;
  941. }
  942. /**
  943. * Create tracking version for multiple tables
  944. *
  945. * @param array $selected list of selected tables
  946. *
  947. * @return void
  948. */
  949. public static function createTrackingForMultipleTables(array $selected)
  950. {
  951. $tracking_set = self::getTrackingSet();
  952. foreach ($selected as $selected_table) {
  953. Tracker::createVersion(
  954. $GLOBALS['db'],
  955. $selected_table,
  956. $_POST['version'],
  957. $tracking_set,
  958. $GLOBALS['dbi']->getTable($GLOBALS['db'], $selected_table)->isView()
  959. );
  960. }
  961. }
  962. /**
  963. * Function to get the entries
  964. *
  965. * @param array $data data
  966. * @param int $filter_ts_from filter time stamp from
  967. * @param int $filter_ts_to filter time stamp to
  968. * @param array $filter_users filter users
  969. *
  970. * @return array
  971. */
  972. public static function getEntries(array $data, $filter_ts_from, $filter_ts_to, array $filter_users)
  973. {
  974. $entries = array();
  975. // Filtering data definition statements
  976. if ($_POST['logtype'] == 'schema'
  977. || $_POST['logtype'] == 'schema_and_data'
  978. ) {
  979. $entries = array_merge(
  980. $entries,
  981. self::filterTracking(
  982. $data['ddlog'], $filter_ts_from, $filter_ts_to, $filter_users
  983. )
  984. );
  985. }
  986. // Filtering data manipulation statements
  987. if ($_POST['logtype'] == 'data'
  988. || $_POST['logtype'] == 'schema_and_data'
  989. ) {
  990. $entries = array_merge(
  991. $entries,
  992. self::filterTracking(
  993. $data['dmlog'], $filter_ts_from, $filter_ts_to, $filter_users
  994. )
  995. );
  996. }
  997. // Sort it
  998. $ids = $timestamps = $usernames = $statements = array();
  999. foreach ($entries as $key => $row) {
  1000. $ids[$key] = $row['id'];
  1001. $timestamps[$key] = $row['timestamp'];
  1002. $usernames[$key] = $row['username'];
  1003. $statements[$key] = $row['statement'];
  1004. }
  1005. array_multisort(
  1006. $timestamps, SORT_ASC, $ids, SORT_ASC, $usernames,
  1007. SORT_ASC, $statements, SORT_ASC, $entries
  1008. );
  1009. return $entries;
  1010. }
  1011. /**
  1012. * Function to get version status
  1013. *
  1014. * @param array $version version info
  1015. *
  1016. * @return string $version_status The status message
  1017. */
  1018. public static function getVersionStatus(array $version)
  1019. {
  1020. if ($version['tracking_active'] == 1) {
  1021. return __('active');
  1022. }
  1023. return __('not active');
  1024. }
  1025. /**
  1026. * Get HTML for untracked tables
  1027. *
  1028. * @param string $db current database
  1029. * @param array $untrackedTables untracked tables
  1030. * @param string $urlQuery url query string
  1031. * @param string $pmaThemeImage path to theme's image folder
  1032. * @param string $textDir text direction
  1033. *
  1034. * @return string HTML
  1035. */
  1036. public static function getHtmlForUntrackedTables(
  1037. $db,
  1038. array $untrackedTables,
  1039. $urlQuery,
  1040. $pmaThemeImage,
  1041. $textDir
  1042. ) {
  1043. return Template::get('database/tracking/untracked_tables')->render([
  1044. 'db' => $db,
  1045. 'untracked_tables' => $untrackedTables,
  1046. 'url_query' => $urlQuery,
  1047. 'pma_theme_image' => $pmaThemeImage,
  1048. 'text_dir' => $textDir,
  1049. ]);
  1050. }
  1051. /**
  1052. * Helper function: Recursive function for getting table names from $table_list
  1053. *
  1054. * @param array $table_list Table list
  1055. * @param string $db Current database
  1056. * @param boolean $testing Testing
  1057. *
  1058. * @return array $untracked_tables
  1059. */
  1060. public static function extractTableNames(array $table_list, $db, $testing = false)
  1061. {
  1062. $untracked_tables = array();
  1063. $sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
  1064. foreach ($table_list as $key => $value) {
  1065. if (is_array($value) && array_key_exists(('is' . $sep . 'group'), $value)
  1066. && $value['is' . $sep . 'group']
  1067. ) {
  1068. $untracked_tables = array_merge(self::extractTableNames($value, $db), $untracked_tables); //Recursion step
  1069. }
  1070. else {
  1071. if (is_array($value) && ($testing || Tracker::getVersion($db, $value['Name']) == -1)) {
  1072. $untracked_tables[] = $value['Name'];
  1073. }
  1074. }
  1075. }
  1076. return $untracked_tables;
  1077. }
  1078. /**
  1079. * Get untracked tables
  1080. *
  1081. * @param string $db current database
  1082. *
  1083. * @return array $untracked_tables
  1084. */
  1085. public static function getUntrackedTables($db)
  1086. {
  1087. $table_list = Util::getTableList($db);
  1088. $untracked_tables = self::extractTableNames($table_list, $db); //Use helper function to get table list recursively.
  1089. return $untracked_tables;
  1090. }
  1091. /**
  1092. * Get tracked tables
  1093. *
  1094. * @param string $db current database
  1095. * @param object $allTablesResult result set of tracked tables
  1096. * @param string $urlQuery url query string
  1097. * @param string $pmaThemeImage path to theme's image folder
  1098. * @param string $textDir text direction
  1099. * @param array $cfgRelation configuration storage info
  1100. *
  1101. * @return string HTML
  1102. */
  1103. public static function getHtmlForTrackedTables(
  1104. $db,
  1105. $allTablesResult,
  1106. $urlQuery,
  1107. $pmaThemeImage,
  1108. $textDir,
  1109. array $cfgRelation
  1110. ) {
  1111. $relation = new Relation();
  1112. $versions = [];
  1113. while ($oneResult = $GLOBALS['dbi']->fetchArray($allTablesResult)) {
  1114. list($tableName, $versionNumber) = $oneResult;
  1115. $tableQuery = ' SELECT * FROM ' .
  1116. Util::backquote($cfgRelation['db']) . '.' .
  1117. Util::backquote($cfgRelation['tracking']) .
  1118. ' WHERE `db_name` = \''
  1119. . $GLOBALS['dbi']->escapeString($GLOBALS['db'])
  1120. . '\' AND `table_name` = \''
  1121. . $GLOBALS['dbi']->escapeString($tableName)
  1122. . '\' AND `version` = \'' . $versionNumber . '\'';
  1123. $tableResult = $relation->queryAsControlUser($tableQuery);
  1124. $versionData = $GLOBALS['dbi']->fetchArray($tableResult);
  1125. $versionData['status_button'] = self::getStatusButton(
  1126. $versionData,
  1127. $urlQuery
  1128. );
  1129. $versions[] = $versionData;
  1130. }
  1131. return Template::get('database/tracking/tracked_tables')->render([
  1132. 'db' => $db,
  1133. 'versions' => $versions,
  1134. 'text_dir' => $textDir,
  1135. 'pma_theme_image' => $pmaThemeImage,
  1136. ]);
  1137. }
  1138. /**
  1139. * Get tracking status button
  1140. *
  1141. * @param array $versionData data about tracking versions
  1142. * @param string $urlQuery url query string
  1143. *
  1144. * @return string HTML
  1145. */
  1146. private static function getStatusButton(array $versionData, $urlQuery)
  1147. {
  1148. $state = self::getVersionStatus($versionData);
  1149. $options = array(
  1150. 0 => array(
  1151. 'label' => __('not active'),
  1152. 'value' => 'deactivate_now',
  1153. 'selected' => ($state != 'active')
  1154. ),
  1155. 1 => array(
  1156. 'label' => __('active'),
  1157. 'value' => 'activate_now',
  1158. 'selected' => ($state == 'active')
  1159. )
  1160. );
  1161. $link = 'tbl_tracking.php' . $urlQuery . '&amp;table='
  1162. . htmlspecialchars($versionData['table_name'])
  1163. . '&amp;version=' . $versionData['version'];
  1164. return Util::toggleButton(
  1165. $link,
  1166. 'toggle_activation',
  1167. $options,
  1168. null
  1169. );
  1170. }
  1171. }