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