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