2 /* vim: set expandtab sw=4 ts=4 sts=4: */
10 * Gets relation settings
12 require_once './libraries/relation.lib.php';
15 * This class tracks changes on databases, tables and views.
16 * For more information please see phpMyAdmin/Documentation.html
20 * @todo use stristr instead of strstr
25 * Whether tracking is ready.
27 static protected $enabled = false;
30 * Defines the internal PMA table which contains tracking data.
35 static protected $pma_table;
38 * Defines the usage of DROP TABLE statment in SQL dumps.
43 static protected $add_drop_table;
46 * Defines the usage of DROP VIEW statment in SQL dumps.
51 static protected $add_drop_view;
54 * Defines the usage of DROP DATABASE statment in SQL dumps.
59 static protected $add_drop_database;
62 * Defines auto-creation of tracking versions.
66 static protected $version_auto_create;
69 * Defines the default set of tracked statements.
73 static protected $default_tracking_set;
76 * Initializes settings. See phpMyAdmin/Documentation.html.
81 static public function init()
83 self
::$pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
84 PMA_backquote($GLOBALS['cfg']['Server']['tracking']);
86 self
::$add_drop_table = $GLOBALS['cfg']['Server']['tracking_add_drop_table'];
88 self
::$add_drop_view = $GLOBALS['cfg']['Server']['tracking_add_drop_view'];
90 self
::$add_drop_database = $GLOBALS['cfg']['Server']['tracking_add_drop_database'];
92 self
::$default_tracking_set = $GLOBALS['cfg']['Server']['tracking_default_statements'];
94 self
::$version_auto_create = $GLOBALS['cfg']['Server']['tracking_version_auto_create'];
99 * Actually enables tracking. This needs to be done after all
100 * underlaying code is initialized.
105 static public function enable()
107 self
::$enabled = true;
111 * Gets the on/off value of the Tracker module, starts initialization.
115 * @return boolean (true=on|false=off)
117 static public function isActive()
119 if (! self
::$enabled) {
122 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
123 self
::$enabled = false;
124 $cfgRelation = PMA_getRelationsParam();
125 /* Restore original state */
126 self
::$enabled = true;
127 if (! $cfgRelation['trackingwork']) {
132 if (isset(self
::$pma_table)) {
140 * Returns a simple DROP TABLE statement.
142 * @param string $tablename
145 static public function getStatementDropTable($tablename)
147 return 'DROP TABLE IF EXISTS ' . $tablename;
151 * Returns a simple DROP VIEW statement.
153 * @param string $viewname
156 static public function getStatementDropView($viewname)
158 return 'DROP VIEW IF EXISTS ' . $viewname;
162 * Returns a simple DROP DATABASE statement.
164 * @param string $dbname
167 static public function getStatementDropDatabase($dbname)
169 return 'DROP DATABASE IF EXISTS ' . $dbname;
173 * Parses the name of a table from a SQL statement substring.
177 * @param string $string part of SQL statement
179 * @return string the name of table
181 static protected function getTableName($string)
183 if (strstr($string, '.')) {
184 $temp = explode('.', $string);
185 $tablename = $temp[1];
188 $tablename = $string;
191 $str = explode("\n", $tablename);
192 $tablename = $str[0];
194 $tablename = str_replace(';', '', $tablename);
195 $tablename = str_replace('`', '', $tablename);
196 $tablename = trim($tablename);
203 * Gets the tracking status of a table, is it active or deactive ?
207 * @param string $dbname name of database
208 * @param string $tablename name of table
210 * @return boolean true or false
212 static public function isTracked($dbname, $tablename)
214 if (! self
::$enabled) {
217 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
218 self
::$enabled = false;
219 $cfgRelation = PMA_getRelationsParam();
220 /* Restore original state */
221 self
::$enabled = true;
222 if (! $cfgRelation['trackingwork']) {
227 " SELECT tracking_active FROM " . self
::$pma_table .
228 " WHERE " . PMA_backquote('db_name') . " = '" . PMA_sqlAddslashes($dbname) . "' " .
229 " AND " . PMA_backquote('table_name') . " = '" . PMA_sqlAddslashes($tablename) . "' " .
230 " ORDER BY version DESC";
232 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
234 if (isset($row['tracking_active']) && $row['tracking_active'] == 1) {
242 * Returns the comment line for the log.
244 * @return string Comment, contains date and username
246 static public function getLogComment()
248 $date = date('Y-m-d H:i:s');
250 return "# log " . $date . " " . $GLOBALS['cfg']['Server']['user'] . "\n";
254 * Creates tracking version of a table / view
255 * (in other words: create a job to track future changes on the table).
259 * @param string $dbname name of database
260 * @param string $tablename name of table
261 * @param string $version version
262 * @param string $tracking_set set of tracking statements
263 * @param string $is_view if table is a view
265 * @return int result of version insertion
267 static public function createVersion($dbname, $tablename, $version, $tracking_set = '', $is_view = false)
269 global $sql_backquotes;
271 if ($tracking_set == '') {
272 $tracking_set = self
::$default_tracking_set;
275 require_once './libraries/export/sql.php';
277 $sql_backquotes = true;
279 $date = date('Y-m-d H:i:s');
281 // Get data definition snapshot of table
283 SHOW FULL COLUMNS FROM ' . PMA_backquote($dbname) . '.' . PMA_backquote($tablename);
285 $sql_result = PMA_DBI_query($sql_query);
287 while ($row = PMA_DBI_fetch_array($sql_result)) {
292 SHOW INDEX FROM ' . PMA_backquote($dbname) . '.' . PMA_backquote($tablename);
294 $sql_result = PMA_DBI_query($sql_query);
298 while($row = PMA_DBI_fetch_array($sql_result)) {
302 $snapshot = array('COLUMNS' => $columns, 'INDEXES' => $indexes);
303 $snapshot = serialize($snapshot);
305 // Get DROP TABLE / DROP VIEW and CREATE TABLE SQL statements
306 $sql_backquotes = true;
310 if (self
::$add_drop_table == true && $is_view == false) {
311 $create_sql .= self
::getLogComment() .
312 self
::getStatementDropTable(PMA_backquote($tablename)) . ";\n";
316 if (self
::$add_drop_view == true && $is_view == true) {
317 $create_sql .= self
::getLogComment() .
318 self
::getStatementDropView(PMA_backquote($tablename)) . ";\n";
321 $create_sql .= self
::getLogComment() .
322 PMA_getTableDef($dbname, $tablename, "\n", "");
328 "INSERT INTO" . self
::$pma_table . " (" .
334 "schema_snapshot, " .
340 '" . PMA_sqlAddslashes($dbname) . "',
341 '" . PMA_sqlAddslashes($tablename) . "',
342 '" . PMA_sqlAddslashes($version) . "',
343 '" . PMA_sqlAddslashes($date) . "',
344 '" . PMA_sqlAddslashes($date) . "',
345 '" . PMA_sqlAddslashes($snapshot) . "',
346 '" . PMA_sqlAddslashes($create_sql) . "',
347 '" . PMA_sqlAddslashes("\n") . "',
348 '" . PMA_sqlAddslashes($tracking_set) . "' )";
350 $result = PMA_query_as_controluser($sql_query);
353 // Deactivate previous version
354 self
::deactivateTracking($dbname, $tablename, ($version - 1));
362 * Removes all tracking data for a table
366 * @param string $dbname name of database
367 * @param string $tablename name of table
369 * @return int result of version insertion
371 static public function deleteTracking($dbname, $tablename)
375 "DELETE FROM " . self
::$pma_table . " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' AND `table_name` = '" . PMA_sqlAddslashes($tablename) . "'";
376 $result = PMA_query_as_controluser($sql_query);
382 * Creates tracking version of a database
383 * (in other words: create a job to track future changes on the database).
387 * @param string $dbname name of database
388 * @param string $version version
389 * @param string $query query
390 * @param string $tracking_set set of tracking statements
392 * @return int result of version insertion
394 static public function createDatabaseVersion($dbname, $version, $query, $tracking_set = 'CREATE DATABASE,ALTER DATABASE,DROP DATABASE')
396 global $sql_backquotes;
398 $date = date('Y-m-d H:i:s');
400 if ($tracking_set == '') {
401 $tracking_set = self
::$default_tracking_set;
404 require_once './libraries/export/sql.php';
408 if (self
::$add_drop_database == true) {
409 $create_sql .= self
::getLogComment() .
410 self
::getStatementDropDatabase(PMA_backquote($dbname)) . ";\n";
413 $create_sql .= self
::getLogComment() . $query;
418 "INSERT INTO" . self
::$pma_table . " (" .
424 "schema_snapshot, " .
430 '" . PMA_sqlAddslashes($dbname) . "',
431 '" . PMA_sqlAddslashes('') . "',
432 '" . PMA_sqlAddslashes($version) . "',
433 '" . PMA_sqlAddslashes($date) . "',
434 '" . PMA_sqlAddslashes($date) . "',
435 '" . PMA_sqlAddslashes('') . "',
436 '" . PMA_sqlAddslashes($create_sql) . "',
437 '" . PMA_sqlAddslashes("\n") . "',
438 '" . PMA_sqlAddslashes($tracking_set) . "' )";
440 $result = PMA_query_as_controluser($sql_query);
448 * Changes tracking of a table.
452 * @param string $dbname name of database
453 * @param string $tablename name of table
454 * @param string $version version
455 * @param integer $new_state the new state of tracking
457 * @return int result of SQL query
459 static private function changeTracking($dbname, $tablename, $version, $new_state)
462 " UPDATE " . self
::$pma_table .
463 " SET `tracking_active` = '" . $new_state . "' " .
464 " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' " .
465 " AND `table_name` = '" . PMA_sqlAddslashes($tablename) . "' " .
466 " AND `version` = '" . PMA_sqlAddslashes($version) . "' ";
468 $result = PMA_query_as_controluser($sql_query);
474 * Activates tracking of a table.
478 * @param string $dbname name of database
479 * @param string $tablename name of table
480 * @param string $version version
482 * @return int result of SQL query
484 static public function activateTracking($dbname, $tablename, $version)
486 return self
::changeTracking($dbname, $tablename, $version, 1);
491 * Deactivates tracking of a table.
495 * @param string $dbname name of database
496 * @param string $tablename name of table
497 * @param string $version version
499 * @return int result of SQL query
501 static public function deactivateTracking($dbname, $tablename, $version)
503 return self
::changeTracking($dbname, $tablename, $version, 0);
508 * Gets the newest version of a tracking job
509 * (in other words: gets the HEAD version).
513 * @param string $dbname name of database
514 * @param string $tablename name of table
515 * @param string $statement tracked statement
517 * @return int (-1 if no version exists | > 0 if a version exists)
519 static public function getVersion($dbname, $tablename, $statement = null)
522 " SELECT MAX(version) FROM " . self
::$pma_table .
523 " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' " .
524 " AND `table_name` = '" . PMA_sqlAddslashes($tablename) . "' ";
526 if ($statement != "") {
527 $sql_query .= " AND FIND_IN_SET('" . $statement . "',tracking) > 0" ;
529 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
530 if (isset($row[0])) {
533 if (! isset($version)) {
541 * Gets the record of a tracking job.
545 * @param string $dbname name of database
546 * @param string $tablename name of table
547 * @param string $version version number
549 * @return mixed record DDM log, DDL log, structure snapshot, tracked statements.
551 static public function getTrackedData($dbname, $tablename, $version)
553 if (! isset(self
::$pma_table)) {
556 $sql_query = " SELECT * FROM " . self
::$pma_table .
557 " WHERE `db_name` = '" . PMA_sqlAddslashes($dbname) . "' ";
558 if (! empty($tablename)) {
559 $sql_query .= " AND `table_name` = '" . PMA_sqlAddslashes($tablename) ."' ";
561 $sql_query .= " AND `version` = '" . PMA_sqlAddslashes($version) ."' ".
562 " ORDER BY `version` DESC ";
564 $mixed = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
567 $log_schema_entries = explode('# log ', $mixed['schema_sql']);
568 $log_data_entries = explode('# log ', $mixed['data_sql']);
570 $ddl_date_from = $date = date('Y-m-d H:i:s');
575 // Iterate tracked data definition statements
576 // For each log entry we want to get date, username and statement
577 foreach ($log_schema_entries as $log_entry) {
578 if (trim($log_entry) != '') {
579 $date = substr($log_entry, 0, 19);
580 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
582 $ddl_date_from = $date;
584 $statement = rtrim(strstr($log_entry, "\n"));
586 $ddlog[] = array( 'date' => $date,
587 'username'=> $username,
588 'statement' => $statement );
593 $date_from = $ddl_date_from;
594 $date_to = $ddl_date_to = $date;
596 $dml_date_from = $date_from;
601 // Iterate tracked data manipulation statements
602 // For each log entry we want to get date, username and statement
603 foreach ($log_data_entries as $log_entry) {
604 if (trim($log_entry) != '') {
605 $date = substr($log_entry, 0, 19);
606 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
608 $dml_date_from = $date;
610 $statement = rtrim(strstr($log_entry, "\n"));
612 $dmlog[] = array( 'date' => $date,
613 'username' => $username,
614 'statement' => $statement );
619 $dml_date_to = $date;
621 // Define begin and end of date range for both logs
622 if (strtotime($ddl_date_from) <= strtotime($dml_date_from)) {
623 $data['date_from'] = $ddl_date_from;
625 $data['date_from'] = $dml_date_from;
627 if (strtotime($ddl_date_to) >= strtotime($dml_date_to)) {
628 $data['date_to'] = $ddl_date_to;
630 $data['date_to'] = $dml_date_to;
632 $data['ddlog'] = $ddlog;
633 $data['dmlog'] = $dmlog;
634 $data['tracking'] = $mixed['tracking'];
635 $data['schema_snapshot'] = $mixed['schema_snapshot'];
642 * Parses a query. Gets
643 * - statement identifier (UPDATE, ALTER TABLE, ...)
644 * - type of statement, is it part of DDL or DML ?
648 * @todo: using PMA SQL Parser when possible
649 * @todo: support multi-table/view drops
651 * @param string $query
653 * @return mixed Array containing identifier, type and tablename.
656 static public function parseQuery($query)
659 // Usage of PMA_SQP does not work here
661 // require_once("libraries/sqlparser.lib.php");
662 // $parsed_sql = PMA_SQP_parse($query);
663 // $sql_info = PMA_SQP_analyze($parsed_sql);
665 $query = str_replace("\n", " ", $query);
666 $query = str_replace("\r", " ", $query);
668 $query = trim($query);
669 $query = trim($query, ' -');
671 $tokens = explode(" ", $query);
672 $tokens = array_map('strtoupper', $tokens);
674 // Parse USE statement, need it for SQL dump imports
675 if (substr($query, 0, 4) == 'USE ') {
676 $prefix = explode('USE ', $query);
677 $GLOBALS['db'] = self
::getTableName($prefix[1]);
684 $result['type'] = 'DDL';
686 // Parse CREATE VIEW statement
687 if (in_array('CREATE', $tokens) == true &&
688 in_array('VIEW', $tokens) == true &&
689 in_array('AS', $tokens) == true) {
690 $result['identifier'] = 'CREATE VIEW';
692 $index = array_search('VIEW', $tokens);
694 $result['tablename'] = strtolower(self
::getTableName($tokens[$index +
1]));
697 // Parse ALTER VIEW statement
698 if (in_array('ALTER', $tokens) == true &&
699 in_array('VIEW', $tokens) == true &&
700 in_array('AS', $tokens) == true &&
701 ! isset($result['identifier'])) {
702 $result['identifier'] = 'ALTER VIEW';
704 $index = array_search('VIEW', $tokens);
706 $result['tablename'] = strtolower(self
::getTableName($tokens[$index +
1]));
709 // Parse DROP VIEW statement
710 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP VIEW ') {
711 $result['identifier'] = 'DROP VIEW';
713 $prefix = explode('DROP VIEW ', $query);
714 $str = strstr($prefix[1], 'IF EXISTS');
716 if ($str == FALSE ) {
719 $result['tablename'] = self
::getTableName($str);
722 // Parse CREATE DATABASE statement
723 if (! isset($result['identifier']) && substr($query, 0, 15) == 'CREATE DATABASE') {
724 $result['identifier'] = 'CREATE DATABASE';
725 $str = str_replace('CREATE DATABASE', '', $query);
726 $str = str_replace('IF NOT EXISTS', '', $str);
728 $prefix = explode('DEFAULT ', $str);
730 $result['tablename'] = '';
731 $GLOBALS['db'] = self
::getTableName($prefix[0]);
734 // Parse ALTER DATABASE statement
735 if (! isset($result['identifier']) && substr($query, 0, 14) == 'ALTER DATABASE') {
736 $result['identifier'] = 'ALTER DATABASE';
737 $result['tablename'] = '';
740 // Parse DROP DATABASE statement
741 if (! isset($result['identifier']) && substr($query, 0, 13) == 'DROP DATABASE') {
742 $result['identifier'] = 'DROP DATABASE';
743 $str = str_replace('DROP DATABASE', '', $query);
744 $str = str_replace('IF EXISTS', '', $str);
745 $GLOBALS['db'] = self
::getTableName($str);
746 $result['tablename'] = '';
749 // Parse CREATE TABLE statement
750 if (! isset($result['identifier']) && substr($query, 0, 12) == 'CREATE TABLE' ) {
751 $result['identifier'] = 'CREATE TABLE';
752 $query = str_replace('IF NOT EXISTS', '', $query);
753 $prefix = explode('CREATE TABLE ', $query);
754 $suffix = explode('(', $prefix[1]);
755 $result['tablename'] = self
::getTableName($suffix[0]);
758 // Parse ALTER TABLE statement
759 if (! isset($result['identifier']) && substr($query, 0, 12) == 'ALTER TABLE ') {
760 $result['identifier'] = 'ALTER TABLE';
762 $prefix = explode('ALTER TABLE ', $query);
763 $suffix = explode(' ', $prefix[1]);
764 $result['tablename'] = self
::getTableName($suffix[0]);
767 // Parse DROP TABLE statement
768 if (! isset($result['identifier']) && substr($query, 0, 11) == 'DROP TABLE ') {
769 $result['identifier'] = 'DROP TABLE';
771 $prefix = explode('DROP TABLE ', $query);
772 $str = strstr($prefix[1], 'IF EXISTS');
774 if ($str == FALSE ) {
777 $result['tablename'] = self
::getTableName($str);
780 // Parse CREATE INDEX statement
781 if (! isset($result['identifier']) &&
782 ( substr($query, 0, 12) == 'CREATE INDEX' ||
783 substr($query, 0, 19) == 'CREATE UNIQUE INDEX' ||
784 substr($query, 0, 20) == 'CREATE SPATIAL INDEX'
787 $result['identifier'] = 'CREATE INDEX';
788 $prefix = explode('ON ', $query);
789 $suffix = explode('(', $prefix[1]);
790 $result['tablename'] = self
::getTableName($suffix[0]);
793 // Parse DROP INDEX statement
794 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP INDEX') {
795 $result['identifier'] = 'DROP INDEX';
796 $prefix = explode('ON ', $query);
797 $result['tablename'] = self
::getTableName($prefix[1]);
800 // Parse RENAME TABLE statement
801 if (! isset($result['identifier']) && substr($query, 0, 13) == 'RENAME TABLE ') {
802 $result['identifier'] = 'RENAME TABLE';
803 $prefix = explode('RENAME TABLE ', $query);
804 $names = explode(' TO ', $prefix[1]);
805 $result['tablename'] = self
::getTableName($names[0]);
806 $result["tablename_after_rename"] = self
::getTableName($names[1]);
813 if (! isset($result['identifier'])) {
814 $result["type"] = 'DML';
816 // Parse UPDATE statement
817 if (! isset($result['identifier']) && substr($query, 0, 6) == 'UPDATE') {
818 $result['identifier'] = 'UPDATE';
819 $prefix = explode('UPDATE ', $query);
820 $suffix = explode(' ', $prefix[1]);
821 $result['tablename'] = self
::getTableName($suffix[0]);
824 // Parse INSERT INTO statement
825 if (! isset($result['identifier']) && substr($query, 0, 11 ) == 'INSERT INTO') {
826 $result['identifier'] = 'INSERT';
827 $prefix = explode('INSERT INTO', $query);
828 $suffix = explode('(', $prefix[1]);
829 $result['tablename'] = self
::getTableName($suffix[0]);
832 // Parse DELETE statement
833 if (! isset($result['identifier']) && substr($query, 0, 6 ) == 'DELETE') {
834 $result['identifier'] = 'DELETE';
835 $prefix = explode('FROM ', $query);
836 $suffix = explode(' ', $prefix[1]);
837 $result['tablename'] = self
::getTableName($suffix[0]);
840 // Parse TRUNCATE statement
841 if (! isset($result['identifier']) && substr($query, 0, 8 ) == 'TRUNCATE') {
842 $result['identifier'] = 'TRUNCATE';
843 $prefix = explode('TRUNCATE', $query);
844 $result['tablename'] = self
::getTableName($prefix[1]);
852 * Analyzes a given SQL statement and saves tracking data.
856 * @param string $query a SQL query
858 static public function handleQuery($query)
860 // If query is marked as untouchable, leave
861 if (strstr($query, "/*NOTRACK*/")) {
865 if (! (substr($query, -1) == ';')) {
866 $query = $query . ";\n";
868 // Get some information about query
869 $result = self
::parseQuery($query);
872 $dbname = trim($GLOBALS['db'], '`');
873 // $dbname can be empty, for example when coming from Synchronize
874 // and this is a query for the remote server
875 if (empty($dbname)) {
879 // If we found a valid statement
880 if (isset($result['identifier'])) {
881 $version = self
::getVersion($dbname, $result['tablename'], $result['identifier']);
883 // If version not exists and auto-creation is enabled
884 if (self
::$version_auto_create == true
885 && self
::isTracked($dbname, $result['tablename']) == false
887 // Create the version
889 switch ($result['identifier']) {
891 self
::createVersion($dbname, $result['tablename'], '1');
894 self
::createVersion($dbname, $result['tablename'], '1', '', true);
896 case 'CREATE DATABASE':
897 self
::createDatabaseVersion($dbname, '1', $query);
903 if (self
::isTracked($dbname, $result['tablename']) && $version != -1) {
904 if ($result['type'] == 'DDL') {
905 $save_to = 'schema_sql';
906 } elseif ($result['type'] == 'DML') {
907 $save_to = 'data_sql';
911 $date = date('Y-m-d H:i:s');
913 // Cut off `dbname`. from query
914 $query = preg_replace('/`' . $dbname . '`\s?\./', '', $query);
916 // Add log information
917 $query = self
::getLogComment() . $query ;
919 // Mark it as untouchable
922 " UPDATE " . self
::$pma_table .
923 " SET " . PMA_backquote($save_to) ." = CONCAT( " . PMA_backquote($save_to) . ",'\n" . PMA_sqlAddslashes($query) . "') ," .
924 " `date_updated` = '" . $date . "' ";
926 // If table was renamed we have to change the tablename attribute in pma_tracking too
927 if ($result['identifier'] == 'RENAME TABLE') {
928 $sql_query .= ', `table_name` = \'' . PMA_sqlAddslashes($result['tablename_after_rename']) . '\' ';
931 // Save the tracking information only for
933 // 2. the table / view
937 " WHERE FIND_IN_SET('" . $result['identifier'] . "',tracking) > 0" .
938 " AND `db_name` = '" . PMA_sqlAddslashes($dbname) . "' " .
939 " AND `table_name` = '" . PMA_sqlAddslashes($result['tablename']) . "' " .
940 " AND `version` = '" . PMA_sqlAddslashes($version) . "' ";
942 $result = PMA_query_as_controluser($sql_query);