Merge pull request #20543 from seamuslee001/guards_common
[civicrm-core.git] / CRM / Logging / Schema.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Logging_Schema {
18
19 /**
20 * Default storage engine for log tables
21 *
22 * @var string
23 */
24 const ENGINE = 'InnoDB';
25
26 private $logs = [];
27 private $tables = [];
28
29 private $db;
30 private $useDBPrefix = TRUE;
31
32 private $reports = [
33 'logging/contact/detail',
34 'logging/contact/summary',
35 'logging/contribute/detail',
36 'logging/contribute/summary',
37 ];
38
39 /**
40 * Columns that should never be subject to logging.
41 *
42 * CRM-13028 / NYSS-6933 - table => array (cols) - to be excluded from the update statement
43 *
44 * @var array
45 */
46 private $exceptions = [
47 'civicrm_job' => ['last_run'],
48 'civicrm_group' => ['cache_date', 'refresh_date'],
49 ];
50
51 /**
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.
60 *
61 * @var array
62 */
63 private $logTableSpec = [];
64
65 /**
66 * Setting Callback - Validate.
67 *
68 * @param mixed $value
69 * @param array $fieldSpec
70 *
71 * @return bool
72 * @throws API_Exception
73 */
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."));
77 }
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!"));
81 }
82 return TRUE;
83 }
84
85 /**
86 * Setting Callback - On Change.
87 *
88 * Respond to changes in the "logging" setting. Set up or destroy
89 * triggers, etal.
90 *
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).
97 */
98 public static function onToggle($oldValue, $newValue, $metadata) {
99 if ($oldValue == $newValue) {
100 return;
101 }
102
103 $logging = new CRM_Logging_Schema();
104 if ($newValue) {
105 $logging->enableLogging();
106 }
107 else {
108 $logging->disableLogging();
109 }
110 }
111
112 /**
113 * Populate $this->tables and $this->logs with current db state.
114 */
115 public function __construct() {
116 $dao = new CRM_Contact_DAO_Contact();
117 $civiDBName = $dao->_database;
118
119 $dao = CRM_Core_DAO::executeQuery("
120 SELECT TABLE_NAME
121 FROM INFORMATION_SCHEMA.TABLES
122 WHERE TABLE_SCHEMA = '{$civiDBName}'
123 AND TABLE_TYPE = 'BASE TABLE'
124 AND TABLE_NAME LIKE 'civicrm_%'
125 ");
126 while ($dao->fetch()) {
127 $this->tables[] = $dao->TABLE_NAME;
128 }
129
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);
135 //CRM-14672
136 $this->tables = preg_grep('/^civicrm_menu/', $this->tables, PREG_GREP_INVERT);
137 $this->tables = preg_grep('/_temp_/', $this->tables, PREG_GREP_INVERT);
138 // CRM-18178
139 $this->tables = preg_grep('/_bak$/', $this->tables, PREG_GREP_INVERT);
140 $this->tables = preg_grep('/_backup$/', $this->tables, PREG_GREP_INVERT);
141 // dev/core#462
142 $this->tables = preg_grep('/^civicrm_tmp_/', $this->tables, PREG_GREP_INVERT);
143
144 // do not log civicrm_mailing_event* tables, CRM-12300
145 $this->tables = preg_grep('/^civicrm_mailing_event_/', $this->tables, PREG_GREP_INVERT);
146
147 // dev/core#1762 Don't log subscription_history
148 $this->tables = preg_grep('/^civicrm_subscription_history/', $this->tables, PREG_GREP_INVERT);
149
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;
155 }
156 CRM_Utils_Hook::alterLogTables($this->logTableSpec);
157 $this->tables = array_keys($this->logTableSpec);
158 $nonStandardTableNameString = $this->getNonStandardTableNameFilterString();
159
160 if (defined('CIVICRM_LOGGING_DSN')) {
161 $dsn = CRM_Utils_SQL::autoSwitchDSN(CIVICRM_LOGGING_DSN);
162 $dsn = DB::parseDSN($dsn);
163 $this->useDBPrefix = (CIVICRM_LOGGING_DSN != CIVICRM_DSN);
164 }
165 else {
166 $dsn = CRM_Utils_SQL::autoSwitchDSN(CIVICRM_DSN);
167 $dsn = DB::parseDSN($dsn);
168 $this->useDBPrefix = FALSE;
169 }
170 $this->db = $dsn['database'];
171
172 $dao = CRM_Core_DAO::executeQuery("
173 SELECT TABLE_NAME
174 FROM INFORMATION_SCHEMA.TABLES
175 WHERE TABLE_SCHEMA = '{$this->db}'
176 AND TABLE_TYPE = 'BASE TABLE'
177 AND (TABLE_NAME LIKE 'log_civicrm_%' $nonStandardTableNameString )
178 ");
179 while ($dao->fetch()) {
180 $log = $dao->TABLE_NAME;
181 $this->logs[substr($log, 4)] = $log;
182 }
183 }
184
185 /**
186 * Return logging custom data tables.
187 */
188 public function customDataLogTables() {
189 return preg_grep('/^log_civicrm_value_/', $this->logs);
190 }
191
192 /**
193 * Return custom data tables for specified entity / extends.
194 *
195 * @param string $extends
196 *
197 * @return array
198 */
199 public function entityCustomDataLogTables($extends) {
200 $customGroupTables = [];
201 $customGroupDAO = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity($extends);
202 $customGroupDAO->find();
203 while ($customGroupDAO->fetch()) {
204 // logging is disabled for the table (e.g by hook) then $this->logs[$customGroupDAO->table_name]
205 // will be empty.
206 if (!empty($this->logs[$customGroupDAO->table_name])) {
207 $customGroupTables[$customGroupDAO->table_name] = $this->logs[$customGroupDAO->table_name];
208 }
209 }
210 return $customGroupTables;
211 }
212
213 /**
214 * Disable logging by dropping the triggers (but keep the log tables intact).
215 */
216 public function disableLogging() {
217 $config = CRM_Core_Config::singleton();
218 $config->logging = FALSE;
219
220 $this->dropTriggers();
221
222 // invoke the meta trigger creation call
223 CRM_Core_DAO::triggerRebuild();
224
225 $this->deleteReports();
226 }
227
228 /**
229 * Drop triggers for all logged tables.
230 *
231 * @param string $tableName
232 */
233 public function dropTriggers($tableName = NULL) {
234 /** @var \Civi\Core\SqlTriggers $sqlTriggers */
235 $sqlTriggers = Civi::service('sql_triggers');
236 $dao = new CRM_Core_DAO();
237
238 if ($tableName) {
239 $tableNames = [$tableName];
240 }
241 else {
242 $tableNames = $this->tables;
243 }
244
245 // Sort the table names so the sql output is consistent for those sites
246 // loading it asynchronously (using the setting 'logging_no_trigger_permission')
247 asort($tableNames);
248 foreach ($tableNames as $table) {
249 $validName = CRM_Core_DAO::shortenSQLName($table, 48, TRUE);
250
251 // before triggers
252 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_insert");
253 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_update");
254 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_before_delete");
255
256 // after triggers
257 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_insert");
258 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_update");
259 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$validName}_after_delete");
260 }
261
262 // now lets also be safe and drop all triggers that start with
263 // civicrm_ if we are dropping all triggers
264 // we need to do this to capture all the leftover triggers since
265 // we did the shortening trigger name for CRM-11794
266 if ($tableName === NULL) {
267 $triggers = $dao->executeQuery("SHOW TRIGGERS LIKE 'civicrm_%'");
268
269 while ($triggers->fetch()) {
270 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$triggers->Trigger}");
271 }
272 }
273 }
274
275 /**
276 * Enable site-wide logging.
277 */
278 public function enableLogging() {
279 $this->fixSchemaDifferences(TRUE);
280 $this->addReports();
281 }
282
283 /**
284 * Sync log tables and rebuild triggers.
285 *
286 * @param bool $enableLogging : Ensure logging is enabled
287 */
288 public function fixSchemaDifferences($enableLogging = FALSE) {
289 $config = CRM_Core_Config::singleton();
290 if ($enableLogging) {
291 $config->logging = TRUE;
292 }
293 if ($config->logging) {
294 $this->fixSchemaDifferencesForAll();
295 }
296 // invoke the meta trigger creation call
297 CRM_Core_DAO::triggerRebuild(NULL, TRUE);
298 }
299
300 /**
301 * Update log tables structure.
302 *
303 * This function updates log tables to have the log_conn_id type of varchar
304 * and also implements the engine change defined by the hook (i.e. INNODB).
305 *
306 * Note changing engine & adding hook-defined indexes, but not changing back
307 * to INNODB if engine has not been deliberately set (by hook) and not
308 * dropping indexes. Sysadmin will need to manually intervene to revert to
309 * defaults.
310 *
311 * @param array $params
312 * 'updateChangedEngineConfig' - update if the engine config changes?
313 * 'forceEngineMigration' - force engine upgrade from ARCHIVE to InnoDB?
314 *
315 * @return int $updateTablesCount
316 * @throws \CiviCRM_API3_Exception
317 */
318 public function updateLogTableSchema($params) {
319 $updateLogConn = FALSE;
320 $updatedTablesCount = 0;
321 foreach ($this->logs as $mainTable => $logTable) {
322 $alterSql = [];
323 $tableSpec = $this->logTableSpec[$mainTable];
324 $currentEngine = strtoupper($this->getEngineForLogTable($logTable));
325 if (!isset($tableSpec['engine']) && $currentEngine == 'ARCHIVE' && $params['forceEngineMigration']) {
326 // table uses ARCHIVE engine (the previous default) and no one set an
327 // alternative engine via hook_civicrm_alterLogTables => force change to
328 // new default
329 $tableSpec['engine'] = self::ENGINE;
330 }
331 $engineChanged = isset($tableSpec['engine']) && (strtoupper($tableSpec['engine']) != $currentEngine);
332 $engineConfigChanged = isset($tableSpec['engine_config']) && (strtoupper($tableSpec['engine_config']) != $this->getEngineConfigForLogTable($logTable));
333 if ($engineChanged || ($engineConfigChanged && $params['updateChangedEngineConfig'])) {
334 $alterSql[] = "ENGINE=" . $tableSpec['engine'] . " " . CRM_Utils_Array::value('engine_config', $tableSpec);
335 }
336 if (!empty($tableSpec['indexes'])) {
337 $indexes = $this->getIndexesForTable($logTable);
338 foreach ($tableSpec['indexes'] as $indexName => $indexSpec) {
339 if (!in_array($indexName, $indexes)) {
340 if (is_array($indexSpec)) {
341 $indexSpec = implode(" , ", $indexSpec);
342 }
343 $alterSql[] = "ADD INDEX {$indexName}($indexSpec)";
344 }
345 }
346 }
347 $columns = $this->columnSpecsOf($logTable);
348 if (empty($columns['log_conn_id'])) {
349 throw new Exception($logTable . print_r($columns, TRUE));
350 }
351 if ($columns['log_conn_id']['DATA_TYPE'] != 'varchar' || $columns['log_conn_id']['LENGTH'] != 17) {
352 $alterSql[] = "MODIFY log_conn_id VARCHAR(17)";
353 $updateLogConn = TRUE;
354 }
355 if (!empty($alterSql)) {
356 CRM_Core_DAO::executeQuery("ALTER TABLE {$this->db}.{$logTable} " . implode(', ', $alterSql), [], TRUE, NULL, FALSE, FALSE);
357 $updatedTablesCount++;
358 }
359 }
360 if ($updateLogConn) {
361 civicrm_api3('Setting', 'create', ['logging_uniqueid_date' => date('Y-m-d H:i:s')]);
362 }
363 return $updatedTablesCount;
364 }
365
366 /**
367 * Get the engine for the given table.
368 *
369 * @param string $table
370 *
371 * @return string
372 */
373 public function getEngineForLogTable($table) {
374 return strtoupper(CRM_Core_DAO::singleValueQuery("
375 SELECT ENGINE FROM information_schema.tables WHERE TABLE_NAME = %1
376 AND table_schema = %2
377 ", [1 => [$table, 'String'], 2 => [$this->db, 'String']]));
378 }
379
380 /**
381 * Get the engine config for the given table.
382 *
383 * @param string $table
384 *
385 * @return string
386 */
387 public function getEngineConfigForLogTable($table) {
388 return strtoupper(CRM_Core_DAO::singleValueQuery("
389 SELECT CREATE_OPTIONS FROM information_schema.tables WHERE TABLE_NAME = %1
390 AND table_schema = %2
391 ", [1 => [$table, 'String'], 2 => [$this->db, 'String']]));
392 }
393
394 /**
395 * Get all the indexes in the table.
396 *
397 * @param string $table
398 *
399 * @return array
400 */
401 public function getIndexesForTable($table) {
402 $indexes = [];
403 $result = CRM_Core_DAO::executeQuery("
404 SELECT constraint_name AS index_name
405 FROM information_schema.key_column_usage
406 WHERE table_schema = %2 AND table_name = %1
407 UNION
408 SELECT index_name AS index_name
409 FROM information_schema.statistics
410 WHERE table_schema = %2 AND table_name = %1
411 ",
412 [1 => [$table, 'String'], 2 => [$this->db, 'String']]
413 );
414 while ($result->fetch()) {
415 $indexes[] = $result->index_name;
416 }
417 return $indexes;
418 }
419
420 /**
421 * Add missing (potentially specified) log table columns for the given table.
422 *
423 * @param string $table
424 * name of the relevant table.
425 * @param array $cols
426 * Mixed array of columns to add or null (to check for the missing columns).
427 *
428 * @return bool
429 */
430 public function fixSchemaDifferencesFor($table, $cols = []) {
431 if (empty($table)) {
432 return FALSE;
433 }
434 if (empty($this->logs[$table])) {
435 $this->createLogTableFor($table);
436 return TRUE;
437 }
438
439 if (empty($cols)) {
440 $cols = $this->columnsWithDiffSpecs($table, "log_$table");
441 }
442
443 // If a column that already exists on logging table is being added, we
444 // should treat it as a modification.
445 $this->resetSchemaCacheForTable("log_$table");
446 $logTableSchema = $this->columnSpecsOf("log_$table");
447 if (!empty($cols['ADD'])) {
448 foreach ($cols['ADD'] as $colKey => $col) {
449 if (array_key_exists($col, $logTableSchema)) {
450 $cols['MODIFY'][] = $col;
451 unset($cols['ADD'][$colKey]);
452 }
453 }
454 }
455
456 // use the relevant lines from CREATE TABLE to add colums to the log table
457 $create = $this->_getCreateQuery($table);
458 foreach ((['ADD', 'MODIFY']) as $alterType) {
459 if (!empty($cols[$alterType])) {
460 foreach ($cols[$alterType] as $col) {
461 $line = $this->_getColumnQuery($col, $create);
462 CRM_Core_DAO::executeQuery("ALTER TABLE `{$this->db}`.log_$table {$alterType} {$line}", [], TRUE, NULL, FALSE, FALSE);
463 }
464 }
465 }
466
467 // for any obsolete columns (not null) we just make the column nullable.
468 if (!empty($cols['OBSOLETE'])) {
469 $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}");
470 foreach ($cols['OBSOLETE'] as $col) {
471 $line = $this->_getColumnQuery($col, $create);
472 // This is just going to make a not null column to nullable
473 CRM_Core_DAO::executeQuery("ALTER TABLE `{$this->db}`.log_$table MODIFY {$line}", [], TRUE, NULL, FALSE, FALSE);
474 }
475 }
476
477 $this->resetSchemaCacheForTable("log_$table");
478
479 return TRUE;
480 }
481
482 /**
483 * Resets schema cache for the given table.
484 *
485 * @param string $table
486 * Name of the table.
487 */
488 private function resetSchemaCacheForTable($table) {
489 unset(\Civi::$statics[__CLASS__]['columnSpecs'][$table]);
490 }
491
492 /**
493 * Get query table.
494 *
495 * @param string $table
496 *
497 * @return array
498 */
499 private function _getCreateQuery($table) {
500 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE {$table}", [], TRUE, NULL, FALSE, FALSE);
501 $dao->fetch();
502 $create = explode("\n", $dao->Create_Table);
503 return $create;
504 }
505
506 /**
507 * Get column query.
508 *
509 * @param string $col
510 * @param bool $createQuery
511 *
512 * @return array|mixed|string
513 */
514 private function _getColumnQuery($col, $createQuery) {
515 $line = preg_grep("/^ `$col` /", $createQuery);
516 $line = rtrim(array_pop($line), ',');
517 // CRM-11179
518 $line = self::fixTimeStampAndNotNullSQL($line);
519 return $line;
520 }
521
522 /**
523 * Fix schema differences.
524 */
525 public function fixSchemaDifferencesForAll(): void {
526 $diffs = [];
527 $this->resetTableColumnsCache();
528
529 foreach ($this->tables as $table) {
530 if (empty($this->logs[$table])) {
531 $this->createLogTableFor($table);
532 }
533 else {
534 $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table");
535 }
536 }
537
538 foreach ($diffs as $table => $cols) {
539 $this->fixSchemaDifferencesFor($table, $cols);
540 }
541 }
542
543 /**
544 * Resets columnSpecs.
545 *
546 * Resets columnSpecs static array in Civi's $statics to make sure we use the
547 * real state of the schema to perform sync operations between core and
548 * logging tables.
549 */
550 private function resetTableColumnsCache() {
551 unset(\Civi::$statics[__CLASS__]['columnSpecs']);
552 }
553
554 /**
555 * Fix timestamp.
556 *
557 * Log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
558 * so there's no need for a default timestamp and therefore we remove such default timestamps
559 * also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
560 *
561 * @param string $query
562 *
563 * @return mixed
564 */
565 public static function fixTimeStampAndNotNullSQL($query) {
566 $query = str_ireplace("TIMESTAMP() NOT NULL", "TIMESTAMP NULL", $query);
567 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
568 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()", '', $query);
569 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
570 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP()", '', $query);
571 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
572 $query = str_ireplace("NOT NULL", '', $query);
573 return $query;
574 }
575
576 /**
577 * Add reports.
578 */
579 private function addReports() {
580 $titles = [
581 'logging/contact/detail' => ts('Logging Details'),
582 'logging/contact/summary' => ts('Contact Logging Report (Summary)'),
583 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'),
584 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'),
585 ];
586 // enable logging templates
587 CRM_Core_DAO::executeQuery("
588 UPDATE civicrm_option_value
589 SET is_active = 1
590 WHERE value IN ('" . implode("', '", $this->reports) . "')
591 ");
592
593 // add report instances
594 $domain_id = CRM_Core_Config::domainID();
595 foreach ($this->reports as $report) {
596 $dao = new CRM_Report_DAO_ReportInstance();
597 $dao->domain_id = $domain_id;
598 $dao->report_id = $report;
599 $dao->title = $titles[$report];
600 $dao->permission = 'administer CiviCRM';
601 if ($report == 'logging/contact/summary') {
602 $dao->is_reserved = 1;
603 }
604 $dao->insert();
605 }
606 }
607
608 /**
609 * Get an array of column names of the given table.
610 *
611 * @param string $table
612 * @param bool $force
613 *
614 * @return array
615 */
616 private function columnsOf($table, $force = FALSE) {
617 if ($force || !isset(\Civi::$statics[__CLASS__]['columnsOf'][$table])) {
618 $from = (substr($table, 0, 4) == 'log_') ? "`{$this->db}`.$table" : $table;
619 $dao = CRM_Core_DAO::executeQuery("SHOW COLUMNS FROM $from", [], TRUE, NULL, FALSE, FALSE);
620 if (is_a($dao, 'DB_Error')) {
621 return [];
622 }
623 \Civi::$statics[__CLASS__]['columnsOf'][$table] = [];
624 while ($dao->fetch()) {
625 \Civi::$statics[__CLASS__]['columnsOf'][$table][] = CRM_Utils_Type::escape($dao->Field, 'MysqlColumnNameOrAlias');
626 }
627 }
628 return \Civi::$statics[__CLASS__]['columnsOf'][$table];
629 }
630
631 /**
632 * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table.
633 *
634 * @param string $table
635 *
636 * @return array
637 */
638 private function columnSpecsOf($table) {
639 static $civiDB = NULL;
640 if (empty(\Civi::$statics[__CLASS__]['columnSpecs'])) {
641 \Civi::$statics[__CLASS__]['columnSpecs'] = [];
642 }
643 if (empty(\Civi::$statics[__CLASS__]['columnSpecs']) || !isset(\Civi::$statics[__CLASS__]['columnSpecs'][$table])) {
644 if (!$civiDB) {
645 $dao = new CRM_Contact_DAO_Contact();
646 $civiDB = $dao->_database;
647 }
648
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.
651 $query = "
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')) {
657 return [];
658 }
659 while ($dao->fetch()) {
660 if (!array_key_exists($dao->TABLE_NAME, \Civi::$statics[__CLASS__]['columnSpecs'])) {
661 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME] = [];
662 }
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,
669 ];
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')")
674 $parValue = substr(
675 $dao->COLUMN_TYPE, $first + 1, strpos($dao->COLUMN_TYPE, ')') - $first - 1
676 );
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;
680 }
681 else {
682 // single quote means enum permitted values
683 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME][$dao->COLUMN_NAME]['ENUM_VALUES'] = $parValue;
684 }
685 }
686 }
687 }
688 return \Civi::$statics[__CLASS__]['columnSpecs'][$table];
689 }
690
691 /**
692 * Get columns that have changed.
693 *
694 * @param string $civiTable
695 * @param string $logTable
696 *
697 * @return array
698 */
699 public function columnsWithDiffSpecs($civiTable, $logTable) {
700 $civiTableSpecs = $this->columnSpecsOf($civiTable);
701 $logTableSpecs = $this->columnSpecsOf($logTable);
702
703 $diff = ['ADD' => [], 'MODIFY' => [], 'OBSOLETE' => []];
704
705 // Columns to be added
706 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
707
708 // Columns to be modified
709 // Only pick columns where there is a spec change and the column definition was not deliberately modified by
710 // fixTimeStampAndNotNullSQL() method, also accounting for differences in db version.
711 foreach ($civiTableSpecs as $col => $colSpecs) {
712 if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col])) {
713 $logTableSpecs[$col] = [];
714 }
715 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
716 if (!empty($specDiff) && $col !== 'id' && !in_array($col, $diff['ADD'])) {
717 if (empty($colSpecs['EXTRA']) || (!empty($colSpecs['EXTRA']) && $colSpecs['EXTRA'] !== 'auto_increment')) {
718 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
719 if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array::value('DATA_TYPE', $logTableSpecs[$col])
720 // We won't alter the log if the length is decreased in case some of the existing data won't fit.
721 || CRM_Utils_Array::value('LENGTH', $civiTableSpecs[$col]) > CRM_Utils_Array::value('LENGTH', $logTableSpecs[$col])
722 ) {
723 // if data-type is different, surely consider the column
724 $diff['MODIFY'][] = $col;
725 }
726 elseif ($civiTableSpecs[$col]['DATA_TYPE'] === 'enum' &&
727 CRM_Utils_Array::value('ENUM_VALUES', $civiTableSpecs[$col]) != CRM_Utils_Array::value('ENUM_VALUES', $logTableSpecs[$col])
728 ) {
729 // column is enum and the permitted values have changed
730 $diff['MODIFY'][] = $col;
731 }
732 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) &&
733 $logTableSpecs[$col]['IS_NULLABLE'] === 'NO'
734 ) {
735 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
736 $diff['MODIFY'][] = $col;
737 }
738 elseif (
739 $civiTableSpecs[$col]['COLUMN_DEFAULT'] != ($logTableSpecs[$col]['COLUMN_DEFAULT'] ?? NULL)
740 && !stristr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'timestamp')
741 && !($civiTableSpecs[$col]['COLUMN_DEFAULT'] === NULL && ($logTableSpecs[$col]['COLUMN_DEFAULT'] ?? NULL) === 'NULL')
742 ) {
743 // if default property is different, and its not about a timestamp column, consider it
744 $diff['MODIFY'][] = $col;
745 }
746 }
747 }
748 }
749
750 // columns to made obsolete by turning into not-null
751 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
752 foreach ($oldCols as $col) {
753 if (!in_array($col, ['log_date', 'log_conn_id', 'log_user_id', 'log_action']) &&
754 $logTableSpecs[$col]['IS_NULLABLE'] === 'NO'
755 // This could be to support replication - https://lab.civicrm.org/dev/core/-/issues/2120
756 && $logTableSpecs[$col]['EXTRA'] !== 'auto_increment'
757 ) {
758 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
759 $diff['OBSOLETE'][] = $col;
760 }
761 }
762
763 return $diff;
764 }
765
766 /**
767 * Getter for logTableSpec.
768 *
769 * @return array
770 */
771 public function getLogTableSpec() {
772 return $this->logTableSpec;
773 }
774
775 /**
776 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
777 *
778 * @param string $table
779 */
780 private function createLogTableFor($table) {
781 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE $table", [], TRUE, NULL, FALSE, FALSE);
782 $dao->fetch();
783 $query = $dao->Create_Table;
784
785 // rewrite the queries into CREATE TABLE queries for log tables:
786 $cols = <<<COLS
787 ,
788 log_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
789 log_conn_id VARCHAR(17),
790 log_user_id INTEGER,
791 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
792 COLS;
793
794 if (!empty($this->logTableSpec[$table]['indexes'])) {
795 foreach ($this->logTableSpec[$table]['indexes'] as $indexName => $indexSpec) {
796 if (is_array($indexSpec)) {
797 $indexSpec = implode(" , ", $indexSpec);
798 }
799 $cols .= ", INDEX {$indexName}($indexSpec)";
800 }
801 }
802
803 // - prepend the name with log_
804 // - drop AUTO_INCREMENT columns
805 // - drop non-column rows of the query (keys, constraints, etc.)
806 // - set the ENGINE to the specified engine (default is INNODB)
807 // - add log-specific columns (at the end of the table)
808 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
809 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
810 $query = preg_replace("/^ [^`].*$/m", '', $query);
811 $engine = strtoupper(empty($this->logTableSpec[$table]['engine']) ? self::ENGINE : $this->logTableSpec[$table]['engine']);
812 $engine .= " " . ($this->logTableSpec[$table]['engine_config'] ?? '');
813 if (strpos($engine, 'ROW_FORMAT') !== FALSE) {
814 $query = preg_replace("/ROW_FORMAT=\w+/m", '', $query);
815 }
816 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=' . $engine . ' ', $query);
817
818 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
819 // so there's no need for a default timestamp and therefore we remove such default timestamps
820 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
821 $query = self::fixTimeStampAndNotNullSQL($query);
822 $query = preg_replace("/(,*\n*\) )ENGINE/m", "$cols\n) ENGINE", $query);
823
824 CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
825
826 $columns = implode(', ', $this->columnsOf($table));
827 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);
828
829 $this->tables[] = $table;
830 if (empty($this->logs)) {
831 civicrm_api3('Setting', 'create', ['logging_uniqueid_date' => date('Y-m-d H:i:s')]);
832 civicrm_api3('Setting', 'create', ['logging_all_tables_uniquid' => 1]);
833 }
834 $this->logs[$table] = "log_$table";
835 }
836
837 /**
838 * Delete reports.
839 */
840 private function deleteReports() {
841 // disable logging templates
842 CRM_Core_DAO::executeQuery("
843 UPDATE civicrm_option_value
844 SET is_active = 0
845 WHERE value IN ('" . implode("', '", $this->reports) . "')
846 ");
847
848 // delete report instances
849 $domain_id = CRM_Core_Config::domainID();
850 foreach ($this->reports as $report) {
851 $dao = new CRM_Report_DAO_ReportInstance();
852 $dao->domain_id = $domain_id;
853 $dao->report_id = $report;
854 $dao->delete();
855 }
856 }
857
858 /**
859 * Predicate whether logging is enabled.
860 */
861 public function isEnabled() {
862 if (\Civi::settings()->get('logging')) {
863 return ($this->tablesExist() && (\Civi::settings()->get('logging_no_trigger_permission') || $this->triggersExist()));
864 }
865 return FALSE;
866 }
867
868 /**
869 * Predicate whether any log tables exist.
870 */
871 private function tablesExist() {
872 return !empty($this->logs);
873 }
874
875 /**
876 * Drop all log tables.
877 *
878 * This does not currently have a usage outside the tests.
879 */
880 public function dropAllLogTables() {
881 if ($this->tablesExist()) {
882 foreach ($this->logs as $log_table) {
883 CRM_Core_DAO::executeQuery("DROP TABLE $log_table");
884 }
885 }
886 }
887
888 /**
889 * Get an sql clause to find the names of any log tables that do not match the normal pattern.
890 *
891 * Most tables are civicrm_xxx with the log table being log_civicrm_xxx
892 * However, they don't have to match this pattern (e.g when defined by hook) so find the
893 * anomalies and return a filter string to include them.
894 *
895 * @return string
896 */
897 public function getNonStandardTableNameFilterString() {
898 $nonStandardTableNames = preg_grep('/^civicrm_/', $this->tables, PREG_GREP_INVERT);
899 if (empty($nonStandardTableNames)) {
900 return '';
901 }
902 $nonStandardTableLogs = [];
903 foreach ($nonStandardTableNames as $nonStandardTableName) {
904 $nonStandardTableLogs[] = "'log_{$nonStandardTableName}'";
905 }
906 return " OR TABLE_NAME IN (" . implode(',', $nonStandardTableLogs) . ")";
907 }
908
909 /**
910 * Predicate whether the logging triggers are in place.
911 */
912 private function triggersExist() {
913 // FIXME: probably should be a bit more thorough…
914 // note that the LIKE parameter is TABLE NAME
915 return (bool) CRM_Core_DAO::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
916 }
917
918 /**
919 * Get trigger info.
920 *
921 * @param array $info
922 * @param null $tableName
923 * @param bool $force
924 */
925 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
926 if (!CRM_Core_Config::singleton()->logging) {
927 return;
928 }
929
930 $insert = ['INSERT'];
931 $update = ['UPDATE'];
932 $delete = ['DELETE'];
933
934 if ($tableName) {
935 $tableNames = [$tableName];
936 }
937 else {
938 $tableNames = $this->tables;
939 }
940
941 // logging is enabled, so now lets create the trigger info tables
942 foreach ($tableNames as $table) {
943 if (!isset($this->logTableSpec[$table])) {
944 // Per testIgnoreCustomTableByHook this would be unset if a hook had
945 // intervened to prevent logging / triggers on this table.
946 // This could go to the extent of blocking the updates to 'modified_date'
947 // which makes sense, in particular, for calculated fields.
948 continue;
949 }
950 $columns = $this->columnsOf($table, $force);
951
952 // only do the change if any data has changed
953 $cond = [];
954 foreach ($columns as $column) {
955 $tableExceptions = array_key_exists('exceptions', $this->logTableSpec[$table]) ? $this->logTableSpec[$table]['exceptions'] : [];
956 // ignore modified_date changes
957 $tableExceptions[] = 'modified_date';
958 // exceptions may be provided with or without backticks
959 $excludeColumn = in_array($column, $tableExceptions) ||
960 in_array(str_replace('`', '', $column), $tableExceptions);
961 if (!$excludeColumn) {
962 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
963 }
964 }
965 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
966 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
967
968 if ($this->useDBPrefix) {
969 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
970 }
971 else {
972 $sqlStmt = "INSERT INTO log_{tableName} (";
973 }
974 foreach ($columns as $column) {
975 $sqlStmt .= "$column, ";
976 }
977 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
978
979 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
980 $updateSQL .= $sqlStmt;
981
982 $sqlStmt = '';
983 foreach ($columns as $column) {
984 $sqlStmt .= "NEW.$column, ";
985 $deleteSQL .= "OLD.$column, ";
986 }
987 if (civicrm_api3('Setting', 'getvalue', ['name' => 'logging_uniqueid_date'])) {
988 // Note that when connecting directly via mysql @uniqueID may not be set so a fallback is
989 // 'c_' to identify a non-CRM connection + timestamp to the hour + connection_id
990 // If the connection_id is longer than 6 chars it will be truncated.
991 // We tried setting the @uniqueID in the trigger but it was unreliable.
992 // An external interaction could split over 2 connections & it seems worth blocking the revert on
993 // these reports & adding extra permissioning to the api for this.
994 $connectionSQLString = "COALESCE(@uniqueID, LEFT(CONCAT('c_', unix_timestamp()/3600, CONNECTION_ID()), 17))";
995 }
996 else {
997 // The log tables have not yet been converted to have varchar(17) fields for log_conn_id.
998 // Continue to use the less reliable connection_id for al tables for now.
999 $connectionSQLString = "CONNECTION_ID()";
1000 }
1001 $sqlStmt .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
1002 $deleteSQL .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
1003
1004 $insertSQL .= $sqlStmt;
1005 $updateSQL .= $sqlStmt;
1006
1007 $info[] = [
1008 'table' => [$table],
1009 'when' => 'AFTER',
1010 'event' => $insert,
1011 'sql' => $insertSQL,
1012 ];
1013
1014 $info[] = [
1015 'table' => [$table],
1016 'when' => 'AFTER',
1017 'event' => $update,
1018 'sql' => $updateSQL,
1019 ];
1020
1021 $info[] = [
1022 'table' => [$table],
1023 'when' => 'AFTER',
1024 'event' => $delete,
1025 'sql' => $deleteSQL,
1026 ];
1027 }
1028 }
1029
1030 /**
1031 * Disable logging temporarily.
1032 *
1033 * This allow logging to be temporarily disabled for certain cases
1034 * where we want to do a mass cleanup but do not want to bother with
1035 * an audit trail.
1036 */
1037 public static function disableLoggingForThisConnection() {
1038 if (CRM_Core_Config::singleton()->logging) {
1039 CRM_Core_DAO::executeQuery('SET @civicrm_disable_logging = 1');
1040 }
1041 }
1042
1043 /**
1044 * Get all the log tables that reference civicrm_contact.
1045 *
1046 * Note that it might make sense to wrap this in a getLogTablesForEntity
1047 * but this is the only entity currently available...
1048 */
1049 public function getLogTablesForContact() {
1050 $tables = array_keys(CRM_Core_DAO::getReferencesToContactTable());
1051 // This additional hardcoding has been moved from getReferencesToContactTable
1052 // to here as it is not needed in the other place where the function is called.
1053 // It may not be needed here either...
1054 $tables[] = 'civicrm_entity_tag';
1055 return array_intersect($tables, $this->tables);
1056 }
1057
1058 /**
1059 * Retrieve missing log tables.
1060 *
1061 * @return array
1062 */
1063 public function getMissingLogTables() {
1064 if ($this->tablesExist()) {
1065 return array_diff($this->tables, array_keys($this->logs));
1066 }
1067 return [];
1068 }
1069
1070 }