3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 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_task_action_temp_/', $this->tables
, PREG_GREP_INVERT
);
78 $this->tables
= preg_grep('/^civicrm_export_temp_/', $this->tables
, PREG_GREP_INVERT
);
79 $this->tables
= preg_grep('/^civicrm_queue_/', $this->tables
, PREG_GREP_INVERT
);
80 $this->tables
= preg_grep('/^civicrm_menu/', $this->tables
, PREG_GREP_INVERT
); //CRM-14672
82 // do not log civicrm_mailing_event* tables, CRM-12300
83 $this->tables
= preg_grep('/^civicrm_mailing_event_/', $this->tables
, PREG_GREP_INVERT
);
85 if (defined('CIVICRM_LOGGING_DSN')) {
86 $dsn = DB
::parseDSN(CIVICRM_LOGGING_DSN
);
87 $this->useDBPrefix
= (CIVICRM_LOGGING_DSN
!= CIVICRM_DSN
);
90 $dsn = DB
::parseDSN(CIVICRM_DSN
);
91 $this->useDBPrefix
= FALSE;
93 $this->db
= $dsn['database'];
95 $dao = CRM_Core_DAO
::executeQuery("
97 FROM INFORMATION_SCHEMA.TABLES
98 WHERE TABLE_SCHEMA = '{$this->db}'
99 AND TABLE_TYPE = 'BASE TABLE'
100 AND TABLE_NAME LIKE 'log_civicrm_%'
102 while ($dao->fetch()) {
103 $log = $dao->TABLE_NAME
;
104 $this->logs
[substr($log, 4)] = $log;
109 * Return logging custom data tables.
111 function customDataLogTables() {
112 return preg_grep('/^log_civicrm_value_/', $this->logs
);
116 * Return custom data tables for specified entity / extends.
118 function entityCustomDataLogTables($extends) {
119 $customGroupTables = array();
120 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity($extends);
121 $customGroupDAO->find();
122 while ($customGroupDAO->fetch()) {
123 $customGroupTables[$customGroupDAO->table_name
] = $this->logs
[$customGroupDAO->table_name
];
125 return $customGroupTables;
129 * Disable logging by dropping the triggers (but keep the log tables intact).
131 function disableLogging() {
132 $config = CRM_Core_Config
::singleton();
133 $config->logging
= FALSE;
135 $this->dropTriggers();
137 // invoke the meta trigger creation call
138 CRM_Core_DAO
::triggerRebuild();
140 $this->deleteReports();
144 * Drop triggers for all logged tables.
146 function dropTriggers($tableName = NULL) {
147 $dao = new CRM_Core_DAO
;
150 $tableNames = array($tableName);
153 $tableNames = $this->tables
;
156 foreach ($tableNames as $table) {
157 $validName = CRM_Core_DAO
::shortenSQLName($table, 48, TRUE);
160 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_insert");
161 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_update");
162 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_delete");
165 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_insert");
166 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_update");
167 $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_delete");
170 // now lets also be safe and drop all triggers that start with
171 // civicrm_ if we are dropping all triggers
172 // we need to do this to capture all the leftover triggers since
173 // we did the shortening trigger name for CRM-11794
174 if ($tableName === NULL) {
175 $triggers = $dao->executeQuery("SHOW TRIGGERS LIKE 'civicrm_%'");
177 while ($triggers->fetch()) {
178 // note that drop trigger has a wierd syntax and hence we do not
179 // send the trigger name as a string (i.e. its not quoted
180 $dao->executeQuery("DROP TRIGGER IF EXISTS {$triggers->Trigger}");
186 * Enable sitewide logging.
190 function enableLogging() {
191 $this->fixSchemaDifferences(TRUE);
196 * Sync log tables and rebuild triggers.
198 * @param bool $enableLogging: Ensure logging is enabled
202 function fixSchemaDifferences($enableLogging = FALSE) {
203 $config = CRM_Core_Config
::singleton();
204 if ($enableLogging) {
205 $config->logging
= TRUE;
207 if ($config->logging
) {
208 $this->fixSchemaDifferencesForALL();
210 // invoke the meta trigger creation call
211 CRM_Core_DAO
::triggerRebuild(NULL, TRUE);
215 * Add missing (potentially specified) log table columns for the given table.
217 * @param $table string name of the relevant table
218 * @param $cols mixed array of columns to add or null (to check for the missing columns)
219 * @param $rebuildTrigger boolean should we rebuild the triggers
223 function fixSchemaDifferencesFor($table, $cols = array(), $rebuildTrigger = FALSE) {
227 if (empty($this->logs
[$table])) {
228 $this->createLogTableFor($table);
233 $cols = $this->columnsWithDiffSpecs($table, "log_$table");
236 // use the relevant lines from CREATE TABLE to add colums to the log table
237 $create = $this->_getCreateQuery($table);
238 foreach ((array('ADD', 'MODIFY')) as $alterType) {
239 if (!empty($cols[$alterType])) {
240 foreach ($cols[$alterType] as $col) {
241 $line = $this->_getColumnQuery($col, $create);
242 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table {$alterType} {$line}");
247 // for any obsolete columns (not null) we just make the column nullable.
248 if (!empty($cols['OBSOLETE'])) {
249 $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}");
250 foreach ($cols['OBSOLETE'] as $col) {
251 $line = $this->_getColumnQuery($col, $create);
252 // This is just going to make a not null column to nullable
253 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table MODIFY {$line}");
257 if ($rebuildTrigger) {
258 // invoke the meta trigger creation call
259 CRM_Core_DAO
::triggerRebuild($table);
264 private function _getCreateQuery($table) {
265 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE {$table}");
267 $create = explode("\n", $dao->Create_Table
);
271 private function _getColumnQuery($col, $createQuery) {
272 $line = preg_grep("/^ `$col` /", $createQuery);
273 $line = rtrim(array_pop($line), ',');
275 $line = $this->fixTimeStampAndNotNullSQL($line);
279 function fixSchemaDifferencesForAll($rebuildTrigger = FALSE) {
281 foreach ($this->tables
as $table) {
282 if (empty($this->logs
[$table])) {
283 $this->createLogTableFor($table);
286 $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table");
290 foreach ($diffs as $table => $cols) {
291 $this->fixSchemaDifferencesFor($table, $cols, FALSE);
294 if ($rebuildTrigger) {
295 // invoke the meta trigger creation call
296 CRM_Core_DAO
::triggerRebuild($table);
301 * log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
302 * so there's no need for a default timestamp and therefore we remove such default timestamps
303 * also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
305 function fixTimeStampAndNotNullSQL($query) {
306 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
307 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
308 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
309 $query = str_ireplace("NOT NULL", '', $query);
313 private function addReports() {
315 'logging/contact/detail' => ts('Logging Details'),
316 'logging/contact/summary' => ts('Contact Logging Report (Summary)'),
317 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'),
318 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'),
320 // enable logging templates
321 CRM_Core_DAO
::executeQuery("
322 UPDATE civicrm_option_value
324 WHERE value IN ('" . implode("', '", $this->reports
) . "')
327 // add report instances
328 $domain_id = CRM_Core_Config
::domainID();
329 foreach ($this->reports
as $report) {
330 $dao = new CRM_Report_DAO_ReportInstance
;
331 $dao->domain_id
= $domain_id;
332 $dao->report_id
= $report;
333 $dao->title
= $titles[$report];
334 $dao->permission
= 'administer CiviCRM';
335 if ($report == 'logging/contact/summary')
336 $dao->is_reserved
= 1;
342 * Get an array of column names of the given table.
344 private function columnsOf($table, $force = FALSE) {
345 static $columnsOf = array();
347 $from = (substr($table, 0, 4) == 'log_') ?
"`{$this->db}`.$table" : $table;
349 if (!isset($columnsOf[$table]) ||
$force) {
350 CRM_Core_Error
::ignoreException();
351 $dao = CRM_Core_DAO
::executeQuery("SHOW COLUMNS FROM $from");
352 CRM_Core_Error
::setCallback();
353 if (is_a($dao, 'DB_Error')) {
356 $columnsOf[$table] = array();
357 while ($dao->fetch()) {
358 $columnsOf[$table][] = $dao->Field
;
362 return $columnsOf[$table];
366 * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table.
368 private function columnSpecsOf($table) {
369 static $columnSpecs = array(), $civiDB = NULL;
371 if (empty($columnSpecs)) {
373 $dao = new CRM_Contact_DAO_Contact();
374 $civiDB = $dao->_database
;
376 CRM_Core_Error
::ignoreException();
377 // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
378 // than firing query for every given table.
380 SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
381 FROM INFORMATION_SCHEMA.COLUMNS
382 WHERE table_schema IN ('{$this->db}', '{$civiDB}')";
383 $dao = CRM_Core_DAO
::executeQuery($query);
384 CRM_Core_Error
::setCallback();
385 if (is_a($dao, 'DB_Error')) {
388 while ($dao->fetch()) {
389 if (!array_key_exists($dao->TABLE_NAME
, $columnSpecs)) {
390 $columnSpecs[$dao->TABLE_NAME
] = array();
392 $columnSpecs[$dao->TABLE_NAME
][$dao->COLUMN_NAME
] =
394 'COLUMN_NAME' => $dao->COLUMN_NAME
,
395 'DATA_TYPE' => $dao->DATA_TYPE
,
396 'IS_NULLABLE' => $dao->IS_NULLABLE
,
397 'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT
401 return $columnSpecs[$table];
404 function columnsWithDiffSpecs($civiTable, $logTable) {
405 $civiTableSpecs = $this->columnSpecsOf($civiTable);
406 $logTableSpecs = $this->columnSpecsOf($logTable);
408 $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array());
410 // columns to be added
411 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
413 // columns to be modified
414 // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
415 // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
416 foreach ($civiTableSpecs as $col => $colSpecs) {
417 if ( !is_array($logTableSpecs[$col]) ) {
418 $logTableSpecs[$col] = array();
421 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
422 if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) {
423 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
424 if ($civiTableSpecs[$col]['DATA_TYPE'] != $logTableSpecs[$col]['DATA_TYPE']) {
425 // if data-type is different, surely consider the column
426 $diff['MODIFY'][] = $col;
427 } else if ($civiTableSpecs[$col]['IS_NULLABLE'] != $logTableSpecs[$col]['IS_NULLABLE'] &&
428 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO') {
429 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
430 $diff['MODIFY'][] = $col;
431 } else if ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != $logTableSpecs[$col]['COLUMN_DEFAULT'] &&
432 !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')) {
433 // if default property is different, and its not about a timestamp column, consider it
434 $diff['MODIFY'][] = $col;
439 // columns to made obsolete by turning into not-null
440 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
441 foreach ($oldCols as $col) {
442 if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) &&
443 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO') {
444 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
445 $diff['OBSOLETE'][] = $col;
453 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
455 private function createLogTableFor($table) {
456 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE $table");
458 $query = $dao->Create_Table
;
460 // rewrite the queries into CREATE TABLE queries for log tables:
462 log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
465 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
468 // - prepend the name with log_
469 // - drop AUTO_INCREMENT columns
470 // - drop non-column rows of the query (keys, constraints, etc.)
471 // - set the ENGINE to ARCHIVE
472 // - add log-specific columns (at the end of the table)
473 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
474 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
475 $query = preg_replace("/^ [^`].*$/m", '', $query);
476 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=ARCHIVE ', $query);
478 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
479 // so there's no need for a default timestamp and therefore we remove such default timestamps
480 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
481 $query = self
::fixTimeStampAndNotNullSQL($query);
482 $query = preg_replace("/^\) /m", "$cols\n) ", $query);
484 CRM_Core_DAO
::executeQuery($query);
486 $columns = implode(', ', $this->columnsOf($table));
487 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}");
489 $this->tables
[] = $table;
490 $this->logs
[$table] = "log_$table";
493 private function deleteReports() {
494 // disable logging templates
495 CRM_Core_DAO
::executeQuery("
496 UPDATE civicrm_option_value
498 WHERE value IN ('" . implode("', '", $this->reports
) . "')
501 // delete report instances
502 $domain_id = CRM_Core_Config
::domainID();
503 foreach ($this->reports
as $report) {
504 $dao = new CRM_Report_DAO_ReportInstance
;
505 $dao->domain_id
= $domain_id;
506 $dao->report_id
= $report;
512 * Predicate whether logging is enabled.
514 public function isEnabled() {
515 $config = CRM_Core_Config
::singleton();
517 if ($config->logging
) {
518 return $this->tablesExist() and $this->triggersExist();
524 * Predicate whether any log tables exist.
526 private function tablesExist() {
527 return !empty($this->logs
);
531 * Predicate whether the logging triggers are in place.
533 private function triggersExist() {
534 // FIXME: probably should be a bit more thorough…
535 // note that the LIKE parameter is TABLE NAME
536 return (bool) CRM_Core_DAO
::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
539 function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
540 // check if we have logging enabled
541 $config =& CRM_Core_Config
::singleton();
542 if (!$config->logging
) {
546 $insert = array('INSERT');
547 $update = array('UPDATE');
548 $delete = array('DELETE');
551 $tableNames = array($tableName);
554 $tableNames = $this->tables
;
557 // logging is enabled, so now lets create the trigger info tables
558 foreach ($tableNames as $table) {
559 $columns = $this->columnsOf($table, $force);
561 // only do the change if any data has changed
563 foreach ($columns as $column) {
564 // ignore modified_date changes
565 if ($column != 'modified_date' && !in_array($column, CRM_Utils_Array
::value($table, $this->exceptions
, array()))) {
566 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
569 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
570 $updateSQL = "IF ( (" . implode( ' OR ', $cond ) . ") AND ( $suppressLoggingCond ) ) THEN ";
572 if ($this->useDBPrefix
) {
573 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
576 $sqlStmt = "INSERT INTO log_{tableName} (";
578 foreach ($columns as $column) {
579 $sqlStmt .= "$column, ";
581 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
583 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
584 $updateSQL .= $sqlStmt;
587 foreach ($columns as $column) {
588 $sqlStmt .= "NEW.$column, ";
589 $deleteSQL .= "OLD.$column, ";
591 $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
592 $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
594 $sqlStmt .= "END IF;";
595 $deleteSQL .= "END IF;";
597 $insertSQL .= $sqlStmt;
598 $updateSQL .= $sqlStmt;
601 'table' => array($table),
608 'table' => array($table),
615 'table' => array($table),
624 * This allow logging to be temporarily disabled for certain cases
625 * where we want to do a mass cleanup but dont want to bother with
631 static function disableLoggingForThisConnection( ) {
632 // do this only if logging is enabled
633 $config = CRM_Core_Config
::singleton( );
634 if ( $config->logging
) {
635 CRM_Core_DAO
::executeQuery( 'SET @civicrm_disable_logging = 1' );