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