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 * Name of the database where the logging data is stored.
36 private $useDBPrefix = TRUE;
39 'logging/contact/detail',
40 'logging/contact/summary',
41 'logging/contribute/detail',
42 'logging/contribute/summary',
46 * Columns that should never be subject to logging.
48 * CRM-13028 / NYSS-6933 - table => array (cols) - to be excluded from the update statement
52 private $exceptions = [
53 'civicrm_job' => ['last_run'],
54 'civicrm_group' => ['cache_date', 'refresh_date'],
58 * Specifications of all log table including
59 * - engine (default is InnoDB, if not set.)
60 * - engine_config, a string appended to the engine type.
61 * For INNODB space can be saved with 'ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4'
62 * - indexes (default is none and they cannot be added unless engine is innodb. If they are added and
63 * engine is not set to innodb an exception will be thrown since quiet acquiescence is easier to miss).
64 * - exceptions (by default those stored in $this->exceptions are included). These are
65 * excluded from the triggers.
69 private $logTableSpec = [];
72 * Setting Callback - Validate.
75 * @param array $fieldSpec
78 * @throws API_Exception
80 public static function checkLoggingSupport(&$value, $fieldSpec) {
81 if (!(CRM_Core_DAO
::checkTriggerViewPermission(FALSE)) && $value) {
82 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."));
84 // dev/core#1812 Disable logging in a multilingual environment.
85 if (CRM_Core_I18n
::isMultilingual() && $value) {
86 throw new API_Exception(ts("Logging is not supported in a multilingual environment!"));
92 * Setting Callback - On Change.
94 * Respond to changes in the "logging" setting. Set up or destroy
97 * @param array $oldValue
98 * List of component names.
99 * @param array $newValue
100 * List of component names.
101 * @param array $metadata
102 * Specification of the setting (per *.settings.php).
104 public static function onToggle($oldValue, $newValue, $metadata) {
105 if ($oldValue == $newValue) {
109 $logging = new CRM_Logging_Schema();
111 $logging->enableLogging();
114 $logging->disableLogging();
119 * Populate $this->tables and $this->logs with current db state.
121 public function __construct() {
122 $civiDBName = $this->getCiviCRMDatabaseName();
124 $dao = CRM_Core_DAO
::executeQuery("
126 FROM INFORMATION_SCHEMA.TABLES
127 WHERE TABLE_SCHEMA = '{$civiDBName}'
128 AND TABLE_TYPE = 'BASE TABLE'
129 AND TABLE_NAME LIKE 'civicrm_%'
131 while ($dao->fetch()) {
132 $this->tables
[] = $dao->TABLE_NAME
;
134 // Get any non standard table names used for custom groups.
135 // include these BEFORE the hook is called.
136 $customFieldDAO = CRM_Core_DAO
::executeQuery("
137 SELECT DISTINCT table_name as TABLE_NAME FROM civicrm_custom_group
138 where table_name NOT LIKE 'civicrm_%';
140 while ($customFieldDAO->fetch()) {
141 $this->tables
[] = $customFieldDAO->TABLE_NAME
;
144 // do not log temp import, cache, menu and log tables
145 $this->tables
= preg_grep('/^civicrm_import_job_/', $this->tables
, PREG_GREP_INVERT
);
146 $this->tables
= preg_grep('/_cache$/', $this->tables
, PREG_GREP_INVERT
);
147 $this->tables
= preg_grep('/_log/', $this->tables
, PREG_GREP_INVERT
);
148 $this->tables
= preg_grep('/^civicrm_queue_/', $this->tables
, PREG_GREP_INVERT
);
150 $this->tables
= preg_grep('/^civicrm_menu/', $this->tables
, PREG_GREP_INVERT
);
151 $this->tables
= preg_grep('/_temp_/', $this->tables
, PREG_GREP_INVERT
);
153 $this->tables
= preg_grep('/_bak$/', $this->tables
, PREG_GREP_INVERT
);
154 $this->tables
= preg_grep('/_backup$/', $this->tables
, PREG_GREP_INVERT
);
156 $this->tables
= preg_grep('/^civicrm_tmp_/', $this->tables
, PREG_GREP_INVERT
);
158 // do not log civicrm_mailing_event* tables, CRM-12300
159 $this->tables
= preg_grep('/^civicrm_mailing_event_/', $this->tables
, PREG_GREP_INVERT
);
161 // dev/core#1762 Don't log subscription_history
162 $this->tables
= preg_grep('/^civicrm_subscription_history/', $this->tables
, PREG_GREP_INVERT
);
164 // do not log civicrm_mailing_recipients table, CRM-16193
165 $this->tables
= array_diff($this->tables
, ['civicrm_mailing_recipients']);
166 $this->logTableSpec
= array_fill_keys($this->tables
, []);
167 foreach ($this->exceptions
as $tableName => $fields) {
168 $this->logTableSpec
[$tableName]['exceptions'] = $fields;
170 CRM_Utils_Hook
::alterLogTables($this->logTableSpec
);
171 $this->tables
= array_keys($this->logTableSpec
);
172 $nonStandardTableNameString = $this->getNonStandardTableNameFilterString();
174 $this->db
= $this->getDatabaseNameFromDSN(defined('CIVICRM_LOGGING_DSN') ? CIVICRM_LOGGING_DSN
: CIVICRM_DSN
);
175 $this->useDBPrefix
= $this->db
!== $civiDBName;
177 $dao = CRM_Core_DAO
::executeQuery("
179 FROM INFORMATION_SCHEMA.TABLES
180 WHERE TABLE_SCHEMA = '{$this->db}'
181 AND TABLE_TYPE = 'BASE TABLE'
182 AND (TABLE_NAME LIKE 'log_civicrm_%' $nonStandardTableNameString )
184 while ($dao->fetch()) {
185 $log = $dao->TABLE_NAME
;
186 $this->logs
[substr($log, 4)] = $log;
191 * Return logging custom data tables.
193 public function customDataLogTables() {
194 return preg_grep('/^log_civicrm_value_/', $this->logs
);
198 * Return custom data tables for specified entity / extends.
200 * @param string $extends
204 public function entityCustomDataLogTables($extends) {
205 $customGroupTables = [];
206 $customGroupDAO = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity($extends);
207 $customGroupDAO->find();
208 while ($customGroupDAO->fetch()) {
209 // logging is disabled for the table (e.g by hook) then $this->logs[$customGroupDAO->table_name]
211 if (!empty($this->logs
[$customGroupDAO->table_name
])) {
212 $customGroupTables[$customGroupDAO->table_name
] = $this->logs
[$customGroupDAO->table_name
];
215 return $customGroupTables;
219 * Disable logging by dropping the triggers (but keep the log tables intact).
221 public function disableLogging() {
222 $config = CRM_Core_Config
::singleton();
223 $config->logging
= FALSE;
225 $this->dropTriggers();
227 // invoke the meta trigger creation call
228 CRM_Core_DAO
::triggerRebuild();
230 $this->deleteReports();
234 * Drop triggers for all logged tables.
236 * @param string $tableName
238 public function dropTriggers($tableName = NULL): void
{
239 /** @var \Civi\Core\SqlTriggers $sqlTriggers */
240 $sqlTriggers = Civi
::service('sql_triggers');
241 $dao = new CRM_Core_DAO();
244 $tableNames = [$tableName];
247 $tableNames = $this->tables
;
250 // Sort the table names so the sql output is consistent for those sites
251 // loading it asynchronously (using the setting 'logging_no_trigger_permission')
253 foreach ($tableNames as $table) {
254 $validName = CRM_Core_DAO
::shortenSQLName($table, 48, TRUE);
257 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_insert");
258 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_update");
259 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_delete");
262 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_insert");
263 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_update");
264 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_delete");
267 // now lets also be safe and drop all triggers that start with
268 // civicrm_ if we are dropping all triggers
269 // we need to do this to capture all the leftover triggers since
270 // we did the shortening trigger name for CRM-11794
271 if ($tableName === NULL) {
272 $triggers = $dao->executeQuery("SHOW TRIGGERS LIKE 'civicrm_%'");
274 while ($triggers->fetch()) {
275 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$triggers->Trigger}");
281 * Enable site-wide logging.
283 public function enableLogging() {
284 $this->fixSchemaDifferences(TRUE);
289 * Sync log tables and rebuild triggers.
291 * @param bool $enableLogging : Ensure logging is enabled
293 public function fixSchemaDifferences($enableLogging = FALSE) {
294 $config = CRM_Core_Config
::singleton();
295 if ($enableLogging) {
296 $config->logging
= TRUE;
298 if ($config->logging
) {
299 $this->fixSchemaDifferencesForAll();
301 // invoke the meta trigger creation call
302 CRM_Core_DAO
::triggerRebuild(NULL, TRUE);
306 * Update log tables structure.
308 * This function updates log tables to have the log_conn_id type of varchar
309 * and also implements the engine change defined by the hook (i.e. INNODB).
311 * Note changing engine & adding hook-defined indexes, but not changing back
312 * to INNODB if engine has not been deliberately set (by hook) and not
313 * dropping indexes. Sysadmin will need to manually intervene to revert to
316 * @param array $params
317 * 'updateChangedEngineConfig' - update if the engine config changes?
318 * 'forceEngineMigration' - force engine upgrade from ARCHIVE to InnoDB?
320 * @return int $updateTablesCount
321 * @throws \CiviCRM_API3_Exception
323 public function updateLogTableSchema($params) {
324 $updateLogConn = FALSE;
325 $updatedTablesCount = 0;
326 foreach ($this->logs
as $mainTable => $logTable) {
328 $tableSpec = $this->logTableSpec
[$mainTable];
329 $currentEngine = strtoupper($this->getEngineForLogTable($logTable));
330 if (!isset($tableSpec['engine']) && $currentEngine == 'ARCHIVE' && $params['forceEngineMigration']) {
331 // table uses ARCHIVE engine (the previous default) and no one set an
332 // alternative engine via hook_civicrm_alterLogTables => force change to
334 $tableSpec['engine'] = self
::ENGINE
;
336 $engineChanged = isset($tableSpec['engine']) && (strtoupper($tableSpec['engine']) != $currentEngine);
337 $engineConfigChanged = isset($tableSpec['engine_config']) && (strtoupper($tableSpec['engine_config']) != $this->getEngineConfigForLogTable($logTable));
338 if ($engineChanged ||
($engineConfigChanged && $params['updateChangedEngineConfig'])) {
339 $alterSql[] = "ENGINE=" . $tableSpec['engine'] . " " . CRM_Utils_Array
::value('engine_config', $tableSpec);
341 if (!empty($tableSpec['indexes'])) {
342 $indexes = $this->getIndexesForTable($logTable);
343 foreach ($tableSpec['indexes'] as $indexName => $indexSpec) {
344 if (!in_array($indexName, $indexes)) {
345 if (is_array($indexSpec)) {
346 $indexSpec = implode(" , ", $indexSpec);
348 $alterSql[] = "ADD INDEX {$indexName}($indexSpec)";
352 $columns = $this->columnSpecsOf($logTable);
353 if (empty($columns['log_conn_id'])) {
354 throw new Exception($logTable . print_r($columns, TRUE));
356 if ($columns['log_conn_id']['DATA_TYPE'] != 'varchar' ||
$columns['log_conn_id']['LENGTH'] != 17) {
357 $alterSql[] = "MODIFY log_conn_id VARCHAR(17)";
358 $updateLogConn = TRUE;
360 if (!empty($alterSql)) {
361 CRM_Core_DAO
::executeQuery("ALTER TABLE {$this->db}.{$logTable} " . implode(', ', $alterSql), [], TRUE, NULL, FALSE, FALSE);
362 $updatedTablesCount++
;
365 if ($updateLogConn) {
366 civicrm_api3('Setting', 'create', ['logging_uniqueid_date' => date('Y-m-d H:i:s')]);
368 return $updatedTablesCount;
372 * Get the engine for the given table.
374 * @param string $table
378 public function getEngineForLogTable($table) {
379 return strtoupper(CRM_Core_DAO
::singleValueQuery("
380 SELECT ENGINE FROM information_schema.tables WHERE TABLE_NAME = %1
381 AND table_schema = %2
382 ", [1 => [$table, 'String'], 2 => [$this->db
, 'String']]));
386 * Get the engine config for the given table.
388 * @param string $table
392 public function getEngineConfigForLogTable($table) {
393 return strtoupper(CRM_Core_DAO
::singleValueQuery("
394 SELECT CREATE_OPTIONS FROM information_schema.tables WHERE TABLE_NAME = %1
395 AND table_schema = %2
396 ", [1 => [$table, 'String'], 2 => [$this->db
, 'String']]));
400 * Get all the indexes in the table.
402 * @param string $table
406 public function getIndexesForTable($table) {
408 $result = CRM_Core_DAO
::executeQuery("
409 SELECT constraint_name AS index_name
410 FROM information_schema.key_column_usage
411 WHERE table_schema = %2 AND table_name = %1
413 SELECT index_name AS index_name
414 FROM information_schema.statistics
415 WHERE table_schema = %2 AND table_name = %1
417 [1 => [$table, 'String'], 2 => [$this->db
, 'String']]
419 while ($result->fetch()) {
420 $indexes[] = $result->index_name
;
426 * Add missing (potentially specified) log table columns for the given table.
428 * @param string $table
429 * name of the relevant table.
431 * Mixed array of columns to add or null (to check for the missing columns).
433 public function fixSchemaDifferencesFor(string $table, array $cols = []): void
{
434 if (!in_array($table, $this->tables
, TRUE)) {
435 // Create the table if the log table does not exist and
436 // the table is in 'this->tables'. This latter array
437 // could have been altered by a hook if the site does not
438 // want to log a specific table.
441 if (empty($this->logs
[$table])) {
442 $this->createLogTableFor($table);
447 $cols = $this->columnsWithDiffSpecs($table, "log_$table");
450 // If a column that already exists on logging table is being added, we
451 // should treat it as a modification.
452 $this->resetSchemaCacheForTable("log_$table");
453 $logTableSchema = $this->columnSpecsOf("log_$table");
454 if (!empty($cols['ADD'])) {
455 foreach ($cols['ADD'] as $colKey => $col) {
456 if (array_key_exists($col, $logTableSchema)) {
457 $cols['MODIFY'][] = $col;
458 unset($cols['ADD'][$colKey]);
463 // use the relevant lines from CREATE TABLE to add colums to the log table
464 $create = $this->_getCreateQuery($table);
465 foreach ((['ADD', 'MODIFY']) as $alterType) {
466 if (!empty($cols[$alterType])) {
467 foreach ($cols[$alterType] as $col) {
468 $line = $this->_getColumnQuery($col, $create);
469 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table {$alterType} {$line}", [], TRUE, NULL, FALSE, FALSE);
474 // for any obsolete columns (not null) we just make the column nullable.
475 if (!empty($cols['OBSOLETE'])) {
476 $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}");
477 foreach ($cols['OBSOLETE'] as $col) {
478 $line = $this->_getColumnQuery($col, $create);
479 // This is just going to make a not null column to nullable
480 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table MODIFY {$line}", [], TRUE, NULL, FALSE, FALSE);
484 $this->resetSchemaCacheForTable("log_$table");
488 * Resets schema cache for the given table.
490 * @param string $table
493 private function resetSchemaCacheForTable($table) {
494 unset(\Civi
::$statics[__CLASS__
]['columnSpecs'][$table]);
500 * @param string $table
504 private function _getCreateQuery($table) {
505 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE {$table}", [], TRUE, NULL, FALSE, FALSE);
507 $create = explode("\n", $dao->Create_Table
);
515 * @param array $createQuery
517 * @return array|mixed|string
519 private function _getColumnQuery($col, $createQuery) {
520 $line = preg_grep("/^ `$col` /", $createQuery);
521 $line = rtrim(array_pop($line), ',');
523 $line = self
::fixTimeStampAndNotNullSQL($line);
528 * Fix schema differences.
530 public function fixSchemaDifferencesForAll(): void
{
532 $this->resetTableColumnsCache();
534 foreach ($this->tables
as $table) {
535 if (empty($this->logs
[$table])) {
536 $this->createLogTableFor($table);
539 $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table");
543 foreach ($diffs as $table => $cols) {
544 $this->fixSchemaDifferencesFor($table, $cols);
549 * Resets columnSpecs.
551 * Resets columnSpecs static array in Civi's $statics to make sure we use the
552 * real state of the schema to perform sync operations between core and
555 private function resetTableColumnsCache() {
556 unset(\Civi
::$statics[__CLASS__
]['columnSpecs']);
562 * Log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
563 * so there's no need for a default timestamp and therefore we remove such default timestamps
564 * also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
566 * @param string $query
570 public static function fixTimeStampAndNotNullSQL($query) {
571 $query = str_ireplace("TIMESTAMP() NOT NULL", "TIMESTAMP NULL", $query);
572 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
573 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()", '', $query);
574 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
575 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP()", '', $query);
576 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
577 $query = str_ireplace("NOT NULL", '', $query);
584 private function addReports() {
586 'logging/contact/detail' => ts('Logging Details'),
587 'logging/contact/summary' => ts('Contact Logging Report (Summary)'),
588 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'),
589 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'),
591 // enable logging templates
592 CRM_Core_DAO
::executeQuery("
593 UPDATE civicrm_option_value
595 WHERE value IN ('" . implode("', '", $this->reports
) . "')
598 // add report instances
599 $domain_id = CRM_Core_Config
::domainID();
600 foreach ($this->reports
as $report) {
601 $dao = new CRM_Report_DAO_ReportInstance();
602 $dao->domain_id
= $domain_id;
603 $dao->report_id
= $report;
604 $dao->title
= $titles[$report];
605 $dao->permission
= 'administer CiviCRM';
606 if ($report == 'logging/contact/summary') {
607 $dao->is_reserved
= 1;
614 * Get an array of column names of the given table.
616 * @param string $table
621 private function columnsOf($table, $force = FALSE) {
622 if ($force ||
!isset(\Civi
::$statics[__CLASS__
]['columnsOf'][$table])) {
623 $from = (substr($table, 0, 4) == 'log_') ?
"`{$this->db}`.$table" : $table;
624 $dao = CRM_Core_DAO
::executeQuery("SHOW COLUMNS FROM $from", [], TRUE, NULL, FALSE, FALSE);
625 if (is_a($dao, 'DB_Error')) {
628 \Civi
::$statics[__CLASS__
]['columnsOf'][$table] = [];
629 while ($dao->fetch()) {
630 \Civi
::$statics[__CLASS__
]['columnsOf'][$table][] = CRM_Utils_Type
::escape($dao->Field
, 'MysqlColumnNameOrAlias');
633 return \Civi
::$statics[__CLASS__
]['columnsOf'][$table];
637 * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table.
639 * @param string $table
643 private function columnSpecsOf($table) {
644 static $civiDB = NULL;
645 if (empty(\Civi
::$statics[__CLASS__
]['columnSpecs'])) {
646 \Civi
::$statics[__CLASS__
]['columnSpecs'] = [];
648 if (empty(\Civi
::$statics[__CLASS__
]['columnSpecs']) ||
!isset(\Civi
::$statics[__CLASS__
]['columnSpecs'][$table])) {
650 $dao = new CRM_Contact_DAO_Contact();
651 $civiDB = $dao->_database
;
654 // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
655 // than firing query for every given table.
657 SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE, EXTRA
658 FROM INFORMATION_SCHEMA.COLUMNS
659 WHERE table_schema IN ('{$this->db}', '{$civiDB}')";
660 $dao = CRM_Core_DAO
::executeQuery($query);
661 if (is_a($dao, 'DB_Error')) {
664 while ($dao->fetch()) {
665 if (!array_key_exists($dao->TABLE_NAME
, \Civi
::$statics[__CLASS__
]['columnSpecs'])) {
666 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
] = [];
668 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
][$dao->COLUMN_NAME
] = [
669 'COLUMN_NAME' => $dao->COLUMN_NAME
,
670 'DATA_TYPE' => $dao->DATA_TYPE
,
671 'IS_NULLABLE' => $dao->IS_NULLABLE
,
672 'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT
,
673 'EXTRA' => $dao->EXTRA
,
675 if (($first = strpos($dao->COLUMN_TYPE
, '(')) != 0) {
676 // this extracts the value between parentheses after the column type.
677 // it could be the column length, i.e. "int(8)", "decimal(20,2)")
678 // or the permitted values of an enum (e.g. "enum('A','B')")
680 $dao->COLUMN_TYPE
, $first +
1, strpos($dao->COLUMN_TYPE
, ')') - $first - 1
682 if (strpos($parValue, "'") === FALSE) {
683 // no quote in value means column length
684 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
][$dao->COLUMN_NAME
]['LENGTH'] = $parValue;
687 // single quote means enum permitted values
688 \Civi
::$statics[__CLASS__
]['columnSpecs'][$dao->TABLE_NAME
][$dao->COLUMN_NAME
]['ENUM_VALUES'] = $parValue;
693 return \Civi
::$statics[__CLASS__
]['columnSpecs'][$table];
697 * Get columns that have changed.
699 * @param string $civiTable
700 * @param string $logTable
704 public function columnsWithDiffSpecs($civiTable, $logTable) {
705 $civiTableSpecs = $this->columnSpecsOf($civiTable);
706 $logTableSpecs = $this->columnSpecsOf($logTable);
708 $diff = ['ADD' => [], 'MODIFY' => [], 'OBSOLETE' => []];
710 // Columns to be added
711 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
713 // Columns to be modified
714 // Only pick columns where there is a spec change and the column definition was not deliberately modified by
715 // fixTimeStampAndNotNullSQL() method, also accounting for differences in db version.
716 foreach ($civiTableSpecs as $col => $colSpecs) {
717 if (!isset($logTableSpecs[$col]) ||
!is_array($logTableSpecs[$col])) {
718 $logTableSpecs[$col] = [];
720 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
721 if (!empty($specDiff) && $col !== 'id' && !in_array($col, $diff['ADD'])) {
722 if (empty($colSpecs['EXTRA']) ||
(!empty($colSpecs['EXTRA']) && $colSpecs['EXTRA'] !== 'auto_increment')) {
723 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
724 if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array
::value('DATA_TYPE', $logTableSpecs[$col])
725 // We won't alter the log if the length is decreased in case some of the existing data won't fit.
726 || CRM_Utils_Array
::value('LENGTH', $civiTableSpecs[$col]) > CRM_Utils_Array
::value('LENGTH', $logTableSpecs[$col])
728 // if data-type is different, surely consider the column
729 $diff['MODIFY'][] = $col;
731 elseif ($civiTableSpecs[$col]['DATA_TYPE'] === 'enum' &&
732 CRM_Utils_Array
::value('ENUM_VALUES', $civiTableSpecs[$col]) != CRM_Utils_Array
::value('ENUM_VALUES', $logTableSpecs[$col])
734 // column is enum and the permitted values have changed
735 $diff['MODIFY'][] = $col;
737 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array
::value('IS_NULLABLE', $logTableSpecs[$col]) &&
738 $logTableSpecs[$col]['IS_NULLABLE'] === 'NO'
740 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
741 $diff['MODIFY'][] = $col;
744 $civiTableSpecs[$col]['COLUMN_DEFAULT'] != ($logTableSpecs[$col]['COLUMN_DEFAULT'] ??
NULL)
745 && !stristr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'timestamp')
746 && !($civiTableSpecs[$col]['COLUMN_DEFAULT'] === NULL && ($logTableSpecs[$col]['COLUMN_DEFAULT'] ??
NULL) === 'NULL')
748 // if default property is different, and its not about a timestamp column, consider it
749 $diff['MODIFY'][] = $col;
755 // columns to made obsolete by turning into not-null
756 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
757 foreach ($oldCols as $col) {
758 if (!in_array($col, ['log_date', 'log_conn_id', 'log_user_id', 'log_action']) &&
759 $logTableSpecs[$col]['IS_NULLABLE'] === 'NO'
760 // This could be to support replication - https://lab.civicrm.org/dev/core/-/issues/2120
761 && $logTableSpecs[$col]['EXTRA'] !== 'auto_increment'
763 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
764 $diff['OBSOLETE'][] = $col;
772 * Getter for logTableSpec.
776 public function getLogTableSpec() {
777 return $this->logTableSpec
;
781 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
783 * @param string $table
785 private function createLogTableFor($table) {
786 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE $table", [], TRUE, NULL, FALSE, FALSE);
788 $query = $dao->Create_Table
;
790 // rewrite the queries into CREATE TABLE queries for log tables:
793 log_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
794 log_conn_id VARCHAR(17),
796 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
799 if (!empty($this->logTableSpec
[$table]['indexes'])) {
800 foreach ($this->logTableSpec
[$table]['indexes'] as $indexName => $indexSpec) {
801 if (is_array($indexSpec)) {
802 $indexSpec = implode(" , ", $indexSpec);
804 $cols .= ", INDEX {$indexName}($indexSpec)";
808 // - prepend the name with log_
809 // - drop AUTO_INCREMENT columns
810 // - drop non-column rows of the query (keys, constraints, etc.)
811 // - set the ENGINE to the specified engine (default is INNODB)
812 // - add log-specific columns (at the end of the table)
813 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
814 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
815 $query = preg_replace("/^ [^`].*$/m", '', $query);
816 $engine = strtoupper(empty($this->logTableSpec
[$table]['engine']) ? self
::ENGINE
: $this->logTableSpec
[$table]['engine']);
817 $engine .= " " . ($this->logTableSpec
[$table]['engine_config'] ??
'');
818 if (strpos($engine, 'ROW_FORMAT') !== FALSE) {
819 $query = preg_replace("/ROW_FORMAT=\w+/m", '', $query);
821 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=' . $engine . ' ', $query);
823 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
824 // so there's no need for a default timestamp and therefore we remove such default timestamps
825 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
826 $query = self
::fixTimeStampAndNotNullSQL($query);
827 $query = preg_replace("/(,*\n*\) )ENGINE/m", "$cols\n) ENGINE", $query);
829 CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
831 $columns = implode(', ', $this->columnsOf($table));
832 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);
834 $this->tables
[] = $table;
835 if (empty($this->logs
)) {
836 civicrm_api3('Setting', 'create', ['logging_uniqueid_date' => date('Y-m-d H:i:s')]);
837 civicrm_api3('Setting', 'create', ['logging_all_tables_uniquid' => 1]);
839 $this->logs
[$table] = "log_$table";
845 private function deleteReports() {
846 // disable logging templates
847 CRM_Core_DAO
::executeQuery("
848 UPDATE civicrm_option_value
850 WHERE value IN ('" . implode("', '", $this->reports
) . "')
853 // delete report instances
854 $domain_id = CRM_Core_Config
::domainID();
855 foreach ($this->reports
as $report) {
856 $dao = new CRM_Report_DAO_ReportInstance();
857 $dao->domain_id
= $domain_id;
858 $dao->report_id
= $report;
864 * Predicate whether logging is enabled.
866 public function isEnabled() {
867 if (\Civi
::settings()->get('logging')) {
868 return ($this->tablesExist() && (\Civi
::settings()->get('logging_no_trigger_permission') ||
$this->triggersExist()));
874 * Predicate whether any log tables exist.
876 private function tablesExist() {
877 return !empty($this->logs
);
881 * Drop all log tables.
883 * This does not currently have a usage outside the tests.
885 public function dropAllLogTables() {
886 if ($this->tablesExist()) {
887 foreach ($this->logs
as $log_table) {
888 CRM_Core_DAO
::executeQuery("DROP TABLE $log_table");
894 * Get an sql clause to find the names of any log tables that do not match the normal pattern.
896 * Most tables are civicrm_xxx with the log table being log_civicrm_xxx
897 * However, they don't have to match this pattern (e.g when defined by hook) so find the
898 * anomalies and return a filter string to include them.
902 public function getNonStandardTableNameFilterString() {
903 $nonStandardTableNames = preg_grep('/^civicrm_/', $this->tables
, PREG_GREP_INVERT
);
904 if (empty($nonStandardTableNames)) {
907 $nonStandardTableLogs = [];
908 foreach ($nonStandardTableNames as $nonStandardTableName) {
909 $nonStandardTableLogs[] = "'log_{$nonStandardTableName}'";
911 return " OR TABLE_NAME IN (" . implode(',', $nonStandardTableLogs) . ")";
915 * Predicate whether the logging triggers are in place.
917 private function triggersExist() {
918 // FIXME: probably should be a bit more thorough…
919 // note that the LIKE parameter is TABLE NAME
920 return (bool) CRM_Core_DAO
::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
927 * @param string|null $tableName
930 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
931 if (!CRM_Core_Config
::singleton()->logging
) {
935 $insert = ['INSERT'];
936 $update = ['UPDATE'];
937 $delete = ['DELETE'];
940 $tableNames = [$tableName];
943 $tableNames = $this->tables
;
946 // logging is enabled, so now lets create the trigger info tables
947 foreach ($tableNames as $table) {
948 if (!isset($this->logTableSpec
[$table])) {
949 // Per testIgnoreCustomTableByHook this would be unset if a hook had
950 // intervened to prevent logging / triggers on this table.
951 // This could go to the extent of blocking the updates to 'modified_date'
952 // which makes sense, in particular, for calculated fields.
955 $columns = $this->columnsOf($table, $force);
957 // only do the change if any data has changed
959 foreach ($columns as $column) {
960 $tableExceptions = array_key_exists('exceptions', $this->logTableSpec
[$table]) ?
$this->logTableSpec
[$table]['exceptions'] : [];
961 // ignore modified_date changes
962 $tableExceptions[] = 'modified_date';
963 // exceptions may be provided with or without backticks
964 $excludeColumn = in_array($column, $tableExceptions) ||
965 in_array(str_replace('`', '', $column), $tableExceptions);
966 if (!$excludeColumn) {
967 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
970 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
971 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
973 if ($this->useDBPrefix
) {
974 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
977 $sqlStmt = "INSERT INTO log_{tableName} (";
979 foreach ($columns as $column) {
980 $sqlStmt .= "$column, ";
982 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
984 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
985 $updateSQL .= $sqlStmt;
988 foreach ($columns as $column) {
989 $sqlStmt .= "NEW.$column, ";
990 $deleteSQL .= "OLD.$column, ";
992 if (civicrm_api3('Setting', 'getvalue', ['name' => 'logging_uniqueid_date'])) {
993 // Note that when connecting directly via mysql @uniqueID may not be set so a fallback is
994 // 'c_' to identify a non-CRM connection + timestamp to the hour + connection_id
995 // If the connection_id is longer than 6 chars it will be truncated.
996 // We tried setting the @uniqueID in the trigger but it was unreliable.
997 // An external interaction could split over 2 connections & it seems worth blocking the revert on
998 // these reports & adding extra permissioning to the api for this.
999 $connectionSQLString = "COALESCE(@uniqueID, LEFT(CONCAT('c_', unix_timestamp()/3600, CONNECTION_ID()), 17))";
1002 // The log tables have not yet been converted to have varchar(17) fields for log_conn_id.
1003 // Continue to use the less reliable connection_id for al tables for now.
1004 $connectionSQLString = "CONNECTION_ID()";
1006 $sqlStmt .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
1007 $deleteSQL .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
1009 $insertSQL .= $sqlStmt;
1010 $updateSQL .= $sqlStmt;
1013 'table' => [$table],
1016 'sql' => $insertSQL,
1020 'table' => [$table],
1023 'sql' => $updateSQL,
1027 'table' => [$table],
1030 'sql' => $deleteSQL,
1036 * Disable logging temporarily.
1038 * This allow logging to be temporarily disabled for certain cases
1039 * where we want to do a mass cleanup but do not want to bother with
1042 public static function disableLoggingForThisConnection() {
1043 if (CRM_Core_Config
::singleton()->logging
) {
1044 CRM_Core_DAO
::executeQuery('SET @civicrm_disable_logging = 1');
1049 * Get all the log tables that reference civicrm_contact.
1051 * Note that it might make sense to wrap this in a getLogTablesForEntity
1052 * but this is the only entity currently available...
1054 public function getLogTablesForContact() {
1055 $tables = array_keys(CRM_Core_DAO
::getReferencesToContactTable());
1056 // This additional hardcoding has been moved from getReferencesToContactTable
1057 // to here as it is not needed in the other place where the function is called.
1058 // It may not be needed here either...
1059 $tables[] = 'civicrm_entity_tag';
1060 return array_intersect($tables, $this->tables
);
1064 * Retrieve missing log tables.
1068 public function getMissingLogTables() {
1069 if ($this->tablesExist()) {
1070 return array_diff($this->tables
, array_keys($this->logs
));
1076 * Get the name of the database from the dsn string.
1078 * @param string $dsnString
1082 protected function getDatabaseNameFromDSN($dsnString): string {
1083 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsnString);
1084 $dsn = DB
::parseDSN($dsn);
1085 return $dsn['database'];
1089 * Get the database name for the CiviCRM connection.
1091 * Note that we want to get it from the database connection,
1092 * not the dsn, because there is at least one extension
1093 * (https://github.com/totten/rpow) that 'meddles' with
1098 protected function getCiviCRMDatabaseName(): string {
1099 return (new CRM_Contact_DAO_Contact())->_database
;