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