CRM-21809: 'Advance search' group by issue
[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
91bd5c14 447 $line = self::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 */
91bd5c14
SL
487 public static function fixTimeStampAndNotNullSQL($query) {
488 $query = str_ireplace("TIMESTAMP() NOT NULL", "TIMESTAMP NULL", $query);
6a488035 489 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
91bd5c14 490 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()", '', $query);
6a488035 491 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
91bd5c14 492 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP()", '', $query);
6a488035 493 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
c28241be 494 $query = str_ireplace("NOT NULL", '', $query);
6a488035
TO
495 return $query;
496 }
497
3d469574 498 /**
499 * Add reports.
500 */
6a488035
TO
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) {
ae5ffbb7 518 $dao = new CRM_Report_DAO_ReportInstance();
353ffa53
TO
519 $dao->domain_id = $domain_id;
520 $dao->report_id = $report;
521 $dao->title = $titles[$report];
6a488035 522 $dao->permission = 'administer CiviCRM';
ae5ffbb7 523 if ($report == 'logging/contact/summary') {
6a488035 524 $dao->is_reserved = 1;
ae5ffbb7 525 }
6a488035
TO
526 $dao->insert();
527 }
528 }
529
530 /**
531 * Get an array of column names of the given table.
ea3ddccf 532 *
3d469574 533 * @param string $table
ea3ddccf 534 * @param bool $force
535 *
536 * @return array
6a488035 537 */
e53944ef 538 private function columnsOf($table, $force = FALSE) {
003b4269 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();
f55f7133 542 $dao = CRM_Core_DAO::executeQuery("SHOW COLUMNS FROM $from", CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
6a488035
TO
543 if (is_a($dao, 'DB_Error')) {
544 return array();
545 }
003b4269 546 \Civi::$statics[__CLASS__]['columnsOf'][$table] = array();
6a488035 547 while ($dao->fetch()) {
26f88fb3 548 \Civi::$statics[__CLASS__]['columnsOf'][$table][] = CRM_Utils_type::escape($dao->Field, 'MysqlColumnNameOrAlias');
6a488035
TO
549 }
550 }
003b4269 551 return \Civi::$statics[__CLASS__]['columnsOf'][$table];
6a488035
TO
552 }
553
bfb723bb
DS
554 /**
555 * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table.
ea3ddccf 556 *
557 * @param string $table
558 *
559 * @return array
bfb723bb
DS
560 */
561 private function columnSpecsOf($table) {
87a52027 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])) {
bfb723bb
DS
567 if (!$civiDB) {
568 $dao = new CRM_Contact_DAO_Contact();
569 $civiDB = $dao->_database;
570 }
cf0bd1e1 571 CRM_Core_TemporaryErrorScope::ignoreException();
6842bb53 572 // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
bfb723bb
DS
573 // than firing query for every given table.
574 $query = "
cf0bd1e1 575SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE
bfb723bb
DS
576FROM INFORMATION_SCHEMA.COLUMNS
577WHERE table_schema IN ('{$this->db}', '{$civiDB}')";
bfb723bb 578 $dao = CRM_Core_DAO::executeQuery($query);
bfb723bb
DS
579 if (is_a($dao, 'DB_Error')) {
580 return array();
581 }
582 while ($dao->fetch()) {
87a52027 583 if (!array_key_exists($dao->TABLE_NAME, \Civi::$statics[__CLASS__]['columnSpecs'])) {
584 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME] = array();
bfb723bb 585 }
87a52027 586 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME][$dao->COLUMN_NAME] = array(
ae5ffbb7
TO
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 );
cf0bd1e1 592 if (($first = strpos($dao->COLUMN_TYPE, '(')) != 0) {
87a52027 593 \Civi::$statics[__CLASS__]['columnSpecs'][$dao->TABLE_NAME][$dao->COLUMN_NAME]['LENGTH'] = substr(
594 $dao->COLUMN_TYPE, $first, strpos($dao->COLUMN_TYPE, ')')
595 );
cf0bd1e1 596 }
bfb723bb 597 }
bfb723bb 598 }
87a52027 599 return \Civi::$statics[__CLASS__]['columnSpecs'][$table];
bfb723bb
DS
600 }
601
e0ef6999 602 /**
3d469574 603 * Get columns that have changed.
604 *
605 * @param string $civiTable
606 * @param string $logTable
e0ef6999
EM
607 *
608 * @return array
609 */
00be9182 610 public function columnsWithDiffSpecs($civiTable, $logTable) {
4a423b7a 611 $civiTableSpecs = $this->columnSpecsOf($civiTable);
353ffa53 612 $logTableSpecs = $this->columnSpecsOf($logTable);
6842bb53 613
31c270e1 614 $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array());
6842bb53 615
4a423b7a
DS
616 // columns to be added
617 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
6842bb53 618
4a423b7a 619 // columns to be modified
6842bb53 620 // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
4a423b7a
DS
621 // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
622 foreach ($civiTableSpecs as $col => $colSpecs) {
481a74f4 623 if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col])) {
e53944ef
BS
624 $logTableSpecs[$col] = array();
625 }
626
cd71572a 627 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
12de149a 628 if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) {
4a423b7a 629 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
cf0bd1e1
EM
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 ) {
6842bb53 634 // if data-type is different, surely consider the column
4a423b7a 635 $diff['MODIFY'][] = $col;
0db6c3e1 636 }
4c9b6178 637 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) &&
353ffa53
TO
638 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
639 ) {
4a423b7a
DS
640 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
641 $diff['MODIFY'][] = $col;
0db6c3e1 642 }
4c9b6178 643 elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
353ffa53
TO
644 !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')
645 ) {
4a423b7a
DS
646 // if default property is different, and its not about a timestamp column, consider it
647 $diff['MODIFY'][] = $col;
648 }
6842bb53 649 }
bfb723bb
DS
650 }
651
4a423b7a
DS
652 // columns to made obsolete by turning into not-null
653 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
31c270e1 654 foreach ($oldCols as $col) {
6842bb53 655 if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) &&
353ffa53
TO
656 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
657 ) {
4a423b7a 658 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
31c270e1 659 $diff['OBSOLETE'][] = $col;
bfb723bb
DS
660 }
661 }
662
663 return $diff;
664 }
665
d7ea7150 666 /**
667 * Getter for logTableSpec.
668 *
669 * @return array
670 */
671 public function getLogTableSpec() {
672 return $this->logTableSpec;
673 }
674
6a488035
TO
675 /**
676 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
ea3ddccf 677 *
678 * @param string $table
6a488035
TO
679 */
680 private function createLogTableFor($table) {
20139237 681 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE $table", CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
6a488035
TO
682 $dao->fetch();
683 $query = $dao->Create_Table;
684
685 // rewrite the queries into CREATE TABLE queries for log tables:
6a488035 686 $cols = <<<COLS
1f4627e9 687 ,
6a488035 688 log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
8dd883ca 689 log_conn_id VARCHAR(17),
6a488035
TO
690 log_user_id INTEGER,
691 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
692COLS;
c28241be 693
ef587f9c 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
c28241be
DL
703 // - prepend the name with log_
704 // - drop AUTO_INCREMENT columns
705 // - drop non-column rows of the query (keys, constraints, etc.)
d7ea7150 706 // - set the ENGINE to the specified engine (default is archive)
c28241be 707 // - add log-specific columns (at the end of the table)
6a488035
TO
708 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
709 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
710 $query = preg_replace("/^ [^`].*$/m", '', $query);
ef587f9c 711 $engine = strtoupper(CRM_Utils_Array::value('engine', $this->logTableSpec[$table], 'ARCHIVE'));
d7ea7150 712 $engine .= " " . CRM_Utils_Array::value('engine_config', $this->logTableSpec[$table]);
ef587f9c 713 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=' . $engine . ' ', $query);
c28241be 714
6a488035 715 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
c28241be
DL
716 // so there's no need for a default timestamp and therefore we remove such default timestamps
717 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
718 $query = self::fixTimeStampAndNotNullSQL($query);
1f4627e9 719 $query = preg_replace("/(,*\n*\) )ENGINE/m", "$cols\n) ENGINE", $query);
6a488035 720
f55f7133 721 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
6a488035
TO
722
723 $columns = implode(', ', $this->columnsOf($table));
8dd883ca 724 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
725
726 $this->tables[] = $table;
d7ea7150 727 if (empty($this->logs)) {
728 civicrm_api3('Setting', 'create', array('logging_uniqueid_date' => date('Y-m-d H:i:s')));
8dd883ca 729 civicrm_api3('Setting', 'create', array('logging_all_tables_uniquid' => 1));
730 }
6a488035
TO
731 $this->logs[$table] = "log_$table";
732 }
733
3d469574 734 /**
735 * Delete reports.
736 */
6a488035
TO
737 private function deleteReports() {
738 // disable logging templates
739 CRM_Core_DAO::executeQuery("
740 UPDATE civicrm_option_value
741 SET is_active = 0
742 WHERE value IN ('" . implode("', '", $this->reports) . "')
743 ");
744
745 // delete report instances
746 $domain_id = CRM_Core_Config::domainID();
747 foreach ($this->reports as $report) {
ae5ffbb7 748 $dao = new CRM_Report_DAO_ReportInstance();
6a488035
TO
749 $dao->domain_id = $domain_id;
750 $dao->report_id = $report;
751 $dao->delete();
752 }
753 }
754
755 /**
756 * Predicate whether logging is enabled.
757 */
758 public function isEnabled() {
509e50b7 759 if (\Civi::settings()->get('logging')) {
760 return ($this->tablesExist() && (\Civi::settings()->get('logging_no_trigger_permission') || $this->triggersExist()));
6a488035
TO
761 }
762 return FALSE;
763 }
764
765 /**
766 * Predicate whether any log tables exist.
767 */
768 private function tablesExist() {
769 return !empty($this->logs);
770 }
771
1f43f9e2 772 /**
773 * Drop all log tables.
774 *
775 * This does not currently have a usage outside the tests.
776 */
777 public function dropAllLogTables() {
778 if ($this->tablesExist()) {
779 foreach ($this->logs as $log_table) {
780 CRM_Core_DAO::executeQuery("DROP TABLE $log_table");
781 }
782 }
783 }
784
f8d28563 785 /**
786 * Get an sql clause to find the names of any log tables that do not match the normal pattern.
787 *
788 * Most tables are civicrm_xxx with the log table being log_civicrm_xxx
789 * However, they don't have to match this pattern (e.g when defined by hook) so find the
790 * anomalies and return a filter string to include them.
791 *
792 * @return string
793 */
794 public function getNonStandardTableNameFilterString() {
795 $nonStandardTableNames = preg_grep('/^civicrm_/', $this->tables, PREG_GREP_INVERT);
796 if (empty($nonStandardTableNames)) {
797 return '';
798 }
799 $nonStandardTableLogs = array();
800 foreach ($nonStandardTableNames as $nonStandardTableName) {
801 $nonStandardTableLogs[] = "'log_{$nonStandardTableName}'";
802 }
803 return " OR TABLE_NAME IN (" . implode(',', $nonStandardTableLogs) . ")";
804 }
805
6a488035
TO
806 /**
807 * Predicate whether the logging triggers are in place.
808 */
809 private function triggersExist() {
810 // FIXME: probably should be a bit more thorough…
811 // note that the LIKE parameter is TABLE NAME
812 return (bool) CRM_Core_DAO::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
813 }
814
e0ef6999 815 /**
3d469574 816 * Get trigger info.
817 *
818 * @param array $info
e0ef6999
EM
819 * @param null $tableName
820 * @param bool $force
821 */
00be9182 822 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
74b348da 823 if (!CRM_Core_Config::singleton()->logging) {
6a488035
TO
824 return;
825 }
826
827 $insert = array('INSERT');
828 $update = array('UPDATE');
829 $delete = array('DELETE');
830
831 if ($tableName) {
832 $tableNames = array($tableName);
833 }
834 else {
835 $tableNames = $this->tables;
836 }
837
838 // logging is enabled, so now lets create the trigger info tables
839 foreach ($tableNames as $table) {
e53944ef 840 $columns = $this->columnsOf($table, $force);
6a488035
TO
841
842 // only do the change if any data has changed
481a74f4 843 $cond = array();
6a488035 844 foreach ($columns as $column) {
ef587f9c 845 $tableExceptions = array_key_exists('exceptions', $this->logTableSpec[$table]) ? $this->logTableSpec[$table]['exceptions'] : array();
6a488035 846 // ignore modified_date changes
ef587f9c 847 if ($column != 'modified_date' && !in_array($column, $tableExceptions)) {
6a488035
TO
848 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
849 }
850 }
851 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
481a74f4 852 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
6a488035 853
340f6aa0
DL
854 if ($this->useDBPrefix) {
855 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
856 }
857 else {
858 $sqlStmt = "INSERT INTO log_{tableName} (";
859 }
6a488035
TO
860 foreach ($columns as $column) {
861 $sqlStmt .= "$column, ";
862 }
863 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
864
865 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
866 $updateSQL .= $sqlStmt;
867
868 $sqlStmt = '';
869 foreach ($columns as $column) {
353ffa53 870 $sqlStmt .= "NEW.$column, ";
6a488035
TO
871 $deleteSQL .= "OLD.$column, ";
872 }
5cb4bffc 873 if (civicrm_api3('Setting', 'getvalue', array('name' => 'logging_uniqueid_date'))) {
8d2c1ae5
E
874 // Note that when connecting directly via mysql @uniqueID may not be set so a fallback is
875 // 'c_' to identify a non-CRM connection + timestamp to the hour + connection_id
876 // If the connection_id is longer than 6 chars it will be truncated.
877 // We tried setting the @uniqueID in the trigger but it was unreliable.
878 // An external interaction could split over 2 connections & it seems worth blocking the revert on
879 // these reports & adding extra permissioning to the api for this.
08a50e27 880 $connectionSQLString = "COALESCE(@uniqueID, LEFT(CONCAT('c_', unix_timestamp()/3600, CONNECTION_ID()), 17))";
8dd883ca 881 }
882 else {
883 // The log tables have not yet been converted to have varchar(17) fields for log_conn_id.
884 // Continue to use the less reliable connection_id for al tables for now.
8d2c1ae5 885 $connectionSQLString = "CONNECTION_ID()";
8dd883ca 886 }
8d2c1ae5
E
887 $sqlStmt .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
888 $deleteSQL .= $connectionSQLString . ", @civicrm_user_id, '{eventName}'); END IF;";
6a488035
TO
889
890 $insertSQL .= $sqlStmt;
891 $updateSQL .= $sqlStmt;
892
893 $info[] = array(
894 'table' => array($table),
895 'when' => 'AFTER',
896 'event' => $insert,
897 'sql' => $insertSQL,
898 );
899
900 $info[] = array(
901 'table' => array($table),
902 'when' => 'AFTER',
903 'event' => $update,
904 'sql' => $updateSQL,
905 );
906
907 $info[] = array(
908 'table' => array($table),
909 'when' => 'AFTER',
910 'event' => $delete,
911 'sql' => $deleteSQL,
912 );
913 }
914 }
915
916 /**
3d469574 917 * Disable logging temporarily.
918 *
6a488035 919 * This allow logging to be temporarily disabled for certain cases
74b348da 920 * where we want to do a mass cleanup but do not want to bother with
921 * an audit trail.
6a488035 922 */
481a74f4 923 public static function disableLoggingForThisConnection() {
74b348da 924 if (CRM_Core_Config::singleton()->logging) {
481a74f4 925 CRM_Core_DAO::executeQuery('SET @civicrm_disable_logging = 1');
6a488035
TO
926 }
927 }
928
93afbc3a 929 /**
930 * Get all the log tables that reference civicrm_contact.
931 *
932 * Note that it might make sense to wrap this in a getLogTablesForEntity
933 * but this is the only entity currently available...
934 */
935 public function getLogTablesForContact() {
936 $tables = array_keys(CRM_Dedupe_Merger::cidRefs());
937 return array_intersect($tables, $this->tables);
938 }
939
74044663
JP
940 /**
941 * Retrieve missing log tables.
942 *
943 * @return array
944 */
945 public function getMissingLogTables() {
946 if ($this->tablesExist()) {
947 return array_diff($this->tables, array_keys($this->logs));
948 }
949 return array();
950 }
951
6a488035 952}