INFRA-132 - SpacingAfterBeak
[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 public 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 public 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 public 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
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;
98
99 case 'civicrm_entity_tag':
100 $contactIdClause = "AND entity_id = %3 AND entity_table = 'civicrm_contact'";
101 break;
102
103 case 'civicrm_relationship':
104 $contactIdClause = "AND (contact_id_a = %3 OR contact_id_b = %3)";
105 break;
106
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);
112
113 $join = "
114 LEFT JOIN civicrm_activity_contact at ON at.activity_id = lt.id AND at.contact_id = %3 AND at.record_type_id = {$targetID}
115 LEFT JOIN civicrm_activity_contact aa ON aa.activity_id = lt.id AND aa.contact_id = %3 AND aa.record_type_id = {$assigneeID}
116 LEFT JOIN civicrm_activity_contact source ON source.activity_id = lt.id AND source.contact_id = %3 AND source.record_type_id = {$sourceID} ";
117 $contactIdClause = "AND (at.id IS NOT NULL OR aa.id IS NOT NULL OR source.id IS NOT NULL)";
118 break;
119
120 case 'civicrm_case':
121 $contactIdClause = "AND id = (select case_id FROM civicrm_case_contact WHERE contact_id = %3 LIMIT 1)";
122 break;
123
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 }
130
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 }
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)
144 $sql = "
145 SELECT DISTINCT lt.id FROM `{$this->db}`.`log_$table` lt
146 {$join}
147 WHERE lt.log_conn_id = %1 AND
148 lt.log_date BETWEEN DATE_SUB(%2, INTERVAL {$this->interval}) AND DATE_ADD(%2, INTERVAL {$this->interval})
149 {$contactIdClause}";
150
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
159 /**
160 * @param $table
161 * @param int $id
162 *
163 * @return array
164 */
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
174 // 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
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);
178 while ($changedDAO->fetch()) {
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) $val = NULL;
191 $changed['log_action'] = 'Delete';
192 break;
193
194 case 'Insert':
195 // the previous state does not exist
196 $original = array();
197 break;
198
199 case 'Update':
200 // look for the previous state (different log_conn_id) of the given id
201 $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";
202 $original = $this->sqlToArray($originalSQL, $params);
203 if (empty($original)) {
204 // A blank original array is not possible for Update action, otherwise we 'll end up displaying all information
205 // in $changed variable as updated-info
206 $original = $changed;
207 }
208
209 break;
210 }
211
212 // populate $diffs with only the differences between $changed and $original
213 $skipped = array('log_action', 'log_conn_id', 'log_date', 'log_user_id');
214 foreach (array_keys(array_diff_assoc($changed, $original)) as $diff) {
215 if (in_array($diff, $skipped)) {
216 continue;
217 }
218
219 if (CRM_Utils_Array::value($diff, $original) === CRM_Utils_Array::value($diff, $changed)) {
220 continue;
221 }
222
223 // hack: case_type_id column is a varchar with separator. For proper mapping to type labels,
224 // we need to make sure separators are trimmed
225 if ($diff == 'case_type_id') {
226 foreach (array('original', 'changed') as $var) {
227 if (!empty($$var[$diff])) {
228 $holder =& $$var;
229 $val = explode(CRM_Case_BAO_Case::VALUE_SEPARATOR, $holder[$diff]);
230 $holder[$diff] = CRM_Utils_Array::value(1, $val);
231 }
232 }
233 }
234
235 $diffs[] = array(
236 'action' => $changed['log_action'],
237 'id' => $id,
238 'field' => $diff,
239 'from' => CRM_Utils_Array::value($diff, $original),
240 'to' => CRM_Utils_Array::value($diff, $changed),
241 );
242 }
243 }
244
245 return $diffs;
246 }
247
248 /**
249 * @param $table
250 *
251 * @return array
252 */
253 public function titlesAndValuesForTable($table) {
254 // static caches for subsequent calls with the same $table
255 static $titles = array();
256 static $values = array();
257
258 // FIXME: split off the table → DAO mapping to a GenCode-generated class
259 static $daos = array(
260 'civicrm_address' => 'CRM_Core_DAO_Address',
261 'civicrm_contact' => 'CRM_Contact_DAO_Contact',
262 'civicrm_email' => 'CRM_Core_DAO_Email',
263 'civicrm_im' => 'CRM_Core_DAO_IM',
264 'civicrm_openid' => 'CRM_Core_DAO_OpenID',
265 'civicrm_phone' => 'CRM_Core_DAO_Phone',
266 'civicrm_website' => 'CRM_Core_DAO_Website',
267 'civicrm_contribution' => 'CRM_Contribute_DAO_Contribution',
268 'civicrm_note' => 'CRM_Core_DAO_Note',
269 'civicrm_relationship' => 'CRM_Contact_DAO_Relationship',
270 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
271 'civicrm_case' => 'CRM_Case_DAO_Case',
272 );
273
274 if (!isset($titles[$table]) or !isset($values[$table])) {
275
276 if (in_array($table, array_keys($daos))) {
277 // FIXME: these should be populated with pseudo constants as they
278 // were at the time of logging rather than their current values
279 // FIXME: Use *_BAO:buildOptions() method rather than pseudoconstants & fetch programmatically
280 $values[$table] = array(
281 'contribution_page_id' => CRM_Contribute_PseudoConstant::contributionPage(),
282 'contribution_status_id' => CRM_Contribute_PseudoConstant::contributionStatus(),
283 'financial_type_id' => CRM_Contribute_PseudoConstant::financialType(),
284 'country_id' => CRM_Core_PseudoConstant::country(),
285 'gender_id' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
286 'location_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'),
287 'payment_instrument_id' => CRM_Contribute_PseudoConstant::paymentInstrument(),
288 'phone_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
289 'preferred_communication_method' => CRM_Contact_BAO_Contact::buildOptions('preferred_communication_method'),
290 'preferred_language' => CRM_Contact_BAO_Contact::buildOptions('preferred_language'),
291 'prefix_id' => CRM_Contact_BAO_Contact::buildOptions('prefix_id'),
292 'provider_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
293 'state_province_id' => CRM_Core_PseudoConstant::stateProvince(),
294 'suffix_id' => CRM_Contact_BAO_Contact::buildOptions('suffix_id'),
295 'website_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'),
296 'activity_type_id' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE),
297 'case_type_id' => CRM_Case_PseudoConstant::caseType('title', FALSE),
298 'priority_id' => CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'),
299 );
300
301 // for columns that appear in more than 1 table
302 switch ($table) {
303 case 'civicrm_case':
304 $values[$table]['status_id'] = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
305 break;
306
307 case 'civicrm_activity':
308 $values[$table]['status_id'] = CRM_Core_PseudoConstant::activityStatus();
309 break;
310 }
311
312 $dao = new $daos[$table];
313 foreach ($dao->fields() as $field) {
314 $titles[$table][$field['name']] = CRM_Utils_Array::value('title', $field);
315
316 if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
317 $values[$table][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
318 }
319 }
320 }
321 elseif (substr($table, 0, 14) == 'civicrm_value_') {
322 list($titles[$table], $values[$table]) = $this->titlesAndValuesForCustomDataTable($table);
323 }
324 else {
325 $titles[$table] = $values[$table] = array();
326 }
327 }
328
329 return array($titles[$table], $values[$table]);
330 }
331
332 /**
333 * @param $sql
334 * @param array $params
335 *
336 * @return mixed
337 */
338 private function sqlToArray($sql, $params) {
339 $dao = CRM_Core_DAO::executeQuery($sql, $params);
340 $dao->fetch();
341 return $dao->toArray();
342 }
343
344 /**
345 * @param $table
346 *
347 * @return array
348 */
349 private function titlesAndValuesForCustomDataTable($table) {
350 $titles = array();
351 $values = array();
352
353 $params = array(
354 1 => array($this->log_conn_id, 'Integer'),
355 2 => array($this->log_date, 'String'),
356 3 => array($table, 'String'),
357 );
358
359 $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";
360 $cgDao = CRM_Core_DAO::executeQuery($sql, $params);
361 $cgDao->fetch();
362
363 $params[3] = array($cgDao->id, 'Integer');
364 $sql = "
365 SELECT column_name, data_type, label, name, option_group_id
366 FROM `{$this->db}`.log_civicrm_custom_field
367 WHERE log_date <= %2
368 AND custom_group_id = %3
369 ORDER BY log_date
370 ";
371 $cfDao = CRM_Core_DAO::executeQuery($sql, $params);
372
373 while ($cfDao->fetch()) {
374 $titles[$cfDao->column_name] = "{$cgDao->title}: {$cfDao->label}";
375
376 switch ($cfDao->data_type) {
377 case 'Boolean':
378 $values[$cfDao->column_name] = array('0' => ts('false'), '1' => ts('true'));
379 break;
380
381 case 'String':
382 $values[$cfDao->column_name] = array();
383 if (!empty($cfDao->option_group_id)) {
384 $params[3] = array($cfDao->option_group_id, 'Integer');
385 $sql = "
386 SELECT label, value
387 FROM `{$this->db}`.log_civicrm_option_value
388 WHERE log_date <= %2
389 AND option_group_id = %3
390 ORDER BY log_date
391 ";
392 $ovDao = CRM_Core_DAO::executeQuery($sql, $params);
393 while ($ovDao->fetch()) {
394 $values[$cfDao->column_name][$ovDao->value] = $ovDao->label;
395 }
396 }
397 break;
398 }
399 }
400
401 return array($titles, $values);
402 }
403 }