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