| 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'), |
| 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 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 | } |
| 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 | $errorScope = 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 |
| 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 | } |
| 421 | } |
| 422 | return $columnSpecs[$table]; |
| 423 | } |
| 424 | |
| 425 | /** |
| 426 | * @param $civiTable |
| 427 | * @param $logTable |
| 428 | * |
| 429 | * @return array |
| 430 | */ |
| 431 | public function columnsWithDiffSpecs($civiTable, $logTable) { |
| 432 | $civiTableSpecs = $this->columnSpecsOf($civiTable); |
| 433 | $logTableSpecs = $this->columnSpecsOf($logTable); |
| 434 | |
| 435 | $diff = array('ADD' => array(), 'MODIFY' => array(), 'OBSOLETE' => array()); |
| 436 | |
| 437 | // columns to be added |
| 438 | $diff['ADD'] = array_diff(array_keys($civiTableSpecs), array_keys($logTableSpecs)); |
| 439 | |
| 440 | // columns to be modified |
| 441 | // NOTE: we consider only those columns for modifications where there is a spec change, and that the column definition |
| 442 | // wasn't deliberately modified by fixTimeStampAndNotNullSQL() method. |
| 443 | foreach ($civiTableSpecs as $col => $colSpecs) { |
| 444 | if (!isset($logTableSpecs[$col]) || !is_array($logTableSpecs[$col])) { |
| 445 | $logTableSpecs[$col] = array(); |
| 446 | } |
| 447 | |
| 448 | $specDiff = array_diff($civiTableSpecs[$col], $logTableSpecs[$col]); |
| 449 | if (!empty($specDiff) && $col != 'id' && !array_key_exists($col, $diff['ADD'])) { |
| 450 | // ignore 'id' column for any spec changes, to avoid any auto-increment mysql errors |
| 451 | if ($civiTableSpecs[$col]['DATA_TYPE'] != CRM_Utils_Array::value('DATA_TYPE', $logTableSpecs[$col])) { |
| 452 | // if data-type is different, surely consider the column |
| 453 | $diff['MODIFY'][] = $col; |
| 454 | } |
| 455 | elseif ($civiTableSpecs[$col]['IS_NULLABLE'] != CRM_Utils_Array::value('IS_NULLABLE', $logTableSpecs[$col]) && |
| 456 | $logTableSpecs[$col]['IS_NULLABLE'] == 'NO' |
| 457 | ) { |
| 458 | // if is-null property is different, and log table's column is NOT-NULL, surely consider the column |
| 459 | $diff['MODIFY'][] = $col; |
| 460 | } |
| 461 | elseif ($civiTableSpecs[$col]['COLUMN_DEFAULT'] != CRM_Utils_Array::value('COLUMN_DEFAULT', $logTableSpecs[$col]) && |
| 462 | !strstr($civiTableSpecs[$col]['COLUMN_DEFAULT'], 'TIMESTAMP') |
| 463 | ) { |
| 464 | // if default property is different, and its not about a timestamp column, consider it |
| 465 | $diff['MODIFY'][] = $col; |
| 466 | } |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | // columns to made obsolete by turning into not-null |
| 471 | $oldCols = array_diff(array_keys($logTableSpecs), array_keys($civiTableSpecs)); |
| 472 | foreach ($oldCols as $col) { |
| 473 | if (!in_array($col, array('log_date', 'log_conn_id', 'log_user_id', 'log_action')) && |
| 474 | $logTableSpecs[$col]['IS_NULLABLE'] == 'NO' |
| 475 | ) { |
| 476 | // if its a column present only in log table, not among those used by log tables for special purpose, and not-null |
| 477 | $diff['OBSOLETE'][] = $col; |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | return $diff; |
| 482 | } |
| 483 | |
| 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: |
| 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') |
| 498 | COLS; |
| 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) |
| 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); |
| 509 | |
| 510 | // log_civicrm_contact.modified_date for example would always be copied from civicrm_contact.modified_date, |
| 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); |
| 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) { |
| 536 | $dao = new CRM_Report_DAO_ReportInstance(); |
| 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 | |
| 571 | /** |
| 572 | * @param $info |
| 573 | * @param null $tableName |
| 574 | * @param bool $force |
| 575 | */ |
| 576 | public function triggerInfo(&$info, $tableName = NULL, $force = FALSE) { |
| 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) { |
| 596 | $columns = $this->columnsOf($table, $force); |
| 597 | |
| 598 | // only do the change if any data has changed |
| 599 | $cond = array(); |
| 600 | foreach ($columns as $column) { |
| 601 | // ignore modified_date changes |
| 602 | if ($column != 'modified_date' && !in_array($column, CRM_Utils_Array::value($table, $this->exceptions, array()))) { |
| 603 | $cond[] = "IFNULL(OLD.$column,'') <> IFNULL(NEW.$column,'')"; |
| 604 | } |
| 605 | } |
| 606 | $suppressLoggingCond = "@civicrm_disable_logging IS NULL OR @civicrm_disable_logging = 0"; |
| 607 | $updateSQL = "IF ( (" . implode(' OR ', $cond) . ") AND ( $suppressLoggingCond ) ) THEN "; |
| 608 | |
| 609 | if ($this->useDBPrefix) { |
| 610 | $sqlStmt = "INSERT INTO `{$this->db}`.log_{tableName} ("; |
| 611 | } |
| 612 | else { |
| 613 | $sqlStmt = "INSERT INTO log_{tableName} ("; |
| 614 | } |
| 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) { |
| 625 | $sqlStmt .= "NEW.$column, "; |
| 626 | $deleteSQL .= "OLD.$column, "; |
| 627 | } |
| 628 | $sqlStmt .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');"; |
| 629 | $deleteSQL .= "CONNECTION_ID(), @civicrm_user_id, '{eventName}');"; |
| 630 | |
| 631 | $sqlStmt .= "END IF;"; |
| 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 | * |
| 665 | */ |
| 666 | public static function disableLoggingForThisConnection() { |
| 667 | // do this only if logging is enabled |
| 668 | $config = CRM_Core_Config::singleton(); |
| 669 | if ($config->logging) { |
| 670 | CRM_Core_DAO::executeQuery('SET @civicrm_disable_logging = 1'); |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | } |