3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Logging_Schema
{
20 * Default storage engine for log tables
24 const ENGINE
= 'InnoDB';
30 private $useDBPrefix = TRUE;
33 'logging/contact/detail',
34 'logging/contact/summary',
35 'logging/contribute/detail',
36 'logging/contribute/summary',
40 * Columns that should never be subject to logging.
42 * CRM-13028 / NYSS-6933 - table => array (cols) - to be excluded from the update statement
46 private $exceptions = [
47 'civicrm_job' => ['last_run'],
48 'civicrm_group' => ['cache_date', 'refresh_date'],
52 * Specifications of all log table including
53 * - engine (default is InnoDB, if not set.)
54 * - engine_config, a string appended to the engine type.
55 * For INNODB space can be saved with 'ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4'
56 * - indexes (default is none and they cannot be added unless engine is innodb. If they are added and
57 * engine is not set to innodb an exception will be thrown since quiet acquiescence is easier to miss).
58 * - exceptions (by default those stored in $this->exceptions are included). These are
59 * excluded from the triggers.
63 private $logTableSpec = [];
66 * Setting Callback - Validate.
69 * @param array $fieldSpec
72 * @throws API_Exception
74 public static function checkLoggingSupport(&$value, $fieldSpec) {
75 if (!(CRM_Core_DAO
::checkTriggerViewPermission(FALSE)) && $value) {
76 throw new API_Exception(ts("In order to use this functionality, the installation's database user must have privileges to create triggers and views (if binary logging is enabled – this means the SUPER privilege). This install does not have the required privilege(s) enabled."));
78 // dev/core#1812 Disable logging in a multilingual environment.
79 if (CRM_Core_I18n
::isMultilingual() && $value) {
80 throw new API_Exception(ts("Logging is not supported in a multilingual environment!"));
86 * Setting Callback - On Change.
88 * Respond to changes in the "logging" setting. Set up or destroy
91 * @param array $oldValue
92 * List of component names.
93 * @param array $newValue
94 * List of component names.
95 * @param array $metadata
96 * Specification of the setting (per *.settings.php).
98 public static function onToggle($oldValue, $newValue, $metadata) {
99 if ($oldValue == $newValue) {
103 $logging = new CRM_Logging_Schema();
105 $logging->enableLogging();
108 $logging->disableLogging();
113 * Populate $this->tables and $this->logs with current db state.
115 public function __construct() {
116 $dao = new CRM_Contact_DAO_Contact();
117 $civiDBName = $dao->_database
;
119 $dao = CRM_Core_DAO
::executeQuery("
121 FROM INFORMATION_SCHEMA.TABLES
122 WHERE TABLE_SCHEMA = '{$civiDBName}'
123 AND TABLE_TYPE = 'BASE TABLE'
124 AND TABLE_NAME LIKE 'civicrm_%'
126 while ($dao->fetch()) {
127 $this->tables
[] = $dao->TABLE_NAME
;
130 // do not log temp import, cache, menu and log tables
131 $this->tables
= preg_grep('/^civicrm_import_job_/', $this->tables
, PREG_GREP_INVERT
);
132 $this->tables
= preg_grep('/_cache$/', $this->tables
, PREG_GREP_INVERT
);
133 $this->tables
= preg_grep('/_log/', $this->tables
, PREG_GREP_INVERT
);
134 $this->tables
= preg_grep('/^civicrm_queue_/', $this->tables
, PREG_GREP_INVERT
);
136 $this->tables
= preg_grep('/^civicrm_menu/', $this->tables
, PREG_GREP_INVERT
);
137 $this->tables
= preg_grep('/_temp_/', $this->tables
, PREG_GREP_INVERT
);
139 $this->tables
= preg_grep('/_bak$/', $this->tables
, PREG_GREP_INVERT
);
140 $this->tables
= preg_grep('/_backup$/', $this->tables
, PREG_GREP_INVERT
);
142 $this->tables
= preg_grep('/^civicrm_tmp_/', $this->tables
, PREG_GREP_INVERT
);
144 // do not log civicrm_mailing_event* tables, CRM-12300
145 $this->tables
= preg_grep('/^civicrm_mailing_event_/', $this->tables
, PREG_GREP_INVERT
);
147 // dev/core#1762 Don't log subscription_history
148 $this->tables
= preg_grep('/^civicrm_subscription_history/', $this->tables
, PREG_GREP_INVERT
);
150 // do not log civicrm_mailing_recipients table, CRM-16193
151 $this->tables
= array_diff($this->tables
, ['civicrm_mailing_recipients']);
152 $this->logTableSpec
= array_fill_keys($this->tables
, []);
153 foreach ($this->exceptions
as $tableName => $fields) {
154 $this->logTableSpec
[$tableName]['exceptions'] = $fields;
156 CRM_Utils_Hook
::alterLogTables($this->logTableSpec
);
157 $this->tables
= array_keys($this->logTableSpec
);
158 $nonStandardTableNameString = $this->getNonStandardTableNameFilterString();
160 if (defined('CIVICRM_LOGGING_DSN')) {
161 $dsn = DB
::parseDSN(CIVICRM_LOGGING_DSN
);
162 $this->useDBPrefix
= (CIVICRM_LOGGING_DSN
!= CIVICRM_DSN
);
165 $dsn = DB
::parseDSN(CIVICRM_DSN
);
166 $this->useDBPrefix
= FALSE;
168 $this->db
= $dsn['database'];
170 $dao = CRM_Core_DAO
::executeQuery("
172 FROM INFORMATION_SCHEMA.TABLES
173 WHERE TABLE_SCHEMA = '{$this->db}'
174 AND TABLE_TYPE = 'BASE TABLE'
175 AND (TABLE_NAME LIKE 'log_civicrm_%' $nonStandardTableNameString )
177 while ($dao->fetch()) {
178 $log = $dao->TABLE_NAME
;
179 $this->logs
[substr($log, 4)] = $log;
184 * Return logging custom data tables.
186 public function customDataLogTables() {
187 return preg_grep('/^log_civicrm_value_/', $this->logs
);
191 * Return custom data tables for specified entity / extends.
193 * @param string $extends
197 public function entityCustomDataLogTables($extends) {
198 $customGroupTables = [];
199 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity($extends);
200 $customGroupDAO->find();
201 while ($customGroupDAO->fetch()) {
202 // logging is disabled for the table (e.g by hook) then $this->logs[$customGroupDAO->table_name]
204 if (!empty($this->logs
[$customGroupDAO->table_name
])) {
205 $customGroupTables[$customGroupDAO->table_name
] = $this->logs
[$customGroupDAO->table_name
];
208 return $customGroupTables;
212 * Disable logging by dropping the triggers (but keep the log tables intact).
214 public function disableLogging() {
215 $config = CRM_Core_Config
::singleton();
216 $config->logging
= FALSE;
218 $this->dropTriggers();
220 // invoke the meta trigger creation call
221 CRM_Core_DAO
::triggerRebuild();
223 $this->deleteReports();
227 * Drop triggers for all logged tables.
229 * @param string $tableName
231 public function dropTriggers($tableName = NULL) {
232 /** @var \Civi\Core\SqlTriggers $sqlTriggers */
233 $sqlTriggers = Civi
::service('sql_triggers');
234 $dao = new CRM_Core_DAO();
237 $tableNames = [$tableName];
240 $tableNames = $this->tables
;
243 foreach ($tableNames as $table) {
244 $validName = CRM_Core_DAO
::shortenSQLName($table, 48, TRUE);
247 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_insert");
248 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_update");
249 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_delete");
252 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_insert");
253 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_update");
254 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_delete");
257 // now lets also be safe and drop all triggers that start with
258 // civicrm_ if we are dropping all triggers
259 // we need to do this to capture all the leftover triggers since
260 // we did the shortening trigger name for CRM-11794
261 if ($tableName === NULL) {
262 $triggers = $dao->executeQuery("SHOW TRIGGERS LIKE 'civicrm_%'");
264 while ($triggers->fetch()) {
265 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$triggers->Trigger}");
271 * Enable site-wide logging.
273 public function enableLogging() {
274 $this->fixSchemaDifferences(TRUE);
279 * Sync log tables and rebuild triggers.
281 * @param bool $enableLogging : Ensure logging is enabled
283 public function fixSchemaDifferences($enableLogging = FALSE) {
284 $config = CRM_Core_Config
::singleton();
285 if ($enableLogging) {
286 $config->logging
= TRUE;
288 if ($config->logging
) {
289 $this->fixSchemaDifferencesForALL();
291 // invoke the meta trigger creation call
292 CRM_Core_DAO
::triggerRebuild(NULL, TRUE);
296 * Update log tables structure.
298 * This function updates log tables to have the log_conn_id type of varchar
299 * and also implements the engine change defined by the hook (i.e. INNODB).
301 * Note changing engine & adding hook-defined indexes, but not changing back
302 * to INNODB if engine has not been deliberately set (by hook) and not
303 * dropping indexes. Sysadmin will need to manually intervene to revert to
306 * @param array $params
307 * 'updateChangedEngineConfig' - update if the engine config changes?
308 * 'forceEngineMigration' - force engine upgrade from ARCHIVE to InnoDB?
310 * @return int $updateTablesCount
311 * @throws \CiviCRM_API3_Exception
313 public function updateLogTableSchema($params) {
314 $updateLogConn = FALSE;
315 $updatedTablesCount = 0;
316 foreach ($this->logs
as $mainTable => $logTable) {
318 $tableSpec = $this->logTableSpec
[$mainTable];
319 $currentEngine = strtoupper($this->getEngineForLogTable($logTable));
320 if (!isset($tableSpec['engine']) && $currentEngine == 'ARCHIVE' && $params['forceEngineMigration']) {
321 // table uses ARCHIVE engine (the previous default) and no one set an
322 // alternative engine via hook_civicrm_alterLogTables => force change to
324 $tableSpec['engine'] = self
::ENGINE
;
326 $engineChanged = isset($tableSpec['engine']) && (strtoupper($tableSpec['engine']) != $currentEngine);
327 $engineConfigChanged = isset($tableSpec['engine_config']) && (strtoupper($tableSpec['engine_config']) != $this->getEngineConfigForLogTable($logTable));
328 if ($engineChanged ||
($engineConfigChanged && $params['updateChangedEngineConfig'])) {
329 $alterSql[] = "ENGINE=" . $tableSpec['engine'] . " " . CRM_Utils_Array
::value('engine_config', $tableSpec);
331 if (!empty($tableSpec['indexes'])) {
332 $indexes = $this->getIndexesForTable($logTable);
333 foreach ($tableSpec['indexes'] as $indexName => $indexSpec) {
334 if (!in_array($indexName, $indexes)) {
335 if (is_array($indexSpec)) {
336 $indexSpec = implode(" , ", $indexSpec);
338 $alterSql[] = "ADD INDEX {$indexName}($indexSpec)";
342 $columns = $this->columnSpecsOf($logTable);
343 if (empty($columns['log_conn_id'])) {
344 throw new Exception($logTable . print_r($columns, TRUE));
346 if ($columns['log_conn_id']['DATA_TYPE'] != 'varchar' ||
$columns['log_conn_id']['LENGTH'] != 17) {
347 $alterSql[] = "MODIFY log_conn_id VARCHAR(17)";
348 $updateLogConn = TRUE;
350 if (!empty($alterSql)) {
351 CRM_Core_DAO
::executeQuery("ALTER TABLE {$this->db}.{$logTable} " . implode(', ', $alterSql), [], TRUE, NULL, FALSE, FALSE);
352 $updatedTablesCount++
;
355 if ($updateLogConn) {
356 civicrm_api3('Setting', 'create', ['logging_uniqueid_date' => date('Y-m-d H:i:s')]);
358 return $updatedTablesCount;
362 * Get the engine for the given table.
364 * @param string $table
368 public function getEngineForLogTable($table) {
369 return strtoupper(CRM_Core_DAO
::singleValueQuery("
370 SELECT ENGINE FROM information_schema.tables WHERE TABLE_NAME = %1
371 AND table_schema = %2
372 ", [1 => [$table, 'String'], 2 => [$this->db
, 'String']]));
376 * Get the engine config for the given table.
378 * @param string $table
382 public function getEngineConfigForLogTable($table) {
383 return strtoupper(CRM_Core_DAO
::singleValueQuery("
384 SELECT CREATE_OPTIONS FROM information_schema.tables WHERE TABLE_NAME = %1
385 AND table_schema = %2
386 ", [1 => [$table, 'String'], 2 => [$this->db
, 'String']]));
390 * Get all the indexes in the table.
392 * @param string $table
396 public function getIndexesForTable($table) {
398 $result = CRM_Core_DAO
::executeQuery("
399 SELECT constraint_name AS index_name
400 FROM information_schema.key_column_usage
401 WHERE table_schema = %2 AND table_name = %1
403 SELECT index_name AS index_name
404 FROM information_schema.statistics
405 WHERE table_schema = %2 AND table_name = %1
407 [1 => [$table, 'String'], 2 => [$this->db
, 'String']]
409 while ($result->fetch()) {
410 $indexes[] = $result->index_name
;
416 * Add missing (potentially specified) log table columns for the given table.
418 * @param string $table
419 * name of the relevant table.
421 * Mixed array of columns to add or null (to check for the missing columns).
425 public function fixSchemaDifferencesFor($table, $cols = []) {
429 if (empty($this->logs
[$table])) {
430 $this->createLogTableFor($table);
435 $cols = $this->columnsWithDiffSpecs($table, "log_$table");
438 // If a column that already exists on logging table is being added, we
439 // should treat it as a modification.
440 $this->resetSchemaCacheForTable("log_$table");
441 $logTableSchema = $this->columnSpecsOf("log_$table");
442 foreach ($cols['ADD'] as $colKey => $col) {
443 if (array_key_exists($col, $logTableSchema)) {
444 $cols['MODIFY'][] = $col;
445 unset($cols['ADD'][$colKey]);
449 // use the relevant lines from CREATE TABLE to add colums to the log table
450 $create = $this->_getCreateQuery($table);
451 foreach ((['ADD', 'MODIFY']) as $alterType) {
452 if (!empty($cols[$alterType])) {
453 foreach ($cols[$alterType] as $col) {
454 $line = $this->_getColumnQuery($col, $create);
455 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table {$alterType} {$line}", [], TRUE, NULL, FALSE, FALSE);
460 // for any obsolete columns (not null) we just make the column nullable.
461 if (!empty($cols['OBSOLETE'])) {
462 $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}");
463 foreach ($cols['OBSOLETE'] as $col) {
464 $line = $this->_getColumnQuery($col, $create);
465 // This is just going to make a not null column to nullable
466 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table MODIFY {$line}", [], TRUE, NULL, FALSE, FALSE);
470 $this->resetSchemaCacheForTable("log_$table");
476 * Resets schema cache for the given table.
478 * @param string $table
481 private function resetSchemaCacheForTable($table) {
482 unset(\Civi
::$statics[__CLASS__
]['columnSpecs'][$table]);
488 * @param string $table
492 private function _getCreateQuery($table) {
493 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE {$table}", [], TRUE, NULL, FALSE, FALSE);
495 $create = explode("\n", $dao->Create_Table
);
503 * @param bool $createQuery
505 * @return array|mixed|string
507 private function _getColumnQuery($col, $createQuery) {
508 $line = preg_grep("/^ `$col` /", $createQuery);
509 $line = rtrim(array_pop($line), ',');
511 $line = self
::fixTimeStampAndNotNullSQL($line);
516 * Fix schema differences.
518 * @param bool $rebuildTrigger
520 public function fixSchemaDifferencesForAll($rebuildTrigger = FALSE) {
522 $this->resetTableColumnsCache();
524 foreach ($this->tables
as $table) {
525 if (empty($this->logs
[$table])) {
526 $this->createLogTableFor($table);
529 $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table");
533 foreach ($diffs as $table => $cols) {
534 $this->fixSchemaDifferencesFor($table, $cols);
536 if ($rebuildTrigger) {
537 // invoke the meta trigger creation call
538 CRM_Core_DAO
::triggerRebuild(NULL, TRUE);
543 * Resets columnSpecs.
545 * Resets columnSpecs static array in Civi's $statics to make sure we use the
546 * real state of the schema to perform sync operations between core and
549 private function resetTableColumnsCache() {
550 unset(\Civi
::$statics[__CLASS__
]['columnSpecs']);
556 * Log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
557 * so there's no need for a default timestamp and therefore we remove such default timestamps
558 * also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
560 * @param string $query
564 public static function fixTimeStampAndNotNullSQL($query) {
565 $query = str_ireplace("TIMESTAMP() NOT NULL", "TIMESTAMP NULL", $query);
566 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
567 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()", '', $query);
568 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
569 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP()", '', $query);
570 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
571 $query = str_ireplace("NOT NULL", '', $query);
578 private function addReports() {
580 'logging/contact/detail' => ts('Logging Details'),
581 'logging/contact/summary' => ts('Contact Logging Report (Summary)'),
582 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'),
583 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'),
585 // enable logging templates
586 CRM_Core_DAO
::executeQuery("
587 UPDATE civicrm_option_value
589 WHERE value IN ('" . implode("', '", $this->reports
) . "')
592 // add report instances
593 $domain_id = CRM_Core_Config
::domainID();
594 foreach ($this->reports
as $report) {
595 $dao = new CRM_Report_DAO_ReportInstance();
596 $dao->domain_id
= $domain_id;
597 $dao->report_id
= $report;
598 $dao->title
= $titles[$report];
599 $dao->permission
= 'administer CiviCRM';
600 if ($report == 'logging/contact/summary') {
601 $dao->is_reserved
= 1;
608 * Get an array of column names of the given table.
610 * @param string $table
615 private function columnsOf($table, $force = FALSE) {
616 if ($force ||
!isset(\Civi
::$statics[__CLASS__
]['columnsOf'][$table])) {
617 $from = (substr($table, 0, 4) == 'log_') ?
"`{$this->db}`.$table" : $table;
618 CRM_Core_TemporaryErrorScope
::ignoreException();
619 $dao = CRM_Core_DAO
::executeQuery("SHOW COLUMNS FROM $from", [], TRUE, NULL, FALSE, FALSE);
620 if (is_a($dao, 'DB_Error')) {
623 \Civi
::$statics[__CLASS__
]['columnsOf'][$table] = [];
624 while ($dao->fetch()) {
625 \Civi
::$statics[__CLASS__
]['columnsOf'][$table][] = CRM_Utils_Type
::escape($dao->Field
, 'MysqlColumnNameOrAlias');
628 return \Civi
::$statics[__CLASS__
]['columnsOf'][$table];
632 * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table.
634 * @param string $table
638 private function columnSpecsOf($table) {
639 static $civiDB = NULL;
640 if (empty(\Civi
::$statics[__CLASS__
]['columnSpecs'])) {
641 \Civi
::$statics[__CLASS__
]['columnSpecs'] = [];
643 if (empty(\Civi
::$statics[__CLASS__
]['columnSpecs']) ||
!isset(\Civi
::$statics[__CLASS__
]['columnSpecs'][$table])) {
645 $dao = new CRM_Contact_DAO_Contact();
646 $civiDB = $dao->_database
;
648 CRM_Core_TemporaryErrorScope
::ignoreException();
649 // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
650 // than firing query for every given table.
652 SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE, EXTRA
653 FROM INFORMATION_SCHEMA.COLUMNS
654 WHERE table_schema IN ('{$this->db}', '{$civiDB}')";
655 $dao = CRM_Core_DAO
::executeQuery($query);
656 if (is_a($dao, 'DB_Error')) {
659 while ($dao->fetch()) {
660 if (!array_key_exists($dao->TABLE_NAME
, \Civi
::$statics[__CLASS__
]['columnSpecs'])) {
661 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
] = [];
663 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
][$dao->COLUMN_NAME
] = [
664 'COLUMN_NAME' => $dao->COLUMN_NAME
,
665 'DATA_TYPE' => $dao->DATA_TYPE
,
666 'IS_NULLABLE' => $dao->IS_NULLABLE
,
667 'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT
,
668 'EXTRA' => $dao->EXTRA
,
670 if (($first = strpos($dao->COLUMN_TYPE
, '(')) != 0) {
671 // this extracts the value between parentheses after the column type.
672 // it could be the column length, i.e. "int(8)", "decimal(20,2)")
673 // or the permitted values of an enum (e.g. "enum('A','B')")
675 $dao->COLUMN_TYPE
, $first +
1, strpos($dao->COLUMN_TYPE
, ')') - $first - 1
677 if (strpos($parValue, "'") === FALSE) {
678 // no quote in value means column length
679 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
][$dao->COLUMN_NAME
]['LENGTH'] = $parValue;
682 // single quote means enum permitted values
683 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
][$dao->COLUMN_NAME
]['ENUM_VALUES'] = $parValue;
688 return \Civi
::$statics[__CLASS__
]['columnSpecs'][$table];
692 * Get columns that have changed.
694 * @param string $civiTable
695 * @param string $logTable
699 public function columnsWithDiffSpecs($civiTable, $logTable) {
700 $civiTableSpecs = $this->columnSpecsOf($civiTable);
701 $logTableSpecs = $this->columnSpecsOf($logTable);
703 $diff = ['ADD' => [], 'MODIFY' => [], 'OBSOLETE' => []];
704 // columns to be added
705 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
706 // columns to be modified
707 // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
708 // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
709 foreach ($civiTableSpecs as $col => $colSpecs) {
710 if (!isset($logTableSpecs[$col]) ||
!is_array($logTableSpecs[$col])) {
711 $logTableSpecs[$col] = [];
713 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
714 if (!empty($specDiff) && $col != 'id' && !in_array($col, $diff['ADD'])) {
715 if (empty($colSpecs['EXTRA']) ||
(!empty($colSpecs['EXTRA']) && $colSpecs['EXTRA'] !== 'auto_increment')) {
716 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
717 if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array
::value('DATA_TYPE', $logTableSpecs[$col])
718 // We won't alter the log if the length is decreased in case some of the existing data won't fit.
719 || CRM_Utils_Array
::value('LENGTH', $civiTableSpecs[$col]) > CRM_Utils_Array
::value('LENGTH', $logTableSpecs[$col])
721 // if data-type is different, surely consider the column
722 $diff['MODIFY'][] = $col;
724 elseif ($civiTableSpecs[$col]['DATA_TYPE'] == 'enum' &&
725 CRM_Utils_Array
::value('ENUM_VALUES', $civiTableSpecs[$col]) != CRM_Utils_Array
::value('ENUM_VALUES', $logTableSpecs[$col])
727 // column is enum and the permitted values have changed
728 $diff['MODIFY'][] = $col;
730 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array
::value('IS_NULLABLE', $logTableSpecs[$col]) &&
731 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
733 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
734 $diff['MODIFY'][] = $col;
736 elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array
::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
737 !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')
739 // if default property is different, and its not about a timestamp column, consider it
740 $diff['MODIFY'][] = $col;
746 // columns to made obsolete by turning into not-null
747 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
748 foreach ($oldCols as $col) {
749 if (!in_array($col, ['log_date', 'log_conn_id', 'log_user_id', 'log_action']) &&
750 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
752 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
753 $diff['OBSOLETE'][] = $col;
761 * Getter for logTableSpec.
765 public function getLogTableSpec() {
766 return $this->logTableSpec
;
770 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
772 * @param string $table
774 private function createLogTableFor($table) {
775 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE $table", [], TRUE, NULL, FALSE, FALSE);
777 $query = $dao->Create_Table
;
779 // rewrite the queries into CREATE TABLE queries for log tables:
782 log_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
783 log_conn_id VARCHAR(17),
785 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
788 if (!empty($this->logTableSpec
[$table]['indexes'])) {
789 foreach ($this->logTableSpec
[$table]['indexes'] as $indexName => $indexSpec) {
790 if (is_array($indexSpec)) {
791 $indexSpec = implode(" , ", $indexSpec);
793 $cols .= ", INDEX {$indexName}($indexSpec)";
797 // - prepend the name with log_
798 // - drop AUTO_INCREMENT columns
799 // - drop non-column rows of the query (keys, constraints, etc.)
800 // - set the ENGINE to the specified engine (default is INNODB)
801 // - add log-specific columns (at the end of the table)
803 $engines = CRM_Core_DAO
::executeQuery("SHOW ENGINES");
804 while ($engines->fetch()) {
805 if ($engines->Support
== 'YES' ||
$engines->Support
== 'DEFAULT') {
806 $mysqlEngines[] = $engines->Engine
;
809 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
810 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
811 $query = preg_replace("/^ [^`].*$/m", '', $query);
812 $engine = strtoupper(CRM_Utils_Array
::value('engine', $this->logTableSpec
[$table], self
::ENGINE
));
813 $engine .= " " . CRM_Utils_Array
::value('engine_config', $this->logTableSpec
[$table]);
814 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=' . $engine . ' ', $query);
816 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
817 // so there's no need for a default timestamp and therefore we remove such default timestamps
818 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
819 $query = self
::fixTimeStampAndNotNullSQL($query);
820 $query = preg_replace("/(,*\n*\) )ENGINE/m", "$cols\n) ENGINE", $query);
822 CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
824 $columns = implode(', ', $this->columnsOf($table));
825 CRM_Core_DAO
::executeQuery("INSERT INTO `{$this->db}`.log_$table ($columns, log_conn_id, log_user_id, log_action) SELECT $columns, @uniqueID, @civicrm_user_id, 'Initialization' FROM {$table}", [], TRUE, NULL, FALSE, FALSE);
827 $this->tables
[] = $table;
828 if (empty($this->logs
)) {
829 civicrm_api3('Setting', 'create', ['logging_uniqueid_date' => date('Y-m-d H:i:s')]);
830 civicrm_api3('Setting', 'create', ['logging_all_tables_uniquid' => 1]);
832 $this->logs
[$table] = "log_$table";
838 private function deleteReports() {
839 // disable logging templates
840 CRM_Core_DAO
::executeQuery("
841 UPDATE civicrm_option_value
843 WHERE value IN ('" . implode("', '", $this->reports
) . "')
846 // delete report instances
847 $domain_id = CRM_Core_Config
::domainID();
848 foreach ($this->reports
as $report) {
849 $dao = new CRM_Report_DAO_ReportInstance();
850 $dao->domain_id
= $domain_id;
851 $dao->report_id
= $report;
857 * Predicate whether logging is enabled.
859 public function isEnabled() {
860 if (\Civi
::settings()->get('logging')) {
861 return ($this->tablesExist() && (\Civi
::settings()->get('logging_no_trigger_permission') ||
$this->triggersExist()));
867 * Predicate whether any log tables exist.
869 private function tablesExist() {
870 return !empty($this->logs
);
874 * Drop all log tables.
876 * This does not currently have a usage outside the tests.
878 public function dropAllLogTables() {
879 if ($this->tablesExist()) {
880 foreach ($this->logs
as $log_table) {
881 CRM_Core_DAO
::executeQuery("DROP TABLE $log_table");
887 * Get an sql clause to find the names of any log tables that do not match the normal pattern.
889 * Most tables are civicrm_xxx with the log table being log_civicrm_xxx
890 * However, they don't have to match this pattern (e.g when defined by hook) so find the
891 * anomalies and return a filter string to include them.
895 public function getNonStandardTableNameFilterString() {
896 $nonStandardTableNames = preg_grep('/^civicrm_/', $this->tables
, PREG_GREP_INVERT
);
897 if (empty($nonStandardTableNames)) {
900 $nonStandardTableLogs = [];
901 foreach ($nonStandardTableNames as $nonStandardTableName) {
902 $nonStandardTableLogs[] = "'log_{$nonStandardTableName}'";
904 return " OR TABLE_NAME IN (" . implode(',', $nonStandardTableLogs) . ")";
908 * Predicate whether the logging triggers are in place.
910 private function triggersExist() {
911 // FIXME: probably should be a bit more thorough…
912 // note that the LIKE parameter is TABLE NAME
913 return (bool) CRM_Core_DAO
::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
920 * @param null $tableName
923 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
924 if (!CRM_Core_Config
::singleton()->logging
) {
928 $insert = ['INSERT'];
929 $update = ['UPDATE'];
930 $delete = ['DELETE'];
933 $tableNames = [$tableName];
936 $tableNames = $this->tables
;
939 // logging is enabled, so now lets create the trigger info tables
940 foreach ($tableNames as $table) {
941 if (!isset($this->logTableSpec
[$table])) {
942 // Per testIgnoreCustomTableByHook this would be unset if a hook had
943 // intervened to prevent logging / triggers on this table.
944 // This could go to the extent of blocking the updates to 'modified_date'
945 // which makes sense, in particular, for calculated fields.
948 $columns = $this->columnsOf($table, $force);
950 // only do the change if any data has changed
952 foreach ($columns as $column) {
953 $tableExceptions = array_key_exists('exceptions', $this->logTableSpec
[$table]) ?
$this->logTableSpec
[$table]['exceptions'] : [];
954 // ignore modified_date changes
955 $tableExceptions[] = 'modified_date';
956 // exceptions may be provided with or without backticks
957 $excludeColumn = in_array($column, $tableExceptions) ||
958 in_array(str_replace('`', '', $column), $tableExceptions);
959 if (!$excludeColumn) {
960 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
963 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
964 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
966 if ($this->useDBPrefix
) {
967 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
970 $sqlStmt = "INSERT INTO log_{tableName} (";
972 foreach ($columns as $column) {
973 $sqlStmt .= "$column, ";
975 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
977 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
978 $updateSQL .= $sqlStmt;
981 foreach ($columns as $column) {
982 $sqlStmt .= "NEW.$column, ";
983 $deleteSQL .= "OLD.$column, ";
985 if (civicrm_api3('Setting', 'getvalue', ['name' => 'logging_uniqueid_date'])) {
986 // Note that when connecting directly via mysql @uniqueID may not be set so a fallback is
987 // 'c_' to identify a non-CRM connection + timestamp to the hour + connection_id
988 // If the connection_id is longer than 6 chars it will be truncated.
989 // We tried setting the @uniqueID in the trigger but it was unreliable.
990 // An external interaction could split over 2 connections & it seems worth blocking the revert on
991 // these reports & adding extra permissioning to the api for this.
992 $connectionSQLString = "COALESCE(@uniqueID, LEFT(CONCAT('c_', unix_timestamp()/3600, CONNECTION_ID()), 17))";
995 // The log tables have not yet been converted to have varchar(17) fields for log_conn_id.
996 // Continue to use the less reliable connection_id for al tables for now.
997 $connectionSQLString = "CONNECTION_ID()";
999 $sqlStmt .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
1000 $deleteSQL .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
1002 $insertSQL .= $sqlStmt;
1003 $updateSQL .= $sqlStmt;
1006 'table' => [$table],
1009 'sql' => $insertSQL,
1013 'table' => [$table],
1016 'sql' => $updateSQL,
1020 'table' => [$table],
1023 'sql' => $deleteSQL,
1029 * Disable logging temporarily.
1031 * This allow logging to be temporarily disabled for certain cases
1032 * where we want to do a mass cleanup but do not want to bother with
1035 public static function disableLoggingForThisConnection() {
1036 if (CRM_Core_Config
::singleton()->logging
) {
1037 CRM_Core_DAO
::executeQuery('SET @civicrm_disable_logging = 1');
1042 * Get all the log tables that reference civicrm_contact.
1044 * Note that it might make sense to wrap this in a getLogTablesForEntity
1045 * but this is the only entity currently available...
1047 public function getLogTablesForContact() {
1048 $tables = array_keys(CRM_Core_DAO
::getReferencesToContactTable());
1049 // This additional hardcoding has been moved from getReferencesToContactTable
1050 // to here as it is not needed in the other place where the function is called.
1051 // It may not be needed here either...
1052 $tables[] = 'civicrm_entity_tag';
1053 return array_intersect($tables, $this->tables
);
1057 * Retrieve missing log tables.
1061 public function getMissingLogTables() {
1062 if ($this->tablesExist()) {
1063 return array_diff($this->tables
, array_keys($this->logs
));