2 /* vim: set expandtab sw=4 ts=4 sts=4: */
9 * This class tracks changes on databases, tables and views.
10 * For more information please see phpMyAdmin/Documentation.html
14 * @todo use stristr instead of strstr
19 * Whether tracking is ready.
21 static protected $enabled = false;
24 * Defines the internal PMA table which contains tracking data.
29 static protected $pma_table;
32 * Defines the usage of DROP TABLE statment in SQL dumps.
37 static protected $add_drop_table;
40 * Defines the usage of DROP VIEW statment in SQL dumps.
45 static protected $add_drop_view;
48 * Defines the usage of DROP DATABASE statment in SQL dumps.
53 static protected $add_drop_database;
56 * Defines auto-creation of tracking versions.
60 static protected $version_auto_create;
63 * Defines the default set of tracked statements.
67 static protected $default_tracking_set;
70 * Initializes settings. See phpMyAdmin/Documentation.html.
75 static public function init()
77 self
::$pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
78 PMA_backquote($GLOBALS['cfg']['Server']['tracking']);
80 self
::$add_drop_table = $GLOBALS['cfg']['Server']['tracking_add_drop_table'];
82 self
::$add_drop_view = $GLOBALS['cfg']['Server']['tracking_add_drop_view'];
84 self
::$add_drop_database = $GLOBALS['cfg']['Server']['tracking_add_drop_database'];
86 self
::$default_tracking_set = $GLOBALS['cfg']['Server']['tracking_default_statements'];
88 self
::$version_auto_create = $GLOBALS['cfg']['Server']['tracking_version_auto_create'];
93 * Actually enables tracking. This needs to be done after all
94 * underlaying code is initialized.
99 static public function enable()
101 self
::$enabled = true;
105 * Gets the on/off value of the Tracker module, starts initialization.
109 * @return boolean (true=on|false=off)
111 static public function isActive()
113 if (! self
::$enabled) {
116 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
117 self
::$enabled = false;
118 $cfgRelation = PMA_getRelationsParam();
119 /* Restore original state */
120 self
::$enabled = true;
121 if (! $cfgRelation['trackingwork']) {
126 if (isset(self
::$pma_table)) {
134 * Returns a simple DROP TABLE statement.
136 * @param string $tablename
139 static public function getStatementDropTable($tablename)
141 return 'DROP TABLE IF EXISTS ' . $tablename;
145 * Returns a simple DROP VIEW statement.
147 * @param string $viewname
150 static public function getStatementDropView($viewname)
152 return 'DROP VIEW IF EXISTS ' . $viewname;
156 * Returns a simple DROP DATABASE statement.
158 * @param string $dbname
161 static public function getStatementDropDatabase($dbname)
163 return 'DROP DATABASE IF EXISTS ' . $dbname;
167 * Parses the name of a table from a SQL statement substring.
171 * @param string $string part of SQL statement
173 * @return string the name of table
175 static protected function getTableName($string)
177 if (strstr($string, '.')) {
178 $temp = explode('.', $string);
179 $tablename = $temp[1];
182 $tablename = $string;
185 $str = explode("\n", $tablename);
186 $tablename = $str[0];
188 $tablename = str_replace(';', '', $tablename);
189 $tablename = str_replace('`', '', $tablename);
190 $tablename = trim($tablename);
197 * Gets the tracking status of a table, is it active or deactive ?
201 * @param string $dbname name of database
202 * @param string $tablename name of table
204 * @return boolean true or false
206 static public function isTracked($dbname, $tablename)
208 if (! self
::$enabled) {
211 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
212 self
::$enabled = false;
213 $cfgRelation = PMA_getRelationsParam();
214 /* Restore original state */
215 self
::$enabled = true;
216 if (! $cfgRelation['trackingwork']) {
221 " SELECT tracking_active FROM " . self
::$pma_table .
222 " WHERE " . PMA_backquote('db_name') . " = '" . PMA_sqlAddslashes($dbname) . "' " .
223 " AND " . PMA_backquote('table_name') . " = '" . PMA_sqlAddslashes($tablename) . "' " .
224 " ORDER BY version DESC";
226 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
228 if (isset($row['tracking_active']) && $row['tracking_active'] == 1) {
236 * Returns the comment line for the log.
238 * @return string Comment, contains date and username
240 static public function getLogComment()
242 $date = date('Y-m-d H:i:s');
244 return "# log " . $date . " " . $GLOBALS['cfg']['Server']['user'] . "\n";
248 * Creates tracking version of a table / view
249 * (in other words: create a job to track future changes on the table).
253 * @param string $dbname name of database
254 * @param string $tablename name of table
255 * @param string $version version
256 * @param string $tracking_set set of tracking statements
257 * @param string $is_view if table is a view
259 * @return int result of version insertion
261 static public function createVersion($dbname, $tablename, $version, $tracking_set = '', $is_view = false)
263 global $sql_backquotes;
265 if ($tracking_set == '') {
266 $tracking_set = self
::$default_tracking_set;
269 require_once './libraries/export/sql.php';
271 $sql_backquotes = true;
273 $date = date('Y-m-d H:i:s');
275 // Get data definition snapshot of table
277 SHOW FULL COLUMNS FROM ' . PMA_backquote($dbname) . '.' . PMA_backquote($tablename);
279 $sql_result = PMA_DBI_query($sql_query);
281 while ($row = PMA_DBI_fetch_array($sql_result)) {
286 SHOW INDEX FROM ' . PMA_backquote($dbname) . '.' . PMA_backquote($tablename);
288 $sql_result = PMA_DBI_query($sql_query);
292 while($row = PMA_DBI_fetch_array($sql_result)) {
296 $snapshot = array('COLUMNS' => $columns, 'INDEXES' => $indexes);
297 $snapshot = serialize($snapshot);
299 // Get DROP TABLE / DROP VIEW and CREATE TABLE SQL statements
300 $sql_backquotes = true;
304 if (self
::$add_drop_table == true && $is_view == false) {
305 $create_sql .= self
::getLogComment() .
306 self
::getStatementDropTable(PMA_backquote($tablename)) . ";\n";
310 if (self
::$add_drop_view == true && $is_view == true) {
311 $create_sql .= self
::getLogComment() .
312 self
::getStatementDropView(PMA_backquote($tablename)) . ";\n";
315 $create_sql .= self
::getLogComment() .
316 PMA_getTableDef($dbname, $tablename, "\n", "");
322 "INSERT INTO" . self
::$pma_table . " (" .
328 "schema_snapshot, " .
334 '" . PMA_sqlAddslashes($dbname) . "',
335 '" . PMA_sqlAddslashes($tablename) . "',
336 '" . PMA_sqlAddslashes($version) . "',
337 '" . PMA_sqlAddslashes($date) . "',
338 '" . PMA_sqlAddslashes($date) . "',
339 '" . PMA_sqlAddslashes($snapshot) . "',
340 '" . PMA_sqlAddslashes($create_sql) . "',
341 '" . PMA_sqlAddslashes("\n") . "',
342 '" . PMA_sqlAddslashes($tracking_set) . "' )";
344 $result = PMA_query_as_controluser($sql_query);
347 // Deactivate previous version
348 self
::deactivateTracking($dbname, $tablename, ($version - 1));
356 * Removes all tracking data for a table
360 * @param string $dbname name of database
361 * @param string $tablename name of table
363 * @return int result of version insertion
365 static public function deleteTracking($dbname, $tablename)
369 "DELETE FROM " . self
::$pma_table . " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' AND `table_name` = '" . PMA_sqlAddslashes($tablename) . "'";
370 $result = PMA_query_as_controluser($sql_query);
376 * Creates tracking version of a database
377 * (in other words: create a job to track future changes on the database).
381 * @param string $dbname name of database
382 * @param string $version version
383 * @param string $query query
384 * @param string $tracking_set set of tracking statements
386 * @return int result of version insertion
388 static public function createDatabaseVersion($dbname, $version, $query, $tracking_set = 'CREATE DATABASE,ALTER DATABASE,DROP DATABASE')
390 global $sql_backquotes;
392 $date = date('Y-m-d H:i:s');
394 if ($tracking_set == '') {
395 $tracking_set = self
::$default_tracking_set;
398 require_once './libraries/export/sql.php';
402 if (self
::$add_drop_database == true) {
403 $create_sql .= self
::getLogComment() .
404 self
::getStatementDropDatabase(PMA_backquote($dbname)) . ";\n";
407 $create_sql .= self
::getLogComment() . $query;
412 "INSERT INTO" . self
::$pma_table . " (" .
418 "schema_snapshot, " .
424 '" . PMA_sqlAddslashes($dbname) . "',
425 '" . PMA_sqlAddslashes('') . "',
426 '" . PMA_sqlAddslashes($version) . "',
427 '" . PMA_sqlAddslashes($date) . "',
428 '" . PMA_sqlAddslashes($date) . "',
429 '" . PMA_sqlAddslashes('') . "',
430 '" . PMA_sqlAddslashes($create_sql) . "',
431 '" . PMA_sqlAddslashes("\n") . "',
432 '" . PMA_sqlAddslashes($tracking_set) . "' )";
434 $result = PMA_query_as_controluser($sql_query);
442 * Changes tracking of a table.
446 * @param string $dbname name of database
447 * @param string $tablename name of table
448 * @param string $version version
449 * @param integer $new_state the new state of tracking
451 * @return int result of SQL query
453 static private function changeTracking($dbname, $tablename, $version, $new_state)
456 " UPDATE " . self
::$pma_table .
457 " SET `tracking_active` = '" . $new_state . "' " .
458 " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' " .
459 " AND `table_name` = '" . PMA_sqlAddslashes($tablename) . "' " .
460 " AND `version` = '" . PMA_sqlAddslashes($version) . "' ";
462 $result = PMA_query_as_controluser($sql_query);
468 * Activates tracking of a table.
472 * @param string $dbname name of database
473 * @param string $tablename name of table
474 * @param string $version version
476 * @return int result of SQL query
478 static public function activateTracking($dbname, $tablename, $version)
480 return self
::changeTracking($dbname, $tablename, $version, 1);
485 * Deactivates tracking of a table.
489 * @param string $dbname name of database
490 * @param string $tablename name of table
491 * @param string $version version
493 * @return int result of SQL query
495 static public function deactivateTracking($dbname, $tablename, $version)
497 return self
::changeTracking($dbname, $tablename, $version, 0);
502 * Gets the newest version of a tracking job
503 * (in other words: gets the HEAD version).
507 * @param string $dbname name of database
508 * @param string $tablename name of table
509 * @param string $statement tracked statement
511 * @return int (-1 if no version exists | > 0 if a version exists)
513 static public function getVersion($dbname, $tablename, $statement = null)
516 " SELECT MAX(version) FROM " . self
::$pma_table .
517 " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' " .
518 " AND `table_name` = '" . PMA_sqlAddslashes($tablename) . "' ";
520 if ($statement != "") {
521 $sql_query .= " AND FIND_IN_SET('" . $statement . "',tracking) > 0" ;
523 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
524 if (isset($row[0])) {
527 if (! isset($version)) {
535 * Gets the record of a tracking job.
539 * @param string $dbname name of database
540 * @param string $tablename name of table
541 * @param string $version version number
543 * @return mixed record DDM log, DDL log, structure snapshot, tracked statements.
545 static public function getTrackedData($dbname, $tablename, $version)
547 if (! isset(self
::$pma_table)) {
550 $sql_query = " SELECT * FROM " . self
::$pma_table .
551 " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' ";
552 if (! empty($tablename)) {
553 $sql_query .= " AND `table_name` = '" . PMA_sqlAddslashes($tablename) ."' ";
555 $sql_query .= " AND `version` = '" . PMA_sqlAddslashes($version) ."' ".
556 " ORDER BY `version` DESC ";
558 $mixed = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
561 $log_schema_entries = explode('# log ', $mixed['schema_sql']);
562 $log_data_entries = explode('# log ', $mixed['data_sql']);
564 $ddl_date_from = $date = date('Y-m-d H:i:s');
569 // Iterate tracked data definition statements
570 // For each log entry we want to get date, username and statement
571 foreach ($log_schema_entries as $log_entry) {
572 if (trim($log_entry) != '') {
573 $date = substr($log_entry, 0, 19);
574 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
576 $ddl_date_from = $date;
578 $statement = rtrim(strstr($log_entry, "\n"));
580 $ddlog[] = array( 'date' => $date,
581 'username'=> $username,
582 'statement' => $statement );
587 $date_from = $ddl_date_from;
588 $date_to = $ddl_date_to = $date;
590 $dml_date_from = $date_from;
595 // Iterate tracked data manipulation statements
596 // For each log entry we want to get date, username and statement
597 foreach ($log_data_entries as $log_entry) {
598 if (trim($log_entry) != '') {
599 $date = substr($log_entry, 0, 19);
600 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
602 $dml_date_from = $date;
604 $statement = rtrim(strstr($log_entry, "\n"));
606 $dmlog[] = array( 'date' => $date,
607 'username' => $username,
608 'statement' => $statement );
613 $dml_date_to = $date;
615 // Define begin and end of date range for both logs
616 if (strtotime($ddl_date_from) <= strtotime($dml_date_from)) {
617 $data['date_from'] = $ddl_date_from;
619 $data['date_from'] = $dml_date_from;
621 if (strtotime($ddl_date_to) >= strtotime($dml_date_to)) {
622 $data['date_to'] = $ddl_date_to;
624 $data['date_to'] = $dml_date_to;
626 $data['ddlog'] = $ddlog;
627 $data['dmlog'] = $dmlog;
628 $data['tracking'] = $mixed['tracking'];
629 $data['schema_snapshot'] = $mixed['schema_snapshot'];
636 * Parses a query. Gets
637 * - statement identifier (UPDATE, ALTER TABLE, ...)
638 * - type of statement, is it part of DDL or DML ?
642 * @todo: using PMA SQL Parser when possible
643 * @todo: support multi-table/view drops
645 * @param string $query
647 * @return mixed Array containing identifier, type and tablename.
650 static public function parseQuery($query)
653 // Usage of PMA_SQP does not work here
655 // require_once("libraries/sqlparser.lib.php");
656 // $parsed_sql = PMA_SQP_parse($query);
657 // $sql_info = PMA_SQP_analyze($parsed_sql);
659 $query = str_replace("\n", " ", $query);
660 $query = str_replace("\r", " ", $query);
662 $query = trim($query);
663 $query = trim($query, ' -');
665 $tokens = explode(" ", $query);
666 $tokens = array_map('strtoupper', $tokens);
668 // Parse USE statement, need it for SQL dump imports
669 if (substr($query, 0, 4) == 'USE ') {
670 $prefix = explode('USE ', $query);
671 $GLOBALS['db'] = self
::getTableName($prefix[1]);
678 $result['type'] = 'DDL';
680 // Parse CREATE VIEW statement
681 if (in_array('CREATE', $tokens) == true &&
682 in_array('VIEW', $tokens) == true &&
683 in_array('AS', $tokens) == true) {
684 $result['identifier'] = 'CREATE VIEW';
686 $index = array_search('VIEW', $tokens);
688 $result['tablename'] = strtolower(self
::getTableName($tokens[$index +
1]));
691 // Parse ALTER VIEW statement
692 if (in_array('ALTER', $tokens) == true &&
693 in_array('VIEW', $tokens) == true &&
694 in_array('AS', $tokens) == true &&
695 ! isset($result['identifier'])) {
696 $result['identifier'] = 'ALTER VIEW';
698 $index = array_search('VIEW', $tokens);
700 $result['tablename'] = strtolower(self
::getTableName($tokens[$index +
1]));
703 // Parse DROP VIEW statement
704 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP VIEW ') {
705 $result['identifier'] = 'DROP VIEW';
707 $prefix = explode('DROP VIEW ', $query);
708 $str = strstr($prefix[1], 'IF EXISTS');
710 if ($str == FALSE ) {
713 $result['tablename'] = self
::getTableName($str);
716 // Parse CREATE DATABASE statement
717 if (! isset($result['identifier']) && substr($query, 0, 15) == 'CREATE DATABASE') {
718 $result['identifier'] = 'CREATE DATABASE';
719 $str = str_replace('CREATE DATABASE', '', $query);
720 $str = str_replace('IF NOT EXISTS', '', $str);
722 $prefix = explode('DEFAULT ', $str);
724 $result['tablename'] = '';
725 $GLOBALS['db'] = self
::getTableName($prefix[0]);
728 // Parse ALTER DATABASE statement
729 if (! isset($result['identifier']) && substr($query, 0, 14) == 'ALTER DATABASE') {
730 $result['identifier'] = 'ALTER DATABASE';
731 $result['tablename'] = '';
734 // Parse DROP DATABASE statement
735 if (! isset($result['identifier']) && substr($query, 0, 13) == 'DROP DATABASE') {
736 $result['identifier'] = 'DROP DATABASE';
737 $str = str_replace('DROP DATABASE', '', $query);
738 $str = str_replace('IF EXISTS', '', $str);
739 $GLOBALS['db'] = self
::getTableName($str);
740 $result['tablename'] = '';
743 // Parse CREATE TABLE statement
744 if (! isset($result['identifier']) && substr($query, 0, 12) == 'CREATE TABLE' ) {
745 $result['identifier'] = 'CREATE TABLE';
746 $query = str_replace('IF NOT EXISTS', '', $query);
747 $prefix = explode('CREATE TABLE ', $query);
748 $suffix = explode('(', $prefix[1]);
749 $result['tablename'] = self
::getTableName($suffix[0]);
752 // Parse ALTER TABLE statement
753 if (! isset($result['identifier']) && substr($query, 0, 12) == 'ALTER TABLE ') {
754 $result['identifier'] = 'ALTER TABLE';
756 $prefix = explode('ALTER TABLE ', $query);
757 $suffix = explode(' ', $prefix[1]);
758 $result['tablename'] = self
::getTableName($suffix[0]);
761 // Parse DROP TABLE statement
762 if (! isset($result['identifier']) && substr($query, 0, 11) == 'DROP TABLE ') {
763 $result['identifier'] = 'DROP TABLE';
765 $prefix = explode('DROP TABLE ', $query);
766 $str = strstr($prefix[1], 'IF EXISTS');
768 if ($str == FALSE ) {
771 $result['tablename'] = self
::getTableName($str);
774 // Parse CREATE INDEX statement
775 if (! isset($result['identifier']) &&
776 ( substr($query, 0, 12) == 'CREATE INDEX' ||
777 substr($query, 0, 19) == 'CREATE UNIQUE INDEX' ||
778 substr($query, 0, 20) == 'CREATE SPATIAL INDEX'
781 $result['identifier'] = 'CREATE INDEX';
782 $prefix = explode('ON ', $query);
783 $suffix = explode('(', $prefix[1]);
784 $result['tablename'] = self
::getTableName($suffix[0]);
787 // Parse DROP INDEX statement
788 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP INDEX') {
789 $result['identifier'] = 'DROP INDEX';
790 $prefix = explode('ON ', $query);
791 $result['tablename'] = self
::getTableName($prefix[1]);
794 // Parse RENAME TABLE statement
795 if (! isset($result['identifier']) && substr($query, 0, 13) == 'RENAME TABLE ') {
796 $result['identifier'] = 'RENAME TABLE';
797 $prefix = explode('RENAME TABLE ', $query);
798 $names = explode(' TO ', $prefix[1]);
799 $result['tablename'] = self
::getTableName($names[0]);
800 $result["tablename_after_rename"] = self
::getTableName($names[1]);
807 if (! isset($result['identifier'])) {
808 $result["type"] = 'DML';
810 // Parse UPDATE statement
811 if (! isset($result['identifier']) && substr($query, 0, 6) == 'UPDATE') {
812 $result['identifier'] = 'UPDATE';
813 $prefix = explode('UPDATE ', $query);
814 $suffix = explode(' ', $prefix[1]);
815 $result['tablename'] = self
::getTableName($suffix[0]);
818 // Parse INSERT INTO statement
819 if (! isset($result['identifier']) && substr($query, 0, 11 ) == 'INSERT INTO') {
820 $result['identifier'] = 'INSERT';
821 $prefix = explode('INSERT INTO', $query);
822 $suffix = explode('(', $prefix[1]);
823 $result['tablename'] = self
::getTableName($suffix[0]);
826 // Parse DELETE statement
827 if (! isset($result['identifier']) && substr($query, 0, 6 ) == 'DELETE') {
828 $result['identifier'] = 'DELETE';
829 $prefix = explode('FROM ', $query);
830 $suffix = explode(' ', $prefix[1]);
831 $result['tablename'] = self
::getTableName($suffix[0]);
834 // Parse TRUNCATE statement
835 if (! isset($result['identifier']) && substr($query, 0, 8 ) == 'TRUNCATE') {
836 $result['identifier'] = 'TRUNCATE';
837 $prefix = explode('TRUNCATE', $query);
838 $result['tablename'] = self
::getTableName($prefix[1]);
846 * Analyzes a given SQL statement and saves tracking data.
850 * @param string $query a SQL query
852 static public function handleQuery($query)
854 // If query is marked as untouchable, leave
855 if (strstr($query, "/*NOTRACK*/")) {
859 if (! (substr($query, -1) == ';')) {
860 $query = $query . ";\n";
862 // Get some information about query
863 $result = self
::parseQuery($query);
866 $dbname = trim($GLOBALS['db'], '`');
867 // $dbname can be empty, for example when coming from Synchronize
868 // and this is a query for the remote server
869 if (empty($dbname)) {
873 // If we found a valid statement
874 if (isset($result['identifier'])) {
875 $version = self
::getVersion($dbname, $result['tablename'], $result['identifier']);
877 // If version not exists and auto-creation is enabled
878 if (self
::$version_auto_create == true
879 && self
::isTracked($dbname, $result['tablename']) == false
881 // Create the version
883 switch ($result['identifier']) {
885 self
::createVersion($dbname, $result['tablename'], '1');
888 self
::createVersion($dbname, $result['tablename'], '1', '', true);
890 case 'CREATE DATABASE':
891 self
::createDatabaseVersion($dbname, '1', $query);
897 if (self
::isTracked($dbname, $result['tablename']) && $version != -1) {
898 if ($result['type'] == 'DDL') {
899 $save_to = 'schema_sql';
900 } elseif ($result['type'] == 'DML') {
901 $save_to = 'data_sql';
905 $date = date('Y-m-d H:i:s');
907 // Cut off `dbname`. from query
908 $query = preg_replace('/`' . $dbname . '`\s?\./', '', $query);
910 // Add log information
911 $query = self
::getLogComment() . $query ;
913 // Mark it as untouchable
916 " UPDATE " . self
::$pma_table .
917 " SET " . PMA_backquote($save_to) ." = CONCAT( " . PMA_backquote($save_to) . ",'\n" . PMA_sqlAddslashes($query) . "') ," .
918 " `date_updated` = '" . $date . "' ";
920 // If table was renamed we have to change the tablename attribute in pma_tracking too
921 if ($result['identifier'] == 'RENAME TABLE') {
922 $sql_query .= ', `table_name` = \'' . PMA_sqlAddslashes($result['tablename_after_rename']) . '\' ';
925 // Save the tracking information only for
927 // 2. the table / view
931 " WHERE FIND_IN_SET('" . $result['identifier'] . "',tracking) > 0" .
932 " AND `db_name` = '" . PMA_sqlAddslashes($dbname) . "' " .
933 " AND `table_name` = '" . PMA_sqlAddslashes($result['tablename']) . "' " .
934 " AND `version` = '" . PMA_sqlAddslashes($version) . "' ";
936 $result = PMA_query_as_controluser($sql_query);