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