3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Logging_Schema
{
36 private $logs = array();
37 private $tables = array();
40 private $useDBPrefix = TRUE;
42 private $reports = array(
43 'logging/contact/detail',
44 'logging/contact/summary',
45 'logging/contribute/detail',
46 'logging/contribute/summary',
49 //CRM-13028 / NYSS-6933 - table => array (cols) - to be excluded from the update statement
50 private $exceptions = array(
51 'civicrm_job' => array('last_run'),
52 'civicrm_group' => array('cache_date'),
56 * Populate $this->tables and $this->logs with current db state.
58 public function __construct() {
59 $dao = new CRM_Contact_DAO_Contact();
60 $civiDBName = $dao->_database
;
62 $dao = CRM_Core_DAO
::executeQuery("
64 FROM INFORMATION_SCHEMA.TABLES
65 WHERE TABLE_SCHEMA = '{$civiDBName}'
66 AND TABLE_TYPE = 'BASE TABLE'
67 AND TABLE_NAME LIKE 'civicrm_%'
69 while ($dao->fetch()) {
70 $this->tables
[] = $dao->TABLE_NAME
;
73 // do not log temp import, cache, menu and log tables
74 $this->tables
= preg_grep('/^civicrm_import_job_/', $this->tables
, PREG_GREP_INVERT
);
75 $this->tables
= preg_grep('/_cache$/', $this->tables
, PREG_GREP_INVERT
);
76 $this->tables
= preg_grep('/_log/', $this->tables
, PREG_GREP_INVERT
);
77 $this->tables
= preg_grep('/^civicrm_queue_/', $this->tables
, PREG_GREP_INVERT
);
78 $this->tables
= preg_grep('/^civicrm_menu/', $this->tables
, PREG_GREP_INVERT
); //CRM-14672
79 $this->tables
= preg_grep('/_temp_/', $this->tables
, PREG_GREP_INVERT
);
81 // do not log civicrm_mailing_event* tables, CRM-12300
82 $this->tables
= preg_grep('/^civicrm_mailing_event_/', $this->tables
, PREG_GREP_INVERT
);
84 if (defined('CIVICRM_LOGGING_DSN')) {
85 $dsn = DB
::parseDSN(CIVICRM_LOGGING_DSN
);
86 $this->useDBPrefix
= (CIVICRM_LOGGING_DSN
!= CIVICRM_DSN
);
89 $dsn = DB
::parseDSN(CIVICRM_DSN
);
90 $this->useDBPrefix
= FALSE;
92 $this->db
= $dsn['database'];
94 $dao = CRM_Core_DAO
::executeQuery("
96 FROM INFORMATION_SCHEMA.TABLES
97 WHERE TABLE_SCHEMA = '{$this->db}'
98 AND TABLE_TYPE = 'BASE TABLE'
99 AND TABLE_NAME LIKE 'log_civicrm_%'
101 while ($dao->fetch()) {
102 $log = $dao->TABLE_NAME
;
103 $this->logs
[substr($log, 4)] = $log;
108 * Return logging custom data tables.
110 public function customDataLogTables() {
111 return preg_grep('/^log_civicrm_value_/', $this->logs
);
115 * Return custom data tables for specified entity / extends.
117 public function entityCustomDataLogTables($extends) {
118 $customGroupTables = array();
119 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity($extends);
120 $customGroupDAO->find();
121 while ($customGroupDAO->fetch()) {
122 $customGroupTables[$customGroupDAO->table_name
] = $this->logs
[$customGroupDAO->table_name
];
124 return $customGroupTables;
128 * Disable logging by dropping the triggers (but keep the log tables intact).
130 public function disableLogging() {
131 $config = CRM_Core_Config
::singleton();
132 $config->logging
= FALSE;
134 $this->dropTriggers();
136 // invoke the meta trigger creation call
137 CRM_Core_DAO
::triggerRebuild();
139 $this->deleteReports();
143 * Drop triggers for all logged tables.
145 public function dropTriggers($tableName = NULL) {
146 $dao = new CRM_Core_DAO
;
149 $tableNames = array($tableName);
152 $tableNames = $this->tables
;
155 foreach ($tableNames as $table) {
156 $validName = CRM_Core_DAO
::shortenSQLName($table, 48, TRUE);
159 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_insert");
160 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_update");
161 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_delete");
164 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_insert");
165 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_update");
166 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_delete");
169 // now lets also be safe and drop all triggers that start with
170 // civicrm_ if we are dropping all triggers
171 // we need to do this to capture all the leftover triggers since
172 // we did the shortening trigger name for CRM-11794
173 if ($tableName === NULL) {
174 $triggers = $dao->executeQuery("SHOW TRIGGERS LIKE 'civicrm_%'");
176 while ($triggers->fetch()) {
177 // note that drop trigger has a wierd syntax and hence we do not
178 // send the trigger name as a string (i.e. its not quoted
179 $dao->executeQuery("DROP TRIGGER IF EXISTS {$triggers->Trigger}");
185 * Enable sitewide logging.
189 public function enableLogging() {
190 $this->fixSchemaDifferences(TRUE);
195 * Sync log tables and rebuild triggers.
197 * @param bool $enableLogging: Ensure logging is enabled
201 public function fixSchemaDifferences($enableLogging = FALSE) {
202 $config = CRM_Core_Config
::singleton();
203 if ($enableLogging) {
204 $config->logging
= TRUE;
206 if ($config->logging
) {
207 $this->fixSchemaDifferencesForALL();
209 // invoke the meta trigger creation call
210 CRM_Core_DAO
::triggerRebuild(NULL, TRUE);
214 * Add missing (potentially specified) log table columns for the given table.
217 * String name of the relevant table.
219 * Mixed array of columns to add or null (to check for the missing columns).
220 * @param $rebuildTrigger
221 * Boolean should we rebuild the triggers.
225 public function fixSchemaDifferencesFor($table, $cols = array(), $rebuildTrigger = FALSE) {
229 if (empty($this->logs
[$table])) {
230 $this->createLogTableFor($table);
235 $cols = $this->columnsWithDiffSpecs($table, "log_$table");
238 // use the relevant lines from CREATE TABLE to add colums to the log table
239 $create = $this->_getCreateQuery($table);
240 foreach ((array('ADD', 'MODIFY')) as $alterType) {
241 if (!empty($cols[$alterType])) {
242 foreach ($cols[$alterType] as $col) {
243 $line = $this->_getColumnQuery($col, $create);
244 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table {$alterType} {$line}");
249 // for any obsolete columns (not null) we just make the column nullable.
250 if (!empty($cols['OBSOLETE'])) {
251 $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}");
252 foreach ($cols['OBSOLETE'] as $col) {
253 $line = $this->_getColumnQuery($col, $create);
254 // This is just going to make a not null column to nullable
255 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table MODIFY {$line}");
259 if ($rebuildTrigger) {
260 // invoke the meta trigger creation call
261 CRM_Core_DAO
::triggerRebuild($table);
271 private function _getCreateQuery($table) {
272 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE {$table}");
274 $create = explode("\n", $dao->Create_Table
);
280 * @param $createQuery
282 * @return array|mixed|string
284 private function _getColumnQuery($col, $createQuery) {
285 $line = preg_grep("/^ `$col` /", $createQuery);
286 $line = rtrim(array_pop($line), ',');
288 $line = $this->fixTimeStampAndNotNullSQL($line);
293 * @param bool $rebuildTrigger
295 public function fixSchemaDifferencesForAll($rebuildTrigger = FALSE) {
297 foreach ($this->tables
as $table) {
298 if (empty($this->logs
[$table])) {
299 $this->createLogTableFor($table);
302 $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table");
306 foreach ($diffs as $table => $cols) {
307 $this->fixSchemaDifferencesFor($table, $cols, FALSE);
310 if ($rebuildTrigger) {
311 // invoke the meta trigger creation call
312 CRM_Core_DAO
::triggerRebuild($table);
317 * log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
318 * so there's no need for a default timestamp and therefore we remove such default timestamps
319 * also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
326 public function fixTimeStampAndNotNullSQL($query) {
327 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
328 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
329 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
330 $query = str_ireplace("NOT NULL", '', $query);
334 private function addReports() {
336 'logging/contact/detail' => ts('Logging Details'),
337 'logging/contact/summary' => ts('Contact Logging Report (Summary)'),
338 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'),
339 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'),
341 // enable logging templates
342 CRM_Core_DAO
::executeQuery("
343 UPDATE civicrm_option_value
345 WHERE value IN ('" . implode("', '", $this->reports
) . "')
348 // add report instances
349 $domain_id = CRM_Core_Config
::domainID();
350 foreach ($this->reports
as $report) {
351 $dao = new CRM_Report_DAO_ReportInstance
;
352 $dao->domain_id
= $domain_id;
353 $dao->report_id
= $report;
354 $dao->title
= $titles[$report];
355 $dao->permission
= 'administer CiviCRM';
356 if ($report == 'logging/contact/summary')
357 $dao->is_reserved
= 1;
363 * Get an array of column names of the given table.
365 private function columnsOf($table, $force = FALSE) {
366 static $columnsOf = array();
368 $from = (substr($table, 0, 4) == 'log_') ?
"`{$this->db}`.$table" : $table;
370 if (!isset($columnsOf[$table]) ||
$force) {
371 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
372 $dao = CRM_Core_DAO
::executeQuery("SHOW COLUMNS FROM $from");
373 if (is_a($dao, 'DB_Error')) {
376 $columnsOf[$table] = array();
377 while ($dao->fetch()) {
378 $columnsOf[$table][] = $dao->Field
;
382 return $columnsOf[$table];
386 * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table.
388 private function columnSpecsOf($table) {
389 static $columnSpecs = array(), $civiDB = NULL;
391 if (empty($columnSpecs)) {
393 $dao = new CRM_Contact_DAO_Contact();
394 $civiDB = $dao->_database
;
396 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
397 // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
398 // than firing query for every given table.
400 SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
401 FROM INFORMATION_SCHEMA.COLUMNS
402 WHERE table_schema IN ('{$this->db}', '{$civiDB}')";
403 $dao = CRM_Core_DAO
::executeQuery($query);
404 if (is_a($dao, 'DB_Error')) {
407 while ($dao->fetch()) {
408 if (!array_key_exists($dao->TABLE_NAME
, $columnSpecs)) {
409 $columnSpecs[$dao->TABLE_NAME
] = array();
411 $columnSpecs[$dao->TABLE_NAME
][$dao->COLUMN_NAME
] =
413 'COLUMN_NAME' => $dao->COLUMN_NAME
,
414 'DATA_TYPE' => $dao->DATA_TYPE
,
415 'IS_NULLABLE' => $dao->IS_NULLABLE
,
416 'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT
420 return $columnSpecs[$table];
429 public function columnsWithDiffSpecs($civiTable, $logTable) {
430 $civiTableSpecs = $this->columnSpecsOf($civiTable);
431 $logTableSpecs = $this->columnSpecsOf($logTable);
433 $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array());
435 // columns to be added
436 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
438 // columns to be modified
439 // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
440 // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
441 foreach ($civiTableSpecs as $col => $colSpecs) {
442 if (!isset($logTableSpecs[$col]) ||
!is_array($logTableSpecs[$col])) {
443 $logTableSpecs[$col] = array();
446 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
447 if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) {
448 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
449 if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array
::value('DATA_TYPE', $logTableSpecs[$col])) {
450 // if data-type is different, surely consider the column
451 $diff['MODIFY'][] = $col;
453 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array
::value('IS_NULLABLE', $logTableSpecs[$col]) &&
454 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO') {
455 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
456 $diff['MODIFY'][] = $col;
458 elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array
::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
459 !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')) {
460 // if default property is different, and its not about a timestamp column, consider it
461 $diff['MODIFY'][] = $col;
466 // columns to made obsolete by turning into not-null
467 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
468 foreach ($oldCols as $col) {
469 if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) &&
470 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO') {
471 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
472 $diff['OBSOLETE'][] = $col;
480 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
482 private function createLogTableFor($table) {
483 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE $table");
485 $query = $dao->Create_Table
;
487 // rewrite the queries into CREATE TABLE queries for log tables:
489 log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
492 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
495 // - prepend the name with log_
496 // - drop AUTO_INCREMENT columns
497 // - drop non-column rows of the query (keys, constraints, etc.)
498 // - set the ENGINE to ARCHIVE
499 // - add log-specific columns (at the end of the table)
500 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
501 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
502 $query = preg_replace("/^ [^`].*$/m", '', $query);
503 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=ARCHIVE ', $query);
505 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
506 // so there's no need for a default timestamp and therefore we remove such default timestamps
507 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
508 $query = self
::fixTimeStampAndNotNullSQL($query);
509 $query = preg_replace("/^\) /m", "$cols\n) ", $query);
511 CRM_Core_DAO
::executeQuery($query);
513 $columns = implode(', ', $this->columnsOf($table));
514 CRM_Core_DAO
::executeQuery("INSERT INTO `{$this->db}`.log_$table ($columns, log_conn_id, log_user_id, log_action) SELECT $columns, CONNECTION_ID(), @civicrm_user_id, 'Initialization' FROM {$table}");
516 $this->tables
[] = $table;
517 $this->logs
[$table] = "log_$table";
520 private function deleteReports() {
521 // disable logging templates
522 CRM_Core_DAO
::executeQuery("
523 UPDATE civicrm_option_value
525 WHERE value IN ('" . implode("', '", $this->reports
) . "')
528 // delete report instances
529 $domain_id = CRM_Core_Config
::domainID();
530 foreach ($this->reports
as $report) {
531 $dao = new CRM_Report_DAO_ReportInstance
;
532 $dao->domain_id
= $domain_id;
533 $dao->report_id
= $report;
539 * Predicate whether logging is enabled.
541 public function isEnabled() {
542 $config = CRM_Core_Config
::singleton();
544 if ($config->logging
) {
545 return $this->tablesExist() and $this->triggersExist();
551 * Predicate whether any log tables exist.
553 private function tablesExist() {
554 return !empty($this->logs
);
558 * Predicate whether the logging triggers are in place.
560 private function triggersExist() {
561 // FIXME: probably should be a bit more thorough…
562 // note that the LIKE parameter is TABLE NAME
563 return (bool) CRM_Core_DAO
::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
568 * @param null $tableName
571 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
572 // check if we have logging enabled
573 $config =& CRM_Core_Config
::singleton();
574 if (!$config->logging
) {
578 $insert = array('INSERT');
579 $update = array('UPDATE');
580 $delete = array('DELETE');
583 $tableNames = array($tableName);
586 $tableNames = $this->tables
;
589 // logging is enabled, so now lets create the trigger info tables
590 foreach ($tableNames as $table) {
591 $columns = $this->columnsOf($table, $force);
593 // only do the change if any data has changed
595 foreach ($columns as $column) {
596 // ignore modified_date changes
597 if ($column != 'modified_date' && !in_array($column, CRM_Utils_Array
::value($table, $this->exceptions
, array()))) {
598 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
601 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
602 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
604 if ($this->useDBPrefix
) {
605 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
608 $sqlStmt = "INSERT INTO log_{tableName} (";
610 foreach ($columns as $column) {
611 $sqlStmt .= "$column, ";
613 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
615 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
616 $updateSQL .= $sqlStmt;
619 foreach ($columns as $column) {
620 $sqlStmt .= "NEW.$column, ";
621 $deleteSQL .= "OLD.$column, ";
623 $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
624 $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
626 $sqlStmt .= "END IF;";
627 $deleteSQL .= "END IF;";
629 $insertSQL .= $sqlStmt;
630 $updateSQL .= $sqlStmt;
633 'table' => array($table),
640 'table' => array($table),
647 'table' => array($table),
656 * This allow logging to be temporarily disabled for certain cases
657 * where we want to do a mass cleanup but dont want to bother with
662 public static function disableLoggingForThisConnection() {
663 // do this only if logging is enabled
664 $config = CRM_Core_Config
::singleton();
665 if ($config->logging
) {
666 CRM_Core_DAO
::executeQuery('SET @civicrm_disable_logging = 1');