PMA_backquote is not needed for string literals
[phpmyadmin.git] / libraries / Tracker.class.php
blobaa176eafb7fd7b85e20041a7f174d2121d1cfef1
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
5 * @package phpMyAdmin
6 */
8 /**
9 * This class tracks changes on databases, tables and views.
10 * For more information please see phpMyAdmin/Documentation.html
12 * @package phpMyAdmin
14 * @todo use stristr instead of strstr
16 class PMA_Tracker
18 /**
19 * Whether tracking is ready.
21 static protected $enabled = false;
23 /**
24 * Defines the internal PMA table which contains tracking data.
26 * @access protected
27 * @var string
29 static protected $pma_table;
31 /**
32 * Defines the usage of DROP TABLE statment in SQL dumps.
34 * @access protected
35 * @var boolean
37 static protected $add_drop_table;
39 /**
40 * Defines the usage of DROP VIEW statment in SQL dumps.
42 * @access protected
43 * @var boolean
45 static protected $add_drop_view;
47 /**
48 * Defines the usage of DROP DATABASE statment in SQL dumps.
50 * @access protected
51 * @var boolean
53 static protected $add_drop_database;
55 /**
56 * Defines auto-creation of tracking versions.
58 * @var boolean
60 static protected $version_auto_create;
62 /**
63 * Defines the default set of tracked statements.
65 * @var string
67 static protected $default_tracking_set;
69 /**
70 * Initializes settings. See phpMyAdmin/Documentation.html.
72 * @static
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'];
92 /**
93 * Actually enables tracking. This needs to be done after all
94 * underlaying code is initialized.
96 * @static
99 static public function enable()
101 self::$enabled = true;
105 * Gets the on/off value of the Tracker module, starts initialization.
107 * @static
109 * @return boolean (true=on|false=off)
111 static public function isActive()
113 if (! self::$enabled) {
114 return false;
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']) {
122 return false;
124 self::init();
126 if (isset(self::$pma_table)) {
127 return true;
128 } else {
129 return false;
134 * Returns a simple DROP TABLE statement.
136 * @param string $tablename
137 * @return string
139 static public function getStatementDropTable($tablename)
141 return 'DROP TABLE IF EXISTS ' . $tablename;
145 * Returns a simple DROP VIEW statement.
147 * @param string $viewname
148 * @return string
150 static public function getStatementDropView($viewname)
152 return 'DROP VIEW IF EXISTS ' . $viewname;
156 * Returns a simple DROP DATABASE statement.
158 * @param string $dbname
159 * @return string
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.
169 * @static
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];
181 else {
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);
192 return $tablename;
197 * Gets the tracking status of a table, is it active or deactive ?
199 * @static
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) {
209 return false;
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']) {
217 return false;
220 $sql_query =
221 " SELECT tracking_active FROM " . self::$pma_table .
222 " WHERE db_name = '" . PMA_sqlAddSlashes($dbname) . "' " .
223 " AND 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) {
229 return true;
230 } else {
231 return false;
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).
251 * @static
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
276 $sql_query = '
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)) {
282 $columns[] = $row;
285 $sql_query = '
286 SHOW INDEX FROM ' . PMA_backquote($dbname) . '.' . PMA_backquote($tablename);
288 $sql_result = PMA_DBI_query($sql_query);
290 $indexes = array();
292 while($row = PMA_DBI_fetch_array($sql_result)) {
293 $indexes[] = $row;
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;
302 $create_sql = "";
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", "");
318 // Save version
320 $sql_query =
321 "/*NOTRACK*/\n" .
322 "INSERT INTO" . self::$pma_table . " (" .
323 "db_name, " .
324 "table_name, " .
325 "version, " .
326 "date_created, " .
327 "date_updated, " .
328 "schema_snapshot, " .
329 "schema_sql, " .
330 "data_sql, " .
331 "tracking " .
332 ") " .
333 "values (
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);
346 if ($result) {
347 // Deactivate previous version
348 self::deactivateTracking($dbname, $tablename, ($version - 1));
351 return $result;
356 * Removes all tracking data for a table
358 * @static
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)
367 $sql_query =
368 "/*NOTRACK*/\n" .
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);
372 return $result;
376 * Creates tracking version of a database
377 * (in other words: create a job to track future changes on the database).
379 * @static
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';
400 $create_sql = "";
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;
409 // Save version
410 $sql_query =
411 "/*NOTRACK*/\n" .
412 "INSERT INTO" . self::$pma_table . " (" .
413 "db_name, " .
414 "table_name, " .
415 "version, " .
416 "date_created, " .
417 "date_updated, " .
418 "schema_snapshot, " .
419 "schema_sql, " .
420 "data_sql, " .
421 "tracking " .
422 ") " .
423 "values (
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);
436 return $result;
442 * Changes tracking of a table.
444 * @static
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)
455 $sql_query =
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);
464 return $result;
468 * Changes tracking data of a table.
470 * @static
472 * @param string $dbname name of database
473 * @param string $tablename name of table
474 * @param string $version version
475 * @param string $type type of data(DDL || DML)
476 * @param string || array $new_data the new tracking data
478 * @return bool result of change
480 static public function changeTrackingData($dbname, $tablename, $version, $type, $new_data)
482 if ($type == 'DDL')
483 $save_to = 'schema_sql';
484 elseif ($type == 'DML')
485 $save_to = 'data_sql';
486 else
487 return false;
489 $date = date('Y-m-d H:i:s');
491 $new_data_processed = '';
492 if (is_array($new_data)) {
493 foreach ($new_data as $data) {
494 $new_data_processed .= '# log ' . $date . ' ' . $data['username'] . PMA_sqlAddSlashes($data['statement']) . "\n";
496 } else {
497 $new_data_processed = $new_data;
500 $sql_query =
501 " UPDATE " . self::$pma_table .
502 " SET `" . $save_to . "` = '" . $new_data_processed . "' " .
503 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
504 " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' " .
505 " AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
507 $result = PMA_query_as_controluser($sql_query);
509 return $result;
513 * Activates tracking of a table.
515 * @static
517 * @param string $dbname name of database
518 * @param string $tablename name of table
519 * @param string $version version
521 * @return int result of SQL query
523 static public function activateTracking($dbname, $tablename, $version)
525 return self::changeTracking($dbname, $tablename, $version, 1);
530 * Deactivates tracking of a table.
532 * @static
534 * @param string $dbname name of database
535 * @param string $tablename name of table
536 * @param string $version version
538 * @return int result of SQL query
540 static public function deactivateTracking($dbname, $tablename, $version)
542 return self::changeTracking($dbname, $tablename, $version, 0);
547 * Gets the newest version of a tracking job
548 * (in other words: gets the HEAD version).
550 * @static
552 * @param string $dbname name of database
553 * @param string $tablename name of table
554 * @param string $statement tracked statement
556 * @return int (-1 if no version exists | > 0 if a version exists)
558 static public function getVersion($dbname, $tablename, $statement = null)
560 $sql_query =
561 " SELECT MAX(version) FROM " . self::$pma_table .
562 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
563 " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' ";
565 if ($statement != "") {
566 $sql_query .= " AND FIND_IN_SET('" . $statement . "',tracking) > 0" ;
568 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
569 if (isset($row[0])) {
570 $version = $row[0];
572 if (! isset($version)) {
573 $version = -1;
575 return $version;
580 * Gets the record of a tracking job.
582 * @static
584 * @param string $dbname name of database
585 * @param string $tablename name of table
586 * @param string $version version number
588 * @return mixed record DDM log, DDL log, structure snapshot, tracked statements.
590 static public function getTrackedData($dbname, $tablename, $version)
592 if (! isset(self::$pma_table)) {
593 self::init();
595 $sql_query = " SELECT * FROM " . self::$pma_table .
596 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' ";
597 if (! empty($tablename)) {
598 $sql_query .= " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) ."' ";
600 $sql_query .= " AND `version` = '" . PMA_sqlAddSlashes($version) ."' ".
601 " ORDER BY `version` DESC ";
603 $mixed = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
605 // Parse log
606 $log_schema_entries = explode('# log ', $mixed['schema_sql']);
607 $log_data_entries = explode('# log ', $mixed['data_sql']);
609 $ddl_date_from = $date = date('Y-m-d H:i:s');
611 $ddlog = array();
612 $i = 0;
614 // Iterate tracked data definition statements
615 // For each log entry we want to get date, username and statement
616 foreach ($log_schema_entries as $log_entry) {
617 if (trim($log_entry) != '') {
618 $date = substr($log_entry, 0, 19);
619 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
620 if ($i == 0) {
621 $ddl_date_from = $date;
623 $statement = rtrim(strstr($log_entry, "\n"));
625 $ddlog[] = array( 'date' => $date,
626 'username'=> $username,
627 'statement' => $statement );
628 $i++;
632 $date_from = $ddl_date_from;
633 $date_to = $ddl_date_to = $date;
635 $dml_date_from = $date_from;
637 $dmlog = array();
638 $i = 0;
640 // Iterate tracked data manipulation statements
641 // For each log entry we want to get date, username and statement
642 foreach ($log_data_entries as $log_entry) {
643 if (trim($log_entry) != '') {
644 $date = substr($log_entry, 0, 19);
645 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
646 if ($i == 0) {
647 $dml_date_from = $date;
649 $statement = rtrim(strstr($log_entry, "\n"));
651 $dmlog[] = array( 'date' => $date,
652 'username' => $username,
653 'statement' => $statement );
654 $i++;
658 $dml_date_to = $date;
660 // Define begin and end of date range for both logs
661 if (strtotime($ddl_date_from) <= strtotime($dml_date_from)) {
662 $data['date_from'] = $ddl_date_from;
663 } else {
664 $data['date_from'] = $dml_date_from;
666 if (strtotime($ddl_date_to) >= strtotime($dml_date_to)) {
667 $data['date_to'] = $ddl_date_to;
668 } else {
669 $data['date_to'] = $dml_date_to;
671 $data['ddlog'] = $ddlog;
672 $data['dmlog'] = $dmlog;
673 $data['tracking'] = $mixed['tracking'];
674 $data['schema_snapshot'] = $mixed['schema_snapshot'];
676 return $data;
681 * Parses a query. Gets
682 * - statement identifier (UPDATE, ALTER TABLE, ...)
683 * - type of statement, is it part of DDL or DML ?
684 * - tablename
686 * @static
687 * @todo: using PMA SQL Parser when possible
688 * @todo: support multi-table/view drops
690 * @param string $query
692 * @return mixed Array containing identifier, type and tablename.
695 static public function parseQuery($query)
698 // Usage of PMA_SQP does not work here
700 // require_once("libraries/sqlparser.lib.php");
701 // $parsed_sql = PMA_SQP_parse($query);
702 // $sql_info = PMA_SQP_analyze($parsed_sql);
704 $query = str_replace("\n", " ", $query);
705 $query = str_replace("\r", " ", $query);
707 $query = trim($query);
708 $query = trim($query, ' -');
710 $tokens = explode(" ", $query);
711 $tokens = array_map('strtoupper', $tokens);
713 // Parse USE statement, need it for SQL dump imports
714 if (substr($query, 0, 4) == 'USE ') {
715 $prefix = explode('USE ', $query);
716 $GLOBALS['db'] = self::getTableName($prefix[1]);
720 * DDL statements
723 $result['type'] = 'DDL';
725 // Parse CREATE VIEW statement
726 if (in_array('CREATE', $tokens) == true &&
727 in_array('VIEW', $tokens) == true &&
728 in_array('AS', $tokens) == true) {
729 $result['identifier'] = 'CREATE VIEW';
731 $index = array_search('VIEW', $tokens);
733 $result['tablename'] = strtolower(self::getTableName($tokens[$index + 1]));
736 // Parse ALTER VIEW statement
737 if (in_array('ALTER', $tokens) == true &&
738 in_array('VIEW', $tokens) == true &&
739 in_array('AS', $tokens) == true &&
740 ! isset($result['identifier'])) {
741 $result['identifier'] = 'ALTER VIEW';
743 $index = array_search('VIEW', $tokens);
745 $result['tablename'] = strtolower(self::getTableName($tokens[$index + 1]));
748 // Parse DROP VIEW statement
749 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP VIEW ') {
750 $result['identifier'] = 'DROP VIEW';
752 $prefix = explode('DROP VIEW ', $query);
753 $str = strstr($prefix[1], 'IF EXISTS');
755 if ($str == false ) {
756 $str = $prefix[1];
758 $result['tablename'] = self::getTableName($str);
761 // Parse CREATE DATABASE statement
762 if (! isset($result['identifier']) && substr($query, 0, 15) == 'CREATE DATABASE') {
763 $result['identifier'] = 'CREATE DATABASE';
764 $str = str_replace('CREATE DATABASE', '', $query);
765 $str = str_replace('IF NOT EXISTS', '', $str);
767 $prefix = explode('DEFAULT ', $str);
769 $result['tablename'] = '';
770 $GLOBALS['db'] = self::getTableName($prefix[0]);
773 // Parse ALTER DATABASE statement
774 if (! isset($result['identifier']) && substr($query, 0, 14) == 'ALTER DATABASE') {
775 $result['identifier'] = 'ALTER DATABASE';
776 $result['tablename'] = '';
779 // Parse DROP DATABASE statement
780 if (! isset($result['identifier']) && substr($query, 0, 13) == 'DROP DATABASE') {
781 $result['identifier'] = 'DROP DATABASE';
782 $str = str_replace('DROP DATABASE', '', $query);
783 $str = str_replace('IF EXISTS', '', $str);
784 $GLOBALS['db'] = self::getTableName($str);
785 $result['tablename'] = '';
788 // Parse CREATE TABLE statement
789 if (! isset($result['identifier']) && substr($query, 0, 12) == 'CREATE TABLE' ) {
790 $result['identifier'] = 'CREATE TABLE';
791 $query = str_replace('IF NOT EXISTS', '', $query);
792 $prefix = explode('CREATE TABLE ', $query);
793 $suffix = explode('(', $prefix[1]);
794 $result['tablename'] = self::getTableName($suffix[0]);
797 // Parse ALTER TABLE statement
798 if (! isset($result['identifier']) && substr($query, 0, 12) == 'ALTER TABLE ') {
799 $result['identifier'] = 'ALTER TABLE';
801 $prefix = explode('ALTER TABLE ', $query);
802 $suffix = explode(' ', $prefix[1]);
803 $result['tablename'] = self::getTableName($suffix[0]);
806 // Parse DROP TABLE statement
807 if (! isset($result['identifier']) && substr($query, 0, 11) == 'DROP TABLE ') {
808 $result['identifier'] = 'DROP TABLE';
810 $prefix = explode('DROP TABLE ', $query);
811 $str = strstr($prefix[1], 'IF EXISTS');
813 if ($str == false ) {
814 $str = $prefix[1];
816 $result['tablename'] = self::getTableName($str);
819 // Parse CREATE INDEX statement
820 if (! isset($result['identifier']) &&
821 ( substr($query, 0, 12) == 'CREATE INDEX' ||
822 substr($query, 0, 19) == 'CREATE UNIQUE INDEX' ||
823 substr($query, 0, 20) == 'CREATE SPATIAL INDEX'
826 $result['identifier'] = 'CREATE INDEX';
827 $prefix = explode('ON ', $query);
828 $suffix = explode('(', $prefix[1]);
829 $result['tablename'] = self::getTableName($suffix[0]);
832 // Parse DROP INDEX statement
833 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP INDEX') {
834 $result['identifier'] = 'DROP INDEX';
835 $prefix = explode('ON ', $query);
836 $result['tablename'] = self::getTableName($prefix[1]);
839 // Parse RENAME TABLE statement
840 if (! isset($result['identifier']) && substr($query, 0, 13) == 'RENAME TABLE ') {
841 $result['identifier'] = 'RENAME TABLE';
842 $prefix = explode('RENAME TABLE ', $query);
843 $names = explode(' TO ', $prefix[1]);
844 $result['tablename'] = self::getTableName($names[0]);
845 $result["tablename_after_rename"] = self::getTableName($names[1]);
849 * DML statements
852 if (! isset($result['identifier'])) {
853 $result["type"] = 'DML';
855 // Parse UPDATE statement
856 if (! isset($result['identifier']) && substr($query, 0, 6) == 'UPDATE') {
857 $result['identifier'] = 'UPDATE';
858 $prefix = explode('UPDATE ', $query);
859 $suffix = explode(' ', $prefix[1]);
860 $result['tablename'] = self::getTableName($suffix[0]);
863 // Parse INSERT INTO statement
864 if (! isset($result['identifier']) && substr($query, 0, 11 ) == 'INSERT INTO') {
865 $result['identifier'] = 'INSERT';
866 $prefix = explode('INSERT INTO', $query);
867 $suffix = explode('(', $prefix[1]);
868 $result['tablename'] = self::getTableName($suffix[0]);
871 // Parse DELETE statement
872 if (! isset($result['identifier']) && substr($query, 0, 6 ) == 'DELETE') {
873 $result['identifier'] = 'DELETE';
874 $prefix = explode('FROM ', $query);
875 $suffix = explode(' ', $prefix[1]);
876 $result['tablename'] = self::getTableName($suffix[0]);
879 // Parse TRUNCATE statement
880 if (! isset($result['identifier']) && substr($query, 0, 8 ) == 'TRUNCATE') {
881 $result['identifier'] = 'TRUNCATE';
882 $prefix = explode('TRUNCATE', $query);
883 $result['tablename'] = self::getTableName($prefix[1]);
886 return $result;
891 * Analyzes a given SQL statement and saves tracking data.
894 * @static
895 * @param string $query a SQL query
897 static public function handleQuery($query)
899 // If query is marked as untouchable, leave
900 if (strstr($query, "/*NOTRACK*/")) {
901 return false;
904 if (! (substr($query, -1) == ';')) {
905 $query = $query . ";\n";
907 // Get some information about query
908 $result = self::parseQuery($query);
910 // Get database name
911 $dbname = trim($GLOBALS['db'], '`');
912 // $dbname can be empty, for example when coming from Synchronize
913 // and this is a query for the remote server
914 if (empty($dbname)) {
915 return false;
918 // If we found a valid statement
919 if (isset($result['identifier'])) {
920 $version = self::getVersion($dbname, $result['tablename'], $result['identifier']);
922 // If version not exists and auto-creation is enabled
923 if (self::$version_auto_create == true
924 && self::isTracked($dbname, $result['tablename']) == false
925 && $version == -1) {
926 // Create the version
928 switch ($result['identifier']) {
929 case 'CREATE TABLE':
930 self::createVersion($dbname, $result['tablename'], '1');
931 break;
932 case 'CREATE VIEW':
933 self::createVersion($dbname, $result['tablename'], '1', '', true);
934 break;
935 case 'CREATE DATABASE':
936 self::createDatabaseVersion($dbname, '1', $query);
937 break;
938 } // end switch
941 // If version exists
942 if (self::isTracked($dbname, $result['tablename']) && $version != -1) {
943 if ($result['type'] == 'DDL') {
944 $save_to = 'schema_sql';
945 } elseif ($result['type'] == 'DML') {
946 $save_to = 'data_sql';
947 } else {
948 $save_to = '';
950 $date = date('Y-m-d H:i:s');
952 // Cut off `dbname`. from query
953 $query = preg_replace('/`' . $dbname . '`\s?\./', '', $query);
955 // Add log information
956 $query = self::getLogComment() . $query ;
958 // Mark it as untouchable
959 $sql_query =
960 " /*NOTRACK*/\n" .
961 " UPDATE " . self::$pma_table .
962 " SET " . PMA_backquote($save_to) ." = CONCAT( " . PMA_backquote($save_to) . ",'\n" . PMA_sqlAddSlashes($query) . "') ," .
963 " `date_updated` = '" . $date . "' ";
965 // If table was renamed we have to change the tablename attribute in pma_tracking too
966 if ($result['identifier'] == 'RENAME TABLE') {
967 $sql_query .= ', `table_name` = \'' . PMA_sqlAddSlashes($result['tablename_after_rename']) . '\' ';
970 // Save the tracking information only for
971 // 1. the database
972 // 2. the table / view
973 // 3. the statements
974 // we want to track
975 $sql_query .=
976 " WHERE FIND_IN_SET('" . $result['identifier'] . "',tracking) > 0" .
977 " AND `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
978 " AND `table_name` = '" . PMA_sqlAddSlashes($result['tablename']) . "' " .
979 " AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
981 $result = PMA_query_as_controluser($sql_query);