Merge pull request #9788 from fliespl/patch-1
[civicrm-core.git] / CRM / Logging / Schema.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33class CRM_Logging_Schema {
34 private $logs = array();
35 private $tables = array();
36
37 private $db;
340f6aa0 38 private $useDBPrefix = TRUE;
6a488035
TO
39
40 private $reports = array(
41 'logging/contact/detail',
42 'logging/contact/summary',
43 'logging/contribute/detail',
44 'logging/contribute/summary',
45 );
46
74b348da 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 */
4d1040bb 54 private $exceptions = array(
353ffa53 55 'civicrm_job' => array('last_run'),
b5c82b2d 56 'civicrm_group' => array('cache_date', 'refresh_date'),
6842bb53 57 );
4d1040bb 58
ef587f9c 59 /**
60 * Specifications of all log table including
61 * - engine (default is archive, if not set.)
d7ea7150 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'
ef587f9c 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
e299c1d0 73 /**
3d469574 74 * Setting Callback - Validate.
e299c1d0
TO
75 *
76 * @param mixed $value
77 * @param array $fieldSpec
3d469574 78 *
e299c1d0
TO
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);
f55f7133
SB
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.");
e299c1d0
TO
87 }
88 return TRUE;
89 }
90
91 /**
3d469574 92 * Setting Callback - On Change.
93 *
e299c1d0
TO
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
6a488035
TO
118 /**
119 * Populate $this->tables and $this->logs with current db state.
120 */
00be9182 121 public function __construct() {
6a488035
TO
122 $dao = new CRM_Contact_DAO_Contact();
123 $civiDBName = $dao->_database;
124
125 $dao = CRM_Core_DAO::executeQuery("
126SELECT TABLE_NAME
127FROM INFORMATION_SCHEMA.TABLES
128WHERE TABLE_SCHEMA = '{$civiDBName}'
129AND TABLE_TYPE = 'BASE TABLE'
130AND TABLE_NAME LIKE 'civicrm_%'
131");
132 while ($dao->fetch()) {
133 $this->tables[] = $dao->TABLE_NAME;
134 }
135
3292d079 136 // do not log temp import, cache, menu and log tables
6a488035
TO
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);
6a488035 140 $this->tables = preg_grep('/^civicrm_queue_/', $this->tables, PREG_GREP_INVERT);
3d469574 141 //CRM-14672
142 $this->tables = preg_grep('/^civicrm_menu/', $this->tables, PREG_GREP_INVERT);
db70b323 143 $this->tables = preg_grep('/_temp_/', $this->tables, PREG_GREP_INVERT);
e719c24e 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);
6a488035 147
f9b793b0
DL
148 // do not log civicrm_mailing_event* tables, CRM-12300
149 $this->tables = preg_grep('/^civicrm_mailing_event_/', $this->tables, PREG_GREP_INVERT);
150
d0cef561 151 // do not log civicrm_mailing_recipients table, CRM-16193
152 $this->tables = array_diff($this->tables, array('civicrm_mailing_recipients'));
ef587f9c 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);
f8d28563 159 $nonStandardTableNameString = $this->getNonStandardTableNameFilterString();
d0cef561 160
340f6aa0
DL
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 }
6a488035
TO
169 $this->db = $dsn['database'];
170
171 $dao = CRM_Core_DAO::executeQuery("
172SELECT TABLE_NAME
173FROM INFORMATION_SCHEMA.TABLES
174WHERE TABLE_SCHEMA = '{$this->db}'
175AND TABLE_TYPE = 'BASE TABLE'
f8d28563 176AND (TABLE_NAME LIKE 'log_civicrm_%' $nonStandardTableNameString )
6a488035
TO
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 */
00be9182 187 public function customDataLogTables() {
6a488035
TO
188 return preg_grep('/^log_civicrm_value_/', $this->logs);
189 }
190
694e78fd
DS
191 /**
192 * Return custom data tables for specified entity / extends.
ea3ddccf 193 *
194 * @param string $extends
195 *
196 * @return array
694e78fd 197 */
00be9182 198 public function entityCustomDataLogTables($extends) {
694e78fd
DS
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
6a488035
TO
208 /**
209 * Disable logging by dropping the triggers (but keep the log tables intact).
210 */
00be9182 211 public function disableLogging() {
6a488035
TO
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.
ad37ac8e 225 *
226 * @param string $tableName
6a488035 227 */
00be9182 228 public function dropTriggers($tableName = NULL) {
7a29e455
TO
229 /** @var \Civi\Core\SqlTriggers $sqlTriggers */
230 $sqlTriggers = Civi::service('sql_triggers');
ae5ffbb7 231 $dao = new CRM_Core_DAO();
6a488035
TO
232
233 if ($tableName) {
234 $tableNames = array($tableName);
235 }
236 else {
237 $tableNames = $this->tables;
238 }
239
240 foreach ($tableNames as $table) {
6842bb53
DL
241 $validName = CRM_Core_DAO::shortenSQLName($table, 48, TRUE);
242
6a488035 243 // before triggers
7a29e455
TO
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");
6a488035 247
353ffa53 248 // after triggers
7a29e455
TO
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");
6a488035 252 }
a8dd306e
DL
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()) {
7a29e455 262 $sqlTriggers->enqueueQuery("DROP TRIGGER IF EXISTS {$triggers->Trigger}");
a8dd306e
DL
263 }
264 }
6a488035
TO
265 }
266
267 /**
3d469574 268 * Enable site-wide logging.
6a488035 269 */
00be9182 270 public function enableLogging() {
6a488035
TO
271 $this->fixSchemaDifferences(TRUE);
272 $this->addReports();
273 }
274
275 /**
276 * Sync log tables and rebuild triggers.
277 *
353ffa53 278 * @param bool $enableLogging : Ensure logging is enabled
6a488035 279 */
00be9182 280 public function fixSchemaDifferences($enableLogging = FALSE) {
6a488035
TO
281 $config = CRM_Core_Config::singleton();
282 if ($enableLogging) {
283 $config->logging = TRUE;
284 }
285 if ($config->logging) {
bfb723bb 286 $this->fixSchemaDifferencesForALL();
6a488035
TO
287 }
288 // invoke the meta trigger creation call
e53944ef 289 CRM_Core_DAO::triggerRebuild(NULL, TRUE);
6a488035
TO
290 }
291
d7ea7150 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
6a488035
TO
368 /**
369 * Add missing (potentially specified) log table columns for the given table.
370 *
5a4f6742
CW
371 * @param string $table
372 * name of the relevant table.
373 * @param array $cols
4c922589 374 * Mixed array of columns to add or null (to check for the missing columns).
5a4f6742
CW
375 * @param bool $rebuildTrigger
376 * should we rebuild the triggers.
6a488035 377 *
3d469574 378 * @return bool
6a488035 379 */
00be9182 380 public function fixSchemaDifferencesFor($table, $cols = array(), $rebuildTrigger = FALSE) {
bfb723bb
DS
381 if (empty($table)) {
382 return FALSE;
383 }
6a488035
TO
384 if (empty($this->logs[$table])) {
385 $this->createLogTableFor($table);
bfb723bb 386 return TRUE;
6a488035
TO
387 }
388
6a488035 389 if (empty($cols)) {
bfb723bb 390 $cols = $this->columnsWithDiffSpecs($table, "log_$table");
6a488035
TO
391 }
392
393 // use the relevant lines from CREATE TABLE to add colums to the log table
bfb723bb
DS
394 $create = $this->_getCreateQuery($table);
395 foreach ((array('ADD', 'MODIFY')) as $alterType) {
12de149a
DS
396 if (!empty($cols[$alterType])) {
397 foreach ($cols[$alterType] as $col) {
398 $line = $this->_getColumnQuery($col, $create);
15a68d41 399 CRM_Core_DAO::executeQuery("ALTER TABLE `{$this->db}`.log_$table {$alterType} {$line}", array(), TRUE, NULL, FALSE, FALSE);
12de149a 400 }
bfb723bb
DS
401 }
402 }
403
31c270e1
DS
404 // for any obsolete columns (not null) we just make the column nullable.
405 if (!empty($cols['OBSOLETE'])) {
eae2404c 406 $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}");
31c270e1 407 foreach ($cols['OBSOLETE'] as $col) {
bfb723bb 408 $line = $this->_getColumnQuery($col, $create);
31c270e1 409 // This is just going to make a not null column to nullable
15a68d41 410 CRM_Core_DAO::executeQuery("ALTER TABLE `{$this->db}`.log_$table MODIFY {$line}", array(), TRUE, NULL, FALSE, FALSE);
bfb723bb
DS
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
e0ef6999 421 /**
3d469574 422 * Get query table.
423 *
424 * @param string $table
e0ef6999
EM
425 *
426 * @return array
427 */
bfb723bb 428 private function _getCreateQuery($table) {
15a68d41 429 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE {$table}", array(), TRUE, NULL, FALSE, FALSE);
6a488035
TO
430 $dao->fetch();
431 $create = explode("\n", $dao->Create_Table);
bfb723bb
DS
432 return $create;
433 }
6a488035 434
e0ef6999 435 /**
3d469574 436 * Get column query.
437 *
438 * @param string $col
439 * @param bool $createQuery
e0ef6999
EM
440 *
441 * @return array|mixed|string
442 */
bfb723bb
DS
443 private function _getColumnQuery($col, $createQuery) {
444 $line = preg_grep("/^ `$col` /", $createQuery);
4a423b7a 445 $line = rtrim(array_pop($line), ',');
bfb723bb 446 // CRM-11179
4a423b7a 447 $line = $this->fixTimeStampAndNotNullSQL($line);
bfb723bb
DS
448 return $line;
449 }
450
e0ef6999 451 /**
3d469574 452 * Fix schema differences.
453 *
e0ef6999
EM
454 * @param bool $rebuildTrigger
455 */
00be9182 456 public function fixSchemaDifferencesForAll($rebuildTrigger = FALSE) {
bfb723bb 457 $diffs = array();
bfb723bb
DS
458 foreach ($this->tables as $table) {
459 if (empty($this->logs[$table])) {
460 $this->createLogTableFor($table);
e53944ef
BS
461 }
462 else {
bfb723bb
DS
463 $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table");
464 }
465 }
6a488035 466
bfb723bb
DS
467 foreach ($diffs as $table => $cols) {
468 $this->fixSchemaDifferencesFor($table, $cols, FALSE);
6a488035 469 }
6a488035
TO
470 if ($rebuildTrigger) {
471 // invoke the meta trigger creation call
003b4269 472 CRM_Core_DAO::triggerRebuild(NULL, TRUE);
6a488035
TO
473 }
474 }
475
d424ffde 476 /**
3d469574 477 * Fix timestamp.
478 *
d424ffde 479 * Log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
bfb723bb
DS
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)
d424ffde 482 *
3d469574 483 * @param string $query
e0ef6999
EM
484 *
485 * @return mixed
486 */
00be9182 487 public function fixTimeStampAndNotNullSQL($query) {
6a488035
TO
488 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
489 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
490 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
c28241be 491 $query = str_ireplace("NOT NULL", '', $query);
6a488035
TO
492 return $query;
493 }
494
3d469574 495 /**
496 * Add reports.
497 */
6a488035
TO
498 private function addReports() {
499 $titles = array(
500 'logging/contact/detail' => ts('Logging Details'),
501 'logging/contact/summary' => ts('Contact Logging Report (Summary)'),
502 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'),
503 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'),
504 );
505 // enable logging templates
506 CRM_Core_DAO::executeQuery("
507 UPDATE civicrm_option_value
508 SET is_active = 1
509 WHERE value IN ('" . implode("', '", $this->reports) . "')
510 ");
511
512 // add report instances
513 $domain_id = CRM_Core_Config::domainID();
514 foreach ($this->reports as $report) {
ae5ffbb7 515 $dao = new CRM_Report_DAO_ReportInstance();
353ffa53
TO
516 $dao->domain_id = $domain_id;
517 $dao->report_id = $report;
518 $dao->title = $titles[$report];
6a488035 519 $dao->permission = 'administer CiviCRM';
ae5ffbb7 520 if ($report == 'logging/contact/summary') {
6a488035 521 $dao->is_reserved = 1;
ae5ffbb7 522 }
6a488035
TO
523 $dao->insert();
524 }
525 }
526
527 /**
528 * Get an array of column names of the given table.
ea3ddccf 529 *
3d469574 530 * @param string $table
ea3ddccf 531 * @param bool $force
532 *
533 * @return array
6a488035 534 */
e53944ef 535 private function columnsOf($table, $force = FALSE) {
003b4269 536 if ($force || !isset(\Civi::$statics[__CLASS__]['columnsOf'][$table])) {
537 $from = (substr($table, 0, 4) == 'log_') ? "`{$this->db}`.$table" : $table;
538 CRM_Core_TemporaryErrorScope::ignoreException();
f55f7133 539 $dao = CRM_Core_DAO::executeQuery("SHOW COLUMNS FROM $from", CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
6a488035
TO
540 if (is_a($dao, 'DB_Error')) {
541 return array();
542 }
003b4269 543 \Civi::$statics[__CLASS__]['columnsOf'][$table] = array();
6a488035 544 while ($dao->fetch()) {
003b4269 545 \Civi::$statics[__CLASS__]['columnsOf'][$table][] = $dao->Field;
6a488035
TO
546 }
547 }
003b4269 548 return \Civi::$statics[__CLASS__]['columnsOf'][$table];
6a488035
TO
549 }
550
bfb723bb
DS
551 /**
552 * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table.
ea3ddccf 553 *
554 * @param string $table
555 *
556 * @return array
bfb723bb
DS
557 */
558 private function columnSpecsOf($table) {
87a52027 559 static $civiDB = NULL;
560 if (empty(\Civi::$statics[__CLASS__]['columnSpecs'])) {
561 \Civi::$statics[__CLASS__]['columnSpecs'] = array();
562 }
563 if (empty(\Civi::$statics[__CLASS__]['columnSpecs']) || !isset(\Civi::$statics[__CLASS__]['columnSpecs'][$table])) {
bfb723bb
DS
564 if (!$civiDB) {
565 $dao = new CRM_Contact_DAO_Contact();
566 $civiDB = $dao->_database;
567 }
cf0bd1e1 568 CRM_Core_TemporaryErrorScope::ignoreException();
6842bb53 569 // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
bfb723bb
DS
570 // than firing query for every given table.
571 $query = "
cf0bd1e1 572SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE
bfb723bb
DS
573FROM INFORMATION_SCHEMA.COLUMNS
574WHERE table_schema IN ('{$this->db}', '{$civiDB}')";
bfb723bb 575 $dao = CRM_Core_DAO::executeQuery($query);
bfb723bb
DS
576 if (is_a($dao, 'DB_Error')) {
577 return array();
578 }
579 while ($dao->fetch()) {
87a52027 580 if (!array_key_exists($dao->TABLE_NAME, \Civi::$statics[__CLASS__]['columnSpecs'])) {
581 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME] = array();
bfb723bb 582 }
87a52027 583 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME][$dao->COLUMN_NAME] = array(
ae5ffbb7
TO
584 'COLUMN_NAME' => $dao->COLUMN_NAME,
585 'DATA_TYPE' => $dao->DATA_TYPE,
586 'IS_NULLABLE' => $dao->IS_NULLABLE,
587 'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT,
588 );
cf0bd1e1 589 if (($first = strpos($dao->COLUMN_TYPE, '(')) != 0) {
87a52027 590 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME][$dao->COLUMN_NAME]['LENGTH'] = substr(
591 $dao->COLUMN_TYPE, $first, strpos($dao->COLUMN_TYPE, ')')
592 );
cf0bd1e1 593 }
bfb723bb 594 }
bfb723bb 595 }
87a52027 596 return \Civi::$statics[__CLASS__]['columnSpecs'][$table];
bfb723bb
DS
597 }
598
e0ef6999 599 /**
3d469574 600 * Get columns that have changed.
601 *
602 * @param string $civiTable
603 * @param string $logTable
e0ef6999
EM
604 *
605 * @return array
606 */
00be9182 607 public function columnsWithDiffSpecs($civiTable, $logTable) {
4a423b7a 608 $civiTableSpecs = $this->columnSpecsOf($civiTable);
353ffa53 609 $logTableSpecs = $this->columnSpecsOf($logTable);
6842bb53 610
31c270e1 611 $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array());
6842bb53 612
4a423b7a
DS
613 // columns to be added
614 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
6842bb53 615
4a423b7a 616 // columns to be modified
6842bb53 617 // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
4a423b7a
DS
618 // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
619 foreach ($civiTableSpecs as $col => $colSpecs) {
481a74f4 620 if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col])) {
e53944ef
BS
621 $logTableSpecs[$col] = array();
622 }
623
cd71572a 624 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
12de149a 625 if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) {
4a423b7a 626 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
cf0bd1e1
EM
627 if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array::value('DATA_TYPE', $logTableSpecs[$col])
628 // We won't alter the log if the length is decreased in case some of the existing data won't fit.
629 || CRM_Utils_Array::value('LENGTH', $civiTableSpecs[$col]) > CRM_Utils_Array::value('LENGTH', $logTableSpecs[$col])
630 ) {
6842bb53 631 // if data-type is different, surely consider the column
4a423b7a 632 $diff['MODIFY'][] = $col;
0db6c3e1 633 }
4c9b6178 634 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) &&
353ffa53
TO
635 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
636 ) {
4a423b7a
DS
637 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
638 $diff['MODIFY'][] = $col;
0db6c3e1 639 }
4c9b6178 640 elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
353ffa53
TO
641 !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')
642 ) {
4a423b7a
DS
643 // if default property is different, and its not about a timestamp column, consider it
644 $diff['MODIFY'][] = $col;
645 }
6842bb53 646 }
bfb723bb
DS
647 }
648
4a423b7a
DS
649 // columns to made obsolete by turning into not-null
650 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
31c270e1 651 foreach ($oldCols as $col) {
6842bb53 652 if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) &&
353ffa53
TO
653 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
654 ) {
4a423b7a 655 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
31c270e1 656 $diff['OBSOLETE'][] = $col;
bfb723bb
DS
657 }
658 }
659
660 return $diff;
661 }
662
d7ea7150 663 /**
664 * Getter for logTableSpec.
665 *
666 * @return array
667 */
668 public function getLogTableSpec() {
669 return $this->logTableSpec;
670 }
671
6a488035
TO
672 /**
673 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
ea3ddccf 674 *
675 * @param string $table
6a488035
TO
676 */
677 private function createLogTableFor($table) {
20139237 678 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE $table", CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
6a488035
TO
679 $dao->fetch();
680 $query = $dao->Create_Table;
681
682 // rewrite the queries into CREATE TABLE queries for log tables:
6a488035 683 $cols = <<<COLS
1f4627e9 684 ,
6a488035 685 log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
8dd883ca 686 log_conn_id VARCHAR(17),
6a488035
TO
687 log_user_id INTEGER,
688 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
689COLS;
c28241be 690
ef587f9c 691 if (!empty($this->logTableSpec[$table]['indexes'])) {
692 foreach ($this->logTableSpec[$table]['indexes'] as $indexName => $indexSpec) {
693 if (is_array($indexSpec)) {
694 $indexSpec = implode(" , ", $indexSpec);
695 }
696 $cols .= ", INDEX {$indexName}($indexSpec)";
697 }
698 }
699
c28241be
DL
700 // - prepend the name with log_
701 // - drop AUTO_INCREMENT columns
702 // - drop non-column rows of the query (keys, constraints, etc.)
d7ea7150 703 // - set the ENGINE to the specified engine (default is archive)
c28241be 704 // - add log-specific columns (at the end of the table)
6a488035
TO
705 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
706 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
707 $query = preg_replace("/^ [^`].*$/m", '', $query);
ef587f9c 708 $engine = strtoupper(CRM_Utils_Array::value('engine', $this->logTableSpec[$table], 'ARCHIVE'));
d7ea7150 709 $engine .= " " . CRM_Utils_Array::value('engine_config', $this->logTableSpec[$table]);
ef587f9c 710 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=' . $engine . ' ', $query);
c28241be 711
6a488035 712 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
c28241be
DL
713 // so there's no need for a default timestamp and therefore we remove such default timestamps
714 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
715 $query = self::fixTimeStampAndNotNullSQL($query);
1f4627e9 716 $query = preg_replace("/(,*\n*\) )ENGINE/m", "$cols\n) ENGINE", $query);
6a488035 717
f55f7133 718 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
6a488035
TO
719
720 $columns = implode(', ', $this->columnsOf($table));
8dd883ca 721 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);
6a488035
TO
722
723 $this->tables[] = $table;
d7ea7150 724 if (empty($this->logs)) {
725 civicrm_api3('Setting', 'create', array('logging_uniqueid_date' => date('Y-m-d H:i:s')));
8dd883ca 726 civicrm_api3('Setting', 'create', array('logging_all_tables_uniquid' => 1));
727 }
6a488035
TO
728 $this->logs[$table] = "log_$table";
729 }
730
3d469574 731 /**
732 * Delete reports.
733 */
6a488035
TO
734 private function deleteReports() {
735 // disable logging templates
736 CRM_Core_DAO::executeQuery("
737 UPDATE civicrm_option_value
738 SET is_active = 0
739 WHERE value IN ('" . implode("', '", $this->reports) . "')
740 ");
741
742 // delete report instances
743 $domain_id = CRM_Core_Config::domainID();
744 foreach ($this->reports as $report) {
ae5ffbb7 745 $dao = new CRM_Report_DAO_ReportInstance();
6a488035
TO
746 $dao->domain_id = $domain_id;
747 $dao->report_id = $report;
748 $dao->delete();
749 }
750 }
751
752 /**
753 * Predicate whether logging is enabled.
754 */
755 public function isEnabled() {
509e50b7 756 if (\Civi::settings()->get('logging')) {
757 return ($this->tablesExist() && (\Civi::settings()->get('logging_no_trigger_permission') || $this->triggersExist()));
6a488035
TO
758 }
759 return FALSE;
760 }
761
762 /**
763 * Predicate whether any log tables exist.
764 */
765 private function tablesExist() {
766 return !empty($this->logs);
767 }
768
1f43f9e2 769 /**
770 * Drop all log tables.
771 *
772 * This does not currently have a usage outside the tests.
773 */
774 public function dropAllLogTables() {
775 if ($this->tablesExist()) {
776 foreach ($this->logs as $log_table) {
777 CRM_Core_DAO::executeQuery("DROP TABLE $log_table");
778 }
779 }
780 }
781
f8d28563 782 /**
783 * Get an sql clause to find the names of any log tables that do not match the normal pattern.
784 *
785 * Most tables are civicrm_xxx with the log table being log_civicrm_xxx
786 * However, they don't have to match this pattern (e.g when defined by hook) so find the
787 * anomalies and return a filter string to include them.
788 *
789 * @return string
790 */
791 public function getNonStandardTableNameFilterString() {
792 $nonStandardTableNames = preg_grep('/^civicrm_/', $this->tables, PREG_GREP_INVERT);
793 if (empty($nonStandardTableNames)) {
794 return '';
795 }
796 $nonStandardTableLogs = array();
797 foreach ($nonStandardTableNames as $nonStandardTableName) {
798 $nonStandardTableLogs[] = "'log_{$nonStandardTableName}'";
799 }
800 return " OR TABLE_NAME IN (" . implode(',', $nonStandardTableLogs) . ")";
801 }
802
6a488035
TO
803 /**
804 * Predicate whether the logging triggers are in place.
805 */
806 private function triggersExist() {
807 // FIXME: probably should be a bit more thorough…
808 // note that the LIKE parameter is TABLE NAME
809 return (bool) CRM_Core_DAO::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
810 }
811
e0ef6999 812 /**
3d469574 813 * Get trigger info.
814 *
815 * @param array $info
e0ef6999
EM
816 * @param null $tableName
817 * @param bool $force
818 */
00be9182 819 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
74b348da 820 if (!CRM_Core_Config::singleton()->logging) {
6a488035
TO
821 return;
822 }
823
824 $insert = array('INSERT');
825 $update = array('UPDATE');
826 $delete = array('DELETE');
827
828 if ($tableName) {
829 $tableNames = array($tableName);
830 }
831 else {
832 $tableNames = $this->tables;
833 }
834
835 // logging is enabled, so now lets create the trigger info tables
836 foreach ($tableNames as $table) {
e53944ef 837 $columns = $this->columnsOf($table, $force);
6a488035
TO
838
839 // only do the change if any data has changed
481a74f4 840 $cond = array();
6a488035 841 foreach ($columns as $column) {
ef587f9c 842 $tableExceptions = array_key_exists('exceptions', $this->logTableSpec[$table]) ? $this->logTableSpec[$table]['exceptions'] : array();
6a488035 843 // ignore modified_date changes
ef587f9c 844 if ($column != 'modified_date' && !in_array($column, $tableExceptions)) {
6a488035
TO
845 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
846 }
847 }
848 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
481a74f4 849 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
6a488035 850
340f6aa0
DL
851 if ($this->useDBPrefix) {
852 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
853 }
854 else {
855 $sqlStmt = "INSERT INTO log_{tableName} (";
856 }
6a488035
TO
857 foreach ($columns as $column) {
858 $sqlStmt .= "$column, ";
859 }
860 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
861
862 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
863 $updateSQL .= $sqlStmt;
864
865 $sqlStmt = '';
866 foreach ($columns as $column) {
353ffa53 867 $sqlStmt .= "NEW.$column, ";
6a488035
TO
868 $deleteSQL .= "OLD.$column, ";
869 }
5cb4bffc 870 if (civicrm_api3('Setting', 'getvalue', array('name' => 'logging_uniqueid_date'))) {
8d2c1ae5
E
871 // Note that when connecting directly via mysql @uniqueID may not be set so a fallback is
872 // 'c_' to identify a non-CRM connection + timestamp to the hour + connection_id
873 // If the connection_id is longer than 6 chars it will be truncated.
874 // We tried setting the @uniqueID in the trigger but it was unreliable.
875 // An external interaction could split over 2 connections & it seems worth blocking the revert on
876 // these reports & adding extra permissioning to the api for this.
08a50e27 877 $connectionSQLString = "COALESCE(@uniqueID, LEFT(CONCAT('c_', unix_timestamp()/3600, CONNECTION_ID()), 17))";
8dd883ca 878 }
879 else {
880 // The log tables have not yet been converted to have varchar(17) fields for log_conn_id.
881 // Continue to use the less reliable connection_id for al tables for now.
8d2c1ae5 882 $connectionSQLString = "CONNECTION_ID()";
8dd883ca 883 }
8d2c1ae5
E
884 $sqlStmt .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
885 $deleteSQL .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
6a488035
TO
886
887 $insertSQL .= $sqlStmt;
888 $updateSQL .= $sqlStmt;
889
890 $info[] = array(
891 'table' => array($table),
892 'when' => 'AFTER',
893 'event' => $insert,
894 'sql' => $insertSQL,
895 );
896
897 $info[] = array(
898 'table' => array($table),
899 'when' => 'AFTER',
900 'event' => $update,
901 'sql' => $updateSQL,
902 );
903
904 $info[] = array(
905 'table' => array($table),
906 'when' => 'AFTER',
907 'event' => $delete,
908 'sql' => $deleteSQL,
909 );
910 }
911 }
912
913 /**
3d469574 914 * Disable logging temporarily.
915 *
6a488035 916 * This allow logging to be temporarily disabled for certain cases
74b348da 917 * where we want to do a mass cleanup but do not want to bother with
918 * an audit trail.
6a488035 919 */
481a74f4 920 public static function disableLoggingForThisConnection() {
74b348da 921 if (CRM_Core_Config::singleton()->logging) {
481a74f4 922 CRM_Core_DAO::executeQuery('SET @civicrm_disable_logging = 1');
6a488035
TO
923 }
924 }
925
93afbc3a 926 /**
927 * Get all the log tables that reference civicrm_contact.
928 *
929 * Note that it might make sense to wrap this in a getLogTablesForEntity
930 * but this is the only entity currently available...
931 */
932 public function getLogTablesForContact() {
933 $tables = array_keys(CRM_Dedupe_Merger::cidRefs());
934 return array_intersect($tables, $this->tables);
935 }
936
6a488035 937}