Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-07-19-17-34-09
[civicrm-core.git] / CRM / Logging / Schema.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35 class CRM_Logging_Schema {
36 private $logs = array();
37 private $tables = array();
38
39 private $db;
40 private $useDBPrefix = TRUE;
41
42 private $reports = array(
43 'logging/contact/detail',
44 'logging/contact/summary',
45 'logging/contribute/detail',
46 'logging/contribute/summary',
47 );
48
49 //CRM-13028 / NYSS-6933 - table => array (cols) - to be excluded from the update statement
50 private $exceptions = array(
51 'civicrm_job' => array('last_run'),
52 'civicrm_group' => array('cache_date', 'refresh_date'),
53 );
54
55 /**
56 * Populate $this->tables and $this->logs with current db state.
57 */
58 public function __construct() {
59 $dao = new CRM_Contact_DAO_Contact();
60 $civiDBName = $dao->_database;
61
62 $dao = CRM_Core_DAO::executeQuery("
63 SELECT TABLE_NAME
64 FROM INFORMATION_SCHEMA.TABLES
65 WHERE TABLE_SCHEMA = '{$civiDBName}'
66 AND TABLE_TYPE = 'BASE TABLE'
67 AND TABLE_NAME LIKE 'civicrm_%'
68 ");
69 while ($dao->fetch()) {
70 $this->tables[] = $dao->TABLE_NAME;
71 }
72
73 // do not log temp import, cache, menu and log tables
74 $this->tables = preg_grep('/^civicrm_import_job_/', $this->tables, PREG_GREP_INVERT);
75 $this->tables = preg_grep('/_cache$/', $this->tables, PREG_GREP_INVERT);
76 $this->tables = preg_grep('/_log/', $this->tables, PREG_GREP_INVERT);
77 $this->tables = preg_grep('/^civicrm_queue_/', $this->tables, PREG_GREP_INVERT);
78 $this->tables = preg_grep('/^civicrm_menu/', $this->tables, PREG_GREP_INVERT); //CRM-14672
79 $this->tables = preg_grep('/_temp_/', $this->tables, PREG_GREP_INVERT);
80
81 // do not log civicrm_mailing_event* tables, CRM-12300
82 $this->tables = preg_grep('/^civicrm_mailing_event_/', $this->tables, PREG_GREP_INVERT);
83
84 // do not log civicrm_mailing_recipients table, CRM-16193
85 $this->tables = array_diff($this->tables, array('civicrm_mailing_recipients'));
86
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 }
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 */
113 public function customDataLogTables() {
114 return preg_grep('/^log_civicrm_value_/', $this->logs);
115 }
116
117 /**
118 * Return custom data tables for specified entity / extends.
119 */
120 public function entityCustomDataLogTables($extends) {
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
130 /**
131 * Disable logging by dropping the triggers (but keep the log tables intact).
132 */
133 public function disableLogging() {
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 */
148 public function dropTriggers($tableName = NULL) {
149 $dao = new CRM_Core_DAO();
150
151 if ($tableName) {
152 $tableNames = array($tableName);
153 }
154 else {
155 $tableNames = $this->tables;
156 }
157
158 foreach ($tableNames as $table) {
159 $validName = CRM_Core_DAO::shortenSQLName($table, 48, TRUE);
160
161 // before triggers
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");
165
166 // after triggers
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");
170 }
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 weird 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 }
185 }
186
187 /**
188 * Enable sitewide logging.
189 *
190 * @return void
191 */
192 public function enableLogging() {
193 $this->fixSchemaDifferences(TRUE);
194 $this->addReports();
195 }
196
197 /**
198 * Sync log tables and rebuild triggers.
199 *
200 * @param bool $enableLogging : Ensure logging is enabled
201 *
202 * @return void
203 */
204 public function fixSchemaDifferences($enableLogging = FALSE) {
205 $config = CRM_Core_Config::singleton();
206 if ($enableLogging) {
207 $config->logging = TRUE;
208 }
209 if ($config->logging) {
210 $this->fixSchemaDifferencesForALL();
211 }
212 // invoke the meta trigger creation call
213 CRM_Core_DAO::triggerRebuild(NULL, TRUE);
214 }
215
216 /**
217 * Add missing (potentially specified) log table columns for the given table.
218 *
219 * @param string $table
220 * name of the relevant table.
221 * @param array $cols
222 * Mixed array of columns to add or null (to check for the missing columns).
223 * @param bool $rebuildTrigger
224 * should we rebuild the triggers.
225 *
226 * @return void
227 */
228 public function fixSchemaDifferencesFor($table, $cols = array(), $rebuildTrigger = FALSE) {
229 if (empty($table)) {
230 return FALSE;
231 }
232 if (empty($this->logs[$table])) {
233 $this->createLogTableFor($table);
234 return TRUE;
235 }
236
237 if (empty($cols)) {
238 $cols = $this->columnsWithDiffSpecs($table, "log_$table");
239 }
240
241 // use the relevant lines from CREATE TABLE to add colums to the log table
242 $create = $this->_getCreateQuery($table);
243 foreach ((array('ADD', 'MODIFY')) as $alterType) {
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 }
249 }
250 }
251
252 // for any obsolete columns (not null) we just make the column nullable.
253 if (!empty($cols['OBSOLETE'])) {
254 $create = $this->_getCreateQuery("`{$this->db}`.log_{$table}");
255 foreach ($cols['OBSOLETE'] as $col) {
256 $line = $this->_getColumnQuery($col, $create);
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}");
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
269 /**
270 * @param $table
271 *
272 * @return array
273 */
274 private function _getCreateQuery($table) {
275 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE {$table}");
276 $dao->fetch();
277 $create = explode("\n", $dao->Create_Table);
278 return $create;
279 }
280
281 /**
282 * @param $col
283 * @param $createQuery
284 *
285 * @return array|mixed|string
286 */
287 private function _getColumnQuery($col, $createQuery) {
288 $line = preg_grep("/^ `$col` /", $createQuery);
289 $line = rtrim(array_pop($line), ',');
290 // CRM-11179
291 $line = $this->fixTimeStampAndNotNullSQL($line);
292 return $line;
293 }
294
295 /**
296 * @param bool $rebuildTrigger
297 */
298 public function fixSchemaDifferencesForAll($rebuildTrigger = FALSE) {
299 $diffs = array();
300 foreach ($this->tables as $table) {
301 if (empty($this->logs[$table])) {
302 $this->createLogTableFor($table);
303 }
304 else {
305 $diffs[$table] = $this->columnsWithDiffSpecs($table, "log_$table");
306 }
307 }
308
309 foreach ($diffs as $table => $cols) {
310 $this->fixSchemaDifferencesFor($table, $cols, FALSE);
311 }
312
313 if ($rebuildTrigger) {
314 // invoke the meta trigger creation call
315 CRM_Core_DAO::triggerRebuild($table);
316 }
317 }
318
319 /**
320 * Log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
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)
323 *
324 * @param $query
325 *
326 * @return mixed
327 */
328 public function fixTimeStampAndNotNullSQL($query) {
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);
332 $query = str_ireplace("NOT NULL", '', $query);
333 return $query;
334 }
335
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) {
353 $dao = new CRM_Report_DAO_ReportInstance();
354 $dao->domain_id = $domain_id;
355 $dao->report_id = $report;
356 $dao->title = $titles[$report];
357 $dao->permission = 'administer CiviCRM';
358 if ($report == 'logging/contact/summary') {
359 $dao->is_reserved = 1;
360 }
361 $dao->insert();
362 }
363 }
364
365 /**
366 * Get an array of column names of the given table.
367 */
368 private function columnsOf($table, $force = FALSE) {
369 static $columnsOf = array();
370
371 $from = (substr($table, 0, 4) == 'log_') ? "`{$this->db}`.$table" : $table;
372
373 if (!isset($columnsOf[$table]) || $force) {
374 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
375 $dao = CRM_Core_DAO::executeQuery("SHOW COLUMNS FROM $from");
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
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 }
399 CRM_Core_TemporaryErrorScope::ignoreException();
400 // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster
401 // than firing query for every given table.
402 $query = "
403 SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE
404 FROM INFORMATION_SCHEMA.COLUMNS
405 WHERE table_schema IN ('{$this->db}', '{$civiDB}')";
406 $dao = CRM_Core_DAO::executeQuery($query);
407 if (is_a($dao, 'DB_Error')) {
408 return array();
409 }
410 while ($dao->fetch()) {
411 if (!array_key_exists($dao->TABLE_NAME, $columnSpecs)) {
412 $columnSpecs[$dao->TABLE_NAME] = array();
413 }
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 );
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 }
423 }
424 }
425 return $columnSpecs[$table];
426 }
427
428 /**
429 * @param $civiTable
430 * @param $logTable
431 *
432 * @return array
433 */
434 public function columnsWithDiffSpecs($civiTable, $logTable) {
435 $civiTableSpecs = $this->columnSpecsOf($civiTable);
436 $logTableSpecs = $this->columnSpecsOf($logTable);
437
438 $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array());
439
440 // columns to be added
441 $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs));
442
443 // columns to be modified
444 // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition
445 // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method.
446 foreach ($civiTableSpecs as $col => $colSpecs) {
447 if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col])) {
448 $logTableSpecs[$col] = array();
449 }
450
451 $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]);
452 if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) {
453 // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors
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 ) {
458 // if data-type is different, surely consider the column
459 $diff['MODIFY'][] = $col;
460 }
461 elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) &&
462 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
463 ) {
464 // if is-null property is different, and log table's column is NOT-NULL, surely consider the column
465 $diff['MODIFY'][] = $col;
466 }
467 elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) &&
468 !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP')
469 ) {
470 // if default property is different, and its not about a timestamp column, consider it
471 $diff['MODIFY'][] = $col;
472 }
473 }
474 }
475
476 // columns to made obsolete by turning into not-null
477 $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs));
478 foreach ($oldCols as $col) {
479 if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) &&
480 $logTableSpecs[$col]['IS_NULLABLE'] == 'NO'
481 ) {
482 // if its a column present only in log table, not among those used by log tables for special purpose, and not-null
483 $diff['OBSOLETE'][] = $col;
484 }
485 }
486
487 return $diff;
488 }
489
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:
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;
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)
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);
515
516 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
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);
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) {
542 $dao = new CRM_Report_DAO_ReportInstance();
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
577 /**
578 * @param $info
579 * @param null $tableName
580 * @param bool $force
581 */
582 public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) {
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) {
602 $columns = $this->columnsOf($table, $force);
603
604 // only do the change if any data has changed
605 $cond = array();
606 foreach ($columns as $column) {
607 // ignore modified_date changes
608 if ($column != 'modified_date' && !in_array($column, CRM_Utils_Array::value($table, $this->exceptions, array()))) {
609 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
610 }
611 }
612 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
613 $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN ";
614
615 if ($this->useDBPrefix) {
616 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
617 }
618 else {
619 $sqlStmt = "INSERT INTO log_{tableName} (";
620 }
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) {
631 $sqlStmt .= "NEW.$column, ";
632 $deleteSQL .= "OLD.$column, ";
633 }
634 $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
635 $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
636
637 $sqlStmt .= "END IF;";
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 *
671 */
672 public static function disableLoggingForThisConnection() {
673 // do this only if logging is enabled
674 $config = CRM_Core_Config::singleton();
675 if ($config->logging) {
676 CRM_Core_DAO::executeQuery('SET @civicrm_disable_logging = 1');
677 }
678 }
679
680 }