Merge pull request #17 from deepak-srivastava/civicrm43
[civicrm-core.git] / CRM / Logging / Differ.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 function __construct($log_conn_id, $log_date, $interval = '10 SECOND') {
42 $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
43 $this->db = $dsn['database'];
44 $this->log_conn_id = $log_conn_id;
45 $this->log_date = $log_date;
46 $this->interval = $interval;
47 }
48
49 function diffsInTables($tables) {
50 $diffs = array();
51 foreach ($tables as $table) {
52 $diff = $this->diffsInTable($table);
53 if (!empty($diff)) {
54 $diffs[$table] = $diff;
55 }
56 }
57 return $diffs;
58 }
59
60 function diffsInTable($table, $contactID = null) {
61 $diffs = array();
62
63 $params = array(
64 1 => array($this->log_conn_id, 'Integer'),
65 2 => array($this->log_date, 'String'),
66 );
67
68 $contactIdClause = '';
69 if ( $contactID ) {
70 $params[3] = array($contactID, 'Integer');
71 switch ($table) {
72 case 'civicrm_contact':
73 $contactIdClause = "AND id = %3";
74 break;
75 case 'civicrm_note':
76 $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')";
77 break;
78 case 'civicrm_entity_tag':
79 $contactIdClause = "AND entity_id = %3 AND entity_table = 'civicrm_contact'";
80 break;
81 case 'civicrm_relationship':
82 $contactIdClause = "AND (contact_id_a = %3 OR contact_id_b = %3)";
83 break;
84 case 'civicrm_activity':
85 $contactIdClause = "
86 AND (id = (select activity_id FROM civicrm_activity_target WHERE target_contact_id = %3 LIMIT 1) OR
87 id = (select activity_id FROM civicrm_activity_assignment WHERE assignee_contact_id = %3 LIMIT 1) OR
88 source_contact_id = %3)";
89 break;
90 case 'civicrm_case':
91 $contactIdClause = "AND id = (select case_id FROM civicrm_case_contact WHERE contact_id = %3 LIMIT 1)";
92 break;
93 default:
94 $contactIdClause = "AND contact_id = %3";
95 if ( strpos($table, 'civicrm_value') !== false ) {
96 $contactIdClause = "AND entity_id = %3";
97 }
98 }
99 }
100
101 // 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)
102 $sql = "SELECT DISTINCT id FROM `{$this->db}`.`log_$table` WHERE log_conn_id = %1 AND log_date BETWEEN DATE_SUB(%2, INTERVAL {$this->interval}) AND DATE_ADD(%2, INTERVAL {$this->interval}) {$contactIdClause}";
103
104 $dao = CRM_Core_DAO::executeQuery($sql, $params);
105 while ($dao->fetch()) {
106 $diffs = array_merge($diffs, $this->diffsInTableForId($table, $dao->id));
107 }
108
109 return $diffs;
110 }
111
112 private function diffsInTableForId($table, $id) {
113 $diffs = array();
114
115 $params = array(
116 1 => array($this->log_conn_id, 'Integer'),
117 2 => array($this->log_date, 'String'),
118 3 => array($id, 'Integer'),
119 );
120
121 // 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
122 $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";
123
124 $changedDAO = CRM_Core_DAO::executeQuery($changedSQL, $params);
125 while ($changedDAO->fetch( )) {
126 $changed = $changedDAO->toArray();
127
128 // return early if nothing found
129 if (empty($changed)) {
130 continue;
131 }
132
133 switch ($changed['log_action']) {
134 case 'Delete':
135 // the previous state is kept in the current state, current should keep the keys and clear the values
136 $original = $changed;
137 foreach ($changed as & $val) $val = NULL;
138 $changed['log_action'] = 'Delete';
139 break;
140
141 case 'Insert':
142 // the previous state does not exist
143 $original = array();
144 break;
145
146 case 'Update':
147 // look for the previous state (different log_conn_id) of the given id
148 $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";
149 $original = $this->sqlToArray($originalSQL, $params);
150 if (empty($original)) {
151 // A blank original array is not possible for Update action, otherwise we 'll end up displaying all information
152 // in $changed variable as updated-info
153 $original = $changed;
154 }
155
156 break;
157 }
158
159 // populate $diffs with only the differences between $changed and $original
160 $skipped = array('log_action', 'log_conn_id', 'log_date', 'log_user_id');
161 foreach (array_keys(array_diff_assoc($changed, $original)) as $diff) {
162 if (in_array($diff, $skipped)) {
163 continue;
164 }
165
166 if (CRM_Utils_Array::value($diff, $original) === CRM_Utils_Array::value($diff, $changed)) {
167 continue;
168 }
169
170 // hack: case_type_id column is a varchar with separator. For proper mapping to type labels,
171 // we need to make sure separators are trimmed
172 if ($diff == 'case_type_id') {
173 foreach (array('original', 'changed') as $var) {
174 if (CRM_Utils_Array::value($diff, $$var)) {
175 $holder =& $$var;
176 $val = explode(CRM_Case_BAO_Case::VALUE_SEPARATOR, $holder[$diff]);
177 $holder[$diff] = CRM_Utils_Array::value(1, $val);
178 }
179 }
180 }
181
182 $diffs[] = array(
183 'action' => $changed['log_action'],
184 'id' => $id,
185 'field' => $diff,
186 'from' => CRM_Utils_Array::value($diff, $original),
187 'to' => CRM_Utils_Array::value($diff, $changed),
188 );
189 }
190 }
191
192 return $diffs;
193 }
194
195 function titlesAndValuesForTable($table) {
196 // static caches for subsequent calls with the same $table
197 static $titles = array();
198 static $values = array();
199
200 // FIXME: split off the table → DAO mapping to a GenCode-generated class
201 static $daos = array(
202 'civicrm_address' => 'CRM_Core_DAO_Address',
203 'civicrm_contact' => 'CRM_Contact_DAO_Contact',
204 'civicrm_email' => 'CRM_Core_DAO_Email',
205 'civicrm_im' => 'CRM_Core_DAO_IM',
206 'civicrm_openid' => 'CRM_Core_DAO_OpenID',
207 'civicrm_phone' => 'CRM_Core_DAO_Phone',
208 'civicrm_website' => 'CRM_Core_DAO_Website',
209 'civicrm_contribution' => 'CRM_Contribute_DAO_Contribution',
210 'civicrm_note' => 'CRM_Core_DAO_Note',
211 'civicrm_relationship' => 'CRM_Contact_DAO_Relationship',
212 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
213 'civicrm_case' => 'CRM_Case_DAO_Case',
214 );
215
216 if (!isset($titles[$table]) or !isset($values[$table])) {
217
218 if (in_array($table, array_keys($daos))) {
219 // FIXME: these should be populated with pseudo constants as they
220 // were at the time of logging rather than their current values
221 $values[$table] = array(
222 'contribution_page_id' => CRM_Contribute_PseudoConstant::contributionPage(),
223 'contribution_status_id' => CRM_Contribute_PseudoConstant::contributionStatus(),
224 'financial_type_id' => CRM_Contribute_PseudoConstant::financialType(),
225 'country_id' => CRM_Core_PseudoConstant::country(),
226 'gender_id' => CRM_Core_PseudoConstant::gender(),
227 'location_type_id' => CRM_Core_PseudoConstant::locationType(),
228 'payment_instrument_id' => CRM_Contribute_PseudoConstant::paymentInstrument(),
229 'phone_type_id' => CRM_Core_PseudoConstant::phoneType(),
230 'preferred_communication_method' => CRM_Core_PseudoConstant::pcm(),
231 'preferred_language' => CRM_Core_PseudoConstant::languages(),
232 'prefix_id' => CRM_Core_PseudoConstant::individualPrefix(),
233 'provider_id' => CRM_Core_PseudoConstant::IMProvider(),
234 'state_province_id' => CRM_Core_PseudoConstant::stateProvince(),
235 'suffix_id' => CRM_Core_PseudoConstant::individualSuffix(),
236 'website_type_id' => CRM_Core_PseudoConstant::websiteType(),
237 'activity_type_id' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE),
238 'case_type_id' => CRM_Case_PseudoConstant::caseType('label', FALSE),
239 'priority_id' => CRM_Core_PseudoConstant::priority(),
240 );
241
242 // for columns that appear in more than 1 table
243 switch ($table) {
244 case 'civicrm_case':
245 $values[$table]['status_id'] = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
246 break;
247 case 'civicrm_activity':
248 $values[$table]['status_id'] = CRM_Core_PseudoConstant::activityStatus( );
249 break;
250 }
251
252 require_once str_replace('_', DIRECTORY_SEPARATOR, $daos[$table]) . '.php';
253 eval("\$dao = new $daos[$table];");
254 foreach ($dao->fields() as $field) {
255 $titles[$table][$field['name']] = CRM_Utils_Array::value('title', $field);
256
257 if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
258 $values[$table][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
259 }
260 }
261 }
262 elseif (substr($table, 0, 14) == 'civicrm_value_') {
263 list($titles[$table], $values[$table]) = $this->titlesAndValuesForCustomDataTable($table);
264 }
265 }
266
267 return array($titles[$table], $values[$table]);
268 }
269
270 private function sqlToArray($sql, $params) {
271 $dao = CRM_Core_DAO::executeQuery($sql, $params);
272 $dao->fetch();
273 return $dao->toArray();
274 }
275
276 private function titlesAndValuesForCustomDataTable($table) {
277 $titles = array();
278 $values = array();
279
280 $params = array(
281 1 => array($this->log_conn_id, 'Integer'),
282 2 => array($this->log_date, 'String'),
283 3 => array($table, 'String'),
284 );
285
286 $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";
287 $cgDao = CRM_Core_DAO::executeQuery($sql, $params);
288 $cgDao->fetch();
289
290 $params[3] = array($cgDao->id, 'Integer');
291 $sql = "
292 SELECT column_name, data_type, label, name, option_group_id
293 FROM `{$this->db}`.log_civicrm_custom_field
294 WHERE log_date <= %2
295 AND custom_group_id = %3
296 ORDER BY log_date
297 ";
298 $cfDao = CRM_Core_DAO::executeQuery($sql, $params);
299
300 while ($cfDao->fetch()) {
301 $titles[$cfDao->column_name] = "{$cgDao->title}: {$cfDao->label}";
302
303 switch ($cfDao->data_type) {
304 case 'Boolean':
305 $values[$cfDao->column_name] = array('0' => ts('false'), '1' => ts('true'));
306 break;
307
308 case 'String':
309 $values[$cfDao->column_name] = array();
310 if (!empty($cfDao->option_group_id)) {
311 $params[3] = array($cfDao->option_group_id, 'Integer');
312 $sql = "
313 SELECT label, value
314 FROM `{$this->db}`.log_civicrm_option_value
315 WHERE log_date <= %2
316 AND option_group_id = %3
317 ORDER BY log_date
318 ";
319 $ovDao = CRM_Core_DAO::executeQuery($sql, $params);
320 while ($ovDao->fetch()) {
321 $values[$cfDao->column_name][$ovDao->value] = $ovDao->label;
322 }
323 }
324 break;
325 }
326 }
327
328 return array($titles, $values);
329 }
330 }
331