Merge pull request #5657 from jagrutiP/CRM-16317
[civicrm-core.git] / CRM / Logging / Schema.php
CommitLineData
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 */
35class 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("
63SELECT TABLE_NAME
64FROM INFORMATION_SCHEMA.TABLES
65WHERE TABLE_SCHEMA = '{$civiDBName}'
66AND TABLE_TYPE = 'BASE TABLE'
67AND 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("
98SELECT TABLE_NAME
99FROM INFORMATION_SCHEMA.TABLES
100WHERE TABLE_SCHEMA = '{$this->db}'
101AND TABLE_TYPE = 'BASE TABLE'
102AND 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 }
6a4257d4 399 $errorScope = 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 = "
403SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
404FROM INFORMATION_SCHEMA.COLUMNS
405WHERE 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 );
bfb723bb 420 }
bfb723bb 421 }
bfb723bb
DS
422 return $columnSpecs[$table];
423 }
424
e0ef6999
EM
425 /**
426 * @param $civiTable
427 * @param $logTable
428 *
429 * @return array
430 */
00be9182 431 public function columnsWithDiffSpecs($civiTable, $logTable) {
4a423b7a 432 $civiTableSpecs = $this->columnSpecsOf($civiTable);
353ffa53 433 $logTableSpecs = $this->columnSpecsOf($logTable);
6842bb53 434
31c270e1 435 $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array());
6842bb53 436
4a423b7a
DS
437 // columns to be added
438 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
6842bb53 439
4a423b7a 440 // columns to be modified
6842bb53 441 // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
4a423b7a
DS
442 // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
443 foreach ($civiTableSpecs as $col => $colSpecs) {
481a74f4 444 if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col])) {
e53944ef
BS
445 $logTableSpecs[$col] = array();
446 }
447
cd71572a 448 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
12de149a 449 if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) {
4a423b7a 450 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
c5bdd6f0 451 if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array::value('DATA_TYPE', $logTableSpecs[$col])) {
6842bb53 452 // if data-type is different, surely consider the column
4a423b7a 453 $diff['MODIFY'][] = $col;
0db6c3e1 454 }
4c9b6178 455 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) &&
353ffa53
TO
456 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
457 ) {
4a423b7a
DS
458 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
459 $diff['MODIFY'][] = $col;
0db6c3e1 460 }
4c9b6178 461 elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
353ffa53
TO
462 !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')
463 ) {
4a423b7a
DS
464 // if default property is different, and its not about a timestamp column, consider it
465 $diff['MODIFY'][] = $col;
466 }
6842bb53 467 }
bfb723bb
DS
468 }
469
4a423b7a
DS
470 // columns to made obsolete by turning into not-null
471 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
31c270e1 472 foreach ($oldCols as $col) {
6842bb53 473 if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) &&
353ffa53
TO
474 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
475 ) {
4a423b7a 476 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
31c270e1 477 $diff['OBSOLETE'][] = $col;
bfb723bb
DS
478 }
479 }
480
481 return $diff;
482 }
483
6a488035
TO
484 /**
485 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
486 */
487 private function createLogTableFor($table) {
488 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE $table");
489 $dao->fetch();
490 $query = $dao->Create_Table;
491
492 // rewrite the queries into CREATE TABLE queries for log tables:
6a488035
TO
493 $cols = <<<COLS
494 log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
495 log_conn_id INTEGER,
496 log_user_id INTEGER,
497 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
498COLS;
c28241be
DL
499
500 // - prepend the name with log_
501 // - drop AUTO_INCREMENT columns
502 // - drop non-column rows of the query (keys, constraints, etc.)
503 // - set the ENGINE to ARCHIVE
504 // - add log-specific columns (at the end of the table)
6a488035
TO
505 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
506 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
507 $query = preg_replace("/^ [^`].*$/m", '', $query);
508 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=ARCHIVE ', $query);
c28241be 509
6a488035 510 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
c28241be
DL
511 // so there's no need for a default timestamp and therefore we remove such default timestamps
512 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
513 $query = self::fixTimeStampAndNotNullSQL($query);
6a488035
TO
514 $query = preg_replace("/^\) /m", "$cols\n) ", $query);
515
516 CRM_Core_DAO::executeQuery($query);
517
518 $columns = implode(', ', $this->columnsOf($table));
519 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}");
520
521 $this->tables[] = $table;
522 $this->logs[$table] = "log_$table";
523 }
524
525 private function deleteReports() {
526 // disable logging templates
527 CRM_Core_DAO::executeQuery("
528 UPDATE civicrm_option_value
529 SET is_active = 0
530 WHERE value IN ('" . implode("', '", $this->reports) . "')
531 ");
532
533 // delete report instances
534 $domain_id = CRM_Core_Config::domainID();
535 foreach ($this->reports as $report) {
ae5ffbb7 536 $dao = new CRM_Report_DAO_ReportInstance();
6a488035
TO
537 $dao->domain_id = $domain_id;
538 $dao->report_id = $report;
539 $dao->delete();
540 }
541 }
542
543 /**
544 * Predicate whether logging is enabled.
545 */
546 public function isEnabled() {
547 $config = CRM_Core_Config::singleton();
548
549 if ($config->logging) {
550 return $this->tablesExist() and $this->triggersExist();
551 }
552 return FALSE;
553 }
554
555 /**
556 * Predicate whether any log tables exist.
557 */
558 private function tablesExist() {
559 return !empty($this->logs);
560 }
561
562 /**
563 * Predicate whether the logging triggers are in place.
564 */
565 private function triggersExist() {
566 // FIXME: probably should be a bit more thorough…
567 // note that the LIKE parameter is TABLE NAME
568 return (bool) CRM_Core_DAO::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
569 }
570
e0ef6999
EM
571 /**
572 * @param $info
573 * @param null $tableName
574 * @param bool $force
575 */
00be9182 576 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
6a488035
TO
577 // check if we have logging enabled
578 $config =& CRM_Core_Config::singleton();
579 if (!$config->logging) {
580 return;
581 }
582
583 $insert = array('INSERT');
584 $update = array('UPDATE');
585 $delete = array('DELETE');
586
587 if ($tableName) {
588 $tableNames = array($tableName);
589 }
590 else {
591 $tableNames = $this->tables;
592 }
593
594 // logging is enabled, so now lets create the trigger info tables
595 foreach ($tableNames as $table) {
e53944ef 596 $columns = $this->columnsOf($table, $force);
6a488035
TO
597
598 // only do the change if any data has changed
481a74f4 599 $cond = array();
6a488035
TO
600 foreach ($columns as $column) {
601 // ignore modified_date changes
4d1040bb 602 if ($column != 'modified_date' && !in_array($column, CRM_Utils_Array::value($table, $this->exceptions, array()))) {
6a488035
TO
603 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
604 }
605 }
606 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
481a74f4 607 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
6a488035 608
340f6aa0
DL
609 if ($this->useDBPrefix) {
610 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
611 }
612 else {
613 $sqlStmt = "INSERT INTO log_{tableName} (";
614 }
6a488035
TO
615 foreach ($columns as $column) {
616 $sqlStmt .= "$column, ";
617 }
618 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
619
620 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
621 $updateSQL .= $sqlStmt;
622
623 $sqlStmt = '';
624 foreach ($columns as $column) {
353ffa53 625 $sqlStmt .= "NEW.$column, ";
6a488035
TO
626 $deleteSQL .= "OLD.$column, ";
627 }
353ffa53 628 $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
6a488035
TO
629 $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
630
353ffa53 631 $sqlStmt .= "END IF;";
6a488035
TO
632 $deleteSQL .= "END IF;";
633
634 $insertSQL .= $sqlStmt;
635 $updateSQL .= $sqlStmt;
636
637 $info[] = array(
638 'table' => array($table),
639 'when' => 'AFTER',
640 'event' => $insert,
641 'sql' => $insertSQL,
642 );
643
644 $info[] = array(
645 'table' => array($table),
646 'when' => 'AFTER',
647 'event' => $update,
648 'sql' => $updateSQL,
649 );
650
651 $info[] = array(
652 'table' => array($table),
653 'when' => 'AFTER',
654 'event' => $delete,
655 'sql' => $deleteSQL,
656 );
657 }
658 }
659
660 /**
661 * This allow logging to be temporarily disabled for certain cases
662 * where we want to do a mass cleanup but dont want to bother with
663 * an audit trail
664 *
6a488035 665 */
481a74f4 666 public static function disableLoggingForThisConnection() {
6a488035 667 // do this only if logging is enabled
481a74f4
TO
668 $config = CRM_Core_Config::singleton();
669 if ($config->logging) {
670 CRM_Core_DAO::executeQuery('SET @civicrm_disable_logging = 1');
6a488035
TO
671 }
672 }
673
674}