Merge pull request #12683 from civicrm/5.5
[civicrm-core.git] / CRM / Logging / Differ.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
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
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Logging_Differ {
36 private $db;
37 private $log_conn_id;
38 private $log_date;
39 private $interval;
40
e0ef6999 41 /**
3b45d110 42 * Class constructor.
43 *
44 * @param string $log_conn_id
bef3accd 45 * @param string $log_date
e0ef6999
EM
46 * @param string $interval
47 */
00be9182 48 public function __construct($log_conn_id, $log_date, $interval = '10 SECOND') {
353ffa53
TO
49 $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
50 $this->db = $dsn['database'];
6a488035 51 $this->log_conn_id = $log_conn_id;
353ffa53 52 $this->log_date = $log_date;
d32d065d 53 $this->interval = self::filterInterval($interval);
6a488035
TO
54 }
55
e0ef6999
EM
56 /**
57 * @param $tables
58 *
59 * @return array
60 */
00be9182 61 public function diffsInTables($tables) {
6a488035
TO
62 $diffs = array();
63 foreach ($tables as $table) {
64 $diff = $this->diffsInTable($table);
65 if (!empty($diff)) {
66 $diffs[$table] = $diff;
67 }
68 }
69 return $diffs;
70 }
71
e0ef6999
EM
72 /**
73 * @param $table
100fef9d 74 * @param int $contactID
e0ef6999
EM
75 *
76 * @return array
77 */
e60f24eb 78 public function diffsInTable($table, $contactID = NULL) {
6a488035
TO
79 $diffs = array();
80
81 $params = array(
3b45d110 82 1 => array($this->log_conn_id, 'String'),
6a488035
TO
83 );
84
87a890cc 85 $logging = new CRM_Logging_Schema();
694e78fd
DS
86 $addressCustomTables = $logging->entityCustomDataLogTables('Address');
87
0b4c85c3 88 $contactIdClause = $join = '';
481a74f4 89 if ($contactID) {
6a488035
TO
90 $params[3] = array($contactID, 'Integer');
91 switch ($table) {
353ffa53
TO
92 case 'civicrm_contact':
93 $contactIdClause = "AND id = %3";
94 break;
ea100cb5 95
353ffa53
TO
96 case 'civicrm_note':
97 $contactIdClause = "AND (( entity_id = %3 AND entity_table = 'civicrm_contact' ) OR (entity_id IN (SELECT note.id FROM `{$this->db}`.log_civicrm_note note WHERE note.entity_id = %3 AND note.entity_table = 'civicrm_contact') AND entity_table = 'civicrm_note'))";
98 break;
ea100cb5 99
353ffa53
TO
100 case 'civicrm_entity_tag':
101 $contactIdClause = "AND entity_id = %3 AND entity_table = 'civicrm_contact'";
102 break;
ea100cb5 103
353ffa53
TO
104 case 'civicrm_relationship':
105 $contactIdClause = "AND (contact_id_a = %3 OR contact_id_b = %3)";
106 break;
ea100cb5 107
353ffa53 108 case 'civicrm_activity':
44f817d4 109 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
353ffa53
TO
110 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
111 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
112 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
9e74e3ce 113
353ffa53 114 $join = "
9e74e3ce 115LEFT JOIN civicrm_activity_contact at ON at.activity_id = lt.id AND at.contact_id = %3 AND at.record_type_id = {$targetID}
116LEFT JOIN civicrm_activity_contact aa ON aa.activity_id = lt.id AND aa.contact_id = %3 AND aa.record_type_id = {$assigneeID}
117LEFT JOIN civicrm_activity_contact source ON source.activity_id = lt.id AND source.contact_id = %3 AND source.record_type_id = {$sourceID} ";
353ffa53
TO
118 $contactIdClause = "AND (at.id IS NOT NULL OR aa.id IS NOT NULL OR source.id IS NOT NULL)";
119 break;
ea100cb5 120
353ffa53
TO
121 case 'civicrm_case':
122 $contactIdClause = "AND id = (select case_id FROM civicrm_case_contact WHERE contact_id = %3 LIMIT 1)";
694e78fd 123 break;
694e78fd 124
353ffa53
TO
125 default:
126 if (array_key_exists($table, $addressCustomTables)) {
127 $join = "INNER JOIN `{$this->db}`.`log_civicrm_address` et ON et.id = lt.entity_id";
128 $contactIdClause = "AND contact_id = %3";
129 break;
130 }
6b4b11c4 131
353ffa53
TO
132 // allow tables to be extended by report hook query objects
133 list($contactIdClause, $join) = CRM_Report_BAO_Hook::singleton()->logDiffClause($this, $table);
134
135 if (empty($contactIdClause)) {
136 $contactIdClause = "AND contact_id = %3";
137 }
138 if (strpos($table, 'civicrm_value') !== FALSE) {
139 $contactIdClause = "AND entity_id = %3";
140 }
6a488035
TO
141 }
142 }
143
99008b08 144 $logDateClause = '';
145 if ($this->log_date) {
146 $params[2] = array($this->log_date, 'String');
147 $logDateClause = "
148 AND lt.log_date BETWEEN DATE_SUB(%2, INTERVAL {$this->interval}) AND DATE_ADD(%2, INTERVAL {$this->interval})
149 ";
150 }
151
6a488035 152 // find ids in this table that were affected in the given connection (based on connection id and a ±10 s time period around the date)
0b4c85c3 153 $sql = "
8ef12e64 154SELECT DISTINCT lt.id FROM `{$this->db}`.`log_$table` lt
155{$join}
99008b08 156WHERE lt.log_conn_id = %1
157 $logDateClause
158 {$contactIdClause}";
6a488035
TO
159 $dao = CRM_Core_DAO::executeQuery($sql, $params);
160 while ($dao->fetch()) {
161 $diffs = array_merge($diffs, $this->diffsInTableForId($table, $dao->id));
162 }
163
164 return $diffs;
165 }
166
e0ef6999
EM
167 /**
168 * @param $table
100fef9d 169 * @param int $id
e0ef6999
EM
170 *
171 * @return array
aa00132e 172 * @throws \CRM_Core_Exception
e0ef6999 173 */
6a488035
TO
174 private function diffsInTableForId($table, $id) {
175 $diffs = array();
176
177 $params = array(
3b45d110 178 1 => array($this->log_conn_id, 'String'),
6a488035
TO
179 3 => array($id, 'Integer'),
180 );
181
b44e3f84 182 // look for all the changes in the given connection that happened less than {$this->interval} s later than log_date to the given id to catch multi-query changes
99008b08 183 $logDateClause = "";
184 if ($this->log_date && $this->interval) {
185 $logDateClause = " AND log_date >= %2 AND log_date < DATE_ADD(%2, INTERVAL {$this->interval})";
186 $params[2] = array($this->log_date, 'String');
187 }
188
189 $changedSQL = "SELECT * FROM `{$this->db}`.`log_$table` WHERE log_conn_id = %1 $logDateClause AND id = %3 ORDER BY log_date DESC LIMIT 1";
6a488035
TO
190
191 $changedDAO = CRM_Core_DAO::executeQuery($changedSQL, $params);
481a74f4 192 while ($changedDAO->fetch()) {
9bf49a0e 193 if (empty($this->log_date) && !self::checkLogCanBeUsedWithNoLogDate($changedDAO->log_date)) {
99008b08 194 throw new CRM_Core_Exception('The connection date must be passed in to disambiguate this logging entry per CRM-18193');
195 }
6a488035
TO
196 $changed = $changedDAO->toArray();
197
198 // return early if nothing found
199 if (empty($changed)) {
200 continue;
201 }
202
203 switch ($changed['log_action']) {
204 case 'Delete':
205 // the previous state is kept in the current state, current should keep the keys and clear the values
206 $original = $changed;
353ffa53
TO
207 foreach ($changed as & $val) {
208 $val = NULL;
209 }
6a488035
TO
210 $changed['log_action'] = 'Delete';
211 break;
212
213 case 'Insert':
214 // the previous state does not exist
215 $original = array();
216 break;
217
218 case 'Update':
99008b08 219 $params[2] = array($changedDAO->log_date, 'String');
6a488035
TO
220 // look for the previous state (different log_conn_id) of the given id
221 $originalSQL = "SELECT * FROM `{$this->db}`.`log_$table` WHERE log_conn_id != %1 AND log_date < %2 AND id = %3 ORDER BY log_date DESC LIMIT 1";
222 $original = $this->sqlToArray($originalSQL, $params);
223 if (empty($original)) {
8ef12e64 224 // A blank original array is not possible for Update action, otherwise we 'll end up displaying all information
6a488035
TO
225 // in $changed variable as updated-info
226 $original = $changed;
227 }
228
229 break;
230 }
231
232 // populate $diffs with only the differences between $changed and $original
233 $skipped = array('log_action', 'log_conn_id', 'log_date', 'log_user_id');
234 foreach (array_keys(array_diff_assoc($changed, $original)) as $diff) {
235 if (in_array($diff, $skipped)) {
236 continue;
237 }
238
239 if (CRM_Utils_Array::value($diff, $original) === CRM_Utils_Array::value($diff, $changed)) {
240 continue;
241 }
8ef12e64 242
243 // hack: case_type_id column is a varchar with separator. For proper mapping to type labels,
6a488035
TO
244 // we need to make sure separators are trimmed
245 if ($diff == 'case_type_id') {
33421d01 246 foreach (array('original', 'changed') as $var) {
6ef04c72 247 if (!empty(${$var[$diff]})) {
6a488035
TO
248 $holder =& $$var;
249 $val = explode(CRM_Case_BAO_Case::VALUE_SEPARATOR, $holder[$diff]);
250 $holder[$diff] = CRM_Utils_Array::value(1, $val);
251 }
252 }
253 }
254
255 $diffs[] = array(
256 'action' => $changed['log_action'],
257 'id' => $id,
258 'field' => $diff,
259 'from' => CRM_Utils_Array::value($diff, $original),
260 'to' => CRM_Utils_Array::value($diff, $changed),
29444295 261 'table' => $table,
262 'log_date' => $changed['log_date'],
263 'log_conn_id' => $changed['log_conn_id'],
6a488035
TO
264 );
265 }
266 }
267
268 return $diffs;
269 }
270
e0ef6999 271 /**
10b32ed4 272 * Get the titles & metadata option values for the table.
273 *
274 * For custom fields the titles may change so we use the ones as at the reference date.
275 *
276 * @param string $table
277 * @param string $referenceDate
e0ef6999
EM
278 *
279 * @return array
280 */
10b32ed4 281 public function titlesAndValuesForTable($table, $referenceDate) {
6a488035
TO
282 // static caches for subsequent calls with the same $table
283 static $titles = array();
284 static $values = array();
285
6a488035 286 if (!isset($titles[$table]) or !isset($values[$table])) {
8485f8e7 287 if (($tableDAO = CRM_Core_DAO_AllCoreTables::getClassForTable($table)) != FALSE) {
6a488035
TO
288 // FIXME: these should be populated with pseudo constants as they
289 // were at the time of logging rather than their current values
c0c9cd82 290 // FIXME: Use *_BAO:buildOptions() method rather than pseudoconstants & fetch programmatically
6a488035
TO
291 $values[$table] = array(
292 'contribution_page_id' => CRM_Contribute_PseudoConstant::contributionPage(),
293 'contribution_status_id' => CRM_Contribute_PseudoConstant::contributionStatus(),
353ffa53 294 'financial_type_id' => CRM_Contribute_PseudoConstant::financialType(),
6a488035 295 'country_id' => CRM_Core_PseudoConstant::country(),
26cf88b5 296 'gender_id' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
b2b0530a 297 'location_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'),
6a488035 298 'payment_instrument_id' => CRM_Contribute_PseudoConstant::paymentInstrument(),
b4f964d9 299 'phone_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
c0c9cd82
CW
300 'preferred_communication_method' => CRM_Contact_BAO_Contact::buildOptions('preferred_communication_method'),
301 'preferred_language' => CRM_Contact_BAO_Contact::buildOptions('preferred_language'),
302 'prefix_id' => CRM_Contact_BAO_Contact::buildOptions('prefix_id'),
e7e657f0 303 'provider_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
6a488035 304 'state_province_id' => CRM_Core_PseudoConstant::stateProvince(),
c0c9cd82 305 'suffix_id' => CRM_Contact_BAO_Contact::buildOptions('suffix_id'),
cbf48754 306 'website_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'),
6a488035 307 'activity_type_id' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE),
42047ce4 308 'case_type_id' => CRM_Case_PseudoConstant::caseType('title', FALSE),
353ffa53 309 'priority_id' => CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'),
6a488035
TO
310 );
311
312 // for columns that appear in more than 1 table
313 switch ($table) {
314 case 'civicrm_case':
315 $values[$table]['status_id'] = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
316 break;
ea100cb5 317
6a488035 318 case 'civicrm_activity':
481a74f4 319 $values[$table]['status_id'] = CRM_Core_PseudoConstant::activityStatus();
6a488035
TO
320 break;
321 }
322
8485f8e7 323 $dao = new $tableDAO();
6a488035
TO
324 foreach ($dao->fields() as $field) {
325 $titles[$table][$field['name']] = CRM_Utils_Array::value('title', $field);
326
327 if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
328 $values[$table][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
329 }
330 }
331 }
332 elseif (substr($table, 0, 14) == 'civicrm_value_') {
10b32ed4 333 list($titles[$table], $values[$table]) = $this->titlesAndValuesForCustomDataTable($table, $referenceDate);
0db6c3e1
TO
334 }
335 else {
6b4b11c4 336 $titles[$table] = $values[$table] = array();
6a488035
TO
337 }
338 }
339
340 return array($titles[$table], $values[$table]);
341 }
342
e0ef6999
EM
343 /**
344 * @param $sql
c490a46a 345 * @param array $params
e0ef6999
EM
346 *
347 * @return mixed
348 */
6a488035
TO
349 private function sqlToArray($sql, $params) {
350 $dao = CRM_Core_DAO::executeQuery($sql, $params);
351 $dao->fetch();
352 return $dao->toArray();
353 }
354
e0ef6999 355 /**
10b32ed4 356 * Get the field titles & option group values for the custom table as at the reference date.
357 *
358 * @param string $table
359 * @param string $referenceDate
e0ef6999
EM
360 *
361 * @return array
362 */
10b32ed4 363 private function titlesAndValuesForCustomDataTable($table, $referenceDate) {
6a488035
TO
364 $titles = array();
365 $values = array();
366
367 $params = array(
3b45d110 368 1 => array($this->log_conn_id, 'String'),
10b32ed4 369 2 => array($referenceDate, 'String'),
6a488035
TO
370 3 => array($table, 'String'),
371 );
372
373 $sql = "SELECT id, title FROM `{$this->db}`.log_civicrm_custom_group WHERE log_date <= %2 AND table_name = %3 ORDER BY log_date DESC LIMIT 1";
374 $cgDao = CRM_Core_DAO::executeQuery($sql, $params);
375 $cgDao->fetch();
376
377 $params[3] = array($cgDao->id, 'Integer');
378 $sql = "
379SELECT column_name, data_type, label, name, option_group_id
380FROM `{$this->db}`.log_civicrm_custom_field
381WHERE log_date <= %2
382AND custom_group_id = %3
383ORDER BY log_date
384";
385 $cfDao = CRM_Core_DAO::executeQuery($sql, $params);
386
387 while ($cfDao->fetch()) {
388 $titles[$cfDao->column_name] = "{$cgDao->title}: {$cfDao->label}";
389
390 switch ($cfDao->data_type) {
391 case 'Boolean':
392 $values[$cfDao->column_name] = array('0' => ts('false'), '1' => ts('true'));
393 break;
394
395 case 'String':
396 $values[$cfDao->column_name] = array();
397 if (!empty($cfDao->option_group_id)) {
398 $params[3] = array($cfDao->option_group_id, 'Integer');
399 $sql = "
400SELECT label, value
401FROM `{$this->db}`.log_civicrm_option_value
402WHERE log_date <= %2
403AND option_group_id = %3
404ORDER BY log_date
405";
406 $ovDao = CRM_Core_DAO::executeQuery($sql, $params);
407 while ($ovDao->fetch()) {
408 $values[$cfDao->column_name][$ovDao->value] = $ovDao->label;
409 }
410 }
411 break;
412 }
413 }
414
415 return array($titles, $values);
416 }
96025800 417
93afbc3a 418 /**
419 * Get all changes made in the connection.
420 *
421 * @param array $tables
422 * Array of tables to inspect.
423 *
424 * @return array
425 */
426 public function getAllChangesForConnection($tables) {
427 $params = array(1 => array($this->log_conn_id, 'String'));
428 foreach ($tables as $table) {
429 if (empty($sql)) {
430 $sql = " SELECT '{$table}' as table_name, id FROM {$this->db}.log_{$table} WHERE log_conn_id = %1";
431 }
432 else {
433 $sql .= " UNION SELECT '{$table}' as table_name, id FROM {$this->db}.log_{$table} WHERE log_conn_id = %1";
434 }
435 }
436 $diffs = array();
437 $dao = CRM_Core_DAO::executeQuery($sql, $params);
438 while ($dao->fetch()) {
439 if (empty($this->log_date)) {
440 $this->log_date = CRM_Core_DAO::singleValueQuery("SELECT log_date FROM {$this->db}.log_{$table} WHERE log_conn_id = %1 LIMIT 1", $params);
441 }
442 $diffs = array_merge($diffs, $this->diffsInTableForId($dao->table_name, $dao->id));
443 }
444 return $diffs;
445 }
446
99008b08 447 /**
448 * Check that the log record relates to a unique log id.
449 *
450 * If the record was recorded using the old non-unique style then the
451 * log_date
452 * MUST be set to get the (fairly accurate) list of changes. In this case the
453 * nasty 10 second interval rule is applied.
454 *
455 * See CRM-18193 for a discussion of unique log id.
456 *
457 * @param string $change_date
458 *
459 * @return bool
460 * @throws \CiviCRM_API3_Exception
461 */
9bf49a0e 462 public static function checkLogCanBeUsedWithNoLogDate($change_date) {
463
99008b08 464 if (civicrm_api3('Setting', 'getvalue', array('name' => 'logging_all_tables_uniquid', 'group' => 'CiviCRM Preferences'))) {
465 return TRUE;
466 };
467 $uniqueDate = civicrm_api3('Setting', 'getvalue', array(
468 'name' => 'logging_uniqueid_date',
469 'group' => 'CiviCRM Preferences',
470 ));
471 if (strtotime($uniqueDate) <= strtotime($change_date)) {
472 return TRUE;
473 }
474 else {
475 return FALSE;
476 }
477
478 }
479
d32d065d
TO
480 /**
481 * Filter a MySQL interval expression.
482 *
483 * @param string $interval
484 * @return string
485 * Normalized version of $interval
486 * @throws \CRM_Core_Exception
487 * If the expression is invalid.
488 * @see https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
489 */
490 private static function filterInterval($interval) {
491 if (empty($interval)) {
492 return $interval;
493 }
494
495 $units = array('MICROSECOND', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'WEEK', 'MONTH', 'QUARTER', 'YEAR');
496 $interval = strtoupper($interval);
497 if (preg_match('/^([0-9]+) ([A-Z]+)$/', $interval, $matches)) {
498 if (in_array($matches[2], $units)) {
499 return $interval;
500 }
501 }
502 if (preg_match('/^\'([0-9: \.\-]+)\' ([A-Z]+)_([A-Z]+)$/', $interval, $matches)) {
503 if (in_array($matches[2], $units) && in_array($matches[3], $units)) {
504 return $interval;
505 }
506 }
507 throw new CRM_Core_Exception("Malformed interval");
508 }
509
6a488035 510}