Merge pull request #4789 from totten/master-test-tx
[civicrm-core.git] / CRM / Logging / Differ.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Logging_Differ {
36 private $db;
37 private $log_conn_id;
38 private $log_date;
39 private $interval;
40
41 /**
42 * @param int $log_conn_id
43 * @param $log_date
44 * @param string $interval
45 */
46 function __construct($log_conn_id, $log_date, $interval = '10 SECOND') {
47 $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
48 $this->db = $dsn['database'];
49 $this->log_conn_id = $log_conn_id;
50 $this->log_date = $log_date;
51 $this->interval = $interval;
52 }
53
54 /**
55 * @param $tables
56 *
57 * @return array
58 */
59 function diffsInTables($tables) {
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
70 /**
71 * @param $table
72 * @param int $contactID
73 *
74 * @return array
75 */
76 function diffsInTable($table, $contactID = null) {
77 $diffs = array();
78
79 $params = array(
80 1 => array($this->log_conn_id, 'Integer'),
81 2 => array($this->log_date, 'String'),
82 );
83
84 $logging = new CRM_Logging_Schema;
85 $addressCustomTables = $logging->entityCustomDataLogTables('Address');
86
87 $contactIdClause = $join = '';
88 if ( $contactID ) {
89 $params[3] = array($contactID, 'Integer');
90 switch ($table) {
91 case 'civicrm_contact':
92 $contactIdClause = "AND id = %3";
93 break;
94 case 'civicrm_note':
95 $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'))";
96 break;
97 case 'civicrm_entity_tag':
98 $contactIdClause = "AND entity_id = %3 AND entity_table = 'civicrm_contact'";
99 break;
100 case 'civicrm_relationship':
101 $contactIdClause = "AND (contact_id_a = %3 OR contact_id_b = %3)";
102 break;
103 case 'civicrm_activity':
104 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
105 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
106 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
107 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
108
109 $join = "
110 LEFT JOIN civicrm_activity_contact at ON at.activity_id = lt.id AND at.contact_id = %3 AND at.record_type_id = {$targetID}
111 LEFT JOIN civicrm_activity_contact aa ON aa.activity_id = lt.id AND aa.contact_id = %3 AND aa.record_type_id = {$assigneeID}
112 LEFT JOIN civicrm_activity_contact source ON source.activity_id = lt.id AND source.contact_id = %3 AND source.record_type_id = {$sourceID} ";
113 $contactIdClause = "AND (at.id IS NOT NULL OR aa.id IS NOT NULL OR source.id IS NOT NULL)";
114 break;
115 case 'civicrm_case':
116 $contactIdClause = "AND id = (select case_id FROM civicrm_case_contact WHERE contact_id = %3 LIMIT 1)";
117 break;
118 default:
119 if (array_key_exists($table, $addressCustomTables)) {
120 $join = "INNER JOIN `{$this->db}`.`log_civicrm_address` et ON et.id = lt.entity_id";
121 $contactIdClause = "AND contact_id = %3";
122 break;
123 }
124
125 // allow tables to be extended by report hook query objects
126 list($contactIdClause, $join) = CRM_Report_BAO_Hook::singleton()->logDiffClause($this, $table);
127
128 if (empty($contactIdClause)) {
129 $contactIdClause = "AND contact_id = %3";
130 }
131 if ( strpos($table, 'civicrm_value') !== false ) {
132 $contactIdClause = "AND entity_id = %3";
133 }
134 }
135 }
136
137 // 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)
138 $sql = "
139 SELECT DISTINCT lt.id FROM `{$this->db}`.`log_$table` lt
140 {$join}
141 WHERE lt.log_conn_id = %1 AND
142 lt.log_date BETWEEN DATE_SUB(%2, INTERVAL {$this->interval}) AND DATE_ADD(%2, INTERVAL {$this->interval})
143 {$contactIdClause}";
144
145 $dao = CRM_Core_DAO::executeQuery($sql, $params);
146 while ($dao->fetch()) {
147 $diffs = array_merge($diffs, $this->diffsInTableForId($table, $dao->id));
148 }
149
150 return $diffs;
151 }
152
153 /**
154 * @param $table
155 * @param int $id
156 *
157 * @return array
158 */
159 private function diffsInTableForId($table, $id) {
160 $diffs = array();
161
162 $params = array(
163 1 => array($this->log_conn_id, 'Integer'),
164 2 => array($this->log_date, 'String'),
165 3 => array($id, 'Integer'),
166 );
167
168 // look for all the changes in the given connection that happended less than {$this->interval} s later than log_date to the given id to catch multi-query changes
169 $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";
170
171 $changedDAO = CRM_Core_DAO::executeQuery($changedSQL, $params);
172 while ($changedDAO->fetch( )) {
173 $changed = $changedDAO->toArray();
174
175 // return early if nothing found
176 if (empty($changed)) {
177 continue;
178 }
179
180 switch ($changed['log_action']) {
181 case 'Delete':
182 // the previous state is kept in the current state, current should keep the keys and clear the values
183 $original = $changed;
184 foreach ($changed as & $val) $val = NULL;
185 $changed['log_action'] = 'Delete';
186 break;
187
188 case 'Insert':
189 // the previous state does not exist
190 $original = array();
191 break;
192
193 case 'Update':
194 // look for the previous state (different log_conn_id) of the given id
195 $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";
196 $original = $this->sqlToArray($originalSQL, $params);
197 if (empty($original)) {
198 // A blank original array is not possible for Update action, otherwise we 'll end up displaying all information
199 // in $changed variable as updated-info
200 $original = $changed;
201 }
202
203 break;
204 }
205
206 // populate $diffs with only the differences between $changed and $original
207 $skipped = array('log_action', 'log_conn_id', 'log_date', 'log_user_id');
208 foreach (array_keys(array_diff_assoc($changed, $original)) as $diff) {
209 if (in_array($diff, $skipped)) {
210 continue;
211 }
212
213 if (CRM_Utils_Array::value($diff, $original) === CRM_Utils_Array::value($diff, $changed)) {
214 continue;
215 }
216
217 // hack: case_type_id column is a varchar with separator. For proper mapping to type labels,
218 // we need to make sure separators are trimmed
219 if ($diff == 'case_type_id') {
220 foreach (array('original', 'changed') as $var) {
221 if (!empty($$var[$diff])) {
222 $holder =& $$var;
223 $val = explode(CRM_Case_BAO_Case::VALUE_SEPARATOR, $holder[$diff]);
224 $holder[$diff] = CRM_Utils_Array::value(1, $val);
225 }
226 }
227 }
228
229 $diffs[] = array(
230 'action' => $changed['log_action'],
231 'id' => $id,
232 'field' => $diff,
233 'from' => CRM_Utils_Array::value($diff, $original),
234 'to' => CRM_Utils_Array::value($diff, $changed),
235 );
236 }
237 }
238
239 return $diffs;
240 }
241
242 /**
243 * @param $table
244 *
245 * @return array
246 */
247 function titlesAndValuesForTable($table) {
248 // static caches for subsequent calls with the same $table
249 static $titles = array();
250 static $values = array();
251
252 // FIXME: split off the table → DAO mapping to a GenCode-generated class
253 static $daos = array(
254 'civicrm_address' => 'CRM_Core_DAO_Address',
255 'civicrm_contact' => 'CRM_Contact_DAO_Contact',
256 'civicrm_email' => 'CRM_Core_DAO_Email',
257 'civicrm_im' => 'CRM_Core_DAO_IM',
258 'civicrm_openid' => 'CRM_Core_DAO_OpenID',
259 'civicrm_phone' => 'CRM_Core_DAO_Phone',
260 'civicrm_website' => 'CRM_Core_DAO_Website',
261 'civicrm_contribution' => 'CRM_Contribute_DAO_Contribution',
262 'civicrm_note' => 'CRM_Core_DAO_Note',
263 'civicrm_relationship' => 'CRM_Contact_DAO_Relationship',
264 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
265 'civicrm_case' => 'CRM_Case_DAO_Case',
266 );
267
268 if (!isset($titles[$table]) or !isset($values[$table])) {
269
270 if (in_array($table, array_keys($daos))) {
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] = array(
275 'contribution_page_id' => CRM_Contribute_PseudoConstant::contributionPage(),
276 'contribution_status_id' => CRM_Contribute_PseudoConstant::contributionStatus(),
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 case 'civicrm_activity':
301 $values[$table]['status_id'] = CRM_Core_PseudoConstant::activityStatus( );
302 break;
303 }
304
305 $dao = new $daos[$table];
306 foreach ($dao->fields() as $field) {
307 $titles[$table][$field['name']] = CRM_Utils_Array::value('title', $field);
308
309 if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
310 $values[$table][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
311 }
312 }
313 }
314 elseif (substr($table, 0, 14) == 'civicrm_value_') {
315 list($titles[$table], $values[$table]) = $this->titlesAndValuesForCustomDataTable($table);
316 } else {
317 $titles[$table] = $values[$table] = array();
318 }
319 }
320
321 return array($titles[$table], $values[$table]);
322 }
323
324 /**
325 * @param $sql
326 * @param array $params
327 *
328 * @return mixed
329 */
330 private function sqlToArray($sql, $params) {
331 $dao = CRM_Core_DAO::executeQuery($sql, $params);
332 $dao->fetch();
333 return $dao->toArray();
334 }
335
336 /**
337 * @param $table
338 *
339 * @return array
340 */
341 private function titlesAndValuesForCustomDataTable($table) {
342 $titles = array();
343 $values = array();
344
345 $params = array(
346 1 => array($this->log_conn_id, 'Integer'),
347 2 => array($this->log_date, 'String'),
348 3 => array($table, 'String'),
349 );
350
351 $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";
352 $cgDao = CRM_Core_DAO::executeQuery($sql, $params);
353 $cgDao->fetch();
354
355 $params[3] = array($cgDao->id, 'Integer');
356 $sql = "
357 SELECT column_name, data_type, label, name, option_group_id
358 FROM `{$this->db}`.log_civicrm_custom_field
359 WHERE log_date <= %2
360 AND custom_group_id = %3
361 ORDER BY log_date
362 ";
363 $cfDao = CRM_Core_DAO::executeQuery($sql, $params);
364
365 while ($cfDao->fetch()) {
366 $titles[$cfDao->column_name] = "{$cgDao->title}: {$cfDao->label}";
367
368 switch ($cfDao->data_type) {
369 case 'Boolean':
370 $values[$cfDao->column_name] = array('0' => ts('false'), '1' => ts('true'));
371 break;
372
373 case 'String':
374 $values[$cfDao->column_name] = array();
375 if (!empty($cfDao->option_group_id)) {
376 $params[3] = array($cfDao->option_group_id, 'Integer');
377 $sql = "
378 SELECT label, value
379 FROM `{$this->db}`.log_civicrm_option_value
380 WHERE log_date <= %2
381 AND option_group_id = %3
382 ORDER BY log_date
383 ";
384 $ovDao = CRM_Core_DAO::executeQuery($sql, $params);
385 while ($ovDao->fetch()) {
386 $values[$cfDao->column_name][$ovDao->value] = $ovDao->label;
387 }
388 }
389 break;
390 }
391 }
392
393 return array($titles, $values);
394 }
395 }
396