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