CRM-18376 - Manage Group screen shows no groups
[civicrm-core.git] / CRM / Logging / Differ.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
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 /**
100fef9d 42 * @param int $log_conn_id
e0ef6999
EM
43 * @param $log_date
44 * @param string $interval
45 */
00be9182 46 public function __construct($log_conn_id, $log_date, $interval = '10 SECOND') {
353ffa53
TO
47 $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
48 $this->db = $dsn['database'];
6a488035 49 $this->log_conn_id = $log_conn_id;
353ffa53
TO
50 $this->log_date = $log_date;
51 $this->interval = $interval;
6a488035
TO
52 }
53
e0ef6999
EM
54 /**
55 * @param $tables
56 *
57 * @return array
58 */
00be9182 59 public function diffsInTables($tables) {
6a488035
TO
60 $diffs = array();
61 foreach ($tables as $table) {
62 $diff = $this->diffsInTable($table);
63 if (!empty($diff)) {
64 $diffs[$table] = $diff;
65 }
66 }
67 return $diffs;
68 }
69
e0ef6999
EM
70 /**
71 * @param $table
100fef9d 72 * @param int $contactID
e0ef6999
EM
73 *
74 * @return array
75 */
e60f24eb 76 public function diffsInTable($table, $contactID = NULL) {
6a488035
TO
77 $diffs = array();
78
79 $params = array(
80 1 => array($this->log_conn_id, 'Integer'),
81 2 => array($this->log_date, 'String'),
82 );
83
87a890cc 84 $logging = new CRM_Logging_Schema();
694e78fd
DS
85 $addressCustomTables = $logging->entityCustomDataLogTables('Address');
86
0b4c85c3 87 $contactIdClause = $join = '';
481a74f4 88 if ($contactID) {
6a488035
TO
89 $params[3] = array($contactID, 'Integer');
90 switch ($table) {
353ffa53
TO
91 case 'civicrm_contact':
92 $contactIdClause = "AND id = %3";
93 break;
ea100cb5 94
353ffa53
TO
95 case 'civicrm_note':
96 $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'))";
97 break;
ea100cb5 98
353ffa53
TO
99 case 'civicrm_entity_tag':
100 $contactIdClause = "AND entity_id = %3 AND entity_table = 'civicrm_contact'";
101 break;
ea100cb5 102
353ffa53
TO
103 case 'civicrm_relationship':
104 $contactIdClause = "AND (contact_id_a = %3 OR contact_id_b = %3)";
105 break;
ea100cb5 106
353ffa53
TO
107 case 'civicrm_activity':
108 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
109 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
110 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
111 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
9e74e3ce 112
353ffa53 113 $join = "
9e74e3ce 114LEFT JOIN civicrm_activity_contact at ON at.activity_id = lt.id AND at.contact_id = %3 AND at.record_type_id = {$targetID}
115LEFT JOIN civicrm_activity_contact aa ON aa.activity_id = lt.id AND aa.contact_id = %3 AND aa.record_type_id = {$assigneeID}
116LEFT JOIN civicrm_activity_contact source ON source.activity_id = lt.id AND source.contact_id = %3 AND source.record_type_id = {$sourceID} ";
353ffa53
TO
117 $contactIdClause = "AND (at.id IS NOT NULL OR aa.id IS NOT NULL OR source.id IS NOT NULL)";
118 break;
ea100cb5 119
353ffa53
TO
120 case 'civicrm_case':
121 $contactIdClause = "AND id = (select case_id FROM civicrm_case_contact WHERE contact_id = %3 LIMIT 1)";
694e78fd 122 break;
694e78fd 123
353ffa53
TO
124 default:
125 if (array_key_exists($table, $addressCustomTables)) {
126 $join = "INNER JOIN `{$this->db}`.`log_civicrm_address` et ON et.id = lt.entity_id";
127 $contactIdClause = "AND contact_id = %3";
128 break;
129 }
6b4b11c4 130
353ffa53
TO
131 // allow tables to be extended by report hook query objects
132 list($contactIdClause, $join) = CRM_Report_BAO_Hook::singleton()->logDiffClause($this, $table);
133
134 if (empty($contactIdClause)) {
135 $contactIdClause = "AND contact_id = %3";
136 }
137 if (strpos($table, 'civicrm_value') !== FALSE) {
138 $contactIdClause = "AND entity_id = %3";
139 }
6a488035
TO
140 }
141 }
142
143 // 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 144 $sql = "
8ef12e64 145SELECT DISTINCT lt.id FROM `{$this->db}`.`log_$table` lt
146{$join}
694e78fd
DS
147WHERE lt.log_conn_id = %1 AND
148 lt.log_date BETWEEN DATE_SUB(%2, INTERVAL {$this->interval}) AND DATE_ADD(%2, INTERVAL {$this->interval})
0b4c85c3 149 {$contactIdClause}";
5a1bd70b 150
6a488035
TO
151 $dao = CRM_Core_DAO::executeQuery($sql, $params);
152 while ($dao->fetch()) {
153 $diffs = array_merge($diffs, $this->diffsInTableForId($table, $dao->id));
154 }
155
156 return $diffs;
157 }
158
e0ef6999
EM
159 /**
160 * @param $table
100fef9d 161 * @param int $id
e0ef6999
EM
162 *
163 * @return array
164 */
6a488035
TO
165 private function diffsInTableForId($table, $id) {
166 $diffs = array();
167
168 $params = array(
169 1 => array($this->log_conn_id, 'Integer'),
170 2 => array($this->log_date, 'String'),
171 3 => array($id, 'Integer'),
172 );
173
b44e3f84 174 // 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
6a488035
TO
175 $changedSQL = "SELECT * FROM `{$this->db}`.`log_$table` WHERE log_conn_id = %1 AND log_date >= %2 AND log_date < DATE_ADD(%2, INTERVAL {$this->interval}) AND id = %3 ORDER BY log_date DESC LIMIT 1";
176
177 $changedDAO = CRM_Core_DAO::executeQuery($changedSQL, $params);
481a74f4 178 while ($changedDAO->fetch()) {
6a488035
TO
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;
353ffa53
TO
190 foreach ($changed as & $val) {
191 $val = NULL;
192 }
6a488035
TO
193 $changed['log_action'] = 'Delete';
194 break;
195
196 case 'Insert':
197 // the previous state does not exist
198 $original = array();
199 break;
200
201 case 'Update':
202 // look for the previous state (different log_conn_id) of the given id
203 $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";
204 $original = $this->sqlToArray($originalSQL, $params);
205 if (empty($original)) {
8ef12e64 206 // A blank original array is not possible for Update action, otherwise we 'll end up displaying all information
6a488035
TO
207 // in $changed variable as updated-info
208 $original = $changed;
209 }
210
211 break;
212 }
213
214 // populate $diffs with only the differences between $changed and $original
215 $skipped = array('log_action', 'log_conn_id', 'log_date', 'log_user_id');
216 foreach (array_keys(array_diff_assoc($changed, $original)) as $diff) {
217 if (in_array($diff, $skipped)) {
218 continue;
219 }
220
221 if (CRM_Utils_Array::value($diff, $original) === CRM_Utils_Array::value($diff, $changed)) {
222 continue;
223 }
8ef12e64 224
225 // hack: case_type_id column is a varchar with separator. For proper mapping to type labels,
6a488035
TO
226 // we need to make sure separators are trimmed
227 if ($diff == 'case_type_id') {
33421d01 228 foreach (array('original', 'changed') as $var) {
a7488080 229 if (!empty($$var[$diff])) {
6a488035
TO
230 $holder =& $$var;
231 $val = explode(CRM_Case_BAO_Case::VALUE_SEPARATOR, $holder[$diff]);
232 $holder[$diff] = CRM_Utils_Array::value(1, $val);
233 }
234 }
235 }
236
237 $diffs[] = array(
238 'action' => $changed['log_action'],
239 'id' => $id,
240 'field' => $diff,
241 'from' => CRM_Utils_Array::value($diff, $original),
242 'to' => CRM_Utils_Array::value($diff, $changed),
243 );
244 }
245 }
246
247 return $diffs;
248 }
249
e0ef6999
EM
250 /**
251 * @param $table
252 *
253 * @return array
254 */
00be9182 255 public function titlesAndValuesForTable($table) {
6a488035
TO
256 // static caches for subsequent calls with the same $table
257 static $titles = array();
258 static $values = array();
259
6a488035 260 if (!isset($titles[$table]) or !isset($values[$table])) {
8485f8e7 261 if (($tableDAO = CRM_Core_DAO_AllCoreTables::getClassForTable($table)) != FALSE) {
6a488035
TO
262 // FIXME: these should be populated with pseudo constants as they
263 // were at the time of logging rather than their current values
c0c9cd82 264 // FIXME: Use *_BAO:buildOptions() method rather than pseudoconstants & fetch programmatically
6a488035
TO
265 $values[$table] = array(
266 'contribution_page_id' => CRM_Contribute_PseudoConstant::contributionPage(),
267 'contribution_status_id' => CRM_Contribute_PseudoConstant::contributionStatus(),
353ffa53 268 'financial_type_id' => CRM_Contribute_PseudoConstant::financialType(),
6a488035 269 'country_id' => CRM_Core_PseudoConstant::country(),
26cf88b5 270 'gender_id' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
b2b0530a 271 'location_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'),
6a488035 272 'payment_instrument_id' => CRM_Contribute_PseudoConstant::paymentInstrument(),
b4f964d9 273 'phone_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
c0c9cd82
CW
274 'preferred_communication_method' => CRM_Contact_BAO_Contact::buildOptions('preferred_communication_method'),
275 'preferred_language' => CRM_Contact_BAO_Contact::buildOptions('preferred_language'),
276 'prefix_id' => CRM_Contact_BAO_Contact::buildOptions('prefix_id'),
e7e657f0 277 'provider_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
6a488035 278 'state_province_id' => CRM_Core_PseudoConstant::stateProvince(),
c0c9cd82 279 'suffix_id' => CRM_Contact_BAO_Contact::buildOptions('suffix_id'),
cbf48754 280 'website_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'),
6a488035 281 'activity_type_id' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE),
42047ce4 282 'case_type_id' => CRM_Case_PseudoConstant::caseType('title', FALSE),
353ffa53 283 'priority_id' => CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'),
6a488035
TO
284 );
285
286 // for columns that appear in more than 1 table
287 switch ($table) {
288 case 'civicrm_case':
289 $values[$table]['status_id'] = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
290 break;
ea100cb5 291
6a488035 292 case 'civicrm_activity':
481a74f4 293 $values[$table]['status_id'] = CRM_Core_PseudoConstant::activityStatus();
6a488035
TO
294 break;
295 }
296
8485f8e7 297 $dao = new $tableDAO();
6a488035
TO
298 foreach ($dao->fields() as $field) {
299 $titles[$table][$field['name']] = CRM_Utils_Array::value('title', $field);
300
301 if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
302 $values[$table][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
303 }
304 }
305 }
306 elseif (substr($table, 0, 14) == 'civicrm_value_') {
307 list($titles[$table], $values[$table]) = $this->titlesAndValuesForCustomDataTable($table);
0db6c3e1
TO
308 }
309 else {
6b4b11c4 310 $titles[$table] = $values[$table] = array();
6a488035
TO
311 }
312 }
313
314 return array($titles[$table], $values[$table]);
315 }
316
e0ef6999
EM
317 /**
318 * @param $sql
c490a46a 319 * @param array $params
e0ef6999
EM
320 *
321 * @return mixed
322 */
6a488035
TO
323 private function sqlToArray($sql, $params) {
324 $dao = CRM_Core_DAO::executeQuery($sql, $params);
325 $dao->fetch();
326 return $dao->toArray();
327 }
328
e0ef6999
EM
329 /**
330 * @param $table
331 *
332 * @return array
333 */
6a488035
TO
334 private function titlesAndValuesForCustomDataTable($table) {
335 $titles = array();
336 $values = array();
337
338 $params = array(
339 1 => array($this->log_conn_id, 'Integer'),
340 2 => array($this->log_date, 'String'),
341 3 => array($table, 'String'),
342 );
343
344 $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";
345 $cgDao = CRM_Core_DAO::executeQuery($sql, $params);
346 $cgDao->fetch();
347
348 $params[3] = array($cgDao->id, 'Integer');
349 $sql = "
350SELECT column_name, data_type, label, name, option_group_id
351FROM `{$this->db}`.log_civicrm_custom_field
352WHERE log_date <= %2
353AND custom_group_id = %3
354ORDER BY log_date
355";
356 $cfDao = CRM_Core_DAO::executeQuery($sql, $params);
357
358 while ($cfDao->fetch()) {
359 $titles[$cfDao->column_name] = "{$cgDao->title}: {$cfDao->label}";
360
361 switch ($cfDao->data_type) {
362 case 'Boolean':
363 $values[$cfDao->column_name] = array('0' => ts('false'), '1' => ts('true'));
364 break;
365
366 case 'String':
367 $values[$cfDao->column_name] = array();
368 if (!empty($cfDao->option_group_id)) {
369 $params[3] = array($cfDao->option_group_id, 'Integer');
370 $sql = "
371SELECT label, value
372FROM `{$this->db}`.log_civicrm_option_value
373WHERE log_date <= %2
374AND option_group_id = %3
375ORDER BY log_date
376";
377 $ovDao = CRM_Core_DAO::executeQuery($sql, $params);
378 while ($ovDao->fetch()) {
379 $values[$cfDao->column_name][$ovDao->value] = $ovDao->label;
380 }
381 }
382 break;
383 }
384 }
385
386 return array($titles, $values);
387 }
96025800 388
6a488035 389}