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