Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
06b69b18 | 4 | | CiviCRM version 4.5 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
06b69b18 | 6 | | Copyright CiviCRM LLC (c) 2004-2014 | |
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 | +--------------------------------------------------------------------+ | |
26 | */ | |
27 | ||
28 | /** | |
29 | * | |
30 | * @package CRM | |
06b69b18 | 31 | * @copyright CiviCRM LLC (c) 2004-2014 |
6a488035 TO |
32 | * $Id$ |
33 | * | |
34 | */ | |
35 | class CRM_Logging_Schema { | |
36 | private $logs = array(); | |
37 | private $tables = array(); | |
38 | ||
39 | private $db; | |
340f6aa0 | 40 | private $useDBPrefix = TRUE; |
6a488035 TO |
41 | |
42 | private $reports = array( | |
43 | 'logging/contact/detail', | |
44 | 'logging/contact/summary', | |
45 | 'logging/contribute/detail', | |
46 | 'logging/contribute/summary', | |
47 | ); | |
48 | ||
6842bb53 | 49 | //CRM-13028 / NYSS-6933 - table => array (cols) - to be excluded from the update statement |
4d1040bb DS |
50 | private $exceptions = array( |
51 | 'civicrm_job' => array('last_run'), | |
52 | 'civicrm_group' => array('cache_date'), | |
6842bb53 | 53 | ); |
4d1040bb | 54 | |
6a488035 TO |
55 | /** |
56 | * Populate $this->tables and $this->logs with current db state. | |
57 | */ | |
58 | function __construct() { | |
59 | $dao = new CRM_Contact_DAO_Contact(); | |
60 | $civiDBName = $dao->_database; | |
61 | ||
62 | $dao = CRM_Core_DAO::executeQuery(" | |
63 | SELECT TABLE_NAME | |
64 | FROM INFORMATION_SCHEMA.TABLES | |
65 | WHERE TABLE_SCHEMA = '{$civiDBName}' | |
66 | AND TABLE_TYPE = 'BASE TABLE' | |
67 | AND TABLE_NAME LIKE 'civicrm_%' | |
68 | "); | |
69 | while ($dao->fetch()) { | |
70 | $this->tables[] = $dao->TABLE_NAME; | |
71 | } | |
72 | ||
3292d079 | 73 | // do not log temp import, cache, menu and log tables |
6a488035 TO |
74 | $this->tables = preg_grep('/^civicrm_import_job_/', $this->tables, PREG_GREP_INVERT); |
75 | $this->tables = preg_grep('/_cache$/', $this->tables, PREG_GREP_INVERT); | |
76 | $this->tables = preg_grep('/_log/', $this->tables, PREG_GREP_INVERT); | |
77 | $this->tables = preg_grep('/^civicrm_task_action_temp_/', $this->tables, PREG_GREP_INVERT); | |
78 | $this->tables = preg_grep('/^civicrm_export_temp_/', $this->tables, PREG_GREP_INVERT); | |
79 | $this->tables = preg_grep('/^civicrm_queue_/', $this->tables, PREG_GREP_INVERT); | |
3292d079 | 80 | $this->tables = preg_grep('/^civicrm_menu/', $this->tables, PREG_GREP_INVERT); //CRM-14672 |
6a488035 | 81 | |
f9b793b0 DL |
82 | // do not log civicrm_mailing_event* tables, CRM-12300 |
83 | $this->tables = preg_grep('/^civicrm_mailing_event_/', $this->tables, PREG_GREP_INVERT); | |
84 | ||
340f6aa0 DL |
85 | if (defined('CIVICRM_LOGGING_DSN')) { |
86 | $dsn = DB::parseDSN(CIVICRM_LOGGING_DSN); | |
87 | $this->useDBPrefix = (CIVICRM_LOGGING_DSN != CIVICRM_DSN); | |
88 | } | |
89 | else { | |
90 | $dsn = DB::parseDSN(CIVICRM_DSN); | |
91 | $this->useDBPrefix = FALSE; | |
92 | } | |
6a488035 TO |
93 | $this->db = $dsn['database']; |
94 | ||
95 | $dao = CRM_Core_DAO::executeQuery(" | |
96 | SELECT TABLE_NAME | |
97 | FROM INFORMATION_SCHEMA.TABLES | |
98 | WHERE TABLE_SCHEMA = '{$this->db}' | |
99 | AND TABLE_TYPE = 'BASE TABLE' | |
100 | AND TABLE_NAME LIKE 'log_civicrm_%' | |
101 | "); | |
102 | while ($dao->fetch()) { | |
103 | $log = $dao->TABLE_NAME; | |
104 | $this->logs[substr($log, 4)] = $log; | |
105 | } | |
106 | } | |
107 | ||
108 | /** | |
109 | * Return logging custom data tables. | |
110 | */ | |
111 | function customDataLogTables() { | |
112 | return preg_grep('/^log_civicrm_value_/', $this->logs); | |
113 | } | |
114 | ||
694e78fd DS |
115 | /** |
116 | * Return custom data tables for specified entity / extends. | |
117 | */ | |
118 | function entityCustomDataLogTables($extends) { | |
119 | $customGroupTables = array(); | |
120 | $customGroupDAO = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity($extends); | |
121 | $customGroupDAO->find(); | |
122 | while ($customGroupDAO->fetch()) { | |
123 | $customGroupTables[$customGroupDAO->table_name] = $this->logs[$customGroupDAO->table_name]; | |
124 | } | |
125 | return $customGroupTables; | |
126 | } | |
127 | ||
6a488035 TO |
128 | /** |
129 | * Disable logging by dropping the triggers (but keep the log tables intact). | |
130 | */ | |
131 | function disableLogging() { | |
132 | $config = CRM_Core_Config::singleton(); | |
133 | $config->logging = FALSE; | |
134 | ||
135 | $this->dropTriggers(); | |
136 | ||
137 | // invoke the meta trigger creation call | |
138 | CRM_Core_DAO::triggerRebuild(); | |
139 | ||
140 | $this->deleteReports(); | |
141 | } | |
142 | ||
143 | /** | |
144 | * Drop triggers for all logged tables. | |
145 | */ | |
146 | function dropTriggers($tableName = NULL) { | |
147 | $dao = new CRM_Core_DAO; | |
148 | ||
149 | if ($tableName) { | |
150 | $tableNames = array($tableName); | |
151 | } | |
152 | else { | |
153 | $tableNames = $this->tables; | |
154 | } | |
155 | ||
156 | foreach ($tableNames as $table) { | |
6842bb53 DL |
157 | $validName = CRM_Core_DAO::shortenSQLName($table, 48, TRUE); |
158 | ||
6a488035 | 159 | // before triggers |
6842bb53 DL |
160 | $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_insert"); |
161 | $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_update"); | |
162 | $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_before_delete"); | |
6a488035 TO |
163 | |
164 | // after triggers | |
6842bb53 DL |
165 | $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_insert"); |
166 | $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_update"); | |
167 | $dao->executeQuery("DROP TRIGGER IF EXISTS {$validName}_after_delete"); | |
6a488035 | 168 | } |
a8dd306e DL |
169 | |
170 | // now lets also be safe and drop all triggers that start with | |
171 | // civicrm_ if we are dropping all triggers | |
172 | // we need to do this to capture all the leftover triggers since | |
173 | // we did the shortening trigger name for CRM-11794 | |
174 | if ($tableName === NULL) { | |
175 | $triggers = $dao->executeQuery("SHOW TRIGGERS LIKE 'civicrm_%'"); | |
176 | ||
177 | while ($triggers->fetch()) { | |
178 | // note that drop trigger has a wierd syntax and hence we do not | |
179 | // send the trigger name as a string (i.e. its not quoted | |
180 | $dao->executeQuery("DROP TRIGGER IF EXISTS {$triggers->Trigger}"); | |
181 | } | |
182 | } | |
6a488035 TO |
183 | } |
184 | ||
185 | /** | |
186 | * Enable sitewide logging. | |
187 | * | |
188 | * @return void | |
189 | */ | |
190 | function enableLogging() { | |
191 | $this->fixSchemaDifferences(TRUE); | |
192 | $this->addReports(); | |
193 | } | |
194 | ||
195 | /** | |
196 | * Sync log tables and rebuild triggers. | |
197 | * | |
198 | * @param bool $enableLogging: Ensure logging is enabled | |
199 | * | |
200 | * @return void | |
201 | */ | |
202 | function fixSchemaDifferences($enableLogging = FALSE) { | |
203 | $config = CRM_Core_Config::singleton(); | |
204 | if ($enableLogging) { | |
205 | $config->logging = TRUE; | |
206 | } | |
207 | if ($config->logging) { | |
bfb723bb | 208 | $this->fixSchemaDifferencesForALL(); |
6a488035 TO |
209 | } |
210 | // invoke the meta trigger creation call | |
e53944ef | 211 | CRM_Core_DAO::triggerRebuild(NULL, TRUE); |
6a488035 TO |
212 | } |
213 | ||
214 | /** | |
215 | * Add missing (potentially specified) log table columns for the given table. | |
216 | * | |
217 | * @param $table string name of the relevant table | |
218 | * @param $cols mixed array of columns to add or null (to check for the missing columns) | |
219 | * @param $rebuildTrigger boolean should we rebuild the triggers | |
220 | * | |
221 | * @return void | |
222 | */ | |
bfb723bb DS |
223 | function fixSchemaDifferencesFor($table, $cols = array(), $rebuildTrigger = FALSE) { |
224 | if (empty($table)) { | |
225 | return FALSE; | |
226 | } | |
6a488035 TO |
227 | if (empty($this->logs[$table])) { |
228 | $this->createLogTableFor($table); | |
bfb723bb | 229 | return TRUE; |
6a488035 TO |
230 | } |
231 | ||
6a488035 | 232 | if (empty($cols)) { |
bfb723bb | 233 | $cols = $this->columnsWithDiffSpecs($table, "log_$table"); |
6a488035 TO |
234 | } |
235 | ||
236 | // use the relevant lines from CREATE TABLE to add colums to the log table | |
bfb723bb DS |
237 | $create = $this->_getCreateQuery($table); |
238 | foreach ((array('ADD', 'MODIFY')) as $alterType) { | |
12de149a DS |
239 | if (!empty($cols[$alterType])) { |
240 | foreach ($cols[$alterType] as $col) { | |
241 | $line = $this->_getColumnQuery($col, $create); | |
242 | CRM_Core_DAO::executeQuery("ALTER TABLE `{$this->db}`.log_$table {$alterType} {$line}"); | |
243 | } | |
bfb723bb DS |
244 | } |
245 | } | |
246 | ||
31c270e1 DS |
247 | // for any obsolete columns (not null) we just make the column nullable. |
248 | if (!empty($cols['OBSOLETE'])) { | |
eae2404c | 249 | $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}"); |
31c270e1 | 250 | foreach ($cols['OBSOLETE'] as $col) { |
bfb723bb | 251 | $line = $this->_getColumnQuery($col, $create); |
31c270e1 DS |
252 | // This is just going to make a not null column to nullable |
253 | CRM_Core_DAO::executeQuery("ALTER TABLE `{$this->db}`.log_$table MODIFY {$line}"); | |
bfb723bb DS |
254 | } |
255 | } | |
256 | ||
257 | if ($rebuildTrigger) { | |
258 | // invoke the meta trigger creation call | |
259 | CRM_Core_DAO::triggerRebuild($table); | |
260 | } | |
261 | return TRUE; | |
262 | } | |
263 | ||
264 | private function _getCreateQuery($table) { | |
265 | $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE {$table}"); | |
6a488035 TO |
266 | $dao->fetch(); |
267 | $create = explode("\n", $dao->Create_Table); | |
bfb723bb DS |
268 | return $create; |
269 | } | |
6a488035 | 270 | |
bfb723bb DS |
271 | private function _getColumnQuery($col, $createQuery) { |
272 | $line = preg_grep("/^ `$col` /", $createQuery); | |
4a423b7a | 273 | $line = rtrim(array_pop($line), ','); |
bfb723bb | 274 | // CRM-11179 |
4a423b7a | 275 | $line = $this->fixTimeStampAndNotNullSQL($line); |
bfb723bb DS |
276 | return $line; |
277 | } | |
278 | ||
279 | function fixSchemaDifferencesForAll($rebuildTrigger = FALSE) { | |
280 | $diffs = array(); | |
bfb723bb DS |
281 | foreach ($this->tables as $table) { |
282 | if (empty($this->logs[$table])) { | |
283 | $this->createLogTableFor($table); | |
e53944ef BS |
284 | } |
285 | else { | |
bfb723bb DS |
286 | $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table"); |
287 | } | |
288 | } | |
6a488035 | 289 | |
bfb723bb DS |
290 | foreach ($diffs as $table => $cols) { |
291 | $this->fixSchemaDifferencesFor($table, $cols, FALSE); | |
6a488035 TO |
292 | } |
293 | ||
294 | if ($rebuildTrigger) { | |
295 | // invoke the meta trigger creation call | |
296 | CRM_Core_DAO::triggerRebuild($table); | |
297 | } | |
298 | } | |
299 | ||
bfb723bb DS |
300 | /* |
301 | * log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date, | |
302 | * so there's no need for a default timestamp and therefore we remove such default timestamps | |
303 | * also eliminate the NOT NULL constraint, since we always copy and schema can change down the road) | |
304 | */ | |
c28241be | 305 | function fixTimeStampAndNotNullSQL($query) { |
6a488035 TO |
306 | $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query); |
307 | $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query); | |
308 | $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query); | |
c28241be | 309 | $query = str_ireplace("NOT NULL", '', $query); |
6a488035 TO |
310 | return $query; |
311 | } | |
312 | ||
6a488035 TO |
313 | private function addReports() { |
314 | $titles = array( | |
315 | 'logging/contact/detail' => ts('Logging Details'), | |
316 | 'logging/contact/summary' => ts('Contact Logging Report (Summary)'), | |
317 | 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'), | |
318 | 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'), | |
319 | ); | |
320 | // enable logging templates | |
321 | CRM_Core_DAO::executeQuery(" | |
322 | UPDATE civicrm_option_value | |
323 | SET is_active = 1 | |
324 | WHERE value IN ('" . implode("', '", $this->reports) . "') | |
325 | "); | |
326 | ||
327 | // add report instances | |
328 | $domain_id = CRM_Core_Config::domainID(); | |
329 | foreach ($this->reports as $report) { | |
0b25329b | 330 | $dao = new CRM_Report_DAO_ReportInstance; |
6a488035 TO |
331 | $dao->domain_id = $domain_id; |
332 | $dao->report_id = $report; | |
333 | $dao->title = $titles[$report]; | |
334 | $dao->permission = 'administer CiviCRM'; | |
335 | if ($report == 'logging/contact/summary') | |
336 | $dao->is_reserved = 1; | |
337 | $dao->insert(); | |
338 | } | |
339 | } | |
340 | ||
341 | /** | |
342 | * Get an array of column names of the given table. | |
343 | */ | |
e53944ef | 344 | private function columnsOf($table, $force = FALSE) { |
6a488035 TO |
345 | static $columnsOf = array(); |
346 | ||
347 | $from = (substr($table, 0, 4) == 'log_') ? "`{$this->db}`.$table" : $table; | |
348 | ||
e53944ef | 349 | if (!isset($columnsOf[$table]) || $force) { |
6a4257d4 | 350 | $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); |
6a488035 | 351 | $dao = CRM_Core_DAO::executeQuery("SHOW COLUMNS FROM $from"); |
6a488035 TO |
352 | if (is_a($dao, 'DB_Error')) { |
353 | return array(); | |
354 | } | |
355 | $columnsOf[$table] = array(); | |
356 | while ($dao->fetch()) { | |
357 | $columnsOf[$table][] = $dao->Field; | |
358 | } | |
359 | } | |
360 | ||
361 | return $columnsOf[$table]; | |
362 | } | |
363 | ||
bfb723bb DS |
364 | /** |
365 | * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table. | |
366 | */ | |
367 | private function columnSpecsOf($table) { | |
368 | static $columnSpecs = array(), $civiDB = NULL; | |
369 | ||
370 | if (empty($columnSpecs)) { | |
371 | if (!$civiDB) { | |
372 | $dao = new CRM_Contact_DAO_Contact(); | |
373 | $civiDB = $dao->_database; | |
374 | } | |
6a4257d4 | 375 | $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); |
6842bb53 | 376 | // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster |
bfb723bb DS |
377 | // than firing query for every given table. |
378 | $query = " | |
379 | SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT | |
380 | FROM INFORMATION_SCHEMA.COLUMNS | |
381 | WHERE table_schema IN ('{$this->db}', '{$civiDB}')"; | |
bfb723bb | 382 | $dao = CRM_Core_DAO::executeQuery($query); |
bfb723bb DS |
383 | if (is_a($dao, 'DB_Error')) { |
384 | return array(); | |
385 | } | |
386 | while ($dao->fetch()) { | |
bfb723bb DS |
387 | if (!array_key_exists($dao->TABLE_NAME, $columnSpecs)) { |
388 | $columnSpecs[$dao->TABLE_NAME] = array(); | |
389 | } | |
6842bb53 | 390 | $columnSpecs[$dao->TABLE_NAME][$dao->COLUMN_NAME] = |
bfb723bb | 391 | array( |
6842bb53 DL |
392 | 'COLUMN_NAME' => $dao->COLUMN_NAME, |
393 | 'DATA_TYPE' => $dao->DATA_TYPE, | |
394 | 'IS_NULLABLE' => $dao->IS_NULLABLE, | |
bfb723bb DS |
395 | 'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT |
396 | ); | |
397 | } | |
bfb723bb | 398 | } |
bfb723bb DS |
399 | return $columnSpecs[$table]; |
400 | } | |
401 | ||
4a423b7a DS |
402 | function columnsWithDiffSpecs($civiTable, $logTable) { |
403 | $civiTableSpecs = $this->columnSpecsOf($civiTable); | |
404 | $logTableSpecs = $this->columnSpecsOf($logTable); | |
6842bb53 | 405 | |
31c270e1 | 406 | $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array()); |
6842bb53 | 407 | |
4a423b7a DS |
408 | // columns to be added |
409 | $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs)); | |
6842bb53 | 410 | |
4a423b7a | 411 | // columns to be modified |
6842bb53 | 412 | // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition |
4a423b7a DS |
413 | // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method. |
414 | foreach ($civiTableSpecs as $col => $colSpecs) { | |
c5bdd6f0 | 415 | if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col]) ) { |
e53944ef BS |
416 | $logTableSpecs[$col] = array(); |
417 | } | |
418 | ||
cd71572a | 419 | $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]); |
12de149a | 420 | if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) { |
4a423b7a | 421 | // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors |
c5bdd6f0 | 422 | if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array::value('DATA_TYPE', $logTableSpecs[$col])) { |
6842bb53 | 423 | // if data-type is different, surely consider the column |
4a423b7a | 424 | $diff['MODIFY'][] = $col; |
c5bdd6f0 | 425 | } else if ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) && |
4a423b7a DS |
426 | $logTableSpecs[$col]['IS_NULLABLE'] == 'NO') { |
427 | // if is-null property is different, and log table's column is NOT-NULL, surely consider the column | |
428 | $diff['MODIFY'][] = $col; | |
c5bdd6f0 | 429 | } else if ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) && |
4a423b7a DS |
430 | !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')) { |
431 | // if default property is different, and its not about a timestamp column, consider it | |
432 | $diff['MODIFY'][] = $col; | |
433 | } | |
6842bb53 | 434 | } |
bfb723bb DS |
435 | } |
436 | ||
4a423b7a DS |
437 | // columns to made obsolete by turning into not-null |
438 | $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs)); | |
31c270e1 | 439 | foreach ($oldCols as $col) { |
6842bb53 | 440 | if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) && |
4a423b7a DS |
441 | $logTableSpecs[$col]['IS_NULLABLE'] == 'NO') { |
442 | // if its a column present only in log table, not among those used by log tables for special purpose, and not-null | |
31c270e1 | 443 | $diff['OBSOLETE'][] = $col; |
bfb723bb DS |
444 | } |
445 | } | |
446 | ||
447 | return $diff; | |
448 | } | |
449 | ||
6a488035 TO |
450 | /** |
451 | * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents. | |
452 | */ | |
453 | private function createLogTableFor($table) { | |
454 | $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE $table"); | |
455 | $dao->fetch(); | |
456 | $query = $dao->Create_Table; | |
457 | ||
458 | // rewrite the queries into CREATE TABLE queries for log tables: | |
6a488035 TO |
459 | $cols = <<<COLS |
460 | log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | |
461 | log_conn_id INTEGER, | |
462 | log_user_id INTEGER, | |
463 | log_action ENUM('Initialization', 'Insert', 'Update', 'Delete') | |
464 | COLS; | |
c28241be DL |
465 | |
466 | // - prepend the name with log_ | |
467 | // - drop AUTO_INCREMENT columns | |
468 | // - drop non-column rows of the query (keys, constraints, etc.) | |
469 | // - set the ENGINE to ARCHIVE | |
470 | // - add log-specific columns (at the end of the table) | |
6a488035 TO |
471 | $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query); |
472 | $query = preg_replace("/ AUTO_INCREMENT/i", '', $query); | |
473 | $query = preg_replace("/^ [^`].*$/m", '', $query); | |
474 | $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=ARCHIVE ', $query); | |
c28241be | 475 | |
6a488035 | 476 | // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date, |
c28241be DL |
477 | // so there's no need for a default timestamp and therefore we remove such default timestamps |
478 | // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road) | |
479 | $query = self::fixTimeStampAndNotNullSQL($query); | |
6a488035 TO |
480 | $query = preg_replace("/^\) /m", "$cols\n) ", $query); |
481 | ||
482 | CRM_Core_DAO::executeQuery($query); | |
483 | ||
484 | $columns = implode(', ', $this->columnsOf($table)); | |
485 | CRM_Core_DAO::executeQuery("INSERT INTO `{$this->db}`.log_$table ($columns, log_conn_id, log_user_id, log_action) SELECT $columns, CONNECTION_ID(), @civicrm_user_id, 'Initialization' FROM {$table}"); | |
486 | ||
487 | $this->tables[] = $table; | |
488 | $this->logs[$table] = "log_$table"; | |
489 | } | |
490 | ||
491 | private function deleteReports() { | |
492 | // disable logging templates | |
493 | CRM_Core_DAO::executeQuery(" | |
494 | UPDATE civicrm_option_value | |
495 | SET is_active = 0 | |
496 | WHERE value IN ('" . implode("', '", $this->reports) . "') | |
497 | "); | |
498 | ||
499 | // delete report instances | |
500 | $domain_id = CRM_Core_Config::domainID(); | |
501 | foreach ($this->reports as $report) { | |
0b25329b | 502 | $dao = new CRM_Report_DAO_ReportInstance; |
6a488035 TO |
503 | $dao->domain_id = $domain_id; |
504 | $dao->report_id = $report; | |
505 | $dao->delete(); | |
506 | } | |
507 | } | |
508 | ||
509 | /** | |
510 | * Predicate whether logging is enabled. | |
511 | */ | |
512 | public function isEnabled() { | |
513 | $config = CRM_Core_Config::singleton(); | |
514 | ||
515 | if ($config->logging) { | |
516 | return $this->tablesExist() and $this->triggersExist(); | |
517 | } | |
518 | return FALSE; | |
519 | } | |
520 | ||
521 | /** | |
522 | * Predicate whether any log tables exist. | |
523 | */ | |
524 | private function tablesExist() { | |
525 | return !empty($this->logs); | |
526 | } | |
527 | ||
528 | /** | |
529 | * Predicate whether the logging triggers are in place. | |
530 | */ | |
531 | private function triggersExist() { | |
532 | // FIXME: probably should be a bit more thorough… | |
533 | // note that the LIKE parameter is TABLE NAME | |
534 | return (bool) CRM_Core_DAO::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'"); | |
535 | } | |
536 | ||
e53944ef | 537 | function triggerInfo(&$info, $tableName = NULL, $force = FALSE) { |
6a488035 TO |
538 | // check if we have logging enabled |
539 | $config =& CRM_Core_Config::singleton(); | |
540 | if (!$config->logging) { | |
541 | return; | |
542 | } | |
543 | ||
544 | $insert = array('INSERT'); | |
545 | $update = array('UPDATE'); | |
546 | $delete = array('DELETE'); | |
547 | ||
548 | if ($tableName) { | |
549 | $tableNames = array($tableName); | |
550 | } | |
551 | else { | |
552 | $tableNames = $this->tables; | |
553 | } | |
554 | ||
555 | // logging is enabled, so now lets create the trigger info tables | |
556 | foreach ($tableNames as $table) { | |
e53944ef | 557 | $columns = $this->columnsOf($table, $force); |
6a488035 TO |
558 | |
559 | // only do the change if any data has changed | |
560 | $cond = array( ); | |
561 | foreach ($columns as $column) { | |
562 | // ignore modified_date changes | |
4d1040bb | 563 | if ($column != 'modified_date' && !in_array($column, CRM_Utils_Array::value($table, $this->exceptions, array()))) { |
6a488035 TO |
564 | $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')"; |
565 | } | |
566 | } | |
567 | $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0"; | |
568 | $updateSQL = "IF ( (" . implode( ' OR ', $cond ) . ") AND ( $suppressLoggingCond ) ) THEN "; | |
569 | ||
340f6aa0 DL |
570 | if ($this->useDBPrefix) { |
571 | $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} ("; | |
572 | } | |
573 | else { | |
574 | $sqlStmt = "INSERT INTO log_{tableName} ("; | |
575 | } | |
6a488035 TO |
576 | foreach ($columns as $column) { |
577 | $sqlStmt .= "$column, "; | |
578 | } | |
579 | $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES ("; | |
580 | ||
581 | $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt "; | |
582 | $updateSQL .= $sqlStmt; | |
583 | ||
584 | $sqlStmt = ''; | |
585 | foreach ($columns as $column) { | |
586 | $sqlStmt .= "NEW.$column, "; | |
587 | $deleteSQL .= "OLD.$column, "; | |
588 | } | |
589 | $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');"; | |
590 | $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');"; | |
591 | ||
592 | $sqlStmt .= "END IF;"; | |
593 | $deleteSQL .= "END IF;"; | |
594 | ||
595 | $insertSQL .= $sqlStmt; | |
596 | $updateSQL .= $sqlStmt; | |
597 | ||
598 | $info[] = array( | |
599 | 'table' => array($table), | |
600 | 'when' => 'AFTER', | |
601 | 'event' => $insert, | |
602 | 'sql' => $insertSQL, | |
603 | ); | |
604 | ||
605 | $info[] = array( | |
606 | 'table' => array($table), | |
607 | 'when' => 'AFTER', | |
608 | 'event' => $update, | |
609 | 'sql' => $updateSQL, | |
610 | ); | |
611 | ||
612 | $info[] = array( | |
613 | 'table' => array($table), | |
614 | 'when' => 'AFTER', | |
615 | 'event' => $delete, | |
616 | 'sql' => $deleteSQL, | |
617 | ); | |
618 | } | |
619 | } | |
620 | ||
621 | /** | |
622 | * This allow logging to be temporarily disabled for certain cases | |
623 | * where we want to do a mass cleanup but dont want to bother with | |
624 | * an audit trail | |
625 | * | |
626 | * @static | |
627 | * @public | |
628 | */ | |
629 | static function disableLoggingForThisConnection( ) { | |
630 | // do this only if logging is enabled | |
631 | $config = CRM_Core_Config::singleton( ); | |
632 | if ( $config->logging ) { | |
633 | CRM_Core_DAO::executeQuery( 'SET @civicrm_disable_logging = 1' ); | |
634 | } | |
635 | } | |
636 | ||
637 | } | |
638 |