CRM-12877, fixed save-a-copy bug
[civicrm-core.git] / CRM / Logging / Schema.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
49 /**
50 * Populate $this->tables and $this->logs with current db state.
51 */
52 function __construct() {
53 $dao = new CRM_Contact_DAO_Contact();
54 $civiDBName = $dao->_database;
55
56 $dao = CRM_Core_DAO::executeQuery("
57SELECT TABLE_NAME
58FROM INFORMATION_SCHEMA.TABLES
59WHERE TABLE_SCHEMA = '{$civiDBName}'
60AND TABLE_TYPE = 'BASE TABLE'
61AND TABLE_NAME LIKE 'civicrm_%'
62");
63 while ($dao->fetch()) {
64 $this->tables[] = $dao->TABLE_NAME;
65 }
66
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);
74
f9b793b0
DL
75 // do not log civicrm_mailing_event* tables, CRM-12300
76 $this->tables = preg_grep('/^civicrm_mailing_event_/', $this->tables, PREG_GREP_INVERT);
77
340f6aa0
DL
78 if (defined('CIVICRM_LOGGING_DSN')) {
79 $dsn = DB::parseDSN(CIVICRM_LOGGING_DSN);
80 $this->useDBPrefix = (CIVICRM_LOGGING_DSN != CIVICRM_DSN);
81 }
82 else {
83 $dsn = DB::parseDSN(CIVICRM_DSN);
84 $this->useDBPrefix = FALSE;
85 }
6a488035
TO
86 $this->db = $dsn['database'];
87
88 $dao = CRM_Core_DAO::executeQuery("
89SELECT TABLE_NAME
90FROM INFORMATION_SCHEMA.TABLES
91WHERE TABLE_SCHEMA = '{$this->db}'
92AND TABLE_TYPE = 'BASE TABLE'
93AND TABLE_NAME LIKE 'log_civicrm_%'
94");
95 while ($dao->fetch()) {
96 $log = $dao->TABLE_NAME;
97 $this->logs[substr($log, 4)] = $log;
98 }
99 }
100
101 /**
102 * Return logging custom data tables.
103 */
104 function customDataLogTables() {
105 return preg_grep('/^log_civicrm_value_/', $this->logs);
106 }
107
108 /**
109 * Disable logging by dropping the triggers (but keep the log tables intact).
110 */
111 function disableLogging() {
112 $config = CRM_Core_Config::singleton();
113 $config->logging = FALSE;
114
115 $this->dropTriggers();
116
117 // invoke the meta trigger creation call
118 CRM_Core_DAO::triggerRebuild();
119
120 $this->deleteReports();
121 }
122
123 /**
124 * Drop triggers for all logged tables.
125 */
126 function dropTriggers($tableName = NULL) {
127 $dao = new CRM_Core_DAO;
128
129 if ($tableName) {
130 $tableNames = array($tableName);
131 }
132 else {
133 $tableNames = $this->tables;
134 }
135
136 foreach ($tableNames as $table) {
137 // before triggers
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");
141
142 // after triggers
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");
146 }
147 }
148
149 /**
150 * Enable sitewide logging.
151 *
152 * @return void
153 */
154 function enableLogging() {
155 $this->fixSchemaDifferences(TRUE);
156 $this->addReports();
157 }
158
159 /**
160 * Sync log tables and rebuild triggers.
161 *
162 * @param bool $enableLogging: Ensure logging is enabled
163 *
164 * @return void
165 */
166 function fixSchemaDifferences($enableLogging = FALSE) {
167 $config = CRM_Core_Config::singleton();
168 if ($enableLogging) {
169 $config->logging = TRUE;
170 }
171 if ($config->logging) {
172 foreach ($this->schemaDifferences() as $table => $cols) {
173 $this->fixSchemaDifferencesFor($table, $cols, FALSE);
174 }
175 }
176 // invoke the meta trigger creation call
177 CRM_Core_DAO::triggerRebuild();
178 }
179
180 /**
181 * Add missing (potentially specified) log table columns for the given table.
182 *
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
186 *
187 * @return void
188 */
189 function fixSchemaDifferencesFor($table, $cols = NULL, $rebuildTrigger = TRUE) {
190 if (empty($this->logs[$table])) {
191 $this->createLogTableFor($table);
192 return;
193 }
194
195 if (is_null($cols)) {
196 $cols = array_diff($this->columnsOf($table), $this->columnsOf("log_$table"));
197 }
198 if (empty($cols)) {
199 return;
200 }
201
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");
204 $dao->fetch();
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);
209 // CRM-11179
c28241be 210 $line = self::fixTimeStampAndNotNullSQL($line);
6a488035
TO
211
212 CRM_Core_DAO::executeQuery("ALTER TABLE `{$this->db}`.log_$table ADD $line");
213 }
214
215 if ($rebuildTrigger) {
216 // invoke the meta trigger creation call
217 CRM_Core_DAO::triggerRebuild($table);
218 }
219 }
220
c28241be 221 function fixTimeStampAndNotNullSQL($query) {
6a488035
TO
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);
c28241be 225 $query = str_ireplace("NOT NULL", '', $query);
6a488035
TO
226 return $query;
227 }
228
229 /**
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'))
232 */
233 function schemaDifferences() {
234 $diffs = array();
235 foreach ($this->tables as $table) {
236 $diffs[$table] = array_diff($this->columnsOf($table), $this->columnsOf("log_$table"));
237 }
238 return array_filter($diffs);
239 }
240
241 private function addReports() {
242 $titles = array(
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)'),
247 );
248 // enable logging templates
249 CRM_Core_DAO::executeQuery("
250 UPDATE civicrm_option_value
251 SET is_active = 1
252 WHERE value IN ('" . implode("', '", $this->reports) . "')
253 ");
254
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;
265 $dao->insert();
266 }
267 }
268
269 /**
270 * Get an array of column names of the given table.
271 */
272 private function columnsOf($table) {
273 static $columnsOf = array();
274
275 $from = (substr($table, 0, 4) == 'log_') ? "`{$this->db}`.$table" : $table;
276
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')) {
282 return array();
283 }
284 $columnsOf[$table] = array();
285 while ($dao->fetch()) {
286 $columnsOf[$table][] = $dao->Field;
287 }
288 }
289
290 return $columnsOf[$table];
291 }
292
293 /**
294 * Create a log table with schema mirroring the given table’s structure and seeding it with the given table’s contents.
295 */
296 private function createLogTableFor($table) {
297 $dao = CRM_Core_DAO::executeQuery("SHOW CREATE TABLE $table");
298 $dao->fetch();
299 $query = $dao->Create_Table;
300
301 // rewrite the queries into CREATE TABLE queries for log tables:
6a488035
TO
302 $cols = <<<COLS
303 log_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
304 log_conn_id INTEGER,
305 log_user_id INTEGER,
306 log_action ENUM('Initialization', 'Insert', 'Update', 'Delete')
307COLS;
c28241be
DL
308
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)
6a488035
TO
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);
c28241be 318
6a488035 319 // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date,
c28241be
DL
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);
6a488035
TO
323 $query = preg_replace("/^\) /m", "$cols\n) ", $query);
324
325 CRM_Core_DAO::executeQuery($query);
326
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}");
329
330 $this->tables[] = $table;
331 $this->logs[$table] = "log_$table";
332 }
333
334 private function deleteReports() {
335 // disable logging templates
336 CRM_Core_DAO::executeQuery("
337 UPDATE civicrm_option_value
338 SET is_active = 0
339 WHERE value IN ('" . implode("', '", $this->reports) . "')
340 ");
341
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;
348 $dao->delete();
349 }
350 }
351
352 /**
353 * Predicate whether logging is enabled.
354 */
355 public function isEnabled() {
356 $config = CRM_Core_Config::singleton();
357
358 if ($config->logging) {
359 return $this->tablesExist() and $this->triggersExist();
360 }
361 return FALSE;
362 }
363
364 /**
365 * Predicate whether any log tables exist.
366 */
367 private function tablesExist() {
368 return !empty($this->logs);
369 }
370
371 /**
372 * Predicate whether the logging triggers are in place.
373 */
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'");
378 }
379
380 function triggerInfo(&$info, $tableName = NULL) {
381 // check if we have logging enabled
382 $config =& CRM_Core_Config::singleton();
383 if (!$config->logging) {
384 return;
385 }
386
387 $insert = array('INSERT');
388 $update = array('UPDATE');
389 $delete = array('DELETE');
390
391 if ($tableName) {
392 $tableNames = array($tableName);
393 }
394 else {
395 $tableNames = $this->tables;
396 }
397
398 // logging is enabled, so now lets create the trigger info tables
399 foreach ($tableNames as $table) {
400 $columns = $this->columnsOf($table);
401
402 // only do the change if any data has changed
403 $cond = array( );
404 foreach ($columns as $column) {
405 // ignore modified_date changes
406 if ($column != 'modified_date') {
407 $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')";
408 }
409 }
410 $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0";
411 $updateSQL = "IF ( (" . implode( ' OR ', $cond ) . ") AND ( $suppressLoggingCond ) ) THEN ";
412
340f6aa0
DL
413 if ($this->useDBPrefix) {
414 $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} (";
415 }
416 else {
417 $sqlStmt = "INSERT INTO log_{tableName} (";
418 }
6a488035
TO
419 foreach ($columns as $column) {
420 $sqlStmt .= "$column, ";
421 }
422 $sqlStmt .= "log_conn_id, log_user_id, log_action) VALUES (";
423
424 $insertSQL = $deleteSQL = "IF ( $suppressLoggingCond ) THEN $sqlStmt ";
425 $updateSQL .= $sqlStmt;
426
427 $sqlStmt = '';
428 foreach ($columns as $column) {
429 $sqlStmt .= "NEW.$column, ";
430 $deleteSQL .= "OLD.$column, ";
431 }
432 $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
433 $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');";
434
435 $sqlStmt .= "END IF;";
436 $deleteSQL .= "END IF;";
437
438 $insertSQL .= $sqlStmt;
439 $updateSQL .= $sqlStmt;
440
441 $info[] = array(
442 'table' => array($table),
443 'when' => 'AFTER',
444 'event' => $insert,
445 'sql' => $insertSQL,
446 );
447
448 $info[] = array(
449 'table' => array($table),
450 'when' => 'AFTER',
451 'event' => $update,
452 'sql' => $updateSQL,
453 );
454
455 $info[] = array(
456 'table' => array($table),
457 'when' => 'AFTER',
458 'event' => $delete,
459 'sql' => $deleteSQL,
460 );
461 }
462 }
463
464 /**
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
467 * an audit trail
468 *
469 * @static
470 * @public
471 */
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' );
477 }
478 }
479
480}
481