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