Translation update done using Pootle.
[phpmyadmin.git] / libraries / Tracker.class.php
blob07d176896a90384e150cddcaaedd7785c7b8fedb
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
84 * @return nothing
86 static protected function init()
88 self::$pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
89 PMA_backquote($GLOBALS['cfg']['Server']['tracking']);
91 self::$add_drop_table = $GLOBALS['cfg']['Server']['tracking_add_drop_table'];
93 self::$add_drop_view = $GLOBALS['cfg']['Server']['tracking_add_drop_view'];
95 self::$add_drop_database = $GLOBALS['cfg']['Server']['tracking_add_drop_database'];
97 self::$default_tracking_set = $GLOBALS['cfg']['Server']['tracking_default_statements'];
99 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
108 * @return nothing
110 static public function enable()
112 self::$enabled = true;
116 * Gets the on/off value of the Tracker module, starts initialization.
118 * @static
120 * @return boolean (true=on|false=off)
122 static public function isActive()
124 if (! self::$enabled) {
125 return false;
127 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
128 self::$enabled = false;
129 $cfgRelation = PMA_getRelationsParam();
130 /* Restore original state */
131 self::$enabled = true;
132 if (! $cfgRelation['trackingwork']) {
133 return false;
135 self::init();
137 if (isset(self::$pma_table)) {
138 return true;
139 } else {
140 return false;
145 * Parses the name of a table from a SQL statement substring.
147 * @param string $string part of SQL statement
149 * @static
151 * @return string the name of table
153 static protected function getTableName($string)
155 if (strstr($string, '.')) {
156 $temp = explode('.', $string);
157 $tablename = $temp[1];
158 } else {
159 $tablename = $string;
162 $str = explode("\n", $tablename);
163 $tablename = $str[0];
165 $tablename = str_replace(';', '', $tablename);
166 $tablename = str_replace('`', '', $tablename);
167 $tablename = trim($tablename);
169 return $tablename;
174 * Gets the tracking status of a table, is it active or deactive ?
176 * @param string $dbname name of database
177 * @param string $tablename name of table
179 * @static
181 * @return boolean true or false
183 static public function isTracked($dbname, $tablename)
185 if (! self::$enabled) {
186 return false;
188 /* We need to avoid attempt to track any queries from PMA_getRelationsParam */
189 self::$enabled = false;
190 $cfgRelation = PMA_getRelationsParam();
191 /* Restore original state */
192 self::$enabled = true;
193 if (! $cfgRelation['trackingwork']) {
194 return false;
197 $sql_query = " SELECT tracking_active FROM " . self::$pma_table .
198 " WHERE db_name = '" . PMA_sqlAddSlashes($dbname) . "' " .
199 " AND table_name = '" . PMA_sqlAddSlashes($tablename) . "' " .
200 " ORDER BY version DESC";
202 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
204 if (isset($row['tracking_active']) && $row['tracking_active'] == 1) {
205 return true;
206 } else {
207 return false;
212 * Returns the comment line for the log.
214 * @return string Comment, contains date and username
216 static public function getLogComment()
218 $date = date('Y-m-d H:i:s');
220 return "# log " . $date . " " . $GLOBALS['cfg']['Server']['user'] . "\n";
224 * Creates tracking version of a table / view
225 * (in other words: create a job to track future changes on the table).
227 * @param string $dbname name of database
228 * @param string $tablename name of table
229 * @param string $version version
230 * @param string $tracking_set set of tracking statements
231 * @param bool $is_view if table is a view
233 * @static
235 * @return int result of version insertion
237 static public function createVersion($dbname, $tablename, $version, $tracking_set = '', $is_view = false)
239 global $sql_backquotes;
241 if ($tracking_set == '') {
242 $tracking_set = self::$default_tracking_set;
245 include_once './libraries/export/sql.php';
247 $sql_backquotes = true;
249 $date = date('Y-m-d H:i:s');
251 // Get data definition snapshot of table
253 $columns = PMA_DBI_get_columns($dbname, $tablename, null, true);
254 // int indices to reduce size
255 $columns = array_values($columns);
256 // remove Privileges to reduce size
257 for ($i = 0; $i < count($columns); $i++) {
258 unset($columns[$i]['Privileges']);
261 $indexes = PMA_DBI_get_table_indexes($dbname, $tablename);
263 $snapshot = array('COLUMNS' => $columns, 'INDEXES' => $indexes);
264 $snapshot = serialize($snapshot);
266 // Get DROP TABLE / DROP VIEW and CREATE TABLE SQL statements
267 $sql_backquotes = true;
269 $create_sql = "";
271 if (self::$add_drop_table == true && $is_view == false) {
272 $create_sql .= self::getLogComment() .
273 'DROP TABLE IF EXISTS ' . PMA_backquote($tablename) . ";\n";
277 if (self::$add_drop_view == true && $is_view == true) {
278 $create_sql .= self::getLogComment() .
279 'DROP VIEW IF EXISTS ' . PMA_backquote($tablename) . ";\n";
282 $create_sql .= self::getLogComment() .
283 PMA_getTableDef($dbname, $tablename, "\n", "");
285 // Save version
287 $sql_query = "/*NOTRACK*/\n" .
288 "INSERT INTO" . self::$pma_table . " (" .
289 "db_name, " .
290 "table_name, " .
291 "version, " .
292 "date_created, " .
293 "date_updated, " .
294 "schema_snapshot, " .
295 "schema_sql, " .
296 "data_sql, " .
297 "tracking " .
298 ") " .
299 "values (
300 '" . PMA_sqlAddSlashes($dbname) . "',
301 '" . PMA_sqlAddSlashes($tablename) . "',
302 '" . PMA_sqlAddSlashes($version) . "',
303 '" . PMA_sqlAddSlashes($date) . "',
304 '" . PMA_sqlAddSlashes($date) . "',
305 '" . PMA_sqlAddSlashes($snapshot) . "',
306 '" . PMA_sqlAddSlashes($create_sql) . "',
307 '" . PMA_sqlAddSlashes("\n") . "',
308 '" . PMA_sqlAddSlashes(self::transformTrackingSet($tracking_set)) . "' )";
310 $result = PMA_query_as_controluser($sql_query);
312 if ($result) {
313 // Deactivate previous version
314 self::deactivateTracking($dbname, $tablename, ($version - 1));
317 return $result;
322 * Removes all tracking data for a table
324 * @param string $dbname name of database
325 * @param string $tablename name of table
327 * @static
329 * @return int result of version insertion
331 static public function deleteTracking($dbname, $tablename)
333 $sql_query = "/*NOTRACK*/\n" .
334 "DELETE FROM " . self::$pma_table . " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "'";
335 $result = PMA_query_as_controluser($sql_query);
337 return $result;
341 * Creates tracking version of a database
342 * (in other words: create a job to track future changes on the database).
344 * @param string $dbname name of database
345 * @param string $version version
346 * @param string $query query
347 * @param string $tracking_set set of tracking statements
349 * @static
351 * @return int result of version insertion
353 static public function createDatabaseVersion($dbname, $version, $query, $tracking_set = 'CREATE DATABASE,ALTER DATABASE,DROP DATABASE')
355 $date = date('Y-m-d H:i:s');
357 if ($tracking_set == '') {
358 $tracking_set = self::$default_tracking_set;
361 include_once './libraries/export/sql.php';
363 $create_sql = "";
365 if (self::$add_drop_database == true) {
366 $create_sql .= self::getLogComment() .
367 'DROP DATABASE IF EXISTS ' . PMA_backquote($dbname) . ";\n";
370 $create_sql .= self::getLogComment() . $query;
372 // Save version
373 $sql_query = "/*NOTRACK*/\n" .
374 "INSERT INTO" . self::$pma_table . " (" .
375 "db_name, " .
376 "table_name, " .
377 "version, " .
378 "date_created, " .
379 "date_updated, " .
380 "schema_snapshot, " .
381 "schema_sql, " .
382 "data_sql, " .
383 "tracking " .
384 ") " .
385 "values (
386 '" . PMA_sqlAddSlashes($dbname) . "',
387 '" . PMA_sqlAddSlashes('') . "',
388 '" . PMA_sqlAddSlashes($version) . "',
389 '" . PMA_sqlAddSlashes($date) . "',
390 '" . PMA_sqlAddSlashes($date) . "',
391 '" . PMA_sqlAddSlashes('') . "',
392 '" . PMA_sqlAddSlashes($create_sql) . "',
393 '" . PMA_sqlAddSlashes("\n") . "',
394 '" . PMA_sqlAddSlashes(self::transformTrackingSet($tracking_set)) . "' )";
396 $result = PMA_query_as_controluser($sql_query);
398 return $result;
404 * Changes tracking of a table.
406 * @param string $dbname name of database
407 * @param string $tablename name of table
408 * @param string $version version
409 * @param integer $new_state the new state of tracking
411 * @static
413 * @return int result of SQL query
415 static private function _changeTracking($dbname, $tablename, $version, $new_state)
417 $sql_query = " UPDATE " . self::$pma_table .
418 " SET `tracking_active` = '" . $new_state . "' " .
419 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
420 " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' " .
421 " AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
423 $result = PMA_query_as_controluser($sql_query);
425 return $result;
429 * Changes tracking data of a table.
431 * @param string $dbname name of database
432 * @param string $tablename name of table
433 * @param string $version version
434 * @param string $type type of data(DDL || DML)
435 * @param string|array $new_data the new tracking data
437 * @static
439 * @return bool result of change
441 static public function changeTrackingData($dbname, $tablename, $version, $type, $new_data)
443 if ($type == 'DDL') {
444 $save_to = 'schema_sql';
445 } elseif ($type == 'DML') {
446 $save_to = 'data_sql';
447 } else {
448 return false;
450 $date = date('Y-m-d H:i:s');
452 $new_data_processed = '';
453 if (is_array($new_data)) {
454 foreach ($new_data as $data) {
455 $new_data_processed .= '# log ' . $date . ' ' . $data['username']
456 . PMA_sqlAddSlashes($data['statement']) . "\n";
458 } else {
459 $new_data_processed = $new_data;
462 $sql_query = " UPDATE " . self::$pma_table .
463 " SET `" . $save_to . "` = '" . $new_data_processed . "' " .
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);
470 return $result;
474 * Activates tracking of a table.
476 * @param string $dbname name of database
477 * @param string $tablename name of table
478 * @param string $version version
480 * @static
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.
493 * @param string $dbname name of database
494 * @param string $tablename name of table
495 * @param string $version version
497 * @static
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).
511 * @param string $dbname name of database
512 * @param string $tablename name of table
513 * @param string $statement tracked statement
515 * @static
517 * @return int (-1 if no version exists | > 0 if a version exists)
519 static public function getVersion($dbname, $tablename, $statement = null)
521 $sql_query = " SELECT MAX(version) FROM " . self::$pma_table .
522 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
523 " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' ";
525 if ($statement != "") {
526 $sql_query .= PMA_DRIZZLE
527 ? ' AND tracking & ' . self::transformTrackingSet($statement) . ' <> 0'
528 : " AND FIND_IN_SET('" . $statement . "',tracking) > 0" ;
530 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
531 return isset($row[0])
532 ? $row[0]
533 : -1;
538 * Gets the record of a tracking job.
540 * @param string $dbname name of database
541 * @param string $tablename name of table
542 * @param string $version version number
544 * @static
546 * @return mixed record DDM log, DDL log, structure snapshot, tracked statements.
548 static public function getTrackedData($dbname, $tablename, $version)
550 if (! isset(self::$pma_table)) {
551 self::init();
553 $sql_query = " SELECT * FROM " . self::$pma_table .
554 " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' ";
555 if (! empty($tablename)) {
556 $sql_query .= " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) ."' ";
558 $sql_query .= " AND `version` = '" . PMA_sqlAddSlashes($version) ."' ".
559 " ORDER BY `version` DESC LIMIT 1";
561 $mixed = PMA_DBI_fetch_assoc(PMA_query_as_controluser($sql_query));
563 // Parse log
564 $log_schema_entries = explode('# log ', $mixed['schema_sql']);
565 $log_data_entries = explode('# log ', $mixed['data_sql']);
567 $ddl_date_from = $date = date('Y-m-d H:i:s');
569 $ddlog = array();
570 $i = 0;
572 // Iterate tracked data definition statements
573 // For each log entry we want to get date, username and statement
574 foreach ($log_schema_entries as $log_entry) {
575 if (trim($log_entry) != '') {
576 $date = substr($log_entry, 0, 19);
577 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
578 if ($i == 0) {
579 $ddl_date_from = $date;
581 $statement = rtrim(strstr($log_entry, "\n"));
583 $ddlog[] = array( 'date' => $date,
584 'username'=> $username,
585 'statement' => $statement );
586 $i++;
590 $date_from = $ddl_date_from;
591 $date_to = $ddl_date_to = $date;
593 $dml_date_from = $date_from;
595 $dmlog = array();
596 $i = 0;
598 // Iterate tracked data manipulation statements
599 // For each log entry we want to get date, username and statement
600 foreach ($log_data_entries as $log_entry) {
601 if (trim($log_entry) != '') {
602 $date = substr($log_entry, 0, 19);
603 $username = substr($log_entry, 20, strpos($log_entry, "\n") - 20);
604 if ($i == 0) {
605 $dml_date_from = $date;
607 $statement = rtrim(strstr($log_entry, "\n"));
609 $dmlog[] = array( 'date' => $date,
610 'username' => $username,
611 'statement' => $statement );
612 $i++;
616 $dml_date_to = $date;
618 // Define begin and end of date range for both logs
619 if (strtotime($ddl_date_from) <= strtotime($dml_date_from)) {
620 $data['date_from'] = $ddl_date_from;
621 } else {
622 $data['date_from'] = $dml_date_from;
624 if (strtotime($ddl_date_to) >= strtotime($dml_date_to)) {
625 $data['date_to'] = $ddl_date_to;
626 } else {
627 $data['date_to'] = $dml_date_to;
629 $data['ddlog'] = $ddlog;
630 $data['dmlog'] = $dmlog;
631 $data['tracking'] = self::transformTrackingSet($mixed['tracking']);
632 $data['schema_snapshot'] = $mixed['schema_snapshot'];
634 return $data;
639 * Parses a query. Gets
640 * - statement identifier (UPDATE, ALTER TABLE, ...)
641 * - type of statement, is it part of DDL or DML ?
642 * - tablename
644 * @param string $query query
646 * @static
647 * @todo: using PMA SQL Parser when possible
648 * @todo: support multi-table/view drops
650 * @return mixed Array containing identifier, type and tablename.
653 static public function parseQuery($query)
656 // Usage of PMA_SQP does not work here
658 // require_once("libraries/sqlparser.lib.php");
659 // $parsed_sql = PMA_SQP_parse($query);
660 // $sql_info = PMA_SQP_analyze($parsed_sql);
662 $query = str_replace("\n", " ", $query);
663 $query = str_replace("\r", " ", $query);
665 $query = trim($query);
666 $query = trim($query, ' -');
668 $tokens = explode(" ", $query);
669 $tokens = array_map('strtoupper', $tokens);
671 // Parse USE statement, need it for SQL dump imports
672 if (substr($query, 0, 4) == 'USE ') {
673 $prefix = explode('USE ', $query);
674 $GLOBALS['db'] = self::getTableName($prefix[1]);
678 * DDL statements
681 $result['type'] = 'DDL';
683 // Parse CREATE VIEW statement
684 if (in_array('CREATE', $tokens) == true
685 && in_array('VIEW', $tokens) == true
686 && in_array('AS', $tokens) == true
688 $result['identifier'] = 'CREATE VIEW';
690 $index = array_search('VIEW', $tokens);
692 $result['tablename'] = strtolower(self::getTableName($tokens[$index + 1]));
695 // Parse ALTER VIEW statement
696 if (in_array('ALTER', $tokens) == true
697 && in_array('VIEW', $tokens) == true
698 && in_array('AS', $tokens) == true
699 && ! isset($result['identifier'])
701 $result['identifier'] = 'ALTER VIEW';
703 $index = array_search('VIEW', $tokens);
705 $result['tablename'] = strtolower(self::getTableName($tokens[$index + 1]));
708 // Parse DROP VIEW statement
709 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP VIEW ') {
710 $result['identifier'] = 'DROP VIEW';
712 $prefix = explode('DROP VIEW ', $query);
713 $str = strstr($prefix[1], 'IF EXISTS');
715 if ($str == false ) {
716 $str = $prefix[1];
718 $result['tablename'] = self::getTableName($str);
721 // Parse CREATE DATABASE statement
722 if (! isset($result['identifier']) && substr($query, 0, 15) == 'CREATE DATABASE') {
723 $result['identifier'] = 'CREATE DATABASE';
724 $str = str_replace('CREATE DATABASE', '', $query);
725 $str = str_replace('IF NOT EXISTS', '', $str);
727 $prefix = explode('DEFAULT ', $str);
729 $result['tablename'] = '';
730 $GLOBALS['db'] = self::getTableName($prefix[0]);
733 // Parse ALTER DATABASE statement
734 if (! isset($result['identifier']) && substr($query, 0, 14) == 'ALTER DATABASE') {
735 $result['identifier'] = 'ALTER DATABASE';
736 $result['tablename'] = '';
739 // Parse DROP DATABASE statement
740 if (! isset($result['identifier']) && substr($query, 0, 13) == 'DROP DATABASE') {
741 $result['identifier'] = 'DROP DATABASE';
742 $str = str_replace('DROP DATABASE', '', $query);
743 $str = str_replace('IF EXISTS', '', $str);
744 $GLOBALS['db'] = self::getTableName($str);
745 $result['tablename'] = '';
748 // Parse CREATE TABLE statement
749 if (! isset($result['identifier']) && substr($query, 0, 12) == 'CREATE TABLE' ) {
750 $result['identifier'] = 'CREATE TABLE';
751 $query = str_replace('IF NOT EXISTS', '', $query);
752 $prefix = explode('CREATE TABLE ', $query);
753 $suffix = explode('(', $prefix[1]);
754 $result['tablename'] = self::getTableName($suffix[0]);
757 // Parse ALTER TABLE statement
758 if (! isset($result['identifier']) && substr($query, 0, 12) == 'ALTER TABLE ') {
759 $result['identifier'] = 'ALTER TABLE';
761 $prefix = explode('ALTER TABLE ', $query);
762 $suffix = explode(' ', $prefix[1]);
763 $result['tablename'] = self::getTableName($suffix[0]);
766 // Parse DROP TABLE statement
767 if (! isset($result['identifier']) && substr($query, 0, 11) == 'DROP TABLE ') {
768 $result['identifier'] = 'DROP TABLE';
770 $prefix = explode('DROP TABLE ', $query);
771 $str = strstr($prefix[1], 'IF EXISTS');
773 if ($str == false ) {
774 $str = $prefix[1];
776 $result['tablename'] = self::getTableName($str);
779 // Parse CREATE INDEX statement
780 if (! isset($result['identifier'])
781 && (substr($query, 0, 12) == 'CREATE INDEX'
782 || substr($query, 0, 19) == 'CREATE UNIQUE INDEX'
783 || substr($query, 0, 20) == 'CREATE SPATIAL INDEX')
785 $result['identifier'] = 'CREATE INDEX';
786 $prefix = explode('ON ', $query);
787 $suffix = explode('(', $prefix[1]);
788 $result['tablename'] = self::getTableName($suffix[0]);
791 // Parse DROP INDEX statement
792 if (! isset($result['identifier']) && substr($query, 0, 10) == 'DROP INDEX') {
793 $result['identifier'] = 'DROP INDEX';
794 $prefix = explode('ON ', $query);
795 $result['tablename'] = self::getTableName($prefix[1]);
798 // Parse RENAME TABLE statement
799 if (! isset($result['identifier']) && substr($query, 0, 13) == 'RENAME TABLE ') {
800 $result['identifier'] = 'RENAME TABLE';
801 $prefix = explode('RENAME TABLE ', $query);
802 $names = explode(' TO ', $prefix[1]);
803 $result['tablename'] = self::getTableName($names[0]);
804 $result["tablename_after_rename"] = self::getTableName($names[1]);
808 * DML statements
811 if (! isset($result['identifier'])) {
812 $result["type"] = 'DML';
814 // Parse UPDATE statement
815 if (! isset($result['identifier']) && substr($query, 0, 6) == 'UPDATE') {
816 $result['identifier'] = 'UPDATE';
817 $prefix = explode('UPDATE ', $query);
818 $suffix = explode(' ', $prefix[1]);
819 $result['tablename'] = self::getTableName($suffix[0]);
822 // Parse INSERT INTO statement
823 if (! isset($result['identifier']) && substr($query, 0, 11) == 'INSERT INTO') {
824 $result['identifier'] = 'INSERT';
825 $prefix = explode('INSERT INTO', $query);
826 $suffix = explode('(', $prefix[1]);
827 $result['tablename'] = self::getTableName($suffix[0]);
830 // Parse DELETE statement
831 if (! isset($result['identifier']) && substr($query, 0, 6) == 'DELETE') {
832 $result['identifier'] = 'DELETE';
833 $prefix = explode('FROM ', $query);
834 $suffix = explode(' ', $prefix[1]);
835 $result['tablename'] = self::getTableName($suffix[0]);
838 // Parse TRUNCATE statement
839 if (! isset($result['identifier']) && substr($query, 0, 8) == 'TRUNCATE') {
840 $result['identifier'] = 'TRUNCATE';
841 $prefix = explode('TRUNCATE', $query);
842 $result['tablename'] = self::getTableName($prefix[1]);
845 return $result;
850 * Analyzes a given SQL statement and saves tracking data.
852 * @param string $query a SQL query
854 * @static
856 * @return nothing
858 static public function handleQuery($query)
860 // If query is marked as untouchable, leave
861 if (strstr($query, "/*NOTRACK*/")) {
862 return;
865 if (! (substr($query, -1) == ';')) {
866 $query = $query . ";\n";
868 // Get some information about query
869 $result = self::parseQuery($query);
871 // Get database name
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)) {
876 return;
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
886 && $version == -1
888 // Create the version
890 switch ($result['identifier']) {
891 case 'CREATE TABLE':
892 self::createVersion($dbname, $result['tablename'], '1');
893 break;
894 case 'CREATE VIEW':
895 self::createVersion($dbname, $result['tablename'], '1', '', true);
896 break;
897 case 'CREATE DATABASE':
898 self::createDatabaseVersion($dbname, '1', $query);
899 break;
900 } // end switch
903 // If version exists
904 if (self::isTracked($dbname, $result['tablename']) && $version != -1) {
905 if ($result['type'] == 'DDL') {
906 $save_to = 'schema_sql';
907 } elseif ($result['type'] == 'DML') {
908 $save_to = 'data_sql';
909 } else {
910 $save_to = '';
912 $date = date('Y-m-d H:i:s');
914 // Cut off `dbname`. from query
915 $query = preg_replace('/`' . $dbname . '`\s?\./', '', $query);
917 // Add log information
918 $query = self::getLogComment() . $query ;
920 // Mark it as untouchable
921 $sql_query = " /*NOTRACK*/\n" .
922 " UPDATE " . self::$pma_table .
923 " SET " . PMA_backquote($save_to) ." = CONCAT( " . PMA_backquote($save_to) . ",'\n"
924 . PMA_sqlAddSlashes($query) . "') ," . " `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
932 // 1. the database
933 // 2. the table / view
934 // 3. the statements
935 // we want to track
936 $sql_query .=
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);
948 * Transforms tracking set for Drizzle, which has no SET type
950 * Converts int<>string for Drizzle, does nothing for MySQL
952 * @param int|string $tracking_set
953 * @return int|string
955 static private function transformTrackingSet($tracking_set)
957 if (!PMA_DRIZZLE) {
958 return $tracking_set;
961 // init conversion array (key 3 doesn't exist in calculated array)
962 if (isset(self::$tracking_set_flags[3])) {
963 // initialize flags
964 $set = self::$tracking_set_flags;
965 $array = array();
966 for ($i = 0; $i < count($set); $i++) {
967 $flag = 1 << $i;
968 $array[$flag] = $set[$i];
969 $array[$set[$i]] = $flag;
971 self::$tracking_set_flags = $array;
974 if (is_numeric($tracking_set)) {
975 // int > string conversion
976 $aflags = array();
977 // count/2 - conversion table has both int > string and string > int values
978 for ($i = 0; $i < count(self::$tracking_set_flags)/2; $i++) {
979 $flag = 1 << $i;
980 if ($tracking_set & $flag) {
981 $aflags[] = self::$tracking_set_flags[$flag];
984 $flags = implode(',', $aflags);
985 } else {
986 // string > int conversion
987 $flags = 0;
988 foreach (explode(',', $tracking_set) as $strflag) {
989 if ($strflag == '') {
990 continue;
992 $flags |= self::$tracking_set_flags[$strflag];
996 return $flags;