3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
35 class CRM_Logging_Schema
{
36 private $logs = array();
37 private $tables = array();
40 private $useDBPrefix = TRUE;
42 private $reports = array(
43 'logging/contact/detail',
44 'logging/contact/summary',
45 'logging/contribute/detail',
46 'logging/contribute/summary',
50 * Populate $this->tables and $this->logs with current db state.
52 function __construct() {
53 $dao = new CRM_Contact_DAO_Contact();
54 $civiDBName = $dao->_database
;
56 $dao = CRM_Core_DAO
::executeQuery("
58 FROM INFORMATION_SCHEMA.TABLES
59 WHERE TABLE_SCHEMA = '{$civiDBName}'
60 AND TABLE_TYPE = 'BASE TABLE'
61 AND TABLE_NAME LIKE 'civicrm_%'
63 while ($dao->fetch()) {
64 $this->tables
[] = $dao->TABLE_NAME
;
67 // do not log temp import, cache and log tables
68 $this->tables
= preg_grep('/^civicrm_import_job_/', $this->tables
, PREG_GREP_INVERT
);
69 $this->tables
= preg_grep('/_cache$/', $this->tables
, PREG_GREP_INVERT
);
70 $this->tables
= preg_grep('/_log/', $this->tables
, PREG_GREP_INVERT
);
71 $this->tables
= preg_grep('/^civicrm_task_action_temp_/', $this->tables
, PREG_GREP_INVERT
);
72 $this->tables
= preg_grep('/^civicrm_export_temp_/', $this->tables
, PREG_GREP_INVERT
);
73 $this->tables
= preg_grep('/^civicrm_queue_/', $this->tables
, PREG_GREP_INVERT
);
75 // do not log civicrm_mailing_event* tables, CRM-12300
76 $this->tables
= preg_grep('/^civicrm_mailing_event_/', $this->tables
, PREG_GREP_INVERT
);
78 if (defined('CIVICRM_LOGGING_DSN')) {
79 $dsn = DB
::parseDSN(CIVICRM_LOGGING_DSN
);
80 $this->useDBPrefix
= (CIVICRM_LOGGING_DSN
!= CIVICRM_DSN
);
83 $dsn = DB
::parseDSN(CIVICRM_DSN
);
84 $this->useDBPrefix
= FALSE;
86 $this->db
= $dsn['database'];
88 $dao = CRM_Core_DAO
::executeQuery("
90 FROM INFORMATION_SCHEMA.TABLES
91 WHERE TABLE_SCHEMA = '{$this->db}'
92 AND TABLE_TYPE = 'BASE TABLE'
93 AND TABLE_NAME LIKE 'log_civicrm_%'
95 while ($dao->fetch()) {
96 $log = $dao->TABLE_NAME
;
97 $this->logs
[substr($log, 4)] = $log;
102 * Return logging custom data tables.
104 function customDataLogTables() {
105 return preg_grep('/^log_civicrm_value_/', $this->logs
);
109 * Disable logging by dropping the triggers (but keep the log tables intact).
111 function disableLogging() {
112 $config = CRM_Core_Config
::singleton();
113 $config->logging
= FALSE;
115 $this->dropTriggers();
117 // invoke the meta trigger creation call
118 CRM_Core_DAO
::triggerRebuild();
120 $this->deleteReports();
124 * Drop triggers for all logged tables.
126 function dropTriggers($tableName = NULL) {
127 $dao = new CRM_Core_DAO
;
130 $tableNames = array($tableName);
133 $tableNames = $this->tables
;
136 foreach ($tableNames as $table) {
138 $dao->executeQuery("DROP TRIGGER IF EXISTS {$table}_before_insert");
139 $dao->executeQuery("DROP TRIGGER IF EXISTS {$table}_before_update");
140 $dao->executeQuery("DROP TRIGGER IF EXISTS {$table}_before_delete");
143 $dao->executeQuery("DROP TRIGGER IF EXISTS {$table}_after_insert");
144 $dao->executeQuery("DROP TRIGGER IF EXISTS {$table}_after_update");
145 $dao->executeQuery("DROP TRIGGER IF EXISTS {$table}_after_delete");
150 * Enable sitewide logging.
154 function enableLogging() {
155 $this->fixSchemaDifferences(TRUE);
160 * Sync log tables and rebuild triggers.
162 * @param bool $enableLogging: Ensure logging is enabled
166 function fixSchemaDifferences($enableLogging = FALSE) {
167 $config = CRM_Core_Config
::singleton();
168 if ($enableLogging) {
169 $config->logging
= TRUE;
171 if ($config->logging
) {
172 foreach ($this->schemaDifferences() as $table => $cols) {
173 $this->fixSchemaDifferencesFor($table, $cols, FALSE);
176 // invoke the meta trigger creation call
177 CRM_Core_DAO
::triggerRebuild();
181 * Add missing (potentially specified) log table columns for the given table.
183 * @param $table string name of the relevant table
184 * @param $cols mixed array of columns to add or null (to check for the missing columns)
185 * @param $rebuildTrigger boolean should we rebuild the triggers
189 function fixSchemaDifferencesFor($table, $cols = NULL, $rebuildTrigger = TRUE) {
190 if (empty($this->logs
[$table])) {
191 $this->createLogTableFor($table);
195 if (is_null($cols)) {
196 $cols = array_diff($this->columnsOf($table), $this->columnsOf("log_$table"));
202 // use the relevant lines from CREATE TABLE to add colums to the log table
203 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE $table");
205 $create = explode("\n", $dao->Create_Table
);
206 foreach ($cols as $col) {
207 $line = preg_grep("/^ `$col` /", $create);
208 $line = substr(array_pop($line), 0, -1);
210 $line = self
::fixTimeStampAndNotNullSQL($line);
212 CRM_Core_DAO
::executeQuery("ALTER TABLE `{$this->db}`.log_$table ADD $line");
215 if ($rebuildTrigger) {
216 // invoke the meta trigger creation call
217 CRM_Core_DAO
::triggerRebuild($table);
221 function fixTimeStampAndNotNullSQL($query) {
222 $query = str_ireplace("TIMESTAMP NOT NULL", "TIMESTAMP NULL", $query);
223 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", '', $query);
224 $query = str_ireplace("DEFAULT CURRENT_TIMESTAMP", '', $query);
225 $query = str_ireplace("NOT NULL", '', $query);
230 * Find missing log table columns by comparing columns of the relevant tables.
231 * Returns table-name-keyed array of arrays of missing columns, e.g. array('civicrm_value_foo_1' => array('bar_1', 'baz_2'))
233 function schemaDifferences() {
235 foreach ($this->tables
as $table) {
236 $diffs[$table] = array_diff($this->columnsOf($table), $this->columnsOf("log_$table"));
238 return array_filter($diffs);
241 private function addReports() {
243 'logging/contact/detail' => ts('Logging Details'),
244 'logging/contact/summary' => ts('Contact Logging Report (Summary)'),
245 'logging/contribute/detail' => ts('Contribution Logging Report (Detail)'),
246 'logging/contribute/summary' => ts('Contribution Logging Report (Summary)'),
248 // enable logging templates
249 CRM_Core_DAO
::executeQuery("
250 UPDATE civicrm_option_value
252 WHERE value IN ('" . implode("', '", $this->reports
) . "')
255 // add report instances
256 $domain_id = CRM_Core_Config
::domainID();
257 foreach ($this->reports
as $report) {
258 $dao = new CRM_Report_DAO_Instance
;
259 $dao->domain_id
= $domain_id;
260 $dao->report_id
= $report;
261 $dao->title
= $titles[$report];
262 $dao->permission
= 'administer CiviCRM';
263 if ($report == 'logging/contact/summary')
264 $dao->is_reserved
= 1;
270 * Get an array of column names of the given table.
272 private function columnsOf($table) {
273 static $columnsOf = array();
275 $from = (substr($table, 0, 4) == 'log_') ?
"`{$this->db}`.$table" : $table;
277 if (!isset($columnsOf[$table])) {
278 CRM_Core_Error
::ignoreException();
279 $dao = CRM_Core_DAO
::executeQuery("SHOW COLUMNS FROM $from");
280 CRM_Core_Error
::setCallback();
281 if (is_a($dao, 'DB_Error')) {
284 $columnsOf[$table] = array();
285 while ($dao->fetch()) {
286 $columnsOf[$table][] = $dao->Field
;
290 return $columnsOf[$table];
294 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
296 private function createLogTableFor($table) {
297 $dao = CRM_Core_DAO
::executeQuery("SHOW CREATE TABLE $table");
299 $query = $dao->Create_Table
;
301 // rewrite the queries into CREATE TABLE queries for log tables:
303 log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
306 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
309 // - prepend the name with log_
310 // - drop AUTO_INCREMENT columns
311 // - drop non-column rows of the query (keys, constraints, etc.)
312 // - set the ENGINE to ARCHIVE
313 // - add log-specific columns (at the end of the table)
314 $query = preg_replace("/^CREATE TABLE `$table`/i", "CREATE TABLE `{$this->db}`.log_$table", $query);
315 $query = preg_replace("/ AUTO_INCREMENT/i", '', $query);
316 $query = preg_replace("/^ [^`].*$/m", '', $query);
317 $query = preg_replace("/^\) ENGINE=[^ ]+ /im", ') ENGINE=ARCHIVE ', $query);
319 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
320 // so there's no need for a default timestamp and therefore we remove such default timestamps
321 // also eliminate the NOT NULL constraint, since we always copy and schema can change down the road)
322 $query = self
::fixTimeStampAndNotNullSQL($query);
323 $query = preg_replace("/^\) /m", "$cols\n) ", $query);
325 CRM_Core_DAO
::executeQuery($query);
327 $columns = implode(', ', $this->columnsOf($table));
328 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}");
330 $this->tables
[] = $table;
331 $this->logs
[$table] = "log_$table";
334 private function deleteReports() {
335 // disable logging templates
336 CRM_Core_DAO
::executeQuery("
337 UPDATE civicrm_option_value
339 WHERE value IN ('" . implode("', '", $this->reports
) . "')
342 // delete report instances
343 $domain_id = CRM_Core_Config
::domainID();
344 foreach ($this->reports
as $report) {
345 $dao = new CRM_Report_DAO_Instance
;
346 $dao->domain_id
= $domain_id;
347 $dao->report_id
= $report;
353 * Predicate whether logging is enabled.
355 public function isEnabled() {
356 $config = CRM_Core_Config
::singleton();
358 if ($config->logging
) {
359 return $this->tablesExist() and $this->triggersExist();
365 * Predicate whether any log tables exist.
367 private function tablesExist() {
368 return !empty($this->logs
);
372 * Predicate whether the logging triggers are in place.
374 private function triggersExist() {
375 // FIXME: probably should be a bit more thorough…
376 // note that the LIKE parameter is TABLE NAME
377 return (bool) CRM_Core_DAO
::singleValueQuery("SHOW TRIGGERS LIKE 'civicrm_contact'");
380 function triggerInfo(&$info, $tableName = NULL) {
381 // check if we have logging enabled
382 $config =& CRM_Core_Config
::singleton();
383 if (!$config->logging
) {
387 $insert = array('INSERT');
388 $update = array('UPDATE');
389 $delete = array('DELETE');
392 $tableNames = array($tableName);
395 $tableNames = $this->tables
;
398 // logging is enabled, so now lets create the trigger info tables
399 foreach ($tableNames as $table) {
400 $columns = $this->columnsOf($table);
402 // only do the change if any data has changed
404 foreach ($columns as $column) {
405 // ignore modified_date changes
406 if ($column != 'modified_date') {
407 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
410 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
411 $updateSQL = "IF ( (" . implode( ' OR ', $cond ) . ") AND ( $suppressLoggingCond ) ) THEN ";
413 if ($this->useDBPrefix
) {
414 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
417 $sqlStmt = "INSERT INTO log_{tableName} (";
419 foreach ($columns as $column) {
420 $sqlStmt .= "$column, ";
422 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
424 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
425 $updateSQL .= $sqlStmt;
428 foreach ($columns as $column) {
429 $sqlStmt .= "NEW.$column, ";
430 $deleteSQL .= "OLD.$column, ";
432 $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
433 $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
435 $sqlStmt .= "END IF;";
436 $deleteSQL .= "END IF;";
438 $insertSQL .= $sqlStmt;
439 $updateSQL .= $sqlStmt;
442 'table' => array($table),
449 'table' => array($table),
456 'table' => array($table),
465 * This allow logging to be temporarily disabled for certain cases
466 * where we want to do a mass cleanup but dont want to bother with
472 static function disableLoggingForThisConnection( ) {
473 // do this only if logging is enabled
474 $config = CRM_Core_Config
::singleton( );
475 if ( $config->logging
) {
476 CRM_Core_DAO
::executeQuery( 'SET @civicrm_disable_logging = 1' );