Make tracking compatible with Drizzle
[phpmyadmin.git] / libraries / Tracker.class.php
blob3cf4c7953473816a64985cd42da840333493aa81
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 * Flags copied from `tracking` column definition in `pma_tracking` table.
71 * Used for column type conversion in Drizzle.
73 * @var array
75 static private $tracking_set_flags = array('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE DATABASE',
76 'ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX',
77 'DROP INDEX','CREATE VIEW','ALTER VIEW','DROP VIEW');
79 /**
80 * Initializes settings. See phpMyAdmin/Documentation.html.
82 * @static
85 static protected function init()
87 self::$pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
88 PMA_backquote($GLOBALS['cfg']['Server']['tracking']);
90 self::$add_drop_table = $GLOBALS['cfg']['Server']['tracking_add_drop_table'];
92 self::$add_drop_view = $GLOBALS['cfg']['Server']['tracking_add_drop_view'];
94 self::$add_drop_database = $GLOBALS['cfg']['Server']['tracking_add_drop_database'];
96 self::$default_tracking_set = $GLOBALS['cfg']['Server']['tracking_default_statements'];
98 self::$version_auto_create = $GLOBALS['cfg']['Server']['tracking_version_auto_create'];
103 * Actually enables tracking. This needs to be done after all
104 * underlaying code is initialized.
106 * @static
109 static public function enable()
111 self::$enabled = true;
115 * Gets the on/off value of the Tracker module, starts initialization.
117 * @static
119 * @return boolean (true=on|false=off)
121 static public function isActive()
123 if (! self::$enabled) {
124 return false;
126 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
127 self::$enabled = false;
128 $cfgRelation = PMA_getRelationsParam();
129 /* Restore original state */
130 self::$enabled = true;
131 if (! $cfgRelation['trackingwork']) {
132 return false;
134 self::init();
136 if (isset(self::$pma_table)) {
137 return true;
138 } else {
139 return false;
144 * Returns a simple DROP TABLE statement.
146 * @param string $tablename
147 * @return string
149 static public function getStatementDropTable($tablename)
151 return 'DROP TABLE IF EXISTS ' . $tablename;
155 * Returns a simple DROP VIEW statement.
157 * @param string $viewname
158 * @return string
160 static public function getStatementDropView($viewname)
162 return 'DROP VIEW IF EXISTS ' . $viewname;
166 * Returns a simple DROP DATABASE statement.
168 * @param string $dbname
169 * @return string
171 static public function getStatementDropDatabase($dbname)
173 return 'DROP DATABASE IF EXISTS ' . $dbname;
177 * Parses the name of a table from a SQL statement substring.
179 * @static
181 * @param string $string part of SQL statement
183 * @return string the name of table
185 static protected function getTableName($string)
187 if (strstr($string, '.')) {
188 $temp = explode('.', $string);
189 $tablename = $temp[1];
191 else {
192 $tablename = $string;
195 $str = explode("\n", $tablename);
196 $tablename = $str[0];
198 $tablename = str_replace(';', '', $tablename);
199 $tablename = str_replace('`', '', $tablename);
200 $tablename = trim($tablename);
202 return $tablename;
207 * Gets the tracking status of a table, is it active or deactive ?
209 * @static
211 * @param string $dbname name of database
212 * @param string $tablename name of table
214 * @return boolean true or false
216 static public function isTracked($dbname, $tablename)
218 if (! self::$enabled) {
219 return false;
221 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
222 self::$enabled = false;
223 $cfgRelation = PMA_getRelationsParam();
224 /* Restore original state */
225 self::$enabled = true;
226 if (! $cfgRelation['trackingwork']) {
227 return false;
230 $sql_query =
231 " SELECT tracking_active FROM " . self::$pma_table .
232 " WHERE db_name = '" . PMA_sqlAddSlashes($dbname) . "' " .
233 " AND table_name = '" . PMA_sqlAddSlashes($tablename) . "' " .
234 " ORDER BY version DESC";
236 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
238 if (isset($row['tracking_active']) && $row['tracking_active'] == 1) {
239 return true;
240 } else {
241 return false;
246 * Returns the comment line for the log.
248 * @return string Comment, contains date and username
250 static public function getLogComment()
252 $date = date('Y-m-d H:i:s');
254 return "# log " . $date . " " . $GLOBALS['cfg']['Server']['user'] . "\n";
258 * Creates tracking version of a table / view
259 * (in other words: create a job to track future changes on the table).
261 * @static
263 * @param string $dbname name of database
264 * @param string $tablename name of table
265 * @param string $version version
266 * @param string $tracking_set set of tracking statements
267 * @param bool $is_view if table is a view
269 * @return int result of version insertion
271 static public function createVersion($dbname, $tablename, $version, $tracking_set = '', $is_view = false)
273 global $sql_backquotes;
275 if ($tracking_set == '') {
276 $tracking_set = self::$default_tracking_set;
279 require_once './libraries/export/sql.php';
281 $sql_backquotes = true;
283 $date = date('Y-m-d H:i:s');
285 // Get data definition snapshot of table
287 $columns = PMA_DBI_get_columns($dbname, $tablename, true);
288 // int indices to reduce size
289 $columns = array_values($columns);
290 // remove Privileges to reduce size
291 for ($i = 0; $i < count($columns); $i++) {
292 unset($columns[$i]['Privileges']);
295 $indexes = PMA_DBI_get_table_indexes($dbname, $tablename);
297 $snapshot = array('COLUMNS' => $columns, 'INDEXES' => $indexes);
298 $snapshot = serialize($snapshot);
300 // Get DROP TABLE / DROP VIEW and CREATE TABLE SQL statements
301 $sql_backquotes = true;
303 $create_sql = "";
305 if (self::$add_drop_table == true && $is_view == false) {
306 $create_sql .= self::getLogComment() .
307 self::getStatementDropTable(PMA_backquote($tablename)) . ";\n";
311 if (self::$add_drop_view == true && $is_view == true) {
312 $create_sql .= self::getLogComment() .
313 self::getStatementDropView(PMA_backquote($tablename)) . ";\n";
316 $create_sql .= self::getLogComment() .
317 PMA_getTableDef($dbname, $tablename, "\n", "");
319 // Save version
321 $sql_query =
322 "/*NOTRACK*/\n" .
323 "INSERT INTO" . self::$pma_table . " (" .
324 "db_name, " .
325 "table_name, " .
326 "version, " .
327 "date_created, " .
328 "date_updated, " .
329 "schema_snapshot, " .
330 "schema_sql, " .
331 "data_sql, " .
332 "tracking " .
333 ") " .
334 "values (
335 '" . PMA_sqlAddSlashes($dbname) . "',
336 '" . PMA_sqlAddSlashes($tablename) . "',
337 '" . PMA_sqlAddSlashes($version) . "',
338 '" . PMA_sqlAddSlashes($date) . "',
339 '" . PMA_sqlAddSlashes($date) . "',
340 '" . PMA_sqlAddSlashes($snapshot) . "',
341 '" . PMA_sqlAddSlashes($create_sql) . "',
342 '" . PMA_sqlAddSlashes("\n") . "',
343 '" . PMA_sqlAddSlashes($tracking_set) . "' )";
345 $result = PMA_query_as_controluser($sql_query);
347 if ($result) {
348 // Deactivate previous version
349 self::deactivateTracking($dbname, $tablename, ($version - 1));
352 return $result;
357 * Removes all tracking data for a table
359 * @static
361 * @param string $dbname name of database
362 * @param string $tablename name of table
364 * @return int result of version insertion
366 static public function deleteTracking($dbname, $tablename)
368 $sql_query =
369 "/*NOTRACK*/\n" .
370 "DELETE FROM " . self::$pma_table . " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "'";
371 $result = PMA_query_as_controluser($sql_query);
373 return $result;
377 * Creates tracking version of a database
378 * (in other words: create a job to track future changes on the database).
380 * @static
382 * @param string $dbname name of database
383 * @param string $version version
384 * @param string $query query
385 * @param string $tracking_set set of tracking statements
387 * @return int result of version insertion
389 static public function createDatabaseVersion($dbname, $version, $query, $tracking_set = 'CREATE DATABASE,ALTER DATABASE,DROP DATABASE')
391 $date = date('Y-m-d H:i:s');
393 if ($tracking_set == '') {
394 $tracking_set = self::$default_tracking_set;
397 require_once './libraries/export/sql.php';
399 $create_sql = "";
401 if (self::$add_drop_database == true) {
402 $create_sql .= self::getLogComment() .
403 self::getStatementDropDatabase(PMA_backquote($dbname)) . ";\n";
406 $create_sql .= self::getLogComment() . $query;
408 // Save version
409 $sql_query =
410 "/*NOTRACK*/\n" .
411 "INSERT INTO" . self::$pma_table . " (" .
412 "db_name, " .
413 "table_name, " .
414 "version, " .
415 "date_created, " .
416 "date_updated, " .
417 "schema_snapshot, " .
418 "schema_sql, " .
419 "data_sql, " .
420 "tracking " .
421 ") " .
422 "values (
423 '" . PMA_sqlAddSlashes($dbname) . "',
424 '" . PMA_sqlAddSlashes('') . "',
425 '" . PMA_sqlAddSlashes($version) . "',
426 '" . PMA_sqlAddSlashes($date) . "',
427 '" . PMA_sqlAddSlashes($date) . "',
428 '" . PMA_sqlAddSlashes('') . "',
429 '" . PMA_sqlAddSlashes($create_sql) . "',
430 '" . PMA_sqlAddSlashes("\n") . "',
431 '" . PMA_sqlAddSlashes(self::transformTrackingSet($tracking_set)) . "' )";
433 $result = PMA_query_as_controluser($sql_query);
435 return $result;
441 * Changes tracking of a table.
443 * @static
445 * @param string $dbname name of database
446 * @param string $tablename name of table
447 * @param string $version version
448 * @param integer $new_state the new state of tracking
450 * @return int result of SQL query
452 static private function changeTracking($dbname, $tablename, $version, $new_state)
454 $sql_query =
455 " UPDATE " . self::$pma_table .
456 " SET `tracking_active` = '" . $new_state . "' " .
457 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
458 " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' " .
459 " AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
461 $result = PMA_query_as_controluser($sql_query);
463 return $result;
467 * Changes tracking data of a table.
469 * @static
471 * @param string $dbname name of database
472 * @param string $tablename name of table
473 * @param string $version version
474 * @param string $type type of data(DDL || DML)
475 * @param string|array $new_data the new tracking data
477 * @return bool result of change
479 static public function changeTrackingData($dbname, $tablename, $version, $type, $new_data)
481 if ($type == 'DDL')
482 $save_to = 'schema_sql';
483 elseif ($type == 'DML')
484 $save_to = 'data_sql';
485 else
486 return false;
488 $date = date('Y-m-d H:i:s');
490 $new_data_processed = '';
491 if (is_array($new_data)) {
492 foreach ($new_data as $data) {
493 $new_data_processed .= '# log ' . $date . ' ' . $data['username'] . PMA_sqlAddSlashes($data['statement']) . "\n";
495 } else {
496 $new_data_processed = $new_data;
499 $sql_query =
500 " UPDATE " . self::$pma_table .
501 " SET `" . $save_to . "` = '" . $new_data_processed . "' " .
502 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
503 " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' " .
504 " AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
506 $result = PMA_query_as_controluser($sql_query);
508 return $result;
512 * Activates tracking of a table.
514 * @static
516 * @param string $dbname name of database
517 * @param string $tablename name of table
518 * @param string $version version
520 * @return int result of SQL query
522 static public function activateTracking($dbname, $tablename, $version)
524 return self::changeTracking($dbname, $tablename, $version, 1);
529 * Deactivates tracking of a table.
531 * @static
533 * @param string $dbname name of database
534 * @param string $tablename name of table
535 * @param string $version version
537 * @return int result of SQL query
539 static public function deactivateTracking($dbname, $tablename, $version)
541 return self::changeTracking($dbname, $tablename, $version, 0);
546 * Gets the newest version of a tracking job
547 * (in other words: gets the HEAD version).
549 * @static
551 * @param string $dbname name of database
552 * @param string $tablename name of table
553 * @param string $statement tracked statement
555 * @return int (-1 if no version exists | > 0 if a version exists)
557 static public function getVersion($dbname, $tablename, $statement = null)
559 $sql_query =
560 " SELECT MAX(version) FROM " . self::$pma_table .
561 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
562 " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' ";
564 if ($statement != "") {
565 $sql_query .= PMA_DRIZZLE
566 ? ' AND tracking & ' . self::transformTrackingSet($statement) . ' <> 0'
567 : " AND FIND_IN_SET('" . $statement . "',tracking) > 0" ;
569 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
570 if (isset($row[0])) {
571 $version = $row[0];
573 if (! isset($version)) {
574 $version = -1;
576 return $version;
581 * Gets the record of a tracking job.
583 * @static
585 * @param string $dbname name of database
586 * @param string $tablename name of table
587 * @param string $version version number
589 * @return mixed record DDM log, DDL log, structure snapshot, tracked statements.
591 static public function getTrackedData($dbname, $tablename, $version)
593 if (! isset(self::$pma_table)) {
594 self::init();
596 $sql_query = " SELECT * FROM " . self::$pma_table .
597 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' ";
598 if (! empty($tablename)) {
599 $sql_query .= " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) ."' ";
601 $sql_query .= " AND `version` = '" . PMA_sqlAddSlashes($version) ."' ".
602 " ORDER BY `version` DESC ";
604 $mixed = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
606 // Parse log
607 $log_schema_entries = explode('# log ', $mixed['schema_sql']);
608 $log_data_entries = explode('# log ', $mixed['data_sql']);
610 $ddl_date_from = $date = date('Y-m-d H:i:s');
612 $ddlog = array();
613 $i = 0;
615 // Iterate tracked data definition statements
616 // For each log entry we want to get date, username and statement
617 foreach ($log_schema_entries as $log_entry) {
618 if (trim($log_entry) != '') {
619 $date = substr($log_entry, 0, 19);
620 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
621 if ($i == 0) {
622 $ddl_date_from = $date;
624 $statement = rtrim(strstr($log_entry, "\n"));
626 $ddlog[] = array( 'date' => $date,
627 'username'=> $username,
628 'statement' => $statement );
629 $i++;
633 $date_from = $ddl_date_from;
634 $date_to = $ddl_date_to = $date;
636 $dml_date_from = $date_from;
638 $dmlog = array();
639 $i = 0;
641 // Iterate tracked data manipulation statements
642 // For each log entry we want to get date, username and statement
643 foreach ($log_data_entries as $log_entry) {
644 if (trim($log_entry) != '') {
645 $date = substr($log_entry, 0, 19);
646 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
647 if ($i == 0) {
648 $dml_date_from = $date;
650 $statement = rtrim(strstr($log_entry, "\n"));
652 $dmlog[] = array( 'date' => $date,
653 'username' => $username,
654 'statement' => $statement );
655 $i++;
659 $dml_date_to = $date;
661 // Define begin and end of date range for both logs
662 if (strtotime($ddl_date_from) <= strtotime($dml_date_from)) {
663 $data['date_from'] = $ddl_date_from;
664 } else {
665 $data['date_from'] = $dml_date_from;
667 if (strtotime($ddl_date_to) >= strtotime($dml_date_to)) {
668 $data['date_to'] = $ddl_date_to;
669 } else {
670 $data['date_to'] = $dml_date_to;
672 $data['ddlog'] = $ddlog;
673 $data['dmlog'] = $dmlog;
674 $data['tracking'] = self::transformTrackingSet($mixed['tracking']);
675 $data['schema_snapshot'] = $mixed['schema_snapshot'];
677 return $data;
682 * Parses a query. Gets
683 * - statement identifier (UPDATE, ALTER TABLE, ...)
684 * - type of statement, is it part of DDL or DML ?
685 * - tablename
687 * @static
688 * @todo: using PMA SQL Parser when possible
689 * @todo: support multi-table/view drops
691 * @param string $query
693 * @return mixed Array containing identifier, type and tablename.
696 static public function parseQuery($query)
699 // Usage of PMA_SQP does not work here
701 // require_once("libraries/sqlparser.lib.php");
702 // $parsed_sql = PMA_SQP_parse($query);
703 // $sql_info = PMA_SQP_analyze($parsed_sql);
705 $query = str_replace("\n", " ", $query);
706 $query = str_replace("\r", " ", $query);
708 $query = trim($query);
709 $query = trim($query, ' -');
711 $tokens = explode(" ", $query);
712 $tokens = array_map('strtoupper', $tokens);
714 // Parse USE statement, need it for SQL dump imports
715 if (substr($query, 0, 4) == 'USE ') {
716 $prefix = explode('USE ', $query);
717 $GLOBALS['db'] = self::getTableName($prefix[1]);
721 * DDL statements
724 $result['type'] = 'DDL';
726 // Parse CREATE VIEW statement
727 if (in_array('CREATE', $tokens) == true &&
728 in_array('VIEW', $tokens) == true &&
729 in_array('AS', $tokens) == true) {
730 $result['identifier'] = 'CREATE VIEW';
732 $index = array_search('VIEW', $tokens);
734 $result['tablename'] = strtolower(self::getTableName($tokens[$index + 1]));
737 // Parse ALTER VIEW statement
738 if (in_array('ALTER', $tokens) == true &&
739 in_array('VIEW', $tokens) == true &&
740 in_array('AS', $tokens) == true &&
741 ! isset($result['identifier'])) {
742 $result['identifier'] = 'ALTER VIEW';
744 $index = array_search('VIEW', $tokens);
746 $result['tablename'] = strtolower(self::getTableName($tokens[$index + 1]));
749 // Parse DROP VIEW statement
750 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP VIEW ') {
751 $result['identifier'] = 'DROP VIEW';
753 $prefix = explode('DROP VIEW ', $query);
754 $str = strstr($prefix[1], 'IF EXISTS');
756 if ($str == false ) {
757 $str = $prefix[1];
759 $result['tablename'] = self::getTableName($str);
762 // Parse CREATE DATABASE statement
763 if (! isset($result['identifier']) && substr($query, 0, 15) == 'CREATE DATABASE') {
764 $result['identifier'] = 'CREATE DATABASE';
765 $str = str_replace('CREATE DATABASE', '', $query);
766 $str = str_replace('IF NOT EXISTS', '', $str);
768 $prefix = explode('DEFAULT ', $str);
770 $result['tablename'] = '';
771 $GLOBALS['db'] = self::getTableName($prefix[0]);
774 // Parse ALTER DATABASE statement
775 if (! isset($result['identifier']) && substr($query, 0, 14) == 'ALTER DATABASE') {
776 $result['identifier'] = 'ALTER DATABASE';
777 $result['tablename'] = '';
780 // Parse DROP DATABASE statement
781 if (! isset($result['identifier']) && substr($query, 0, 13) == 'DROP DATABASE') {
782 $result['identifier'] = 'DROP DATABASE';
783 $str = str_replace('DROP DATABASE', '', $query);
784 $str = str_replace('IF EXISTS', '', $str);
785 $GLOBALS['db'] = self::getTableName($str);
786 $result['tablename'] = '';
789 // Parse CREATE TABLE statement
790 if (! isset($result['identifier']) && substr($query, 0, 12) == 'CREATE TABLE' ) {
791 $result['identifier'] = 'CREATE TABLE';
792 $query = str_replace('IF NOT EXISTS', '', $query);
793 $prefix = explode('CREATE TABLE ', $query);
794 $suffix = explode('(', $prefix[1]);
795 $result['tablename'] = self::getTableName($suffix[0]);
798 // Parse ALTER TABLE statement
799 if (! isset($result['identifier']) && substr($query, 0, 12) == 'ALTER TABLE ') {
800 $result['identifier'] = 'ALTER TABLE';
802 $prefix = explode('ALTER TABLE ', $query);
803 $suffix = explode(' ', $prefix[1]);
804 $result['tablename'] = self::getTableName($suffix[0]);
807 // Parse DROP TABLE statement
808 if (! isset($result['identifier']) && substr($query, 0, 11) == 'DROP TABLE ') {
809 $result['identifier'] = 'DROP TABLE';
811 $prefix = explode('DROP TABLE ', $query);
812 $str = strstr($prefix[1], 'IF EXISTS');
814 if ($str == false ) {
815 $str = $prefix[1];
817 $result['tablename'] = self::getTableName($str);
820 // Parse CREATE INDEX statement
821 if (! isset($result['identifier']) &&
822 ( substr($query, 0, 12) == 'CREATE INDEX' ||
823 substr($query, 0, 19) == 'CREATE UNIQUE INDEX' ||
824 substr($query, 0, 20) == 'CREATE SPATIAL INDEX'
827 $result['identifier'] = 'CREATE INDEX';
828 $prefix = explode('ON ', $query);
829 $suffix = explode('(', $prefix[1]);
830 $result['tablename'] = self::getTableName($suffix[0]);
833 // Parse DROP INDEX statement
834 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP INDEX') {
835 $result['identifier'] = 'DROP INDEX';
836 $prefix = explode('ON ', $query);
837 $result['tablename'] = self::getTableName($prefix[1]);
840 // Parse RENAME TABLE statement
841 if (! isset($result['identifier']) && substr($query, 0, 13) == 'RENAME TABLE ') {
842 $result['identifier'] = 'RENAME TABLE';
843 $prefix = explode('RENAME TABLE ', $query);
844 $names = explode(' TO ', $prefix[1]);
845 $result['tablename'] = self::getTableName($names[0]);
846 $result["tablename_after_rename"] = self::getTableName($names[1]);
850 * DML statements
853 if (! isset($result['identifier'])) {
854 $result["type"] = 'DML';
856 // Parse UPDATE statement
857 if (! isset($result['identifier']) && substr($query, 0, 6) == 'UPDATE') {
858 $result['identifier'] = 'UPDATE';
859 $prefix = explode('UPDATE ', $query);
860 $suffix = explode(' ', $prefix[1]);
861 $result['tablename'] = self::getTableName($suffix[0]);
864 // Parse INSERT INTO statement
865 if (! isset($result['identifier']) && substr($query, 0, 11 ) == 'INSERT INTO') {
866 $result['identifier'] = 'INSERT';
867 $prefix = explode('INSERT INTO', $query);
868 $suffix = explode('(', $prefix[1]);
869 $result['tablename'] = self::getTableName($suffix[0]);
872 // Parse DELETE statement
873 if (! isset($result['identifier']) && substr($query, 0, 6 ) == 'DELETE') {
874 $result['identifier'] = 'DELETE';
875 $prefix = explode('FROM ', $query);
876 $suffix = explode(' ', $prefix[1]);
877 $result['tablename'] = self::getTableName($suffix[0]);
880 // Parse TRUNCATE statement
881 if (! isset($result['identifier']) && substr($query, 0, 8 ) == 'TRUNCATE') {
882 $result['identifier'] = 'TRUNCATE';
883 $prefix = explode('TRUNCATE', $query);
884 $result['tablename'] = self::getTableName($prefix[1]);
887 return $result;
892 * 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;
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;
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);
987 * Transforms tracking set for Drizzle, which has no SET type
989 * Converts int<>string for Drizzle, does nothing for MySQL
991 * @param int|string $tracking_set
992 * @return int|string
994 static private function transformTrackingSet($tracking_set)
996 if (!PMA_DRIZZLE) {
997 return $tracking_set;
1000 // init conversion array (key 3 doesn't exist in calculated array)
1001 if (isset(self::$tracking_set_flags[3])) {
1002 // initialize flags
1003 $set = self::$tracking_set_flags;
1004 $array = array();
1005 for ($i = 0; $i < count($set); $i++) {
1006 $flag = 1 << $i;
1007 $array[$flag] = $set[$i];
1008 $array[$set[$i]] = $flag;
1010 self::$tracking_set_flags = $array;
1013 if (is_numeric($tracking_set)) {
1014 // int > string conversion
1015 $aflags = array();
1016 // count/2 - conversion table has both int > string and string > int values
1017 for ($i = 0; $i < count(self::$tracking_set_flags)/2; $i++) {
1018 $flag = 1 << $i;
1019 if ($tracking_set & $flag) {
1020 $aflags[] = self::$tracking_set_flags[$flag];
1023 $flags = implode(',', $aflags);
1024 } else {
1025 // string > int conversion
1026 $flags = 0;
1027 foreach (explode(',', $tracking_set) as $strflag) {
1028 $flags |= self::$tracking_set_flags[$strflag];
1032 return $flags;